Skip to content

feat(plugin-gateway): request guild members over the gateway - #126

Merged
kodiakhq[bot] merged 6 commits into
mainfrom
claude/issue-121-member-requests
Sep 26, 2026
Merged

kodiakhq[bot] merged 6 commits into
mainfrom
claude/issue-121-member-requests

Conversation

@RedStar071

Copy link
Copy Markdown
Member

🔗 Linked issue

Part of #121 (item 2: request guild members over the gateway).

🧭 Context

@wolfstar/plugin-cache already writes GUILD_MEMBERS_CHUNK into the cache, but nothing could ask Discord for those chunks. client.members only listed members through REST, one page at a time, and no event exposed the chunks. Bots that keep a full member cache need the gateway request, and the old WolfStar gateway process supported it.

📚 Description

This adds client.members.request(guildId, options), the equivalent of discord.js's guild.members.fetch() with no user argument. It sends REQUEST_GUILD_MEMBERS (opcode 8) on the guild's shard. It resolves with the GuildMembers once every GUILD_MEMBERS_CHUNK with its nonce has been cached, so a client.members.get right after sees them. Each chunk is also emitted as a new guildMembersChunk event.

  • Options: { query?, limit?, userIds?, presences?, nonce?, time? }.
    • query and userIds cannot be combined. With neither, every member is requested (query: "", limit: 0).
    • At most 100 userIds.
    • The nonce is at most 32 bytes, random by default, and must be unique while its request is pending.
    • Invalid options throw before anything is sent.
  • Shard: (guildId >> 22) % shardCount, with the count from client.gateway.getShardCount().
  • Rate limiting is left to @discordjs/ws. Its WebSocketShard#send waits until the shard is ready. After 115 payloads in the current minute on that shard, it queues the rest until the window resets (Discord's limit is 120).
  • Timeout: rejects with GuildMembersTimeoutError when no chunk arrives within time ms. The default is 120 s, and each chunk restarts the timer, as in discord.js. The timer starts only after send resolves, so waiting in the local rate-limit queue doesn't count.
  • RATE_LIMITED answer: Discord replies to an over-limit opcode 8 with a RATE_LIMITED dispatch and sends no chunks. The request then rejects immediately with GuildMembersRateLimitError, whose retryAfter is in ms, instead of hanging until its timeout.
  • Pending state is cleaned up on resolve, timeout, rate limit, and when send throws (for example, a shard this process doesn't run).
  • Requested IDs that aren't members are left out of the result and are listed in data.not_found on the event.
  • Guild#requestMembers(options) is a thin wrapper that follows Guild#fetchOwner. Guild has no members manager, so there's no guild.members.fetchAll().

Deliberately left out:

  • No check of the client's intents; the GuildMembers / GuildPresences requirements are documented.
  • Pending requests aren't rejected on destroy(); they time out.
  • Under the default cacheFailure: "skip", a chunk whose cache write fails is dropped like any other dispatch, so its request ends with a timeout.

Key changes

File Change
managers/GuildMemberManager.ts request, GuildMembersRequestOptions, internal handleChunk / handleRateLimited
util/dispatch.ts / util/events.ts GUILD_MEMBERS_CHUNK handler → guildMembersChunk (members, guild | null, data); it hands the chunk to the pending request after it is cached
GatewayClient.ts passes RATE_LIMITED to the member manager (2 lines)
util/errors.ts GuildMembersTimeoutError, GuildMembersRateLimitError
structures/Guild.ts Guild#requestMembers
tests/member-requests.test.ts 13 tests: shard selection, payloads, validation, multi-chunk resolution after caching, nonce correlation across concurrent requests, timeout and timer restart, RATE_LIMITED, send failure, the event with and without a cache, Guild#requestMembers
README, changeset events table and members section; minor

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 (43 files, 472 tests after merging main)
  • I have updated the documentation accordingly
  • I added a changeset with pnpm changeset

Also run: pnpm lint, pnpm typecheck, and pnpm --filter @wolfstar/plugin-gateway build (attw and publint clean).

🤖 Generated with Claude Code

https://claude.ai/code/session_01RBWEHLtNzWNykJMPqeqqbB


Generated by Claude Code

Add `client.members.request(guildId, options)` (and `guild.requestMembers`), sending
REQUEST_GUILD_MEMBERS on the guild's shard and resolving with the members once the last
GUILD_MEMBERS_CHUNK of its nonce is cached. It rejects with `GuildMembersTimeoutError` when
the chunks stop arriving, or `GuildMembersRateLimitError` on a matching RATE_LIMITED.
Every chunk is also emitted as the new `guildMembersChunk` event.

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 4a5db69, and the branch has new commits since. Tick Redraw to draw the latest one

  • Redraw

🟢 +0 new · 🟠 ~4 changed · 🔴 -0 removed · 2 flows · 9 files · commit 4a5db69


Architecture

Architecture diagram for wolfstar-project/plugins at 4a5db69

4 components touched across 5 lanes.

Play the interactive walkthrough


Inside the changed components — 1 view

Component view — Member request pipeline

Internal modules managing request tracking, chunk dispatching, cache hydration, and timeout handling.

Architecture view of Component view — Member request pipeline in wolfstar-project/plugins

Data flow

Data flow diagram for wolfstar-project/plugins at 4a5db69

Requesting and caching guild members · Gateway rate limit rejection

Follow each request, response and payload


The other flows — 1 sequence

Gateway rate limit rejection

Sequence diagram of Gateway rate limit rejection in wolfstar-project/plugins

View

  • Architecture lens
  • Data flow lens
  • Expand every detail

Tip

Switch GitHub to dark mode and the diagrams follow. The moving dots are this pull request's data in motion

🪧 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
  • The diagrams are links. Click one to open it on the canvas, then press W or click play to walk through the change
  • 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

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

@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 critical issues — one minor nitpick below, otherwise looks solid.

Reviewed changes

Reviewed the full diff adding gateway-based member requests to @wolfstar/plugin-gateway, including the manager logic, chunk/rate-limit correlation, the new public event, error types, docs, and tests.

  • GuildMemberManager#request: validates options (query/userIds mutually exclusive, ≤100 userIds, nonce ≤32 bytes), computes the guild's shard ((guildId >> 22) % shardCount), sends REQUEST_GUILD_MEMBERS via client.gateway.send, and tracks a pending request by nonce until it settles.
  • handleChunk: correlates GUILD_MEMBERS_CHUNK dispatches to the pending request by nonce (+ guild_id cross-check), and completes it once the received-chunk count reaches chunk_count.
  • handleRateLimited: wired into GatewayClient.handleDispatch ahead of the normal action pipeline, rejecting the matching request immediately on a RATE_LIMITED dispatch instead of waiting out the timeout.
  • guildMembersChunk event: emitted from util/dispatch.ts once the chunk is cached, carrying the hydrated members, the resolved guild (or null), and the raw dispatch data.
  • Guild#requestMembers: thin wrapper delegating to client.members.request, following the fetchOwner pattern.
  • New errors: GuildMembersTimeoutError and GuildMembersRateLimitError, matching the existing DispatchTimeoutError shape.
  • Tests: 13 new tests covering shard selection, payload shape, option validation, multi-chunk resolution ordering against cache writes, concurrent-request nonce correlation, timeout and timer-restart behavior, RATE_LIMITED, send() failure cleanup, and the event with/without a cache.
  • Docs: README events table and members section, plus a minor changeset.

I verified the Discord-facing claims against [email protected] directly rather than trusting recollection: GatewayRateLimitedDispatchData's meta.nonce/opcode/retry_after (seconds) all match the usage in handleRateLimited, and the GUILD_MEMBERS_CHUNK cache write this relies on already existed in @wolfstar/plugin-cache's hydrateGuildMembersChunk before this PR. I also checked the completion logic (counting received chunks against chunk_count rather than tracking chunk_index) against discord.js's own GuildMemberManager#_fetchMany, which uses the same "index === chunk.count" approach — this is parity, not a shortcut. What initially looked like a TOCTOU race in the nonce-uniqueness check (request() awaits getShardCount() before reserving the nonce) isn't one: JS's run-to-completion semantics between awaits make the check-then-reserve sequence atomic against other concurrent request() calls.

ℹ️ Nitpicks

  • GuildMembersRequestOptions.userIds is checked with a plain truthy test (userIds ? ... : ...). An explicit userIds: [] is truthy, so it goes down the "request by IDs" branch (user_ids: []) instead of falling back to the default "every member" query — probably not what a caller passing a dynamically-built empty array would expect. Low impact, but userIds && userIds.length > 0 would avoid the surprise.

Pullfrog  | Fix it ➔ | View workflow run | Using Claude Sonnet | 𝕏

@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@126

@wolfstar/plugin-cache

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

@wolfstar/plugin-gateway

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

@wolfstar/plugin-i18next

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

@wolfstar/plugin-logger

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

@wolfstar/plugin-sharder

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

@wolfstar/plugin-subcommands-advanced

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

commit: 5270700

…equests

`userIds: []` is truthy, so it sent a request by an empty list of IDs instead of
falling back to requesting every member.

Refs #121

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RBWEHLtNzWNykJMPqeqqbB

Copy link
Copy Markdown
Member Author

Addressed the userIds: [] nitpick in e26317c. An empty userIds is now treated as if it were omitted, so the request falls back to every member (query: "", limit: 0). It also no longer conflicts with query. A new test covers it: 14 tests in the file, 478 in total. This push also merges the latest main (#127, #129, #130).


Generated by Claude Code

@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 the single new commit (e26317c) since the prior pullfrog review, which fixes the nitpick raised on 4a5db69.

  • Fixed userIds: [] handling: GuildMemberManager#request now does options.userIds?.length ? options.userIds : undefined instead of a plain truthy check, so an empty userIds array falls back to the default "every member" query branch instead of incorrectly taking the "request by IDs" branch with an empty user_ids.
  • Updated JSDoc: GuildMembersRequestOptions.userIds now documents that an empty array is treated like omitting it.
  • Added a regression test: "GIVEN an empty userIds THEN every member is requested" asserts the payload sent is the default query (query: "", limit: 0), not user_ids: [].

Confirmed the reassigned userIds local is still what feeds the ≤100/mutual-exclusivity validation and the payload construction below it, so the fix doesn't disturb either.

Pullfrog  | View workflow run | Using Claude Sonnet | 𝕏

# Conflicts:
#	packages/plugin-gateway/src/managers/GuildMemberManager.ts
@kodiakhq
kodiakhq Bot merged commit d6dc821 into main Sep 26, 2026
15 of 16 checks passed
@kodiakhq
kodiakhq Bot deleted the claude/issue-121-member-requests branch September 26, 2026 22:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

packages:plugin-gateway Changes in plugin-gateway

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants