Skip to content

RFC: plugin-gateway follow-ups from replacing a dedicated gateway process (register entrypoint, member requests, session resume, …) #121

Closed
wolfstar-project/wolfstar
#208

Description

@RedStar071

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Context

WolfStar used to run two processes. projects/gateway connected the shards with @discordjs/ws. It wrote every dispatch into a Redis cache and forwarded the events to the bot over a Redis stream broker. The bot built on @wolfstar/http-framework consumed those events. We are replacing all of that with @wolfstar/plugin-gateway 0.1.1 and @wolfstar/plugin-cache 0.2.0. The bot now builds a GatewayClient with createRedisCache({ redis }) and calls start(), and the dedicated gateway project is deleted.

The migration surfaced one blocking issue and several gaps. This RFC lists them, ordered by impact, with a proposed solution for each. Most can be split into separate PRs.

1. Blocking: no register entrypoint, but the Stars CLI imports one

The Stars CLI (@wolfstar/cli 2.x, the stars:plugin-registrations transform in @wolfstar/vite-server) injects import "<name>/register" into the entry for every dependency matching /^@wolfstar\/plugin-[^/]+$/. Neither @wolfstar/plugin-gateway nor @wolfstar/plugin-cache exports ./register: their exports only has ".". A project that depends on them builds fine, then crashes at startup:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './register' is not defined by "exports" in .../node_modules/@wolfstar/plugin-cache/package.json imported from .../dist/main.mjs

Reproduction: a Stars project with @wolfstar/plugin-gateway in dependencies, then stars build and node dist/main.mjs. The emitted entry starts with:

import '@wolfstar/plugin-api/register';
import '@wolfstar/plugin-cache/register';
import '@wolfstar/plugin-gateway/register';

A plain alias does not work around it: the tsdown defaults set deps.neverBundle: true, so the specifier is externalized before any alias plugin sees it. Our current workaround is an alias to an empty module, plus deps: { neverBundle: true, alwaysBundle: ['@wolfstar/plugin-cache/register', '@wolfstar/plugin-gateway/register'] } in stars.config.ts.

2. No way to request guild members over the gateway

There is no REQUEST_GUILD_MEMBERS (opcode 8) helper and no guildMembersChunk event. @wolfstar/plugin-cache already hydrates GUILD_MEMBERS_CHUNK into the cache in applyGatewayDispatch, but nothing can ask for the chunks. client.members only lists members through REST, one page at a time. Bots that keep a full member cache for moderation or logging (member counts, role checks, the GuildMembers intent) need the gateway request. The old WolfStar gateway handled it.

3. Sessions are not resumed across restarts

With a separate gateway process, restarting the bot never touched the shards. With GatewayClient, every deploy or crash re-identifies every shard: it spends identify quota, misses events, and triggers a full GUILD_CREATE burst. @discordjs/ws already supports resuming through retrieveSessionInfo/updateSessionInfo, but each application has to wire it by hand.

4. README documents subpaths that are not exported

The README lists @wolfstar/plugin-gateway/rest (@discordjs/rest) and @wolfstar/plugin-gateway/ws (@discordjs/ws), but package.json#exports only has ".". Importing either fails with ERR_PACKAGE_PATH_NOT_EXPORTED.

5. container.client stays typed as Client

getGatewayClient() exists, but container.client (what pieces use through this.container.client) is still typed as the base Client. Every piece that needs guilds, members, gateway & co. has to call the helper or cast.

6. Production dependency on a @discordjs/structures dev snapshot

@discordjs/structures is pinned to 1.0.0-dev.1790035407-dbb749062. That snapshot forces engines.node >= 24.17.0 on every consumer and can disappear or change under us, since dev tags are not immutable releases in practice.

7. Published peer ranges lag behind main

On main, every plugin accepts @wolfstar/http-framework ^3.x || ^5.0.0, but the npm releases do not. plugin-api 1.1.6 declares ^3.0.0, plugin-subcommands-advanced 2.0.4 ^3.1.0, and plugin-logger 0.2.0 ^3.4.0. A v5 project that uses GatewayClient (which does accept ^5) together with those plugins gets peer warnings. pnpm may also resolve a second http-framework copy for the plugins, so their ClientOptions augmentations (e.g. subcommandsAdvanced) do not apply to GatewayClientOptions: TS2353: 'subcommandsAdvanced' does not exist in type 'GatewayClientOptions'.

8. Every cache read is async, even in memory

