Skip to content

feat(plugin-gateway,plugin-cache): resume gateway sessions across restarts - #128

Merged
kodiakhq[bot] merged 7 commits into
mainfrom
claude/issue-121-session-store
Sep 26, 2026
Merged

kodiakhq[bot] merged 7 commits into
mainfrom
claude/issue-121-session-store

Conversation

@RedStar071

Copy link
Copy Markdown
Member

🔗 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 full GUILD_CREATE burst. @discordjs/ws can resume sessions through its retrieveSessionInfo/updateSessionInfo options, but each application has to wire them by hand. Wiring them directly to Redis also has problems (checked in @discordjs/ws 2.0.4):

  • ws awaits the read on every dispatch before emitting it, and the write too whenever the sequence changes. It also reads again on every heartbeat, so a Redis-backed store adds a GET/SET round trip before each dispatch.
  • A callback that throws there is invoked through void this.onMessage(...), so the error becomes an unhandled rejection and the dispatch is lost.
  • WebSocketManager#destroy can't pass recover, so it always stores null sessions, and it closes with 1000, which makes Discord invalidate the session. Even a graceful shutdown made resuming impossible.

📚 Description

  • sessionStore option.
    • Each shard's session is read from the store once, on its first connect, and then kept in memory.
    • Writes run in the background, one in flight per shard. Updates that arrive during a write collapse into a single write of the latest session, so dispatches are never held back.
    • A read that fails, or takes longer than sessionStoreTimeout (5 s by default), falls back to identifying, so a hanging Redis can't stall a shard.
    • Store failures are reported as GatewaySessionStoreError (operation, shardId, cause) through error.
  • destroy({ resumable: true }) closes the shards with 4200, which Discord doesn't invalidate, and ignores ws's null writes during shutdown, so the next process resumes. This also works with a custom gateway.updateSessionInfo and with ws's default store. Both destroy modes wait for pending session writes.
  • @wolfstar/plugin-cache ships createRedisSessionStore({ redis, prefix?, ttl? }).
    • It stores JSON at <prefix>:<shardId>, with a 600 s ttl by default (null means no expiry).
    • It only needs get, set and del, so it can reuse the cache's ioredis client.
    • GatewaySessionInfo/GatewaySessionStore have the same shape as ws's SessionInfo, but the package doesn't depend on @discordjs/ws. The gateway wiring checks at compile time that the two shapes stay assignable both ways.
  • Conflict rule: passing sessionStore together with gateway.retrieveSessionInfo or gateway.updateSessionInfo throws a TypeError, instead of silently letting one of them win.

Trade-offs, also in the READMEs:

  • After a crash, the stored sequence can be a few dispatches behind. The session is still resumable, but Discord replays those dispatches, so listeners see them twice. A graceful destroy writes the latest sequence first.
  • Resuming only helps with a persistent cache. A resumed session replays missed events, not guilds, so an in-memory cache starts empty after a restart.

Deliberately left out:

  • createInMemorySessionStore(): the client already keeps sessions in memory, and ws has a default in-memory store.
  • A time-based write throttle: collapsing writes already caps each shard at one write per store round trip.

Key changes

