Repository navigation
feat(plugin-gateway,plugin-cache): resume gateway sessions across restarts - #128
Conversation
…tarts
Add a `sessionStore` option to `GatewayClient`, wired into the WebSocketManager's
`retrieveSessionInfo`/`updateSessionInfo`. The store is read once per shard, then mirrored in
memory, and written in the background with one write in flight per shard, so a Redis round trip
never holds a dispatch back. A failing or slow (`sessionStoreTimeout`) read identifies instead of
stalling the shard, and failures are reported as `GatewaySessionStoreError`s. Passing it alongside
`gateway.retrieveSessionInfo`/`updateSessionInfo` throws.
`@discordjs/ws` drops every session on `WebSocketManager#destroy`, and closes with 1000, which
Discord invalidates: `destroy({ resumable: true })` closes with 4200 and keeps them stored.
`@wolfstar/plugin-cache` ships `createRedisSessionStore` (with a 10 minute ttl by default) and the
`GatewaySessionStore`/`GatewaySessionInfo` types, structurally matching `@discordjs/ws`.
Refs #121
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RBWEHLtNzWNykJMPqeqqbB
◈ PR LensNote This drawing shows
Architecture 5 components touched across 4 lanes. Play the interactive walkthrough Inside the changed components — 2 viewsComponent view — Gateway session management Internal memory mirror, background write queue, and timeout fallback inside GatewayClient. Component view — Redis session store Redis session store module managing session JSON serialization, key prefixes, and sliding TTL. Data flow
Follow each request, response and payload The other flows — 1 sequence
View
Tip The diagrams are links. Click one to open it on the canvas, then press W or click play to walk through the change 🪧 More tips
Thanks for using PR Lens! It's built by Coldtea, free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
@wolfstar/plugin-api
@wolfstar/plugin-cache
@wolfstar/plugin-gateway
@wolfstar/plugin-i18next
@wolfstar/plugin-logger
@wolfstar/plugin-sharder
@wolfstar/plugin-subcommands-advanced
commit: |
There was a problem hiding this comment.
Important
One correctness issue worth addressing before merge, plus a small duplication nit.
Reviewed changes
Reviewed the full diff (11 files) plus the actual @discordjs/[email protected] source installed in the repo, to verify the PR's core claims about WebSocketManager#destroy/CloseCodes/DefaultWebSocketManagerOptions (all confirmed accurate — see details below).
GatewayClientOptions.sessionStore/sessionStoreTimeout: wires aGatewaySessionStoreinto@discordjs/ws'sretrieveSessionInfo/updateSessionInfo, viautil/sessions.ts'sGatewaySessionMirror(read once per shard then served from memory, background writes collapsed per shard).GatewayClient#destroy({ resumable }): closes shards withCloseCodes.Resuming(4200, which Discord doesn't invalidate) and suppresses thenull-session write@discordjs/wsotherwise always issues on destroy, so the next process can resume.GatewaySessionStoreError: reported througherror(or the logger) on a failed/timed-out read or a failed write; neither stops the shard.@wolfstar/plugin-cache'screateRedisSessionStore: JSON at<prefix>:<shardId>, ttl refreshed per write, reusing the existingRedisClientLike/CacheValueErrorconventions fromredis.ts.- Docs (both READMEs) and changesets (minor, both packages) included.
I verified @discordjs/[email protected]'s actual source (node_modules/.pnpm/@[email protected]/...) against the PR's stated claims: WebSocketManager#destroy()'s type indeed omits recover, and WebSocketShard#destroy() unconditionally calls updateSessionInfo(id, null) whenever recover !== Resume — confirming the null-write-suppression workaround is real and necessary, not a hypothetical. SessionInfo/GatewaySessionInfo are field-for-field identical, so the "assignable both ways" claim holds.
Claude Sonnet | 𝕏
There was a problem hiding this comment.
ℹ️ No new changes. Commit 26cc2fd is a merge of
mainwith no effect on this PR's files (every changed file's diff hash is identical to the previous review). Feedback from the prior review still stands.
Claude Sonnet | 𝕏
# Conflicts: # packages/plugin-gateway/README.md
…s session flag A second `destroy()` made while a resumable one was still closing the shards overwrote `#keepSessions`, so the first call's teardown dropped the sessions it was asked to keep. A concurrent call now joins the destroy in progress, keeping its `resumable`. Session store errors now go through `reportError`, like every other gateway error. Refs #121 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RBWEHLtNzWNykJMPqeqqbB
# Conflicts: # packages/plugin-gateway/src/util/errors.ts
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed commit 446aad0, pushed since the last pullfrog review, which fixes both findings raised there.
- Serialized
destroy()behind a shared in-flight promise. Added a private#destroying: Promise<void> | nullfield;destroy(options)now doesthis.#destroying ??= this.disconnect(options.resumable ?? false).finally(() => { this.#destroying = null; }). A second concurrent or re-entrant call now joins the in-flight teardown and inherits itsresumable, instead of racing the shared#keepSessionsflag. - Routed the session-store
onErrorcallback throughreportError.GatewaySessionMirror'sonErrorcallback now callsthis.reportError(error, \the session store ${error.operation}`, error.shardId)instead of reimplementing thelistenerCount("error")` branch inline. - Added a concurrency test (
GIVEN a destroy while a resumable one runs THEN it joins it and the sessions are kept) that fires a resumable and a plaindestroy()concurrently and asserts the shard closes exactly once and the session survives. - Updated the store-timeout test's expected log line to match the new
reportError-routed message shape.
I traced both fixes against the actual code paths: the ??= short-circuit means a second destroy() call never re-invokes disconnect() while one is in flight, since the whole destroy() body runs synchronously up to disconnect()'s first await — there's no window for a race even when both calls land in the same tick. The reported log line ("[Gateway] [Shard 0] Failed to process the session store get:") matches reportError's format and the new test's assertion. Both threads from the prior review were already replied-to and resolved by the author.
Claude Sonnet | 𝕏