The README explains why: the same code has to work with Redis. Still, porting a discord.js codebase means rewriting every synchronous guild.members.cache.get(id) into an awaited call, including in hot paths such as message filters, where the in-memory store could answer synchronously.

Desired solution

  1. register entrypoints. Either option works, and doing both is the safest:
    • Ship a no-op ./register in plugin-gateway and plugin-cache, as the other plugins do. plugin-gateway could also use it to register something useful, such as a gateway ClientOptions augmentation.
    • Make the Stars transform only inject <name>/register when the package's exports actually defines ./register. Also, @wolfstar/plugin-cache is a library rather than a framework plugin. Renaming it (e.g. @wolfstar/cache) would keep it out of the plugin-* convention altogether.
  2. Guild member requests. Add client.members.request(guildId, { query?, limit?, userIds?, presences?, nonce? }) (or guild.members.fetchAll()), resolving once every GUILD_MEMBERS_CHUNK with the matching nonce has arrived. Send it on the guild's shard via client.gateway.send(shardId, { op: GatewayOpcodes.RequestGuildMembers, d }), with a timeout, and respect the per-shard gateway rate limit. Also emit guildMembersChunk (members, guild | null, data) like discord.js.
  3. Session persistence. Add an option such as sessionStore: { get(shardId), set(shardId, info | null) }, wired into retrieveSessionInfo/updateSessionInfo. Ship a Redis implementation next to createRedisCache (e.g. createRedisSessionStore({ redis, prefix })) so the same ioredis client covers both.
  4. Subpath exports. Either add ./rest and ./ws to exports, re-exporting @discordjs/rest and @discordjs/ws, or remove them from the README.
  5. container.client typing. Add an opt-in module augmentation, e.g. import "@wolfstar/plugin-gateway/augment", that declares container.client as GatewayClient. Or document the recommended pattern for pieces.
  6. Structures dependency. Drop the @discordjs/structures runtime dependency until it has a stable release: copy the small base (Structure, kData/kPatch/kClone via Symbol.for) into the package. Or make it an optional peer and relax engines.
  7. Peer ranges. Publish the plugins whose ^5 peer range is only on main (plugin-api, plugin-subcommands-advanced, plugin-logger). Add a CI check that fails when a plugin's peer range excludes the latest @wolfstar/http-framework major.
  8. Synchronous reads. Add an optional synchronous path for in-memory caches, e.g. client.members.cached(guildId, userId) returning GuildMember | undefined when the cache is synchronous and undefined (or a throw) otherwise. Or expose cache.isSynchronous so callers can branch.

Alternatives considered

  • Keep a dedicated gateway process feeding the bot over a Redis stream, as before. It avoids items 3 and 8, but duplicates what plugin-gateway + plugin-cache now provide, and the broker/cache protocol lives only in our repo. plugin-sharder covers multi-process sharding, so the separate process no longer pays for itself.
  • Work around item 1 in every application with aliases and deps.alwaysBundle, as we do now. It works, but every Stars user hits the crash at runtime, not at build time, so it has to be fixed upstream.
  • Use client.members.list() (REST) instead of item 2. It works for small guilds, but it costs one REST call per 1000 members and does not scale to large guilds.

Additional context