Package Change
plugin-gateway GatewayClientOptions.sessionStore / sessionStoreTimeout; destroy(options?: GatewayClientDestroyOptions); internal util/sessions.ts (in-memory copy of each shard's session); GatewaySessionStoreError
plugin-cache src/lib/sessions.ts: createRedisSessionStore, RedisSessionStore, DefaultRedisSessionStorePrefix, session types; the ioredis consumption type test also covers the new store
docs gateway README: options table plus a "Resuming sessions across restarts" section; cache README: a "Gateway sessions" section
tests 11 gateway tests (wiring, read-once, collapsed writes, get/set failures, get timeout, option conflict, resumable and default destroy); 7 cache tests against FakeRedis (ttl, null ttl, invalid JSON, outage)
changeset minor for both packages

Type of Change

  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation change
  • Workflow / CI change

Pre-flight Checklist

  • I have read the Contributing Guidelines (if applicable)
  • My code follows the code style of this project
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes (44 files, 477 tests after merging main)
  • I have updated the documentation accordingly
  • I added a changeset with pnpm changeset

Also 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 two GatewayClients on real @discordjs/ws against a local fake gateway:

  • destroy({ resumable: true }) closed with 4200.
  • The next client sent RESUME with the stored session and sequence and never sent IDENTIFY.
  • A plain destroy() closed with 1000 and deleted the Redis key.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RBWEHLtNzWNykJMPqeqqbB


Generated by Claude Code

…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
@coldtea-pr-lens

coldtea-pr-lens Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

◈ PR Lens

Note

This drawing shows b0efa14, and the branch has new commits since. Tick Redraw to draw the latest one

  • Redraw

🟢 +2 new · 🟠 ~3 changed · 🔴 -0 removed · 2 flows · 10 files · commit b0efa14


Architecture

Architecture diagram for wolfstar-project/plugins at b0efa14

5 components touched across 4 lanes.

Play the interactive walkthrough


Inside the changed components — 2 views

Component view — Gateway session management

Internal memory mirror, background write queue, and timeout fallback inside GatewayClient.

Architecture view of Component view — Gateway session management in wolfstar-project/plugins

Component view — Redis session store

Redis session store module managing session JSON serialization, key prefixes, and sliding TTL.

Architecture view of Component view — Redis session store in wolfstar-project/plugins

Data flow

Data flow diagram for wolfstar-project/plugins at b0efa14

Resuming gateway session across restart · Session store read failure fallback

Follow each request, response and payload


The other flows — 1 sequence

Session store read failure fallback

Sequence diagram of Session store read failure fallback in wolfstar-project/plugins

View

  • Architecture lens
  • Data flow lens
  • Expand every detail

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
  • Run npx skills add coldteadotai/pr-lens, then tell your coding agent: "Diagram the change you just made with PR Lens and attach it to the pull request."
  • Run npx @coldtea/pr-lens-cli analyze --base origin/main on a branch, then npx @coldtea/pr-lens-cli render .pr-lens/graph.json. Same lenses, your own model key, before the pull request exists
  • Untick Architecture lens or Data flow lens under View to hide a diagram, or tick Expand every detail to open every section. The comment redraws in a few seconds
  • Click the link under each diagram to open it on a canvas you can zoom, pan and step through
  • Open a diagram on the canvas, then press W or click play to walk through the change one step at a time
  • The CLI's render reads .github/pr-lens.yml and applies your renames, exclusions and lane pins at draw time
  • Set github.comment.collapsed: true in .github/pr-lens.yml to fold the comment behind one View architecture and data flow row. Drawing still runs as before
  • Set github.draw: on-demand in .github/pr-lens.yml and PR Lens stops drawing pull requests on its own. Comment @pr-lens draw on a pull request when you want that one drawn
  • Add .github/workflows/pr-lens.yml with coldteadotai/pr-lens/packages/action@v0 and your model provider's key as its api-key to run PR Lens from your own CI. Any /chat/completions endpoint works
  • Push a commit and the drawing stays, with a note that it is out of date. Tick Redraw in the note to draw the new head
  • Switch GitHub to dark mode and the diagrams follow. The moving dots are this pull request's data in motion

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.

❤️ Share

@wolfstarbot wolfstarbot added packages:plugin-cache Changes in plugin-cache packages:plugin-gateway Changes in plugin-gateway labels Sep 26, 2026
@pkg-pr-new

pkg-pr-new Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@wolfstar/plugin-api

pnpm add https://pkg.pr.new/@wolfstar/plugin-api@128

@wolfstar/plugin-cache

pnpm add https://pkg.pr.new/@wolfstar/plugin-cache@128

@wolfstar/plugin-gateway

pnpm add https://pkg.pr.new/@wolfstar/plugin-gateway@128

@wolfstar/plugin-i18next

pnpm add https://pkg.pr.new/@wolfstar/plugin-i18next@128

@wolfstar/plugin-logger

pnpm add https://pkg.pr.new/@wolfstar/plugin-logger@128

@wolfstar/plugin-sharder

pnpm add https://pkg.pr.new/@wolfstar/plugin-sharder@128

@wolfstar/plugin-subcommands-advanced

pnpm add https://pkg.pr.new/@wolfstar/plugin-subcommands-advanced@128

commit: e70e783

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 a GatewaySessionStore into @discordjs/ws's retrieveSessionInfo/updateSessionInfo, via util/sessions.ts's GatewaySessionMirror (read once per shard then served from memory, background writes collapsed per shard).
  • GatewayClient#destroy({ resumable }): closes shards with CloseCodes.Resuming (4200, which Discord doesn't invalidate) and suppresses the null-session write @discordjs/ws otherwise always issues on destroy, so the next process can resume.
  • GatewaySessionStoreError: reported through error (or the logger) on a failed/timed-out read or a failed write; neither stops the shard.
  • @wolfstar/plugin-cache's createRedisSessionStore: JSON at <prefix>:<shardId>, ttl refreshed per write, reusing the existing RedisClientLike/CacheValueError conventions from redis.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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Sonnet | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new changes. Commit 26cc2fd is a merge of main with 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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> | null field; destroy(options) now does this.#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 its resumable, instead of racing the shared #keepSessions flag.
  • Routed the session-store onError callback through reportError. GatewaySessionMirror's onError callback now calls this.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 plain destroy() 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.

Pullfrog  | View workflow run | Using Claude Sonnet | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

packages:plugin-cache Changes in plugin-cache packages:plugin-gateway Changes in plugin-gateway

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants