Skip to content

RFC: GatewayClient — Gateway (WebSocket) support for @wolfstar/http-framework #54

Closed

Description

@RedStar071

Introduction

@wolfstar/http-framework currently speaks to Discord exclusively through the interactions HTTP endpoint: a bot receives INTERACTION_CREATE payloads on a webhook and responds synchronously. That's a great fit for stateless, serverless-friendly deployments, but it means a bot built on the framework has no way to react to anything that only exists on the Gateway — MESSAGE_CREATE, presence/voice state updates, guild member events, raw moderation-relevant events, etc. Today the only paths forward are to bring in a second, unrelated framework (e.g. Carbon) just for the Gateway half, or to hand-roll a WebSocket client per project.

This was requested directly in wolfstar-project/stars-components#51, which asks for a package that:

  • Provides Gateway connectivity "comparable to Carbon's architecture or the RFC outlined in discordjs/discord.js#11426"
  • Supports both local (in-memory) and Redis-backed caching
  • Is functionally on par with what Carbon and discord.js already offer
  • Supports compressing cached data

This RFC proposes @wolfstar/plugin-gateway, exporting a GatewayClient that extends @wolfstar/http-framework's Client — not a separate object bridged in through a plugin hook. A bot built on GatewayClient keeps every interactions capability of the base Client (load(), listen(), the command/interaction-handler stores, Client.use()) for free, and gains Gateway connectivity, caching, and a set of ready-made Structures on top, in the spirit of the "mini discord.js" Client being prototyped upstream in discordjs/discord.js#10983. Crucially, and unlike raw Gateway dispatch handling, GatewayClient events hand consumers Structure instances (Message, User, Guild, …) rather than raw snake_case API JSON — the same direction discord.js#10983 and the @discordjs/structures package are taking upstream.

The caching half is intentionally split out into its own, more focused RFC — see the companion issue linked in the footnotes. GatewayClient's Managers only depend on the Cache interface defined there, not on any specific store implementation.

Design principles

  1. Extend, don't wrap. GatewayClient extends Client. A bot that wants Gateway support constructs a GatewayClient instead of a Client and otherwise writes exactly the code it already knows — command stores, interaction handlers, client.load(), client.listen() all keep working unmodified.
  2. Events carry Structures, not raw payloads. client.on('messageCreate', (message: Message) => …) gets a Message with typed getters (message.author, message.content, …), not client.on(GatewayDispatchEvents.MessageCreate, (data: APIMessage) => …). Consumers shouldn't need to know the raw API shape to write a handler.
  3. Gateway events are listener pieces too. @wolfstar/http-framework already has a file-based Listener/ListenerStore piece system (loaded via client.load()) for everything else the framework emits. Because GatewayClient extends Client, that same piece loader should work for Gateway-sourced events without a second, parallel mechanism — @wolfstar/plugin-gateway ships EventGatewayListener, a thin Listener subclass, rather than inventing a separate listener API.
  4. Don't reinvent sharding. @discordjs/ws's WebSocketManager already solves reconnects, resumes, rate-limited identify, and shard orchestration correctly. GatewayClient wraps it rather than re-implementing it.
  5. Cache is a seam, not a requirement. GatewayClient accepts any object satisfying the Cache interface from the companion RFC. No cache, an in-memory cache, and a Redis-backed cache are all equally valid — Managers build Structures on top of whatever Cache returns.

Structures

Rather than inventing a parallel structure system, @wolfstar/plugin-gateway depends directly on @discordjs/structures for the base Structure<DataType> class: it already gives us data storage behind a kData symbol, in-place patching via [kPatch], cheap [kClone], and a DataTemplate mechanism to strip fields we never want to keep resident. wolfstar-specific concrete structures live in this package and extend it:

import { Structure, kData } from '@discordjs/structures';
import type { APIUser } from 'discord-api-types/v10';

export class User extends Structure<APIUser> {
	public get id() {
		return this[kData].id;
	}

