Skip to content

phpcent v7: a rewrite to the Centrifugo server SDK specification - #71

Merged
FZambia merged 31 commits into
masterfrom
v7_dev
Nov 5, 2026
Merged

FZambia merged 31 commits into
masterfrom
v7_dev

Conversation

@FZambia

@FZambia FZambia commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

phpcent 7: a rewrite to the Centrifugo server SDK specification, whose reference implementation is gocent v4. It replaces phpcent 6; MIGRATING.md has complete programs in phpcent 6 and 7 side by side, and a table mapping every old call and setter.

$client = new Client('http://localhost:8000/api', apiKey: getenv('CENTRIFUGO_API_KEY'));
$res = $client->publish(channel: 'news', data: ['text' => 'hello']);

What changes

  • PHP 8.3 or newer, namespace Centrifugal\Phpcent. No dependencies but the PSR HTTP interfaces; ext-curl for the default transport, ext-openssl and ext-sodium for asymmetric tokens.
  • A method for every API method, including map, shared poll and Centrifugo PRO methods, generated from Centrifugo's api.proto with its documentation: it takes the request's fields as named arguments and returns a typed result, checked by PHPStan. A batch and Command have the same methods: $batch->publish(...) returns a Pending<PublishResult>.
  • Errors are exceptions: ApiException with a subclass per known code, HttpException, UnauthorizedException, DecodeException, InvalidRequestException, InvalidConfigException, NetworkException, TimeoutException; hints in messages; Centrifugo's transport error mode.
  • A broadcast or batch in which some parts failed throws BroadcastFailedChannelsException or BatchFailedCommandsException, carrying every part's outcome. broadcastWithRetry retries only the channels which may still succeed, under one idempotency key.
  • Payloads: PHP values or RawJson in (also nested), sent as the same JSON value; replies give stdClass, which goes back exactly; Payload::toArray() for arrays. NaN, infinities and binary strings are refused before sending.
  • One deadline per call over curl, which keeps connections alive (across PHP-FPM requests on PHP 8.5). Any PSR-18 client instead: Guzzle, Symfony HttpClient, a fake one in tests. Closes Add support for http-client #55.
  • Tokens with every claim (HS256, RS256, ES256/384/512, EdDSA), JWKS and key rotation, Centrifugo PRO API tokens.
  • Endpoints for client SDKs (connection and subscription tokens, shared poll signatures, JWKS) and a handler for every proxy type: a framework-free core with PSR-15 and plain PHP adapters; Laravel and Symfony wiring in the README.
  • Command::publish(...) and the other methods for async consumers, SharedPoll::sign.
  • API.md, the API reference, generated from the docblocks by composer docs.
  • Releases: composer.json has no version any more - the tag is the version. Pushing a v* tag publishes it through Packagist's hook, and release.yml creates the GitHub release.

Tested

  • composer check: generated code and API.md current, php-cs-fixer, PHPStan at max level, 209 unit tests - on PHP 8.3 and 8.5.
  • Integration tests against Centrifugo v6.10.2 and Centrifugo PRO v6.10.2: every method, tokens connecting a real client, proxy handlers called by Centrifugo, API tokens via JWKS, commands consumed from Redis.
  • The spec's test vectors; RS256 and ES256/384/512 signatures verified with OpenSSL.
  • The README's integrations - Guzzle, Symfony's PSR-18 client and HttpFoundation, Slim - and every MIGRATING program pair, run against Centrifugo with matching output.

PHP 8.3+, namespace Centrifugal\Phpcent. Requests and results generated from
Centrifugo's protos: every API method, PRO ones included. Errors are
exceptions; partial broadcast and batch failures carry every part's outcome;
broadcastWithRetry. Payloads carried exactly: PHP values or RawJson in,
stdClass out, Payload::toArray for arrays. One deadline per call over curl,
or any PSR-18 client (#55). Tokens with every claim (HS256, RS256, ES256/384/512,
EdDSA), JWKS, PRO API tokens, endpoints for client SDKs, proxy handlers with a
framework-free core and PSR-15 and plain PHP adapters, shared poll signatures,
commands for async consumers. API.md generated from the docblocks; releases
on tag push.
…ommand, as spec 0.2 says

$client->publish(channel: ..., data: ...), $batch->publish(...) returning a
typed Pending, Command::publish(...): generated with the same parameters, each
documented from the protos, and listed with them in API.md. The request
classes are internal; nested messages and results stay public classes.
MIGRATING's programs rerun against Centrifugo.
…'t control

