The per-message fork child purged cache/redis manager singletons but never reset
the session bindings, and never actively disconnected the fds it inherited. Once an
app puts session + cache on Redis, the parent's authenticateConnection() opens Redis
sockets before forking; a child touching any un-reset connection interleaves on the
shared fd and desyncs the predis protocol on BOTH sides — flooding
"unserialize(): Error at offset 0 of N bytes" and
"Predis ConnectionException: Error while reading line from the server".
In the child, before purging: disconnect() every configured redis connection (closes
only the child's fd copy — predis disconnect fcloses without sending a command, so
the parent socket is untouched; any later reuse reconnects fresh instead of
desyncing), then also forgetInstance('session') + 'session.store' so a Redis-backed
session store rebuilds lazily too.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Read the shared platform:maintenance DB-cache flag at controll_message (after
auth resolves) and refuse every controller event for non-admins with
{message, maintenance:true}, so a host app can run a deploy / write-locking
migration without clients mutating state. Admins bypass to smoke-test. The key
is hardcoded to match App\Support\Maintenance::CACHE_KEY and dodge the
fork-child package-config-merge gap; cache reads are guarded so a hiccup can
never wedge the socket.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The deferred-message fork path (processDeferredMessages -> forkWithSocketPair)
never re-runs authenticateConnection, so the child inherited $connection->user
(passing the need_auth gate) but a cleared Auth guard — auth()->user() /
User::auth() returned null, crashing handlers that read the guard (learn-atc
GlitchTip #529/#532/#535/#531/#530). Sync the guard from the mock's user per
fork with Auth::setUser() (setUser, not login, to avoid re-firing the Login
event on every message).
Also guard SocketPairIpc::sendToParent with @socket_write: when the WS client
disconnects mid-response the parent tears down its read end, so the child's next
write races a closed pipe (EPIPE / "Broken pipe"). That benign warning was
promoted to a reported ErrorException and flooded GlitchTip (#461). Mirrors the
existing @fwrite in Broadcast/BroadcastClient.php.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A restarting daemon (deploy, supervisor, steer restart-hard) often finds
the predecessor's socket still bound for a few seconds after SIGTERM.
Crashing immediately turned every restart into an EADDRINUSE crash-loop
(146 GlitchTip events on learn-atc prod). Retry the bind for up to 30s
before giving up; a port still taken after that is a real conflict and
rethrows.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The fork-per-message model spawns a child per inbound message; each child
exit(0)s when done. The only reaper was a single, non-looping
pcntl_waitpid(-1, WNOHANG) inside the IPC onClose callback — which fires on
socket EOF, an event that routinely precedes the child's actual process exit,
so it frequently reaped nothing and left <defunct> zombies parented to the
live serve process (where no PID 1 init can reach them). Under sustained
traffic these accumulated until pcntl_fork() itself failed.
- Handler::onClose now drains ALL exited children in a loop (was a single
wait). activeChildCount bookkeeping stays per-socket, untouched.
- StartServer adds a SIGCHLD handler + a 10s periodic backstop (catches
children that crashed before IPC setup, so no onClose fires) + a
drain-on-shutdown so a deploy restart does not hand orphans to PID 1.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- AGENTS.md: canonical agent/contributor reference — #[Websocket] attribute vs native
Websocket\Controller, the :progress/:response/:error wire protocol,
progress/success/error/broadcast/whisper, ws_broadcast/ws_whisper/wsSession globals,
the fork-per-message execution model, auth()->user() over the bridge, defer() vs Jobs,
resolver cache/restart, and a footgun checklist with a source map.
- README + docs/advanced-usage/helpers-and-testing: replace the fictional
wsSession('channel', [...]) "auth payload" example — wsSession() takes no arguments and
returns a per-connection store — and fix WebsocketService::getAuth($socketId) signature.
- docs/getting-started/installation: beyondcode -> blax-software composer require.
Optional parameter $payload (and $event) declared before required
parameter $socketIds is implicitly treated as required by PHP 8.4+,
emitting a deprecation on every class load:
PHP Deprecated: Optional parameter $payload declared before
required parameter $socketIds is implicitly treated as a required
parameter
Made $socketIds optional (= []) — empty matches no connections via
array_flip lookup, so callers that intentionally omit it get a no-op
which preserves the practical contract (you can't whisper to nobody).
All four parameters are now optional. No call-site changes needed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Handler::cacheAuthenticatedUser() and ::cleanupChannelConnections() were
writing/forgetting ws_socket_auth_<rawSocketId> while
WebsocketService::getAuth() and ::setUserAuthed() have always slugged
("123.456" → "123-456"). Result: the cache write was reachable from the
package's own writer path but not from the service-layer reader, so the
admin tooling (websockets:watch -v) saw cache misses and rendered #<id>
instead of the configured IdentityFormatter output.
Also: WatchStats now batch-loads missing users via the configured auth
provider model in one query per render, so the User column still renders
the full formatter shape even when the per-socket cache blob predates
the writer or got evicted.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
websockets:watch -v now delegates User-column rendering to a bound
IdentityFormatter. The package ships DefaultIdentityFormatter which
produces #<id> - <name> | <username> - <email> for typical Eloquent users
(any field absent = that segment dropped). Apps with non-User auth
subjects (Company, ApiClient, multi-tenant blobs) can implement the
contract and either bind it in their service provider or name it in
config/websockets.php as 'identity_formatter'. Resolution order is:
explicit container binding > config class > package default.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Verbose mode reuses Symfony's built-in -v flag (the short option is
reserved, so a custom one can't be added). Each channel summary is
followed by sub-rows showing the socket id, the authed user (falling
back to "Guest" or the user id if the user blob expired), and how long
the connection has been open.
Connection start times are written by Handler::establishConnection() into
ws_connection_<slug(socketId)> on open and forgotten on close. Also
fixed a latent bug in finalizeConnectionClose() where the forget key was
missing the slug() call that the reader has always used — previously
invisible because nothing wrote the key, now load-bearing.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Renders the same Live Stats / channels table that `websockets:info` shows
at the bottom, but loops indefinitely so it can be left open as a quick
status pane. 1-second poll against the existing WebsocketService cache
reads — no pub/sub plumbing because there is no "stats changed" event
emitted today and a 1s tick is fast enough for the granularity humans
care about.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The legacy `websockets:restart` and `websocket:steer restart` rely on the
running server polling a cache key every ~5s, then unwinding the loop.
That fails silently when the cache driver differs across processes, the
poll loop stalls, or the deploy script needs to confirm the restart
happened. This adds a command that pgreps the running process, sends
SIGTERM directly (the existing PCNTL handler in StartServer already
catches it), then waits for supervisord's autorestart to bring up a new
PID before returning. Designed to be invoked from deploy scripts.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Send 'websocket' to list all controllers with methods and metadata
- Send 'auth' to list all methods on AuthController
- Shows need_auth, lifecycle hooks (boot/booted/unboot) per controller
- Only enabled in local env or via WEBSOCKET_INTROSPECTION=true
- Never active in production unless explicitly enabled
- Introduced `helpers-and-testing.md` to document global helpers and WebsocketService class usage.
- Created `HandlerLifecycleTest.php` to test the full WebSocket handler lifecycle, including connection management, channel subscriptions, and message routing.
- Added `WebsocketServiceTest.php` to validate state tracking methods in WebsocketService, covering user authentication, channel tracking, and broadcast functionality.