webpatser/resonate-upstream v0.1.0. A Resonate server plugin that subscribes to external sockets (Socket.IO v4 or a plain websocket) and passes every message to a Resonate channel, to your Laravel application through the queue, or both.
What you get
- One long-lived connection per configured source, held by the Resonate server process, with reconnects and a backoff from 5 to 20 seconds that only starts over once a connection has lasted 30 seconds.
- Two outlets per source, each on or off:
- publish: broadcast the message on a Resonate channel, straight from the server process.
- dispatch: queue a job that fires
UpstreamMessageReceivedin a queue worker, where your ordinary listeners handle it.
UpstreamConnectedafter every (re)connect, and once more after the dispatch outlet lost messages, so the application can run a full sync.UpstreamStatus::alive(), a heartbeat the application can read to fall back on polling while the socket is down.- One connection per source across a
resonate:reload. resonate-upstream:listen, which runs the same driver outside Resonate and prints what arrives.
Limits of v0.1
- No replay. A message sent while a source is disconnected, or dropped by a full outlet buffer, is gone. React to
UpstreamConnectedwith a full sync over the upstream's HTTP API. - One node. Ownership is coordinated through the cache, which covers a reload on one server. Several Resonate nodes behind a load balancer are not coordinated.
- Two protocols. Socket.IO v4 (Engine.IO 4, websocket transport only, text frames, default namespace) and plain websocket text frames. No long-polling, no binary frames, no namespaces or acks.
- No room in the message. Socket.IO does not tell a client which room an event came from. Route on the payload.
Install
composer require webpatser/resonate-upstreamphp artisan vendor:publish --tag=resonate-upstream-config
Register the plugin in config/reverb.php:
'servers' => [ 'reverb' => [ // ... 'plugins' => [ \Webpatser\ResonateUpstream\UpstreamPlugin::class, ], ],],
Restart Resonate (resonate:reload for a zero-downtime swap). The plugin does nothing until config/resonate-upstream.php defines a source. Requirements: PHP 8.6+, Laravel 13, Resonate 1.4+.
Configure a source
// config/resonate-upstream.php'sources' => [ 'prices' => [ 'driver' => 'socketio', 'url' => 'https://stream.example.com', 'headers' => ['User-Agent' => 'example-app (+https://example.com)'], 'rooms' => ['ticker'], 'room_resolver' => null, 'events' => ['price'], 'publish' => ['channel' => 'private-upstream.prices', 'event' => 'upstream.message'], 'dispatch' => true, 'queue' => ['connection' => 'redis', 'name' => 'upstream'], 'reconnect' => ['min' => 5, 'max' => 20, 'reset_after' => 30, 'refused' => 600], ],],
Always send a User-Agent that identifies you. Without one, the websocket client identifies itself as fledge-fiber/http-client.
Shared keys
| Key | Default | Purpose |
|---|---|---|
cache.store |
RESONATE_UPSTREAM_CACHE_STORE, else the default store |
Cache store holding ownership and heartbeat. Must be fiber-safe in the Resonate process and shared with the processes that call UpstreamStatus::alive(). |
cache.prefix |
RESONATE_UPSTREAM_CACHE_PREFIX, else resonate-upstream |
Key prefix. One record per source at {prefix}:{source}:owner. |
log_channel |
RESONATE_UPSTREAM_LOG_CHANNEL, else null |
Log channel of the server plugin. Null is the default channel. |
ownership.interval |
5.0 |
Seconds between ownership checks, spread by 10 percent either way. |
heartbeat.ttl |
40 |
Seconds a lease and heartbeat stay valid without renewal. Raised to at least 2 * ownership.interval + 1. |
rooms.interval |
30.0 |
Seconds between room resolver refreshes. |
sources |
[] |
The sources, keyed by a name of your choosing. |
Keys per source
| Key | Default | Purpose |
|---|---|---|
driver |
socketio |
socketio or websocket. |
url |
required | Socket.IO: the server address (https://host). A path on it replaces the engine path /socket.io/ and is not a namespace. Websocket: the full ws:// or wss:// url. |
headers |
[] |
Request headers sent with every connect. |
rooms |
[] |
Socket.IO rooms joined after every handshake with emit('join', room). |
room_resolver |
null |
Class implementing RoomResolver that supplies additional rooms. |
events |
[] |
Socket.IO event names passed on. Empty passes every event. |
publish |
null |
['channel' => ..., 'event' => 'upstream.message', 'app' => null], or null to switch the outlet off. app is the Resonate app id, null for the only configured app. |
dispatch |
true |
Whether the dispatch outlet queues events. |
queue.connection |
null |
Queue connection for the dispatch outlet. Null is queue.default. |
queue.name |
null |
Queue for the dispatch outlet. Null is the connection's default queue. |
reconnect.min, reconnect.max |
5, 20 |
Backoff bounds in seconds. The delay doubles per failed attempt. |
reconnect.reset_after |
30 |
Seconds a connection must stay up before the backoff starts over. |
reconnect.refused |
600 |
Seconds to wait after the upstream answers the upgrade with a 4xx other than 408 and 429, and after five handshaken connections in a row that ended quickly. |
connect_timeout |
15 |
Seconds for TCP, TLS and the websocket upgrade together. |
idle_timeout |
null |
Websocket only: close and reconnect after this many silent seconds. |
ping_interval |
10 |
Websocket only: seconds of silence before a ping. The connection closes after three unanswered pings. null turns pings off. A websocket source with both ping_interval and idle_timeout null is refused. |
buffer |
1000 |
Messages each outlet holds while busy. When full, the oldest is dropped. A waiting UpstreamConnected is never dropped. |
outlet_timeout |
5 |
Seconds one broadcast or queue push may take. |
A source that fails validation is disabled with an error in the log that names it. The other sources and the server keep running.
The publish outlet
Each message is broadcast from the server process on the configured channel:
{"source": "prices", "event": "price", "payload": {"symbol": "ACME", "price": 12.5}, "arguments": [{"symbol": "ACME", "price": 12.5}], "received_at": "2026-11-23T14:06:17.402+01:00"}
Use a private- channel. Nobody can subscribe until routes/channels.php authorizes it:
Broadcast::channel('upstream.prices', fn (User $user): bool => $user->can('view-prices'));
The dispatch outlet
The plugin queues a DispatchUpstreamMessage job. In the worker it fires UpstreamMessageReceived:
| Property | Type | Content |
|---|---|---|
source |
string |
The source name. |
event |
string |
The Socket.IO event name, or message for a plain websocket. |
payload |
mixed |
See Payloads below. |
arguments |
list<mixed> |
The arguments exactly as they arrived. |
receivedAt |
CarbonImmutable |
When the Resonate server read the message. |
use Webpatser\ResonateUpstream\Events\UpstreamMessageReceived; final class UpdatePrice{ public function handle(UpstreamMessageReceived $message): void { if ($message->source !== 'prices' || ! is_array($message->payload)) { return; } Price::query()->updateOrCreate( ['symbol' => $message->payload['symbol']], ['price' => $message->payload['price'], 'seen_at' => $message->receivedAt], ); }}
UpstreamConnected takes the same route after every connect and reconnect, and after the dispatch outlet lost messages. Anything sent while the connection was down is gone, so fetch the current state here:
use Webpatser\ResonateUpstream\Events\UpstreamConnected; final class ResyncPrices{ public function handle(UpstreamConnected $connected): void { if ($connected->source === 'prices') { SyncAllPrices::dispatch(); } }}
Its reason is UpstreamConnected::CONNECTED after a (re)connect and UpstreamConnected::RECOVERED after lost messages. isRecovery() tells the second apart.
Note: If the queue connection uses the
sync,deferredorbackgrounddriver, or afailoverconnection that falls back on one of them, the dispatch outlet of that source stays off and an error is logged. The push happens inside the Resonate process, so the queue driver must not block.
Payloads
| Driver | event |
arguments |
payload |
|---|---|---|---|
socketio |
The event name | Every argument after the event name, decoded, in order. | The only argument when there is exactly one, otherwise the same list as arguments. |
websocket |
message |
[$payload] |
The frame decoded as JSON. A frame that is not JSON becomes ['raw' => $frame]. |
payload loses information: 42["e",[1,2]] and 42["e",1,2] both have payload [1,2]. Read arguments when the difference matters.
Falling back on polling
The owning process renews its heartbeat every ownership.interval seconds and marks it connected only while the connection is up and the main outlet (dispatch, else publish) delivers.
use Webpatser\ResonateUpstream\UpstreamStatus; $interval = UpstreamStatus::alive('prices') ? 60 : 5;
alive() returns false when the cache cannot be read. app(UpstreamStatus::class)->lastBeat('prices') returns the time of the last renewal. The heartbeat carries the Resonate host's clock, so keep both hosts in sync with NTP.
Dynamic rooms
For rooms that change while the server runs, implement RoomResolver and name the class in room_resolver:
use Webpatser\ResonateUpstream\Contracts\RoomResolver; final class ActiveMarkets implements RoomResolver{ public function rooms(string $source): array { return Cache::get("markets:open:{$source}", []); }}
The plugin asks the resolver when the source connects and every rooms.interval seconds, then joins and leaves the difference. The resolver runs inside the Resonate server, so it must be fiber-safe and quick. Read a fiber-safe cache key that another process keeps up to date. Never query a database or call a slow HTTP API from it.
Debug a source
php artisan resonate-upstream:listen prices --dump
This runs the configured driver outside Resonate and prints each message as one line of JSON. It writes nothing to the cache or the queue and publishes nothing. It opens a second connection next to the one the server holds.
| Option | Purpose |
|---|---|
--rooms=a,b |
Socket.IO rooms to join on top of the configured ones. |
--duration=60 |
Stop after this many seconds. |
Testing
UpstreamStatus::fake() swaps the heartbeat for fixed answers. A source that is not listed is not alive:
use Webpatser\ResonateUpstream\UpstreamStatus; $status = UpstreamStatus::fake(['prices' => true]);// ... assert the application does not poll ...$status->set('prices', false);// ... assert it polls again ...
To run the plugin without a network, bind the fake factory to Contracts\ConnectorFactory:
use Webpatser\ResonateUpstream\Contracts\ConnectorFactory;use Webpatser\ResonateUpstream\Testing\FakeConnector;use Webpatser\ResonateUpstream\Testing\FakeConnectorFactory;use Webpatser\ResonateUpstream\Testing\FakeTransport; $transport = FakeTransport::withHandshake()->push('42["price",{"symbol":"ACME","price":12.5}]'); $this->app->instance(ConnectorFactory::class, new FakeConnectorFactory([ 'prices' => new FakeConnector($transport),]));
Reloads
Resonate has no shutdown hook for plugins, so ownership of each source is a lease in the cache. Processes are ranked by boot time, and a newer process takes over once it reports connected. During a normal reload both processes are connected for up to about 8 seconds with the defaults, so a message in that window can reach the outlets twice. If the new process cannot connect, the old one keeps its connection. If the cache is unreachable, the current connection stays up.