Spec links point at gocent's master branch, which outlives v4_dev. READMEs
leave out what users cannot change - the default pool's size and idle time -
and say who automatic batching is for and to set max_in_flight at about half
the calls a process makes at once.
…esting docs

- Fields the protos mark plainly "Required." are required named arguments.
- Command implements JsonSerializable: json_encode gives payload as an object.
- Results and broadcast and batch results render with wire names under
  json_encode, errors as {code, message}; $result->failed is a property.
- SharedPoll::sign requires expiresAt: a time or Expiry::Never.
- A PSR-18 client's timeouts throw TimeoutException, its TLS certificate
  errors are not retryable; the timeout docs say its timeouts apply.
- A per-call timeout of 0 is refused.
- Token, key and shared poll argument errors are CentException subclasses.
- broadcastWithRetry's whole-failure exception carries the idempotency key.
- API.md's exception tree follows the classes.
- handle() takes framework header arrays.
- README: Testing with broadcast and batch reply shapes, Pending::resolved;
  hooks must not throw; proxy code ranges; null-payload hint; fixed examples.
device_list without a filter lists all devices, so its filter is no longer
marked "Required." (centrifugo#1298, applied to the proto copy ahead of the
next release). The proto now also says that an empty user_topic_update user
updates the global binding, and that empty device_update values clear the
field.

The fields made required are listed in gen/required_fields.txt: generation
fails when the protos list others, since a newly required field breaks every
call without it. --accept-required records a reviewed change.
…ult.profile

api.proto and proxy.proto from Centrifugo's master, e21aeb50: the
"One of:" sentences of centrifugal/centrifugo#1308 and #1309, the
expire_at comment of #1310, and ConnectResult's profile. Not in a
release tag yet: sync them from the tag before releasing.

The required fields are unchanged: "Required when the request sets
limit_strategy." is conditional.
The redirect hint says Centrifugo's API never redirects a call: check
apiEndpoint's scheme and path. The commands' docs say a consumer reads
the payload as the request itself where the method goes apart - a
string of it is dropped - and only a whole-command message may hold it
as a string. The proxy handlers' docs say what Centrifugo makes of a
response with none of result, error and disconnect, per proxy type.

The idempotency docs already name the brokers keeping keys as spec 0.3
does.
…3, 2)

device_update's userUpdate, timezoneUpdate, localeUpdate and metaUpdate
are sent whenever set, even empty - as {}, which detaches the devices
from their user or clears the setting - and not sent when null. Before,
an empty one was left out like any other empty message, so detaching a
device or clearing its timezone could not be written. Their PHP types
do not change: they were nullable objects already.

gen/Rules.php reads the comments: a message named *Value whose one field
is value, or one whose only field's empty value has a meaning after
"Required.". The scalar ones, BoolValue and Int32Value, stay nullable
scalars; the generation fails when the comments and WRAPPERS disagree.
GeneratorTest pins the wrappers and the required fields whose empty
value has a meaning, in both protos. Every other message set but empty
is still not sent: an empty limitStrategy is no limit strategy.
A named argument without a default makes a call pass the field, not give
it a value: channel: '' or version: 0 went out as the field left unset,
which Centrifugo refused with code 107. Every request now gets a
generated checkRequired from the "Required." marks, called before
sending - from a call, a batch and a command - which throws
InvalidRequestException naming the field's path, nested ones included:
"invalid send_push_notification request:
limit_strategy.rate_limit.policies[1].rate is required".

"Required unless ..." and "Required when ..." are conditional and not
checked, and neither is a field whose empty value has a meaning, such as
invalidateUserTokens's user. An optional nested message is checked only
when set and not empty; a required one must be set and not empty; a
list's elements are checked each. The hand-written checks of publish's
channel and broadcast's channels give way to the generated ones, with
the same messages; the data rules stay. The checks are gocent's, which
were compared with Centrifugo PRO's own validation.

The nested messages take their required fields as constructor arguments
without a default too, first: new RateLimitPolicy(rate: ..., intervalMs:
...), new DeviceUserUpdate(user: ''). gen/required_fields.txt lists them.