	public get username() {
		return this[kData].username;
	}

	public get discriminator() {
		return this[kData].discriminator;
	}

	public displayAvatarURL(): string | undefined {
		return this[kData].avatar
			? `https://cdn.discordapp.com/avatars/${this.id}/${this[kData].avatar}.png`
			: undefined;
	}
}

Managers

Each entity type gets a CachedManager, mirroring the createStructure pattern from discord.js#10983's ChannelManager:

import type { Snowflake } from 'discord-api-types/globals';
import type { Structure } from '@discordjs/structures';
import type { Cache, EntityCache } from '@wolfstar/plugin-cache'; // see companion RFC

export abstract class CachedManager<Value extends Structure<{ id: Snowflake }>, Raw = unknown> {
	public constructor(protected readonly client: GatewayClient) {}

	protected abstract entityCache(cache: Cache): EntityCache<Raw>;
	protected abstract createStructure(data: Partial<Raw>): Value;

	public async get(id: Snowflake): Promise<Value | undefined> {
		const raw = await this.entityCache(this.client.cache).get(id);
		return raw ? this.createStructure(raw) : undefined;
	}
}

export class UserManager extends CachedManager<User, APIUser> {
	protected override entityCache(cache: Cache) {
		return cache.users;
	}

	protected override createStructure(data: Partial<APIUser>): User {
		return new User(data);
	}
}

GatewayClient

import type { GatewayIntentBits } from 'discord-api-types/v10';
import { Client, type ClientOptions } from '@wolfstar/http-framework';
import type { Cache } from '@wolfstar/plugin-cache'; // see companion RFC

export interface GatewayClientOptions extends ClientOptions {
	intents: GatewayIntentBits | number;
	/** Explicit shard count/range, or "auto" to let the Gateway session-start-limit endpoint decide. */
	shards?: number | number[] | 'auto';
	/** Optional cache implementation; see the companion Cache RFC. Defaults to a no-op cache. */
	cache?: Cache;
}

export class GatewayClient extends Client {
	public readonly cache?: Cache;
	public readonly users: UserManager;
	public readonly guilds: GuildManager;
	public readonly channels: ChannelManager;

	public constructor(options: GatewayClientOptions);

	/** Starts the WebSocketManager and connects all configured shards. */
	public connect(): Promise<void>;
}

On dispatch, GatewayClient feeds the raw payload to the relevant EntityCache first, then asks the corresponding Manager to build (or patch) the Structure before emitting it — reusing the same AsyncEventEmitter the base Client already uses for interaction events:

gateway.on(WebSocketShardEvents.Dispatch, async ({ data: payload }, shardId) => {
	switch (payload.t) {
		case GatewayDispatchEvents.MessageCreate: {
			await this.cache?.messages.set(payload.d.id, payload.d);
			this.emit('messageCreate', new Message(payload.d), shardId);
			break;
		}
		// ...one case per supported dispatch, table-driven rather than hand-written per event
	}
});
import { GatewayClient } from '@wolfstar/plugin-gateway';
import { createInMemoryCache } from '@wolfstar/plugin-cache';
import { GatewayIntentBits } from 'discord-api-types/v10';

const client = new GatewayClient({
	discordToken: process.env.DISCORD_TOKEN,
	intents: GatewayIntentBits.Guilds | GatewayIntentBits.GuildMessages,
	cache: createInMemoryCache(),
});

await client.load(); // inherited from Client: loads commands & interaction handlers, unchanged

client.on('messageCreate', (message) => {
	console.log(`${message.author.username}: ${message.content}`);
});

await client.connect();
await client.listen({ port: 8_080 }); // interactions webhook still works, unchanged

EventGatewayListener: file-based Gateway event pieces

@wolfstar/http-framework already loads Listener pieces from a listeners/ directory via client.load(), targeting an emitter (resolved either from a concrete Emitter or a container key, e.g. 'client') and an event name, with run(...) receiving whatever that event emits. Since GatewayClient extends Client, Gateway-derived events emitted with this.emit('messageCreate', …) land on the exact same emitter regular framework listeners already target — so @wolfstar/plugin-gateway doesn't need a second piece store, just a strongly-typed Listener subclass that pins emitter to the client and maps each event name to its Structure-typed arguments:

import { Listener, type Awaitable } from '@wolfstar/http-framework';
import type { Message, Guild, User } from './structures/index.js';

export interface GatewayEventMap {
	messageCreate: [message: Message];
	guildCreate: [guild: Guild];
	userUpdate: [oldUser: User | null, newUser: User];
	// ...one entry per dispatch this package builds a Structure + event for
}

export abstract class EventGatewayListener<Event extends keyof GatewayEventMap = keyof GatewayEventMap> extends Listener<
	Listener.Options & { event: Event }
> {
	public constructor(context: Listener.LoaderContext, options: { event: Event; once?: boolean }) {
		super(context, { ...options, emitter: 'client' });
	}

	public abstract override run(...args: GatewayEventMap[Event]): Awaitable<unknown>;
}

A consumer then gets exactly the same file-based, auto-discovered authoring experience as every other framework listener — client.load() picks these up for free, no separate registration call needed beyond enabling GatewayClient:

// listeners/log-messages.ts
import { EventGatewayListener } from '@wolfstar/plugin-gateway';

export class LogMessagesListener extends EventGatewayListener<'messageCreate'> {
	public constructor(context: EventGatewayListener.LoaderContext) {
		super(context, { event: 'messageCreate' });
	}

	public override run(message: Message) {
		console.log(`${message.author.username}: ${message.content}`);
	}
}

RegisterAsGatewayListener: decorator-based registration

@wolfstar/plugin-subcommands-advanced (already in this repo) sets the precedent for this ecosystem: it ships RegisterAsSubcommand/RegisterAsSubcommandGroup, class decorators that let a piece skip writing a constructor entirely — the same trick @sapphire/decorators' ApplyOptions uses upstream in the wider Sapphire ecosystem (a ClassDecorator that wraps the target class's constructor to inject the given options into its super() call). @wolfstar/plugin-gateway should follow the same in-repo convention rather than pull in @sapphire/decorators as a new dependency — EventGatewayListener already needs event to be strongly typed against GatewayEventMap, which a generic ApplyOptions<T> can't give us without an explicit type argument at every call site anyway:

export function RegisterAsGatewayListener<Event extends keyof GatewayEventMap>(
	event: Event,
	options?: { once?: boolean },
): ClassDecorator {
	return (target) =>
		class extends (target as typeof EventGatewayListener) {
			public constructor(context: Listener.LoaderContext) {
				super(context, { event, ...options });
			}
		} as unknown as typeof target;
}
// listeners/log-messages.ts
import { EventGatewayListener, RegisterAsGatewayListener } from '@wolfstar/plugin-gateway';
import type { Message } from '@wolfstar/plugin-gateway';

@RegisterAsGatewayListener('messageCreate')
export class LogMessagesListener extends EventGatewayListener<'messageCreate'> {
	public override run(message: Message) {
		console.log(`${message.author.username}: ${message.content}`);
	}
}

Both forms stay supported — the decorator is sugar over the constructor-based form above, not a replacement for it, exactly like ApplyOptions/RegisterAsSubcommand are sugar over calling super() by hand in their own ecosystems.

Problems

  • You opt in at construction time, not at runtime. Because GatewayClient extends Client rather than composing one, an existing bot already instantiated as new Client() can't gain Gateway support later without switching its constructor call to new GatewayClient(). A composition-based design (a GatewayPlugin bridged in via Client.use()) would avoid that, at the cost of the Managers needing to reach into an external Client instance instead of this. This RFC picks subclassing for the tighter integration and the more direct this.cache/this.users access patterns shown above — but it's a real trade-off, not a free lunch, and is the opposite of what discord.js#10983 chose upstream (it composes a protected core: CoreClient rather than extending). Given @wolfstar/http-framework only has one Client concept to begin with (unlike discord.js's several historical Client-shaped things), extension seems like the better fit here, but this deserves explicit sign-off before implementation.
  • Table-driven dispatch → Structure construction doesn't scale as hand-written code. The switch sketched above needs to become a generated or declaratively-defined mapping from GatewayDispatchEvents to { entityCache, createStructure, eventName } rather than one case per event written by hand — and that same table is what GatewayEventMap (for EventGatewayListener) needs to stay in sync with.
  • emitter: 'client' resolution. Listener.Options.emitter can be a container-key string resolved against @sapphire/pieces's container. We need to confirm the base Client already registers itself under that 'client' key on construction (so EventGatewayListener "just works" for any GatewayClient instance without extra wiring), rather than assuming it and finding out otherwise during implementation.
  • RegisterAsGatewayListener's exact mechanism needs to match RegisterAsSubcommand's, not just rhyme with it. The sketch above (subclassing and overriding the constructor) is the standard way to implement this kind of decorator without a dependency on @sapphire/decorators, but @wolfstar/plugin-subcommands-advanced already solved this exact problem once in this repo — RegisterAsGatewayListener should be implemented the same way RegisterAsSubcommand is, not just aim for the same developer experience, so the two don't drift into two different decorator idioms for the same framework.
  • Structure coverage. @discordjs/structures is itself still pre-1.0 and only covers a subset of entities upstream. We need to decide whether @wolfstar/plugin-gateway only ships Structures for what it actually needs (User, Guild, Channel, Message, …) and falls back to raw API types for anything else, at least for v1.
  • Single source of truth across interactions and Gateway. Since GatewayClient extends Client, an interaction payload's member/user fields and a Gateway-cached User need to resolve to consistent data. Do interaction handlers get upgraded to also read through client.users, or do they keep working against the raw interaction payload as today? Needs a decision so we don't end up with two divergent "current user state" views on the same object.
  • Naming. GatewayClient vs. something closer to the upstream PR's naming (ClientGateway, or nesting it as Client.Gateway) is a bikeshed worth having explicitly rather than silently picking one.
  • Interaction double-delivery. A bot that keeps its HTTP interactions endpoint and enables Gateway intents will, for some interaction types, also receive INTERACTION_CREATE over the Gateway. GatewayClient likely needs to drop INTERACTION_CREATE dispatches unconditionally rather than attempt de-duplication, but this needs confirming against actual Gateway behavior for interactions-endpoint apps.
  • Process model mismatch. @wolfstar/http-framework is designed to be comfortable in short-lived/serverless HTTP handlers; a Gateway connection is inherently long-lived and stateful. GatewayClient effectively requires a persistent-process deployment mode, a meaningfully different operational story from the rest of the framework. Does @wolfstar/plugin-gateway belong in this repository, or should it (and its cache companion) live in the stars-components monorepo next to @wolfstar/http-framework itself? Worth resolving before implementation starts.
  • Multi-process sharding. @discordjs/ws's WebSocketManager supports pluggable IShardingStrategy implementations for multi-process setups, but defaults to single-process. Proposing v1 only supports single-process sharding (matches most self-hosted wolfstar deployments), leaving multi-process as a follow-up.

Alternatives considered

As noted in stars-components#51, the alternatives are depending on Carbon directly, or maintaining a fully custom in-house Gateway client. Both were rejected for the same reason this RFC leans on @discordjs/ws and @discordjs/structures: Gateway session/resume/rate-limit handling and Discord entity modeling are fiddly to get right, already exist, and aren't where @wolfstar/http-framework should be spending its maintenance budget. A composition-based design (a plugin bridged onto an existing Client via lifecycle hooks, with a fully standalone Gateway-only client alongside it) was drafted for an earlier revision of this RFC and rejected in favor of the single GatewayClient extends Client shape above — see the "Problems" section for the trade-off.