🔗 Linked issue
Part of #121 (item 3: sessions are not resumed across restarts).
🧭 Context
With
GatewayClient, every deploy or crash makes every shard identify again. That spends identify quota, loses the events sent in the meantime, and triggers a fullGUILD_CREATEburst.@discordjs/wscan resume sessions through itsretrieveSessionInfo/updateSessionInfooptions, but each application has to wire them by hand. Wiring them directly to Redis also has problems (checked in@discordjs/ws2.0.4):void this.onMessage(...), so the error becomes an unhandled rejection and the dispatch is lost.WebSocketManager#destroycan't passrecover, so it always storesnullsessions, and it closes with1000, which makes Discord invalidate the session. Even a graceful shutdown made resuming impossible.📚 Description
sessionStoreoption.sessionStoreTimeout(5 s by default), falls back to identifying, so a hanging Redis can't stall a shard.GatewaySessionStoreError(operation,shardId,cause) througherror.destroy({ resumable: true })closes the shards with4200, which Discord doesn't invalidate, and ignores ws'snullwrites during shutdown, so the next process resumes. This also works with a customgateway.updateSessionInfoand with ws's default store. Both destroy modes wait for pending session writes.@wolfstar/plugin-cacheshipscreateRedisSessionStore({ redis, prefix?, ttl? }).<prefix>:<shardId>, with a 600 s ttl by default (nullmeans no expiry).get,setanddel, so it can reuse the cache's ioredis client.GatewaySessionInfo/GatewaySessionStorehave the same shape as ws'sSessionInfo, but the package doesn't depend on@discordjs/ws. The gateway wiring checks at compile time that the two shapes stay assignable both ways.sessionStoretogether withgateway.retrieveSessionInfoorgateway.updateSessionInfothrows aTypeError, instead of silently letting one of them win.Trade-offs, also in the READMEs:
destroywrites the latest sequence first.Deliberately left out:
createInMemorySessionStore(): the client already keeps sessions in memory, and ws has a default in-memory store.Key changes
GatewayClientOptions.sessionStore/sessionStoreTimeout;destroy(options?: GatewayClientDestroyOptions); internalutil/sessions.ts(in-memory copy of each shard's session);GatewaySessionStoreErrorsrc/lib/sessions.ts:createRedisSessionStore,RedisSessionStore,DefaultRedisSessionStorePrefix, session types; the ioredis consumption type test also covers the new storeFakeRedis(ttl, null ttl, invalid JSON, outage)minorfor both packagesType of Change
Pre-flight Checklist
main)pnpm changesetAlso checked:
pnpm lint,pnpm typecheck, and both package builds (attw and publint clean). I also ran a one-off end-to-end check, not committed, with twoGatewayClients on real@discordjs/wsagainst a local fake gateway:destroy({ resumable: true })closed with 4200.destroy()closed with 1000 and deleted the Redis key.🤖 Generated with Claude Code
https://claude.ai/code/session_01RBWEHLtNzWNykJMPqeqqbB
Generated by Claude Code