The every-method tests fill every field of their requests, nested ones
included, so that the checks let them through.
The protos list such values in one sentence, "One of: add, remove,
set."; the generator reads it and writes a final class of constants per
field: Provider::FCM, Platform::IOS, Op::ADD, Status::DELIVERED,
KeyMode::IF_NEW, Cmp::EQ, and in the proxy namespace Encoding::BINARY,
Protocol::JSON, Allow::SUB, Type::OCCUPIED and the rest. Fields of one
name listing different values in different messages are told apart by
the message: the API's FilterNodeOp::AND, while the proxy's FilterNode op
is Proxy\Op::AND, as no other proxy field is named op. A class name PHP
reserves is named by its message too: ChannelsCapabilityMatch, as match
is a keyword. A malformed sentence fails the generation, and so does a
class name taken in its namespace.

The fields stay strings, never enums, so a value Centrifugo accepts
which phpcent does not name can still be sent. The fields' docs name
their constants.

GeneratorTest: the parser, the naming rule, a tie, a reserved name, every
listed value a constant, a value without one sent.
Only PHP null leaves a payload field unset: RawJson('null') passes the
required-field check and is sent as null (spec 0.3, 3.4).
historyAll, deviceListAll, deviceTopicListAll, userTopicListAll and
mapReadStateAll take the method's named arguments and return a Generator
of every item of every page, a page read when the iteration reaches it:
by cursor, or for history by since from the last publication. Leaving
the loop early reads no further page; an exception of a page ends the
iteration after the items before it. Keys run on across pages, so
iterator_to_array keeps every item.

The methods are not generator functions themselves: the request is
checked when the method is called, before anything is sent - historyAll
refuses a limit below 1 and reverse there, and every iterator a missing
required field. mapReadStateAll reads every page after the first at the
first page's revision, as revisionOffset and revisionEpoch, unless the
call sets them, so that a map state reset between pages throws
UnrecoverablePositionException instead of mixing two states. The loops
are written by hand in Internal\Pages, once over the cursor and once for
history; the methods are generated with the fields of their requests.

position() on every result holding a stream position - publish's,
history's, map_read_state's, map_read_stream's, map_publish's and
map_remove's - gives the StreamPosition to read on from. It is a method,
not part of a result's JSON.
ConnectionClaims's profile sets the Centrifugo PRO dictionary
compression profile of the connection, overriding the one the client
declared. It is written after labels, as spec 15.1 orders it; the
vectors do not change, as it is not in them.
Against Centrifugo: history read page by page from a publication's
position, a stale epoch failing with code 112; a map's state page by
page, a stale revision failing with 112. Against Centrifugo PRO: pushes
with a rate limit and with a time limit, each setting exactly what the
API requires, so that a check stricter than Centrifugo's fails; a device
detached by an empty user update and a timezone cleared by an empty one;
devices read page by page; the new constants. Pushes with a rate limit
need distributed_rate_limit, now enabled in the compose file with Redis
from the engine, with no API rate limits configured.
The README says phpcent implements spec 0.3, and shows the required
fields' checks, the presence wrappers, the constants, the iterators and
positions. The CHANGELOG names the user-visible changes, those which
break code first, and that the protos come from Centrifugo's master and
must be synced from a release tag before releasing. AGENTS.md lists
Rules.php and the choices 0.3 brought.
Renamed from Endpoints\Unauthorized, which read like the API client's
UnauthorizedException - Centrifugo refusing phpcent's credentials - with
the opposite meaning. Client SDKs report the 403 as their
UnauthorizedError, which the docs now say.
gen/constants_api.txt and gen/constants_proxy.txt hold the names spec
0.3 section 3.3 pins for every SDK, as gocent's lists do. The generator
fails on a field with a "One of:" sentence the list lacks, a pin no
field uses, one name over different values, and a name PHP reserves, so
a name never changes because an unrelated message appeared.

The proxy's names follow the table: Proxy\FilterNodeOp, as in the API,
replaces Proxy\Op; Proxy\CapabilityMatch replaces
ChannelsCapabilityMatch; Proxy\ChannelEventType replaces Proxy\Type. The
count-based naming and its tests are gone; the tests check the pins.
historyAll yields HistoryItems: the publication and its stream's epoch,
with position(), so that a caller who stops can resume, or give a client
its recoverSince, with no fields copied. mapReadStateAll yields
MapStateItems: the entry and state, the position the state was read at -
the first page's, or the revision the call asked for - which
mapReadStream follows it from (spec 0.3, 3.8). The other iterators yield
their items as they are.
… it (spec 0.3, 3.2, 7.3)

