Search by

webpatser / resonate-webhooks

webpatser

Pusher-style HTTP webhooks for Resonate: channel occupancy and presence events delivered to your backend

Package info

github.com/webpatser/resonate-webhooks

pkg:composer/webpatser/resonate-webhooks

Statistics

Installs: 27

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

v1.1.0 2026-11-18 14:27 UTC

This package is auto-updated.

Last update: 2026-11-18 14:35:46 UTC


README

Pusher-style HTTP webhooks for Resonate. It POSTs channel_occupied, channel_vacated, member_added, member_removed, and client_event to your backend, so your application reacts to channel activity without polling the socket server.

The problem it solves

Reverb fires Pusher webhooks; Resonate fires none. A backend that needs to know "this room just emptied", "a user joined", or "someone whispered a client event" has no push signal, so it polls or stands up its own metrics round-trip.

Two things make naive webhooks wrong on a scaled cluster:

  1. Occupancy is per node. Resonate's ChannelCreated/ChannelRemoved events fire on each node independently. Firing channel_occupied from them double-sends it when a channel has subscribers on two nodes, and fires channel_vacated from one node while another still holds subscribers.
  2. Presence is per node. The same user can be present on two nodes; a node firing member_removed for its own last connection is wrong if the user is still on another node.

This package fixes both by reading occupancy from webpatser/resonate-roster, which keeps a cluster-wide, self-healing membership count, and claiming each edge once per cluster, with member_added delivered at least once.

How it works

Edges, not state

The roster answers "how many connections does channel C have" and "which users are in C", cluster-wide. A webhook is an edge: the transition into or out of those states. The plugin derives edges like this:

  • On a subscribe, it reads the cluster connection count from the roster, for that connection's own application. The transition into the first connection is claimed with an atomic Redis flag (SET NX); the one node that wins the flag emits channel_occupied.
  • On an unsubscribe or close that leaves the cluster count at zero, one node wins the flag delete and emits channel_vacated.
  • member_added and member_removed use the same claim, keyed per user, driven by whether the user still appears in the roster.
  • A reconcile tick re-checks every tracked channel against the roster, so an edge missed during a crash is recovered and flag TTLs are refreshed.

Because the flag is the arbiter, each channel and presence edge is claimed once per cluster even when several nodes see the transition at the same instant.

One caveat on member events: each reconcile tick refreshes the TTL only on member flags that still exist, so a refresh never creates a flag. A flag that is missing goes through the same member_added claim against a fresh roster read. A member who is still present gets the flag back and a member_added webhook, so after a lapse your backend may receive a duplicate member_added for that user but never loses one; treat member_added as idempotent. A member who already left (their flag was deleted by member_removed) stays unflagged and gets no event.

Every read and every flag is scoped to one application, so two applications that both serve a presence-lobby get their own edges: the second one to fill up still emits its own channel_occupied, and the first one emptying does not vacate the second.

Delivery, off the connection path

connection fiber                    background tick (every flush_interval)
────────────────                    ─────────────────────────────────────
onSubscribe / onUnsubscribe          coalesce buffered events per endpoint
onClose / onMessage                  build one signed Pusher-format POST
  -> derive edge from the roster     deliver via fledge async HTTP client
  -> buffer a WebhookEvent           retry with exponential backoff

Connection hooks only buffer events; they never make HTTP calls. A delivery tick coalesces the buffer into one POST per endpoint and sends each in a detached fiber, so a slow endpoint never stalls the event loop. A failed delivery is retried with exponential backoff and dropped after max_attempts. Delivery is in-process: undelivered webhooks are lost if the server process crashes.

Plugin ordering

RedisRosterPlugin must be listed before WebhookPlugin in config/reverb.php. Resonate runs plugin hooks sequentially in array order within one fiber, so the roster's Redis writes land before this plugin reads the cluster count.

Installation

composer require webpatser/resonate-webhooks

This pulls in webpatser/resonate-roster. Publish both configs if you want to change defaults:

php artisan vendor:publish --tag=resonate-roster-config
php artisan vendor:publish --tag=resonate-webhooks-config

Configuration

1. Let the roster track all channels

Webhooks need occupancy for every channel type, not just presence channels. Set the roster's track mode to all:

RESONATE_ROSTER_TRACK=all

2. Register both plugins, roster first

// config/reverb.php
'servers' => [
    'reverb' => [
        // ...
        'plugins' => [
            \Webpatser\ResonateRoster\RedisRosterPlugin::class,   // first
            \Webpatser\ResonateWebhooks\WebhookPlugin::class,      // second
        ],
    ],
],

3. Declare your endpoints

// config/resonate-webhooks.php
'endpoints' => [
    [
        'url'    => env('RESONATE_WEBHOOK_URL'),
        'app_id' => '*', // or a specific application id
        'events' => [
            'channel_occupied', 'channel_vacated',
            'member_added', 'member_removed', 'client_event',
        ],
    ],
],

Restart Resonate (php artisan resonate:start, or resonate:reload for a zero-downtime swap).