Activity

  1. added
    packages:plugin-cache
    packages:plugin-gateway
    on Sep 26, 2026
  2. pullfrog commented on Sep 26, 2026

    @pullfrog
    Contributor

    Assessment

    Issue #121 is well-scoped and actionable — the author already reproduced the blocking bug, and the RFC's "Desired solution" section names concrete APIs to add. I verified every claim against the current main source (not just trusting the issue text); details and one correction below.

    Verified as accurate:

    • chore(deps): update all non-major dependencies #1 (register entrypoint, blocking): packages/plugin-gateway/package.json and packages/plugin-cache/package.json only export "." — no ./register, no register.ts. plugin-api, plugin-i18next, plugin-logger, plugin-subcommands-advanced all have src/register.ts + a matching exports["./register"] entry. plugin-sharder (also @wolfstar/plugin-[^/]+) has the same gap and would hit the same crash — worth covering in the Stars-transform fix even though the issue doesn't name it.
    • Dependency Dashboard #2 (member requests): confirmed no RequestGuildMembers opcode helper and no guildMembersChunk event anywhere in plugin-gateway/src. plugin-cache/src/lib/operations.ts (hydrateGuildMembersChunk, line ~953) already hydrates GUILD_MEMBERS_CHUNK into the members/users stores — the write path exists, only the request+correlation path is missing.
    • docs: align README with stars-components layout #3 (session resume): no sessionStore/retrieveSessionInfo/updateSessionInfo reference anywhere in the repo. GatewayClient's WebSocketManager construction (GatewayClient.ts:190) doesn't set either hook.
    • chore(knip): ignore intentional root devDependencies #4 (README subpaths): README.md documents @wolfstar/plugin-gateway/rest and /ws (lines ~489–497), but package.json#exports only has ".". Confirmed mismatch.
    • fix(release): make changelog generator resilient to GitHub API failures #5 (container.client typing): confirmed via source read — plugin-gateway/src/index.ts has no declare module augmenting ClientOptions or container.client (only events.ts augments ClientEvents, unrelated). Compare plugin-subcommands-advanced/src/index.ts:30-37, which does augment ClientOptions — that's the pattern to follow, but for container.client instead.
    • chore: update changelog and release #6 (structures dev-dependency): confirmed, @discordjs/structures is pinned to 1.0.0-dev.1790035407-dbb749062 with engines.node >= 24.17.0 forced by it.
    • chore: republish plugin-api and update pnpm to 11.13.1 #8 (sync reads): confirmed at the architecture level — plugin-cache's EntityCache<Raw> interface already types every method as Awaitable<T> (T | Promise<T>), and MemoryEntityCache.get() (plugin-cache/src/lib/memory.ts) already returns synchronously. The gap is one layer up: CachedManager/GuildMemberManager in plugin-gateway declare every method async, so callers always await even against an in-memory cache. A sync path is a plugin-gateway-side addition, not a plugin-cache one.

    One correction to the issue — #7 (peer ranges) is already resolved for two of the three named packages: plugin-logger (0.2.0), plugin-api (1.1.6), and plugin-subcommands-advanced (2.0.4) all already publish @wolfstar/http-framework peer ranges including ^5.0.0 — this shipped via a generic "update all non-major dependencies" Renovate PR whose changelog entry doesn't call out the peer bump, which is likely why it read as unfixed. No .changeset/ entries are pending for any of this. The only real remaining work here is the CI check the issue itself proposes (fail when a plugin's peer range excludes the latest @wolfstar/http-framework major), to stop this from silently regressing again.

    Proposed plan (mirrors the issue's own impact ordering; each numbered item ships as its own PR)

    1. register entrypoints (blocking). Two changes:

      • Add a no-op src/register.ts + exports["./register"] to plugin-gateway and plugin-cache, matching the existing pattern in plugin-api/plugin-logger/plugin-subcommands-advanced (sideEffects: ["./dist/esm/register.js"], attwEntrypoints updated per the createTsdownOptions convention noted in plugin-api's changelog).
      • Fix the Stars CLI's stars:plugin-registrations transform (in @wolfstar/cli, a separate repo/package — flag as a cross-repo dependency) to only inject import "<name>/register" when exports["./register"] is actually declared. This is the durable fix; the no-op export is the immediate unblock. Also covers plugin-sharder, which has the same gap today.
      • Consider renaming @wolfstar/plugin-cache (e.g. @wolfstar/cache) since it's a library, not an http-framework plugin — larger, separate discussion; don't bundle into this PR.
    2. Guild member requests. Add to GuildMemberManager: request(guildId, { query?, limit?, userIds?, presences?, nonce? }) sending GatewayOpcodes.RequestGuildMembers via client.gateway.send(shardId, payload), resolving once every GUILD_MEMBERS_CHUNK with the matching nonce arrives (track pending requests in a map keyed by nonce, matching chunk_index === chunk_count - 1), with a timeout mirroring DispatchTimeoutError's pattern. Add a GuildMembersChunk entry to DispatchHandlers (util/dispatch.ts) emitting guildMembersChunk (members, guild | null, data) — this is a normal DispatchHandler addition, no different in shape from the existing ones.

    3. Session persistence. Add sessionStore?: { get(shardId): Awaitable<SessionInfo | null>, set(shardId, info): Awaitable<void> } to GatewayClientOptions, wired into the WebSocketManager constructor's retrieveSessionInfo/updateSessionInfo. Ship createRedisSessionStore({ redis, prefix }) in plugin-cache next to createRedisCache, reusing the same ioredis client.

    4. Subpath exports vs. README. Either add ./rest and ./ws to plugin-gateway's exports (thin re-export modules) or trim the README's "Subpath exports" table to match reality — recommend the former since the README already sells this as a @discordjs/next-style convenience.

    5. container.client typing. Add an opt-in @wolfstar/plugin-gateway/augment entrypoint with declare module "@wolfstar/http-framework" { interface Container { client: GatewayClient } } (mirroring plugin-subcommands-advanced's ClientOptions augmentation pattern, applied to the client type instead).

    6. Drop the @discordjs/structures dev-snapshot runtime dependency. Copy the small base (Structure class, kData/kPatch/kClone via Symbol.for) into plugin-gateway/src/structures/Structure.ts directly (it already re-exports these symbols) so a stable Node engine range can be restored; or make it an optional peer if copying the base is judged too invasive.

    7. Peer ranges + CI guard. No package fix needed (see correction above). Add a CI check (probably a pnpm script run in the existing typecheck/lint workflow) that fails when any plugin's peerDependencies["@wolfstar/http-framework"] range excludes whatever major plugin-gateway's own peer range accepts, to catch regressions like this early.

    8. Synchronous cache reads. Add an opt-in sync path to CachedManager/GuildMemberManager, e.g. cached(...args): Value | undefined, usable only when client.cache exposes a synchronous EntityCache (detectable via a cache.isSynchronous flag added to the Cache/EntityCache contract in plugin-cache, since Awaitable alone can't be checked at runtime). Throws or returns undefined against a Redis-backed cache.

    Each item is independently shippable and none blocks the others except that #1 is the one actively breaking consumers today and should land first. Ready to start on #1 whenever you'd like — say the word and I'll open the PR.

    Pullfrog  | Implement plan ➔ | View workflow run | via Pullfrog | Using Claude Sonnet | 𝕏

  3. pullfrog commented on Sep 26, 2026

    @pullfrog
    Contributor

    Implemented item #1 of the plan for #121 — the blocking ./register entrypoint bug.

    Opened PR #122: adds a no-op ./register subpath export to @wolfstar/plugin-gateway, @wolfstar/plugin-cache, and @wolfstar/plugin-sharder (all three match the @wolfstar/plugin-* pattern that @wolfstar/cli's Stars transform unconditionally injects import "<name>/register" for, so they were crashing consumers with ERR_PACKAGE_PATH_NOT_EXPORTED). Each package gets src/register.ts, an exports["./register"] entry, sideEffects array, and updated tsdown.config.ts/attwEntrypoints, plus a patch changeset for all three.

    Verified: builds pass with attw/publint clean for all three packages, tsc --noEmit passes, oxlint/oxfmt --check clean, and a fresh-eyes self-review found no defects.

    The remaining 7 items from the plan (member requests, session persistence, container.client typing, README subpath drift, dropping the @discordjs/structures dev dependency, peer-range CI guard, synchronous cache reads) are separate follow-up PRs — #121 is left open for those.

    Pullfrog  | View workflow run | via Pullfrog | Using Claude Sonnet | 𝕏

  4. RedStar071 commented on Sep 27, 2026

    @RedStar071
    MemberAuthor

    Every item in this RFC is now handled on main:

    # Item Resolution
    1 register entrypoints #123: a no-op ./register in plugin-gateway, plugin-cache and plugin-sharder. None of them needs a Plugin hook. A workspace test fails if any @wolfstar/plugin-* package lacks the subpath. The Stars transform side was already fixed in stars-components #222 and released in @wolfstar/vite-server 0.2.2: it only injects /register when the package exports it.
    2 Guild member requests #126: client.members.request(guildId, options), Guild#requestMembers, and the guildMembersChunk event. It rejects on timeout or on RATE_LIMITED.
    3 Session persistence #128: new sessionStore / sessionStoreTimeout options, plus createRedisSessionStore in plugin-cache. destroy({ resumable: true }) closes the shards with 4200 and keeps their sessions.
    4 README subpaths #134: removed the "Subpath exports" section from the README. The subpaths were never exported. Depend on @discordjs/rest and @discordjs/ws directly. #129 had added the subpaths; #134 reverted it.
    5 container.client typing #130: container.gatewayClient: GatewayClient. Retyping container.client isn't possible: it fails with TS2717, and under skipLibCheck the framework's declaration still takes precedence.
    6 @discordjs/structures Kept as a dependency (#134 reverted the in-package copy from #127).
    7 Peer ranges #125: patch changesets for plugin-api, plugin-logger and plugin-subcommands-advanced, so the ^5 ranges already on main get published. A test guards the peer ranges from now on.
    8 Synchronous reads #131: EntityCache.synchronous, and manager.cached(...) on every manager. It throws on an asynchronous cache instead of returning a false miss.

    The changes ship with the next release.


    Generated by Claude Code

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurepackages:plugin-cachepackages:plugin-gateway

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions