Repository navigation
Bound the MQTT revoke wait and fail closed on verification timeout - #15085
Conversation
expel() disconnects a user's connections and drop() removes a live subscription without re-checking against the database: the paths the broker takes when a revoke or unsubscribe verification cannot complete. revoke() and unsubscribe() now touch only connections still tracked, so a check that finishes after the fail-closed path already acted never tears down a connection reusing the same fd. Co-Authored-By: Claude Fable 5 <[email protected]>
The 'mqtt' pub/sub subscriber waited forever on the revoke child coroutine, so a verification stuck on a half-open database read parked the subscriber: no deliveries, no revokes, no recovery. The wait is now bounded by _APP_MQTT_PERMISSION_TIMEOUT (default 5s); past it the broker fails closed — the user's connections are closed unverified and CONNECT re-authenticates them on reconnect. The unsubscribe membership re-check reads the same database inline, so it gets the same child coroutine and bound, dropping the subscription unverified on timeout. The dispatcher moves to app/init/mqtt/subscriber.php so the regression test can drive it: a revoke whose check never returns must not starve a following delivery. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Review complete. No blocking issues — approved ✅; 1 nitpick below. 🧹 Nitpicks (1) — 🟢 1 low
The change extracts the MQTT event subscriber into a reusable bootstrap file and adds a bounded, coroutine-isolated permission check that expels or drops connections when verification does not complete within a configurable timeout. Unit tests cover revocation, unsubscribe, and subscriber behavior using process-isolated Swoole runs with fakes.
Reviewed commit: 10c87b2 |
🟢 Tier S · Ready to mergeThis pull request routes MQTT pub/sub events through a dedicated handler and bounds revoke and unsubscribe verification, failing closed when checks time out or cannot start. It adds broker-side connection and subscription cleanup guards, structured event spans, and coverage for stalled, normal, saturated, late-completion, and callback-error paths. It also updates MQTT configuration documentation and the CI path map. Latest changes: The newest commits align MQTT database handles and the verification wait with the API database timeout, and catch unexpected event callback exceptions so they are recorded without escaping into phpredis.
📂 Walkthrough · 12
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
When go() could not start a child, revoke and unsubscribe ran their database check inline, so a half-open read could still park the subscriber. At the limit the broker now expels or drops unverified, as on timeout, and logs one error. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply the same tracked() check revoke() and unsubscribe() use, so the fail-closed paths only touch connections still in the index. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Reply to the tenki-reviewer nitpick:
Applied in 6c263d2. |
| @@ -0,0 +1,154 @@ | |||
| <?php | |||
There was a problem hiding this comment.
we should have it as a class Subscriber if required in the src/Appwrite/Mqtt along side the Handler.php cause that makes more sense.
There was a problem hiding this comment.
Done in afb177a. The dispatcher is now Appwrite\Mqtt\Subscriber in src/Appwrite/Mqtt/Subscriber.php, next to Handler. It is the broker's subscriber to the internal mqtt pub/sub channel. The constructor takes Server, Handler, Mqtt and the $timeout, and the public receive($redis, $channel, $payload) method is the phpredis callback, so app/mqtt.php passes $subscriber->receive(...) to subscribe(). The private revoke(), unsubscribe() and deliver() methods keep the same logic: bounded wait, fail-closed expel()/drop(), coroutine-limit fail-closed, spans and logs. app/init/mqtt/subscriber.php is deleted, and SubscriberTest now constructs the class directly with its assertions unchanged (90 tests pass).
There was a problem hiding this comment.
Renamed in f6a2591. The class is now Appwrite\Mqtt\Event\Handler in src/Appwrite/Mqtt/Event/Handler.php. It imports the connection handler as Broker, and its entry method is handle(). app/mqtt.php passes $eventHandler->handle(...) to subscribe(). The test moved to tests/unit/Mqtt/Event/HandlerTest.php with its assertions unchanged (still 90 tests, 401 assertions). I also trimmed the comments this PR added, here and in Mqtt/Handler.php, to one line each; the fail-closed reasoning is in the PR body.
The broker's subscriber to the internal 'mqtt' pub/sub channel becomes a class beside Handler instead of a closure factory in app/init. Its receive() method is the phpredis callback; revoke, unsubscribe and deliver keep their logic unchanged, including the bounded wait and the fail-closed paths. SubscriberTest now constructs the class directly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
It handles the broker's internal events; "Subscriber" only described how it is wired in. The entry method is handle(), the connection handler is imported as Broker, and the test moves to tests/unit/Mqtt/Event/HandlerTest.php with its assertions unchanged. Comments added by this change are trimmed to one line each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
One mqtt.revoke / mqtt.unsubscribe span now covers the whole event, including the fail-closed paths, instead of a span only inside the child coroutine plus Console lines. The child sends its count or throwable back through the channel. The span carries project.id, user.id, mqtt.is_broker, mqtt.topic (unsubscribe), the count (mqtt.disconnected / mqtt.unsubscribed) and mqtt.verification: verified, timed_out, coroutine_limit or failed. Timed-out and coroutine-limit spans finish at error level; a thrown check is set as the span error. The Console logging for these paths is removed, and with nothing left writing to STDERR the MutedStderr fake goes too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Fail-closed outcomes are now recorded on spans instead of Each revoke and unsubscribe event gets one span ( Attributes:
|
A timed_out or coroutine_limit span set only the error level, so the span sampler's trace filters could drop it. It now carries a RuntimeException describing the failure (a check that could not complete is a genuine failure), which keeps it exported and sets the error level through finish(). mqtt.verification is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| }); | ||
|
|
||
| // An inline check could block on the same dead read. | ||
| $outcome = $started === false ? null : $result->pop($this->timeout); |
There was a problem hiding this comment.
this is solving the clog with the help of a timeout
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eout Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
fix(mqtt): never let an exception reach the subscribe loop; wait the API database timeout
Issue / Description
The MQTT broker's
mqttpub/sub subscriber dispatches every event of a worker — revokes, unsubscribes, deliveries — from one coroutine. A revoke runs its verification in a child coroutine, but the subscriber then waited on that child with no timeout. The verification reads the project database, and a read on a silently-dead (half-open) connection never returns and never errors, so one stuck check parked the subscriber forever: no deliveries, no revokes, no logs, no recovery. The realtime service was taken down by this exact mechanism; MQTT shared the gap. A sibling PR applies the same fix philosophy toapp/realtime.php.Tracking: appwrite-labs/cloud#7102
Solution
_APP_MQTT_PERMISSION_TIMEOUT(seconds, default 5, documented inapp/config/variables.php), read once at worker start.Handler::expel()disconnects the user's connections withNOT_AUTHORIZED— the same disconnect a verified revoke uses. Fail closed is safe here because clients reconnect and CONNECT re-authenticates them with fresh credentials, so a legitimate user is restored within one reconnect while an unverifiable one is excluded rather than left connected on unverified access.Handler::unsubscribe()re-checks membership against the same project database inline, so it gets the same treatment: a child coroutine, the same bounded wait, andHandler::drop()removing the subscription unverified on timeout (a user still subscribed can simply re-SUBSCRIBE).revoke()andunsubscribe()now mutate only connections still tracked as the same object, so a late check never closes a connection reusing the fd of oneexpel()removed.expel()/drop()) instead of running the check inline, where it could block on the same dead read.mqtt.revoke/mqtt.unsubscribe) that covers the whole event, fail-closed paths included, so production gets one structured, queryable line per event. Attributes:project.id,user.id,mqtt.is_broker,mqtt.topic(unsubscribe only),mqtt.verification(verified,timed_out,coroutine_limitorfailed) and the count (mqtt.disconnected/mqtt.unsubscribed).timed_outandcoroutine_limitspans carry aRuntimeExceptiondescribing the failure, so they are recorded at error level and the span sampler keeps them even with trace filters set. A check that threw is set as the span error. The child coroutine sends its count or exception back through the channel instead of opening its own span. There is no separateConsolelogging for these paths.app/mqtt.phpinto a new class,Appwrite\Mqtt\Event\Handler(src/Appwrite/Mqtt/Event/Handler.php). It handles the broker's internal events (revoke, unsubscribe and deliver) that arrive on themqttpub/sub channel. It takesServer, the connection handler (imported asBroker),Mqttand the timeout. Itshandle()method is the phpredis callbackapp/mqtt.phppasses tosubscribe(), and privaterevoke(),unsubscribe()anddeliver()methods hold the per-action logic. No change to the CONNECT authentication model or AUTH handling, and delivery logic is unchanged.Tests
tests/unit/Mqtt/Event/HandlerTest.php(a unit test ofAppwrite\Mqtt\Event\Handler, each test in its own process) reproduces the poisoning (red → green): an authorizer that parks on a channel nothing pushes — a faithful stand-in for a half-open TCP read — a revoke event for a user with tracked connections, then a delivery event, both through one subscriber coroutine. On the old code the delivery is never processed (verified failing, bounded, before the fix); on the fixed code the user is disconnectedNOT_AUTHORIZEDwithin the timeout, the delivery goes through, and when the stuck read finally returns the late check closes nothing twice. A second test pins the normal path: a fast check revokes exactly the unauthorized user and delivery continues; a third covers the stuck unsubscribe membership check (subscription dropped, connection kept, delivery unaffected, late check leaves the rest alone). Two more fill the coroutine table sogo()really fails and assert both paths fail closed without running a check. A recording span exporter checks that each of these paths records the rightmqtt.verification, count and level.tests/unit/Mqtt/RevokeTest.php/UnsubscribeTest.phpcoverexpel()anddrop()directly, plus the late-finish guards (an expel landing mid-check causes no double disconnect and no fd teardown).Run:
docker compose exec appwrite test tests/unit/Mqtt/Benchmarks
_APP_MQTT_PERMISSION_TIMEOUT(5s default) and delivery is unaffected; the full Mqtt unit suite (88 tests) runs in ~1s.🤖 Generated with Claude Code