The webhook request

Each delivery is a Pusher-format POST, signed so the receiver can verify it:

POST {endpoint.url}
Content-Type: application/json
X-Pusher-Key: {app key}
X-Pusher-Signature: hmac_sha256(rawBody, app secret)

{"time_ms": 1700000000000, "events": [
  {"name": "channel_occupied", "channel": "presence-chat.42"},
  {"name": "member_added",     "channel": "presence-chat.42", "user_id": "7"},
  {"name": "client_event",     "channel": "presence-chat.42", "event": "client-typing",
   "data": "{...}", "socket_id": "...", "user_id": "7"}
]}

The key and secret come from the matching app in reverb.apps, so a Pusher webhook consumer verifies it with no changes. Verify the signature before trusting the body:

$expected = hash_hmac('sha256', $request->getContent(), config('reverb.apps.apps.0.secret'));

abort_unless(hash_equals($expected, $request->header('X-Pusher-Signature')), 403);

Configuration reference

Key Default Purpose
connection REDIS_* env Redis server. Must be the same server and database as resonate-roster. Takes Laravel's connection keys, scheme (tcp, tls/rediss, unix), read_timeout and the retry keys included.
key_prefix wh Namespace for the edge-detection flag keys, which are {prefix}:{kind}:{appId}:{channel}.
ttl 90 Flag-key TTL in seconds, so a dead node's flag self-heals. The reconcile pass keeps flags alive, so the TTL must exceed reconcile_interval; a value below twice reconcile_interval is raised to twice reconcile_interval.
flush_interval 1.0 Seconds between delivery ticks; events in that window are coalesced.
reconcile_interval 30.0 Seconds between occupancy reconcile ticks.
ignore_channel_prefixes ['#'] Channel prefixes never reported on. The protocol reserves # for channels the server owns, such as the #server-to-user-{id} channels webpatser/resonate-users creates, which are a user's session rather than a room.
max_attempts 5 Delivery attempts before a webhook is dropped.
endpoints [] The endpoints that receive webhooks.

Limits

Four bounds keep a slow or unreachable endpoint from growing memory without limit. Set any of them to 0 to restore the old unbounded behaviour.

Key Env variable Default Meaning
max_buffered_events RESONATE_WEBHOOKS_MAX_BUFFERED_EVENTS 10000 Events held between delivery ticks.
max_pending_deliveries RESONATE_WEBHOOKS_MAX_PENDING 1000 Built deliveries awaiting or retrying.
max_request_bytes RESONATE_WEBHOOKS_MAX_REQUEST_BYTES 1048576 Largest encoded size of the events in one request. A bigger batch is split into several signed POSTs, sent to an endpoint one after the other in order; they can share one time_ms.
max_in_flight_per_endpoint RESONATE_WEBHOOKS_MAX_IN_FLIGHT 16 Concurrent POSTs to one endpoint URL. The rest wait for a later delivery tick.

When the event buffer is full, room is made in this order:

  1. A buffered occupied/vacated pair for one channel, or member added/removed pair for one member, is cancelled. The receiver loses nothing it needs.
  2. The oldest client_event is dropped.
  3. The oldest event is dropped.

When an occupancy or membership edge is dropped, a warning is logged saying receivers need a resync.

When the pending list is full, the oldest delivery that is not in flight is dropped and WebhookDropped fires. If all are in flight, the new delivery is dropped instead. A delivery waiting for an in-flight slot or for its previous chunk can be dropped with 0 attempts. A dropped delivery may contain occupancy edges, so receivers that track occupancy should resync when they see drops.

Redirects are not followed: a 3xx response counts as a failed delivery. Point the webhook URL at the final address.

Notes and caveats

  • Same Redis as the roster. The plugin reads roster keys and writes its flag keys on one connection; it must point at the same server and database as resonate-roster.
  • Roster track must be all. In the default presence mode the roster does not mirror public or private channels, so channel_occupied/channel_vacated would not fire for them.
  • In-process delivery. Retries are bounded; a webhook is lost if the server crashes before delivery. The roster remains queryable as the source of truth.
  • Exactly-once per cluster. Edges are claimed atomically, so a scaled deployment does not double-send.
  • Per application. Occupancy is read and claimed per application, so a channel name shared by two applications produces two independent sets of edges.
  • Upgrade with the roster. This version reads only the roster's app-scoped keys and requires roster 1.0. Coming from a roster older than 0.3.0, upgrade both packages through 0.7.x first; see UPGRADE.md.
  • Not Redis Cluster safe. Occupancy is read with SCAN over the roster's keys, which on Redis Cluster only walks one node. Use a single Redis server.

Requirements

  • PHP 8.5+
  • Resonate 1.0+
  • webpatser/resonate-roster 1.0+, configured with track => all
  • A Redis server reachable from the Resonate process

Testing

composer test

Tests that touch Redis expect a server on 127.0.0.1:6379 and use database 15; they skip cleanly when no Redis is reachable.

License

MIT. See LICENSE.