Address review of exp_discord_sync

- DiscordRest and DiscordGateway are made in fromContext and passed to
  the constructor. Both read the token from config, and guildId is a
  getter over config, so the plugin has no nullable bot state.
- DiscordGateway is an EventEmitter and the plugin listens with bound
  methods (onGatewayReady, onGatewayDispatch, onGatewayFatalClose,
  onLinkChanged).
- Private members start with an underscore.
- DiscordGateway has an explicit state (stopped, connecting,
  identifying, ready, waiting) and _setState throws on a transition not
  in the table. Errors while handling a gateway message are logged so
  a failed assert can't take down the controller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-24 22:18:40 +00:00
1 parent cf968c02bb
commit e88cbf990f
4 files changed
+227 -125

No files matched your search

+50 -39
View File
@@ -4,7 +4,7 @@ import * as path from "node:path";
import type { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js"; import type { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
import * as messages from "./messages.js"; import * as messages from "./messages.js";
import { import {
DiscordApiError, DiscordGateway, DiscordRest, GuildMember, discordApi, discordGateway, gatewayIntents, DiscordApiError, DiscordGateway, DiscordRest, GuildMember, gatewayIntents,
} from "./discord.js"; } from "./discord.js";
const snowflake = /^\d{17,20}$/; const snowflake = /^\d{17,20}$/;
@@ -14,14 +14,6 @@ function roleKey(roleIds: Iterable<number>) {
} }
export class ControllerPlugin { export class ControllerPlugin {
/** Overridden by tests to point at a fake Discord */
apiBase = discordApi;
gatewayUrl = discordGateway;
rest?: DiscordRest;
gateway?: DiscordGateway;
guildId?: string;
/** Discord accounts waiting to be synced */ /** Discord accounts waiting to be synced */
pending = new Set<string>(); pending = new Set<string>();
syncAll = false; syncAll = false;
@@ -37,6 +29,8 @@ export class ControllerPlugin {
public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>, public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>,
/** Undefined if exp_discord_auth did not load, nothing is synced then */ /** Undefined if exp_discord_auth did not load, nothing is synced then */
public discordAuth: DiscordAuth | undefined, public discordAuth: DiscordAuth | undefined,
public rest: DiscordRest,
public gateway: DiscordGateway,
) {} ) {}
static async fromContext(context: ControllerPluginContext) { static async fromContext(context: ControllerPluginContext) {
@@ -49,7 +43,12 @@ export class ControllerPlugin {
)); ));
const discordAuth = await context.plugins.waitFor<DiscordAuth>("exp_discord_auth"); const discordAuth = await context.plugins.waitFor<DiscordAuth>("exp_discord_auth");
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, mappings, discordAuth); const token = () => controller.config.get("exp_discord_sync.bot_token") ?? "";
const rest = new DiscordRest(token);
const gateway = new DiscordGateway(token, gatewayIntents.GUILD_MEMBERS, context.logger);
const plugin = new ControllerPlugin(
controller, context.logger, context.plugin.name, mappings, discordAuth, rest, gateway,
);
plugin.sweepMappings(); plugin.sweepMappings();
for (const user of controller.users.values()) { for (const user of controller.users.values()) {
plugin.userRoles.set(user.id, roleKey(user.roleIds)); plugin.userRoles.set(user.id, roleKey(user.roleIds));
@@ -62,15 +61,19 @@ export class ControllerPlugin {
controller.handle(messages.GuildRoleListRequest, plugin.handleGuildRoleListRequest.bind(plugin)); controller.handle(messages.GuildRoleListRequest, plugin.handleGuildRoleListRequest.bind(plugin));
mappings.on("update", plugin.mappingsUpdated.bind(plugin)); mappings.on("update", plugin.mappingsUpdated.bind(plugin));
controller.roles.on("update", () => plugin.sweepMappings()); controller.roles.on("update", plugin.sweepMappings.bind(plugin));
controller.users.records.on("update", plugin.usersUpdated.bind(plugin)); controller.users.records.on("update", plugin.usersUpdated.bind(plugin));
const hooks = controller.hooks; const hooks = controller.hooks;
hooks.save.attach(plugin.name, plugin.onSave.bind(plugin)); hooks.save.attach(plugin.name, plugin.onSave.bind(plugin));
hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin)); hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin));
hooks.controllerConfigFieldChanged.attach(plugin.name, plugin.onControllerConfigFieldChanged.bind(plugin)); hooks.controllerConfigFieldChanged.attach(plugin.name, plugin.onControllerConfigFieldChanged.bind(plugin));
discordAuth?.hooks.linked.attach(plugin.name, (_playerName, discordUser) => plugin.queue(discordUser.id)); discordAuth?.hooks.linked.attach(plugin.name, plugin.onLinkChanged.bind(plugin));
discordAuth?.hooks.unlinked.attach(plugin.name, (_playerName, discordUser) => plugin.queue(discordUser.id)); discordAuth?.hooks.unlinked.attach(plugin.name, plugin.onLinkChanged.bind(plugin));
gateway.on("ready", plugin.onGatewayReady.bind(plugin));
gateway.on("dispatch", plugin.onGatewayDispatch.bind(plugin));
gateway.on("fatalClose", plugin.onGatewayFatalClose.bind(plugin));
plugin.connect(); plugin.connect();
return plugin; return plugin;
@@ -96,6 +99,13 @@ export class ControllerPlugin {
Discord connection Discord connection
*/ */
/** The configured guild, or undefined if the bot is not configured or can't sync */
get guildId() {
const token = this.controller.config.get("exp_discord_sync.bot_token");
const guildId = this.controller.config.get("exp_discord_sync.guild_id");
return token && guildId && this.discordAuth ? guildId : undefined;
}
connect() { connect() {
const token = this.controller.config.get("exp_discord_sync.bot_token"); const token = this.controller.config.get("exp_discord_sync.bot_token");
const guildId = this.controller.config.get("exp_discord_sync.guild_id"); const guildId = this.controller.config.get("exp_discord_sync.guild_id");
@@ -106,18 +116,27 @@ export class ControllerPlugin {
this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced"); this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced");
return; return;
} }
this.gateway.start();
}
disconnect() {
this.gateway.stop();
this.pending.clear();
this.syncAll = false;
}
this.guildId = guildId;
this.rest = new DiscordRest(token, this.apiBase);
this.gateway = new DiscordGateway(token, gatewayIntents.GUILD_MEMBERS, this.logger, {
// Joins are missed while disconnected, so every (re)connect syncs everyone // Joins are missed while disconnected, so every (re)connect syncs everyone
onReady: () => this.queueAll(), onGatewayReady() {
onDispatch: (type, data) => { this.queueAll();
}
onGatewayDispatch(type: string, data: any) {
if (type === "GUILD_MEMBER_ADD" && data.guild_id === this.guildId) { if (type === "GUILD_MEMBER_ADD" && data.guild_id === this.guildId) {
this.queue(data.user.id); this.queue(data.user.id);
} }
}, }
onFatalClose: (code, reason) => {
onGatewayFatalClose(code: number, reason: string) {
if (code === 4014) { if (code === 4014) {
this.logger.warn( this.logger.warn(
"The Discord bot is missing the Server Members intent, joining the server does not give roles" "The Discord bot is missing the Server Members intent, joining the server does not give roles"
@@ -126,18 +145,10 @@ export class ControllerPlugin {
} else { } else {
this.logger.error(`Discord gateway refused the bot with ${code}: ${reason}`); this.logger.error(`Discord gateway refused the bot with ${code}: ${reason}`);
} }
},
}, this.gatewayUrl);
this.gateway.start();
} }
disconnect() { onLinkChanged(_playerName: string, discordUser: { id: string }) {
this.gateway?.stop(); this.queue(discordUser.id);
this.gateway = undefined;
this.rest = undefined;
this.guildId = undefined;
this.pending.clear();
this.syncAll = false;
} }
/* /*
@@ -145,7 +156,7 @@ export class ControllerPlugin {
*/ */
queue(discordId: string) { queue(discordId: string) {
if (!this.rest) { if (!this.guildId) {
return; return;
} }
this.pending.add(discordId); this.pending.add(discordId);
@@ -153,7 +164,7 @@ export class ControllerPlugin {
} }
queueAll() { queueAll() {
if (!this.rest) { if (!this.guildId) {
return; return;
} }
this.syncAll = true; this.syncAll = true;
@@ -161,11 +172,11 @@ export class ControllerPlugin {
} }
drain() { drain() {
this.draining ??= this.processQueue().finally(() => { this.draining = undefined; }); this.draining ??= this._processQueue().finally(() => { this.draining = undefined; });
return this.draining; return this.draining;
} }
private async processQueue() { private async _processQueue() {
while (this.syncAll || this.pending.size) { while (this.syncAll || this.pending.size) {
if (this.syncAll) { if (this.syncAll) {
this.syncAll = false; this.syncAll = false;
@@ -221,11 +232,11 @@ export class ControllerPlugin {
async syncAccount(discordId: string) { async syncAccount(discordId: string) {
const managed = this.managedRoleIds(); const managed = this.managedRoleIds();
if (!this.rest || !this.guildId || !managed.size) { const guildId = this.guildId;
if (!guildId || !managed.size) {
return; return;
} }
const rest = this.rest; const rest = this.rest;
const guildId = this.guildId;
const member: GuildMember | undefined = await rest.getGuildMember(guildId, discordId); const member: GuildMember | undefined = await rest.getGuildMember(guildId, discordId);
if (!member) { if (!member) {
return; return;
@@ -256,7 +267,7 @@ export class ControllerPlugin {
} else { } else {
this.userRoles.set(user.id, key); this.userRoles.set(user.id, key);
} }
const link = this.rest ? this.discordAuth?.getLink(user.name) : undefined; const link = this.guildId ? this.discordAuth?.getLink(user.name) : undefined;
if (link) { if (link) {
this.queue(link.id); this.queue(link.id);
} }
@@ -306,10 +317,10 @@ export class ControllerPlugin {
} }
async handleGuildRoleListRequest() { async handleGuildRoleListRequest() {
if (!this.rest || !this.guildId) { const guildId = this.guildId;
if (!guildId) {
throw new lib.UnavailableError("The Discord bot is not configured"); throw new lib.UnavailableError("The Discord bot is not configured");
} }
const guildId = this.guildId;
const roles = await this.rest.getGuildRoles(guildId); const roles = await this.rest.getGuildRoles(guildId);
return roles return roles
// @everyone has the guild id, and integration roles can't be given by bots // @everyone has the guild id, and integration roles can't be given by bots
+108 -66
View File
@@ -1,4 +1,5 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { EventEmitter } from "node:events";
import { setTimeout as sleep } from "node:timers/promises"; import { setTimeout as sleep } from "node:timers/promises";
export const discordApi = "https://discord.com/api/v10"; export const discordApi = "https://discord.com/api/v10";
@@ -22,20 +23,21 @@ export class DiscordApiError extends Error {
export class DiscordRest { export class DiscordRest {
/** Requests wait until this time when Discord says a rate limit is used up */ /** Requests wait until this time when Discord says a rate limit is used up */
waitUntilMs = 0; waitUntilMs = 0;
private queue: Promise<unknown> = Promise.resolve(); private _queue: Promise<unknown> = Promise.resolve();
constructor( constructor(
private token: string, /** Read on every request so a new token applies right away */
private _token: () => string,
public baseUrl = discordApi, public baseUrl = discordApi,
) {} ) {}
request(method: string, route: string): Promise<unknown> { request(method: string, route: string): Promise<unknown> {
const result = this.queue.then(() => this.send(method, route)); const result = this._queue.then(() => this._send(method, route));
this.queue = result.catch(() => {}); this._queue = result.catch(() => {});
return result; return result;
} }
private async send(method: string, route: string) { private async _send(method: string, route: string) {
for (let attempt = 0; ; attempt++) { for (let attempt = 0; ; attempt++) {
const waitMs = this.waitUntilMs - Date.now(); const waitMs = this.waitUntilMs - Date.now();
if (waitMs > 0) { if (waitMs > 0) {
@@ -44,7 +46,7 @@ export class DiscordRest {
const response = await fetch(`${this.baseUrl}${route}`, { const response = await fetch(`${this.baseUrl}${route}`, {
method, method,
headers: { "Authorization": `Bot ${this.token}`, "User-Agent": userAgent }, headers: { "Authorization": `Bot ${this._token()}`, "User-Agent": userAgent },
}); });
if (response.headers.get("x-ratelimit-remaining") === "0") { if (response.headers.get("x-ratelimit-remaining") === "0") {
const resetAfter = Number(response.headers.get("x-ratelimit-reset-after")) || 0; const resetAfter = Number(response.headers.get("x-ratelimit-reset-after")) || 0;
@@ -97,127 +99,167 @@ export const fatalCloseCodes = new Set([4004, 4010, 4011, 4012, 4013, 4014]);
type GatewayPayload = { op: number, d: any, s: number | null, t: string | null }; type GatewayPayload = { op: number, d: any, s: number | null, t: string | null };
/**
* stopped: not started, stopped, or closed with a fatal code.
* connecting: socket open, waiting for Hello.
* identifying: identify sent, waiting for READY.
* ready: receiving dispatches.
* waiting: closed, reconnecting after a backoff.
*/
export type GatewayState = "stopped" | "connecting" | "identifying" | "ready" | "waiting";
const gatewayTransitions: Record<GatewayState, GatewayState[]> = {
stopped: ["connecting"],
connecting: ["identifying", "waiting", "stopped"],
identifying: ["ready", "waiting", "stopped"],
ready: ["waiting", "stopped"],
waiting: ["connecting", "stopped"],
};
export type GatewayEvents = {
ready: [],
dispatch: [type: string, data: any],
fatalClose: [code: number, reason: string],
};
/** /**
* Minimal Discord gateway connection which only receives dispatch events. * Minimal Discord gateway connection which only receives dispatch events.
* *
* It identifies again on every reconnect instead of resuming, so events sent * It identifies again on every reconnect instead of resuming, so events sent
* while disconnected are missed. onReady is the place to catch up on them. * while disconnected are missed. The ready event is the place to catch up on them.
*/ */
export class DiscordGateway { export class DiscordGateway extends EventEmitter<GatewayEvents> {
ws?: WebSocket; state: GatewayState = "stopped";
private heartbeatTimer?: ReturnType<typeof setTimeout>;
private reconnectTimer?: ReturnType<typeof setTimeout>;
private sequence: number | null = null;
private acked = true;
private stopped = false;
backoff = new lib.ExponentialBackoff({ base: 2, max: 60 }); backoff = new lib.ExponentialBackoff({ base: 2, max: 60 });
private _ws?: WebSocket;
private _heartbeatTimer?: ReturnType<typeof setTimeout>;
private _reconnectTimer?: ReturnType<typeof setTimeout>;
private _sequence: number | null = null;
private _acked = true;
constructor( constructor(
private token: string, /** Read on every identify so a new token applies on the next start */
private intents: number, private _token: () => string,
private logger: lib.Logger, private _intents: number,
public handlers: { private _logger: lib.Logger,
onReady?: () => void,
onDispatch?: (type: string, data: any) => void,
onFatalClose?: (code: number, reason: string) => void,
},
public url = discordGateway, public url = discordGateway,
) {} ) {
super();
}
start() { start() {
this.stopped = false; this._connect();
this.connect();
} }
stop() { stop() {
this.stopped = true; if (this.state === "stopped") {
clearTimeout(this.reconnectTimer); return;
this.close(1000); }
this._setState("stopped");
clearTimeout(this._reconnectTimer);
this._close(1000);
} }
private connect() { private _setState(next: GatewayState) {
if (!gatewayTransitions[this.state].includes(next)) {
throw new Error(`Invalid Discord gateway transition from ${this.state} to ${next}`);
}
this.state = next;
}
private _connect() {
this._setState("connecting");
const ws = new WebSocket(this.url); const ws = new WebSocket(this.url);
this.ws = ws; this._ws = ws;
this.acked = true; this._acked = true;
ws.addEventListener("message", event => this.receive(JSON.parse(String(event.data)))); ws.addEventListener("message", event => {
ws.addEventListener("close", event => this.closed(ws, event.code, event.reason)); try {
this._receive(JSON.parse(String(event.data)));
} catch (err: any) {
this._logger.error(`Discord gateway failed to handle a message:\n${err.stack}`);
}
});
ws.addEventListener("close", event => this._closed(ws, event.code, event.reason));
ws.addEventListener("error", () => {}); ws.addEventListener("error", () => {});
} }
private close(code: number) { private _close(code: number) {
clearTimeout(this.heartbeatTimer); clearTimeout(this._heartbeatTimer);
if (this.ws && this.ws.readyState <= WebSocket.OPEN) { if (this._ws && this._ws.readyState <= WebSocket.OPEN) {
this.ws.close(code); this._ws.close(code);
} }
} }
private send(op: number, d: unknown) { private _send(op: number, d: unknown) {
this.ws?.send(JSON.stringify({ op, d })); this._ws?.send(JSON.stringify({ op, d }));
} }
private heartbeat(intervalMs: number) { private _heartbeat(intervalMs: number) {
if (!this.acked) { if (!this._acked) {
this.logger.warn("Discord gateway stopped answering heartbeats, reconnecting"); this._logger.warn("Discord gateway stopped answering heartbeats, reconnecting");
this.close(4000); this._close(4000);
return; return;
} }
this.acked = false; this._acked = false;
this.send(1, this.sequence); this._send(1, this._sequence);
this.heartbeatTimer = setTimeout(() => this.heartbeat(intervalMs), intervalMs); this._heartbeatTimer = setTimeout(() => this._heartbeat(intervalMs), intervalMs);
} }
private receive(payload: GatewayPayload) { private _receive(payload: GatewayPayload) {
if (payload.s !== null && payload.s !== undefined) { if (payload.s !== null && payload.s !== undefined) {
this.sequence = payload.s; this._sequence = payload.s;
} }
switch (payload.op) { switch (payload.op) {
case 10: { // Hello case 10: { // Hello
this._setState("identifying");
const intervalMs = payload.d.heartbeat_interval; const intervalMs = payload.d.heartbeat_interval;
this.heartbeatTimer = setTimeout(() => this.heartbeat(intervalMs), intervalMs * Math.random()); this._heartbeatTimer = setTimeout(() => this._heartbeat(intervalMs), intervalMs * Math.random());
this.send(2, { this._send(2, {
token: this.token, token: this._token(),
intents: this.intents, intents: this._intents,
properties: { os: process.platform, browser: "exp_discord_sync", device: "exp_discord_sync" }, properties: { os: process.platform, browser: "exp_discord_sync", device: "exp_discord_sync" },
}); });
break; break;
} }
case 11: // Heartbeat ACK case 11: // Heartbeat ACK
this.acked = true; this._acked = true;
break; break;
case 1: // Heartbeat request case 1: // Heartbeat request
this.send(1, this.sequence); this._send(1, this._sequence);
break; break;
case 7: // Reconnect case 7: // Reconnect
case 9: // Invalid session case 9: // Invalid session
this.close(4000); this._close(4000);
break; break;
case 0: // Dispatch case 0: // Dispatch
if (payload.t === "READY") { if (payload.t === "READY") {
this.handlers.onReady?.(); this._setState("ready");
this.emit("ready");
} else { } else {
this.handlers.onDispatch?.(payload.t!, payload.d); this.emit("dispatch", payload.t!, payload.d);
} }
break; break;
default: default:
} }
} }
private closed(ws: WebSocket, code: number, reason: string) { private _closed(ws: WebSocket, code: number, reason: string) {
if (ws !== this.ws) { if (ws !== this._ws) {
return; return;
} }
clearTimeout(this.heartbeatTimer); clearTimeout(this._heartbeatTimer);
this.sequence = null; this._sequence = null;
if (this.stopped) { if (this.state === "stopped") {
return; return;
} }
if (fatalCloseCodes.has(code)) { if (fatalCloseCodes.has(code)) {
this.stopped = true; this._setState("stopped");
this.handlers.onFatalClose?.(code, reason); this.emit("fatalClose", code, reason);
return; return;
} }
this._setState("waiting");
const delayMs = this.backoff.delay(); const delayMs = this.backoff.delay();
this.logger.verbose(`Discord gateway closed with ${code}, reconnecting in ${Math.round(delayMs / 1e3)}s`); this._logger.verbose(`Discord gateway closed with ${code}, reconnecting in ${Math.round(delayMs / 1e3)}s`);
this.reconnectTimer = setTimeout(() => this.connect(), delayMs); this._reconnectTimer = setTimeout(() => this._connect(), delayMs);
} }
} }
+5 -5
View File
@@ -79,11 +79,11 @@ async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {})
plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids)); plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids));
} }
plugin.apiBase = fake.apiBase; plugin.rest.baseUrl = fake.apiBase;
plugin.gatewayUrl = fake.gatewayUrl; plugin.gateway.url = fake.gatewayUrl;
controller.config.set("exp_discord_sync.bot_token", "token"); controller.config.set("exp_discord_sync.bot_token", "token");
controller.config.set("exp_discord_sync.guild_id", guildId); controller.config.set("exp_discord_sync.guild_id", guildId);
if (!plugin.gateway) { if (plugin.gateway.state === "stopped") {
plugin.connect(); plugin.connect();
} }
return { plugin, auth, controller, fake }; return { plugin, auth, controller, fake };
@@ -206,7 +206,7 @@ t.test("syncing", t2 => {
setRoles(controller, "Player1", [5]); setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1"); auth.linkAccount(alice, "Player1");
await until(() => rolesOf(fake, alice.id).length === 1); await until(() => rolesOf(fake, alice.id).length === 1);
t3.ok(plugin.rest, "rest is kept"); t3.equal(plugin.gateway.state, "stopped", "gateway gave up, REST carries on");
t3.ok(warnings.some(msg => /missing the Server Members intent/.test(msg))); t3.ok(warnings.some(msg => /missing the Server Members intent/.test(msg)));
}); });
@@ -241,7 +241,7 @@ t.test("syncing", t2 => {
}); });
const [plugin] = loaded.values(); const [plugin] = loaded.values();
t3.equal(plugin.discordAuth, undefined); t3.equal(plugin.discordAuth, undefined);
t3.equal(plugin.gateway, undefined, "does not connect"); t3.equal(plugin.gateway.state, "stopped", "does not connect");
t3.ok(warnings.some(msg => /exp_discord_auth is not loaded/.test(msg))); t3.ok(warnings.some(msg => /exp_discord_auth is not loaded/.test(msg)));
}); });
t2.end(); t2.end();
+64 -15
View File
@@ -13,13 +13,13 @@ t.test("class DiscordRest", async t2 => {
fake.members.set(memberId, new Set()); fake.members.set(memberId, new Set());
t2.test(".getGuildMember() returns the member, or undefined when not in the guild", async t3 => { t2.test(".getGuildMember() returns the member, or undefined when not in the guild", async t3 => {
const rest = new DiscordRest("token", fake.apiBase); const rest = new DiscordRest(() => "token", fake.apiBase);
t3.same(await rest.getGuildMember(guildId, memberId), { user: { id: memberId }, roles: [] }); t3.same(await rest.getGuildMember(guildId, memberId), { user: { id: memberId }, roles: [] });
t3.equal(await rest.getGuildMember(guildId, "1"), undefined); t3.equal(await rest.getGuildMember(guildId, "1"), undefined);
}); });
t2.test(".addMemberRole() and .removeMemberRole() change roles", async t3 => { t2.test(".addMemberRole() and .removeMemberRole() change roles", async t3 => {
const rest = new DiscordRest("token", fake.apiBase); const rest = new DiscordRest(() => "token", fake.apiBase);
await rest.addMemberRole(guildId, memberId, roleId); await rest.addMemberRole(guildId, memberId, roleId);
t3.same([...fake.members.get(memberId)], [roleId]); t3.same([...fake.members.get(memberId)], [roleId]);
await rest.removeMemberRole(guildId, memberId, roleId); await rest.removeMemberRole(guildId, memberId, roleId);
@@ -27,7 +27,7 @@ t.test("class DiscordRest", async t2 => {
}); });
t2.test("waits out 429 responses and retries", async t3 => { t2.test("waits out 429 responses and retries", async t3 => {
const rest = new DiscordRest("token", fake.apiBase); const rest = new DiscordRest(() => "token", fake.apiBase);
fake.requests.length = 0; fake.requests.length = 0;
fake.rateLimit = 2; fake.rateLimit = 2;
const start = Date.now(); const start = Date.now();
@@ -37,21 +37,21 @@ t.test("class DiscordRest", async t2 => {
}); });
t2.test("gives up after repeated 429 responses", async t3 => { t2.test("gives up after repeated 429 responses", async t3 => {
const rest = new DiscordRest("token", fake.apiBase); const rest = new DiscordRest(() => "token", fake.apiBase);
fake.rateLimit = 6; fake.rateLimit = 6;
await t3.rejects(rest.getGuildRoles(guildId), { status: 429 }); await t3.rejects(rest.getGuildRoles(guildId), { status: 429 });
fake.rateLimit = 0; fake.rateLimit = 0;
}); });
t2.test("throws DiscordApiError with the status", async t3 => { t2.test("throws DiscordApiError with the status", async t3 => {
const rest = new DiscordRest("wrong", fake.apiBase); const rest = new DiscordRest(() => "wrong", fake.apiBase);
const err = await rest.getGuildRoles(guildId).catch(e => e); const err = await rest.getGuildRoles(guildId).catch(e => e);
t3.ok(err instanceof DiscordApiError); t3.ok(err instanceof DiscordApiError);
t3.equal(err.status, 401); t3.equal(err.status, 401);
}); });
t2.test("sends one request at a time", async t3 => { t2.test("sends one request at a time", async t3 => {
const rest = new DiscordRest("token", fake.apiBase); const rest = new DiscordRest(() => "token", fake.apiBase);
fake.requests.length = 0; fake.requests.length = 0;
fake.rateLimit = 1; fake.rateLimit = 1;
await Promise.all([rest.getGuildRoles(guildId), rest.getGuildMember(guildId, memberId)]); await Promise.all([rest.getGuildRoles(guildId), rest.getGuildMember(guildId, memberId)]);
@@ -68,10 +68,9 @@ t.test("class DiscordGateway", async t2 => {
const fake = await startFakeDiscord(); const fake = await startFakeDiscord();
t3.teardown(fake.close); t3.teardown(fake.close);
const events = []; const events = [];
const gateway = new DiscordGateway("token", gatewayIntents.GUILD_MEMBERS, logger, { const gateway = new DiscordGateway(() => "token", gatewayIntents.GUILD_MEMBERS, logger, fake.gatewayUrl);
onReady: () => events.push("ready"), gateway.on("ready", () => events.push("ready"));
onDispatch: (type, data) => events.push([type, data]), gateway.on("dispatch", (type, data) => events.push([type, data]));
}, fake.gatewayUrl);
t3.teardown(() => gateway.stop()); t3.teardown(() => gateway.stop());
gateway.start(); gateway.start();
await until(() => events.length); await until(() => events.length);
@@ -86,7 +85,8 @@ t.test("class DiscordGateway", async t2 => {
const fake = await startFakeDiscord(); const fake = await startFakeDiscord();
t3.teardown(fake.close); t3.teardown(fake.close);
let ready = 0; let ready = 0;
const gateway = new DiscordGateway("token", 0, logger, { onReady: () => { ready += 1; } }, fake.gatewayUrl); const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.on("ready", () => { ready += 1; });
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 }); gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
t3.teardown(() => gateway.stop()); t3.teardown(() => gateway.stop());
gateway.start(); gateway.start();
@@ -102,13 +102,13 @@ t.test("class DiscordGateway", async t2 => {
const fake = await startFakeDiscord({ closeCode: 4014 }); const fake = await startFakeDiscord({ closeCode: 4014 });
t3.teardown(fake.close); t3.teardown(fake.close);
let closed; let closed;
const gateway = new DiscordGateway("token", 0, logger, { const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
onFatalClose: (code, reason) => { closed = { code, reason }; }, gateway.on("fatalClose", (code, reason) => { closed = { code, reason }; });
}, fake.gatewayUrl);
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 }); gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
gateway.start(); gateway.start();
await until(() => closed); await until(() => closed);
t3.same(closed, { code: 4014, reason: "closed by fake" }); t3.same(closed, { code: 4014, reason: "closed by fake" });
t3.equal(gateway.state, "stopped");
await new Promise(resolve => setTimeout(resolve, 100)); await new Promise(resolve => setTimeout(resolve, 100));
t3.equal(fake.identifies.length, 1, "did not reconnect"); t3.equal(fake.identifies.length, 1, "did not reconnect");
}); });
@@ -117,7 +117,8 @@ t.test("class DiscordGateway", async t2 => {
const fake = await startFakeDiscord(); const fake = await startFakeDiscord();
t3.teardown(fake.close); t3.teardown(fake.close);
let ready = 0; let ready = 0;
const gateway = new DiscordGateway("token", 0, logger, { onReady: () => { ready += 1; } }, fake.gatewayUrl); const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.on("ready", () => { ready += 1; });
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 }); gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
gateway.start(); gateway.start();
await until(() => ready === 1); await until(() => ready === 1);
@@ -125,5 +126,53 @@ t.test("class DiscordGateway", async t2 => {
await until(() => fake.sockets.size === 0); await until(() => fake.sockets.size === 0);
await new Promise(resolve => setTimeout(resolve, 100)); await new Promise(resolve => setTimeout(resolve, 100));
t3.equal(fake.identifies.length, 1); t3.equal(fake.identifies.length, 1);
t3.equal(gateway.state, "stopped");
});
t2.test("goes through the states in order", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
t3.teardown(() => gateway.stop());
const states = [gateway.state];
const setState = gateway._setState;
gateway._setState = function(next) {
setState.call(this, next);
states.push(next);
};
gateway.start();
await until(() => gateway.state === "ready");
for (const ws of fake.sockets) {
ws.terminate();
}
await until(() => states.length === 8);
gateway.stop();
t3.same(states, [
"stopped", "connecting", "identifying", "ready", "waiting", "connecting", "identifying", "ready", "stopped",
]);
});
t2.test("asserts on invalid transitions", async t3 => {
const gateway = new DiscordGateway(() => "token", 0, logger, "ws://127.0.0.1:1");
t3.throws(() => gateway._setState("ready"), /from stopped to ready/);
t3.equal(gateway.state, "stopped");
gateway.stop();
t3.equal(gateway.state, "stopped", "stopping while stopped does nothing");
});
t2.test("a message in the wrong state is logged, not thrown", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
const errors = [];
const errorLogger = { ...logger, error: msg => errors.push(msg) };
const gateway = new DiscordGateway(() => "token", 0, errorLogger, fake.gatewayUrl);
t3.teardown(() => gateway.stop());
gateway.start();
await until(() => gateway.state === "ready");
fake.dispatch("READY", {});
await until(() => errors.length);
t3.match(errors[0], /from ready to ready/);
t3.equal(gateway.state, "ready");
}); });
}); });