Footnotes

Addendum: upstream review and implementation contract (September 2026)

The comments on discord.js#11426 support raw cache storage and Manager-owned Structure construction, while highlighting requirements that the sketch above leaves open. The companion cache RFC #55 owns storage; this issue owns dispatch and event semantics.

  • A cache miss must not silently suppress a Gateway event. Some delete dispatches contain only IDs. Define partial Structures or a documented raw fallback, make absent fields explicit in types, and specify how consumers fetch missing data. See upstream partials discussion and presence events after restart.
  • Separate cache-only lookup from REST fallback. Add an async fetch(id, { force?, cache? }) path where an endpoint exists, as proposed in #11426. State which entities cannot be fetched and ensure a no-op cache still works.
  • Preserve event order with async stores. Awaiting cache writes before emitting may reorder overlapping dispatch callbacks. Serialize within each guild/shard partition while allowing unrelated guilds to proceed independently. Surface queue depth, latency, timeout and failure. Upstream raised the interaction deadline concern.
  • Define old/new Structure semantics. Capture the old raw snapshot, merge a partial update without dropping fields, persist, then construct independent old and new Structures. State that a previously returned instance is not guaranteed to mutate. Upstream identity discussion.
  • Define contextual keys for members, voice states and reactions, and decide whether nested message author data is embedded or referenced. Upstream key discussion. Reconcile guild cache state after reconnect/resume; discord.js#11546 reports stale guilds after disconnection.
  • Await dispatch processing and surface cache failures through an error event or configured handler. Specify whether failure emits uncached data, retries, or stops the affected partition; coordinate this policy with RFC: Pluggable cache layer for @wolfstar/plugin-gateway (Cache, EntityCache, CachedManager) #55.

Suggested first implementation slice

  1. Support message create/update/delete, user update and guild create/delete with documented partial semantics; expose raw dispatch for unsupported structures.
  2. Verify inherited client-emitter resolution and the existing decorator implementation before treating either code sketch above as a guaranteed API.
  3. Test order with memory and delayed async stores, cache miss, remote failure, partial update, reconnect reconciliation and simultaneous HTTP interactions.

These are proposed acceptance criteria, not claims that upstream has settled its RFC.