phpcent already worked so - PHP has no deadline a call runs under, no
context or cancellation, to shorten it - and the docs now say it: a
call's timeout replaces requestTimeout, longer or shorter; a broadcast
retry's attemptTimeout is each attempt's own timeout, replacing
requestTimeout, the call's timeout still ending it sooner. CurlTest
shows each against a server answering after 0.6 s. The transport is
unchanged.
PSR-18 has no way to give a request a deadline, so with a caller's client
the call's timeout did not apply: only the client's own timeouts did. Guzzle
and Symfony's Psr18Client now get it through their own API - Guzzle's
timeout request option, Symfony's max_duration - detected with instanceof,
so neither is a dependency. The caller's client is never changed: Symfony's
withOptions returns a new client, and Guzzle's send() gets the options its
sendRequest() sets itself. Any other PSR-18 client keeps its own timeouts,
as the docs say. Both libraries are dev dependencies, for
tests/Psr18ClientsTest.php against a real server.
…ctionException (spec 0.3, 3.1, 4.1)

An endpoint from apiEndpointFunc failing apiEndpoint's rules, or an empty
or malformed token from bearerTokenFunc, fails the call with
InvalidConfigException before sending, as before; a value which is not a
string does too now. An exception the function throws itself fails the
call as a FunctionException - the kind FunctionError of spec 4.1 - whose
$function names the function, whose message starts with it -
"bearerTokenFunc: RuntimeException: ..." - and whose previous exception
is the function's: it used to propagate as it was. Retry::retryable
judges it by the function's exception; InvalidConfigException is not
retryable.

requestTimeout, a call's timeout and attemptTimeout refuse zero, as a
negative: unset is the default, and zero is not "no timeout" (spec 3.1).
phpcent already refused them; the tests now cover 0 and 0.0 for each,
and the docs say it.

The docs of InvalidConfigException, the options, Retry::retryable and
the README's errors table say it.
…3, 7.1)

The result broadcastWithRetry gives onAttemptError after an attempt
which failed as a whole lists every channel in failed, each with that
error, and replied false. phpcent already did so; a direct broadcast or a
batch failing as a whole throws its own exception, without a result, as
spec 7.1 says for languages with exceptions.
…3, 3.2, 3.8)

A per-call timeout bounds a whole call, and an iteration lasts as long as
the caller's loop, so historyAll and the other <method>All iterators no
longer take timeout. pageTimeout bounds each page's request instead,
replacing requestTimeout for it, as attemptTimeout does for an attempt;
without it each page gets requestTimeout. Zero or less is refused with
InvalidRequestException at the call, before anything is sent.
The source of Centrifugo PRO server API tokens a client's
bearerTokenFunc calls is named as spec 0.3 names it, ApiTokenSource;
Token::api, which signs one, keeps its name. phpcent 7 is unreleased, so
no shipped name changes.
php -S serves one request at a time and goes on with a request whose
client timed out. The slowheaders and trickle tests, for Guzzle and
Symfony, left it about 10 s of work, so the next test's request - bigerror
for Guzzle - waited behind it past its 10 s timeout on macOS CI runners,
failing every run there. Those two tests now run on a server of their own,
stopped after each, which ends the slow request.
Symfony's HTTP client 7.3.0 ends a body at max_duration without an error,
so a call whose deadline passed while the reply trickled in read a cut
reply, and failed as one which is not JSON. A body which ended once the
call's time ran out is now a TimeoutException. Found by the lowest-deps
CI job once the trickling-body test ran on a server of its own, its
deadline landing mid-body as meant.
CHANGELOG.md's v7.0.0 entry reads as release notes, grouped, with
absolute links: every user-visible feature as the code now has it,
nothing of the spec 0.3 delta or stale names left. The note that the
protos come from Centrifugo's master moves to AGENTS.md, under
Releasing. MIGRATING.md adds what a phpcent 6 user notices beyond the
API: arguments which were arrays are now classes, every call has a
10-second default timeout and zero is refused, requests are checked
before sending, and the reference table's rows for subscribe, history,
disconnect and channels.
AGENTS.md describes the package for development: the note about syncing
the protos before this release was a step of one release, not a property
of the package. The durable release procedure stays.
The protos are Centrifugo master's at e21aeb50, after v6.10.2, as spec 0.3
section 2 now allows for a release needing changes no tag has yet: the
release notes name the commit and what it adds. AGENTS.md states the rule
instead of "always a released tag".
@FZambia
FZambia merged commit 1eabc96 into master Nov 5, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for http-client

1 participant