Status and roadmap (updated 2026-09-25, after #112)

Implementation: #92 (@wolfstar/plugin-cache, see #55) and #93 (@wolfstar/plugin-gateway, stacked on #92). The RFC text above is kept as written; this section records what was decided while building it and what is still open. Each remaining phase below is meant to land as its own small or medium PR stacked on #93.

Decisions taken on the problems above

  • Extend vs compose: GatewayClient extends Client, name kept. The base Client sets container.client = this in its constructor, so emitter: 'client' works for EventGatewayListener with no extra wiring.
  • Table-driven dispatch: a single declarative DispatchHandlers table maps each dispatch to { event, before?, build }, type-checked against GatewayEventMap. Dispatches without an entry still go to the cache and to a raw event.
  • Decorator: RegisterAsGatewayListener copies the constructor-wrapping mechanism of RegisterAsSubcommand, plus a once option.
  • Interaction double-delivery: INTERACTION_CREATE is dropped unconditionally (it still shows up in raw).
  • Structures: they extend @discordjs/structures' Structure. The package does not export kData, kPatch or kClone, but creates them with Symbol.for("djs.structures.*"), so we get the same symbols from the global registry. Bitfields come from @discordjs/structures too. Its BitField.resolve returns number enum values as number and then fails mixing them with bigint bits, so every flags bitfield overrides resolve. Worth an upstream issue.
  • Layout: mirrors discord.js's @discordjs/next prototype: GatewayClient.ts, managers/, structures/ with mixins/, util/. Channels get one class per type composed with Mixin(), picked by a createChannel() factory.
  • Managers: users, guilds, channels (falls back to threads), threads, messages, members, roles. get reads the cache only, fetch falls back to REST and caches, refresh always hits REST.
  • Relations resolve through the cache. Every API payload goes through the manager's _add (discord.js's CachedManager#_add, asynchronous because the cache can be Redis), and structures get their relations from the cache when a manager builds them: message.author, message.guild, channel.guild, member.user, ... (feat: resolve gateway structure relations through the cache with _add #102, feat: resolve the guild of gateway structures from the cache #103). Structures still never hold the client. Relations discord.js reads from its cache but that need a lookup here (permissions, parents, owners) are fetch* methods.
  • Options: shardCount / shardIds follow @discordjs/ws instead of shards: number | number[] | 'auto'. @discordjs/ws and @discordjs/rest are re-exported as @wolfstar/plugin-gateway/ws and /rest.

Addendum criteria: where we are

Open questions

  • @discordjs/structures is only published as dev snapshots and requires Node.js >=24.17, while this package declares >=20. Raise engines, or document it?
  • Interaction handlers still read the raw interaction payload rather than client.users & co.
  • Does the package belong here or in stars-components (process model)?

Phases

  1. ✅ Cache package (feat: add @wolfstar/plugin-cache, a storage-agnostic entity cache #92, RFC: Pluggable cache layer for @wolfstar/plugin-gateway (Cache, EntityCache, CachedManager) #55).
  2. ✅ GatewayClient, dispatch table, first managers, channel classes and mixins, listener and decorator (feat: add @wolfstar/plugin-gateway with GatewayClient #93).
  3. 🔄 Structures and bitfields on top of @discordjs/structures, raw-data events (typingStart, channelPinsUpdate, webhooksUpdate, voiceServerUpdate).
  4. 🔄 Dispatch hardening (this issue's addendum): per-guild partitioned queue, timeout and stats, configurable cache-failure policy, fetch(id, { force, cache }), READY reconciliation (feat: partition gateway dispatches per guild and harden the pipeline #95), store side in feat: make plugin-cache Redis writes atomic and reads fail loudly #94. Left: a test with concurrent HTTP interactions, and the latency metric question.
  5. 🔄 Users, members and roles to discord.js parity: ClientUser (presence), GuildMemberRoleManager, role CRUD, permission computation (feat: bring gateway users, members and roles to discord.js parity #97).
  6. 🔄 Guild to parity (minus moderation), emoji, sticker and invite managers (feat: bring gateway guilds, emojis, stickers and invites to discord.js parity #98).
  7. 🔄 Messages: attachments, embeds, mentions, reactions, polls (feat: bring gateway messages, reactions and polls to discord.js parity #101); reaction and poll vote events, counted in the cache (feat: count reactions and poll votes in the cache and emit their gateway events #104). In between: _add and relations resolved from the cache (feat: resolve gateway structure relations through the cache with _add #102), guild on every guild structure (feat: resolve the guild of gateway structures from the cache #103).
  8. 🔄 Channel REST: edit, permission overwrites, permissionsFor, GuildChannelManager (feat: bring gateway channels and permission overwrites to discord.js parity #105); webhooks (feat: add gateway webhooks #106).
  9. 🔄 Threads: thread members, channel thread managers, forum posts, their events (feat: bring gateway threads to discord.js parity #107).
  10. 🔄 Voice states and presences, with their managers and events (feat: add gateway voice states and presences #108).
  11. 🔄 Moderation: bans, audit logs, auto moderation (feat: add gateway bans, audit logs, and auto moderation #109). Scheduled events, stage instances, soundboard (feat: add gateway scheduled events, stage instances, and soundboard sounds #110). Integrations, templates, welcome screen, widget, onboarding (feat: add gateway integrations, templates, welcome screens, widgets, and onboarding #111). Multi-process sharding in the separate @wolfstar/plugin-sharder package (feat: add @wolfstar/plugin-sharder, implementing the discord.js sharder RFC #112), after the discord.js sharder RFC.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions