mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-26 15:47:13 +09:00
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:
1 parent
cf968c02bb
commit
e88cbf990f
4 files changed
+236
-134
No files matched your search
@@ -4,7 +4,7 @@ import * as path from "node:path";
|
||||
import type { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
|
||||
import * as messages from "./messages.js";
|
||||
import {
|
||||
DiscordApiError, DiscordGateway, DiscordRest, GuildMember, discordApi, discordGateway, gatewayIntents,
|
||||
DiscordApiError, DiscordGateway, DiscordRest, GuildMember, gatewayIntents,
|
||||
} from "./discord.js";
|
||||
|
||||
const snowflake = /^\d{17,20}$/;
|
||||
@@ -14,14 +14,6 @@ function roleKey(roleIds: Iterable<number>) {
|
||||
}
|
||||
|
||||
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 */
|
||||
pending = new Set<string>();
|
||||
syncAll = false;
|
||||
@@ -37,6 +29,8 @@ export class ControllerPlugin {
|
||||
public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>,
|
||||
/** Undefined if exp_discord_auth did not load, nothing is synced then */
|
||||
public discordAuth: DiscordAuth | undefined,
|
||||
public rest: DiscordRest,
|
||||
public gateway: DiscordGateway,
|
||||
) {}
|
||||
|
||||
static async fromContext(context: ControllerPluginContext) {
|
||||
@@ -49,7 +43,12 @@ export class ControllerPlugin {
|
||||
));
|
||||
|
||||
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();
|
||||
for (const user of controller.users.values()) {
|
||||
plugin.userRoles.set(user.id, roleKey(user.roleIds));
|
||||
@@ -62,15 +61,19 @@ export class ControllerPlugin {
|
||||
controller.handle(messages.GuildRoleListRequest, plugin.handleGuildRoleListRequest.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));
|
||||
|
||||
const hooks = controller.hooks;
|
||||
hooks.save.attach(plugin.name, plugin.onSave.bind(plugin));
|
||||
hooks.shutdown.attach(plugin.name, plugin.onShutdown.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.unlinked.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, 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();
|
||||
return plugin;
|
||||
@@ -96,6 +99,13 @@ export class ControllerPlugin {
|
||||
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() {
|
||||
const token = this.controller.config.get("exp_discord_sync.bot_token");
|
||||
const guildId = this.controller.config.get("exp_discord_sync.guild_id");
|
||||
@@ -106,46 +116,47 @@ export class ControllerPlugin {
|
||||
this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced");
|
||||
return;
|
||||
}
|
||||
|
||||
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
|
||||
onReady: () => this.queueAll(),
|
||||
onDispatch: (type, data) => {
|
||||
if (type === "GUILD_MEMBER_ADD" && data.guild_id === this.guildId) {
|
||||
this.queue(data.user.id);
|
||||
}
|
||||
},
|
||||
onFatalClose: (code, reason) => {
|
||||
if (code === 4014) {
|
||||
this.logger.warn(
|
||||
"The Discord bot is missing the Server Members intent, joining the server does not give roles"
|
||||
);
|
||||
this.queueAll();
|
||||
} else {
|
||||
this.logger.error(`Discord gateway refused the bot with ${code}: ${reason}`);
|
||||
}
|
||||
},
|
||||
}, this.gatewayUrl);
|
||||
this.gateway.start();
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.gateway?.stop();
|
||||
this.gateway = undefined;
|
||||
this.rest = undefined;
|
||||
this.guildId = undefined;
|
||||
this.gateway.stop();
|
||||
this.pending.clear();
|
||||
this.syncAll = false;
|
||||
}
|
||||
|
||||
// Joins are missed while disconnected, so every (re)connect syncs everyone
|
||||
onGatewayReady() {
|
||||
this.queueAll();
|
||||
}
|
||||
|
||||
onGatewayDispatch(type: string, data: any) {
|
||||
if (type === "GUILD_MEMBER_ADD" && data.guild_id === this.guildId) {
|
||||
this.queue(data.user.id);
|
||||
}
|
||||
}
|
||||
|
||||
onGatewayFatalClose(code: number, reason: string) {
|
||||
if (code === 4014) {
|
||||
this.logger.warn(
|
||||
"The Discord bot is missing the Server Members intent, joining the server does not give roles"
|
||||
);
|
||||
this.queueAll();
|
||||
} else {
|
||||
this.logger.error(`Discord gateway refused the bot with ${code}: ${reason}`);
|
||||
}
|
||||
}
|
||||
|
||||
onLinkChanged(_playerName: string, discordUser: { id: string }) {
|
||||
this.queue(discordUser.id);
|
||||
}
|
||||
|
||||
/*
|
||||
Syncing
|
||||
*/
|
||||
|
||||
queue(discordId: string) {
|
||||
if (!this.rest) {
|
||||
if (!this.guildId) {
|
||||
return;
|
||||
}
|
||||
this.pending.add(discordId);
|
||||
@@ -153,7 +164,7 @@ export class ControllerPlugin {
|
||||
}
|
||||
|
||||
queueAll() {
|
||||
if (!this.rest) {
|
||||
if (!this.guildId) {
|
||||
return;
|
||||
}
|
||||
this.syncAll = true;
|
||||
@@ -161,11 +172,11 @@ export class ControllerPlugin {
|
||||
}
|
||||
|
||||
drain() {
|
||||
this.draining ??= this.processQueue().finally(() => { this.draining = undefined; });
|
||||
this.draining ??= this._processQueue().finally(() => { this.draining = undefined; });
|
||||
return this.draining;
|
||||
}
|
||||
|
||||
private async processQueue() {
|
||||
private async _processQueue() {
|
||||
while (this.syncAll || this.pending.size) {
|
||||
if (this.syncAll) {
|
||||
this.syncAll = false;
|
||||
@@ -221,11 +232,11 @@ export class ControllerPlugin {
|
||||
|
||||
async syncAccount(discordId: string) {
|
||||
const managed = this.managedRoleIds();
|
||||
if (!this.rest || !this.guildId || !managed.size) {
|
||||
const guildId = this.guildId;
|
||||
if (!guildId || !managed.size) {
|
||||
return;
|
||||
}
|
||||
const rest = this.rest;
|
||||
const guildId = this.guildId;
|
||||
const member: GuildMember | undefined = await rest.getGuildMember(guildId, discordId);
|
||||
if (!member) {
|
||||
return;
|
||||
@@ -256,7 +267,7 @@ export class ControllerPlugin {
|
||||
} else {
|
||||
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) {
|
||||
this.queue(link.id);
|
||||
}
|
||||
@@ -306,10 +317,10 @@ export class ControllerPlugin {
|
||||
}
|
||||
|
||||
async handleGuildRoleListRequest() {
|
||||
if (!this.rest || !this.guildId) {
|
||||
const guildId = this.guildId;
|
||||
if (!guildId) {
|
||||
throw new lib.UnavailableError("The Discord bot is not configured");
|
||||
}
|
||||
const guildId = this.guildId;
|
||||
const roles = await this.rest.getGuildRoles(guildId);
|
||||
return roles
|
||||
// @everyone has the guild id, and integration roles can't be given by bots
|
||||
|
||||
+108
-66
@@ -1,4 +1,5 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
|
||||
export const discordApi = "https://discord.com/api/v10";
|
||||
@@ -22,20 +23,21 @@ export class DiscordApiError extends Error {
|
||||
export class DiscordRest {
|
||||
/** Requests wait until this time when Discord says a rate limit is used up */
|
||||
waitUntilMs = 0;
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private _queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
constructor(
|
||||
private token: string,
|
||||
/** Read on every request so a new token applies right away */
|
||||
private _token: () => string,
|
||||
public baseUrl = discordApi,
|
||||
) {}
|
||||
|
||||
request(method: string, route: string): Promise<unknown> {
|
||||
const result = this.queue.then(() => this.send(method, route));
|
||||
this.queue = result.catch(() => {});
|
||||
const result = this._queue.then(() => this._send(method, route));
|
||||
this._queue = result.catch(() => {});
|
||||
return result;
|
||||
}
|
||||
|
||||
private async send(method: string, route: string) {
|
||||
private async _send(method: string, route: string) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const waitMs = this.waitUntilMs - Date.now();
|
||||
if (waitMs > 0) {
|
||||
@@ -44,7 +46,7 @@ export class DiscordRest {
|
||||
|
||||
const response = await fetch(`${this.baseUrl}${route}`, {
|
||||
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") {
|
||||
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 };
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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 {
|
||||
ws?: WebSocket;
|
||||
private heartbeatTimer?: ReturnType<typeof setTimeout>;
|
||||
private reconnectTimer?: ReturnType<typeof setTimeout>;
|
||||
private sequence: number | null = null;
|
||||
private acked = true;
|
||||
private stopped = false;
|
||||
export class DiscordGateway extends EventEmitter<GatewayEvents> {
|
||||
state: GatewayState = "stopped";
|
||||
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(
|
||||
private token: string,
|
||||
private intents: number,
|
||||
private logger: lib.Logger,
|
||||
public handlers: {
|
||||
onReady?: () => void,
|
||||
onDispatch?: (type: string, data: any) => void,
|
||||
onFatalClose?: (code: number, reason: string) => void,
|
||||
},
|
||||
/** Read on every identify so a new token applies on the next start */
|
||||
private _token: () => string,
|
||||
private _intents: number,
|
||||
private _logger: lib.Logger,
|
||||
public url = discordGateway,
|
||||
) {}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
start() {
|
||||
this.stopped = false;
|
||||
this.connect();
|
||||
this._connect();
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.stopped = true;
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.close(1000);
|
||||
if (this.state === "stopped") {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
this.ws = ws;
|
||||
this.acked = true;
|
||||
ws.addEventListener("message", event => this.receive(JSON.parse(String(event.data))));
|
||||
ws.addEventListener("close", event => this.closed(ws, event.code, event.reason));
|
||||
this._ws = ws;
|
||||
this._acked = true;
|
||||
ws.addEventListener("message", event => {
|
||||
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", () => {});
|
||||
}
|
||||
|
||||
private close(code: number) {
|
||||
clearTimeout(this.heartbeatTimer);
|
||||
if (this.ws && this.ws.readyState <= WebSocket.OPEN) {
|
||||
this.ws.close(code);
|
||||
private _close(code: number) {
|
||||
clearTimeout(this._heartbeatTimer);
|
||||
if (this._ws && this._ws.readyState <= WebSocket.OPEN) {
|
||||
this._ws.close(code);
|
||||
}
|
||||
}
|
||||
|
||||
private send(op: number, d: unknown) {
|
||||
this.ws?.send(JSON.stringify({ op, d }));
|
||||
private _send(op: number, d: unknown) {
|
||||
this._ws?.send(JSON.stringify({ op, d }));
|
||||
}
|
||||
|
||||
private heartbeat(intervalMs: number) {
|
||||
if (!this.acked) {
|
||||
this.logger.warn("Discord gateway stopped answering heartbeats, reconnecting");
|
||||
this.close(4000);
|
||||
private _heartbeat(intervalMs: number) {
|
||||
if (!this._acked) {
|
||||
this._logger.warn("Discord gateway stopped answering heartbeats, reconnecting");
|
||||
this._close(4000);
|
||||
return;
|
||||
}
|
||||
this.acked = false;
|
||||
this.send(1, this.sequence);
|
||||
this.heartbeatTimer = setTimeout(() => this.heartbeat(intervalMs), intervalMs);
|
||||
this._acked = false;
|
||||
this._send(1, this._sequence);
|
||||
this._heartbeatTimer = setTimeout(() => this._heartbeat(intervalMs), intervalMs);
|
||||
}
|
||||
|
||||
private receive(payload: GatewayPayload) {
|
||||
private _receive(payload: GatewayPayload) {
|
||||
if (payload.s !== null && payload.s !== undefined) {
|
||||
this.sequence = payload.s;
|
||||
this._sequence = payload.s;
|
||||
}
|
||||
switch (payload.op) {
|
||||
case 10: { // Hello
|
||||
this._setState("identifying");
|
||||
const intervalMs = payload.d.heartbeat_interval;
|
||||
this.heartbeatTimer = setTimeout(() => this.heartbeat(intervalMs), intervalMs * Math.random());
|
||||
this.send(2, {
|
||||
token: this.token,
|
||||
intents: this.intents,
|
||||
this._heartbeatTimer = setTimeout(() => this._heartbeat(intervalMs), intervalMs * Math.random());
|
||||
this._send(2, {
|
||||
token: this._token(),
|
||||
intents: this._intents,
|
||||
properties: { os: process.platform, browser: "exp_discord_sync", device: "exp_discord_sync" },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 11: // Heartbeat ACK
|
||||
this.acked = true;
|
||||
this._acked = true;
|
||||
break;
|
||||
case 1: // Heartbeat request
|
||||
this.send(1, this.sequence);
|
||||
this._send(1, this._sequence);
|
||||
break;
|
||||
case 7: // Reconnect
|
||||
case 9: // Invalid session
|
||||
this.close(4000);
|
||||
this._close(4000);
|
||||
break;
|
||||
case 0: // Dispatch
|
||||
if (payload.t === "READY") {
|
||||
this.handlers.onReady?.();
|
||||
this._setState("ready");
|
||||
this.emit("ready");
|
||||
} else {
|
||||
this.handlers.onDispatch?.(payload.t!, payload.d);
|
||||
this.emit("dispatch", payload.t!, payload.d);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
private closed(ws: WebSocket, code: number, reason: string) {
|
||||
if (ws !== this.ws) {
|
||||
private _closed(ws: WebSocket, code: number, reason: string) {
|
||||
if (ws !== this._ws) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(this.heartbeatTimer);
|
||||
this.sequence = null;
|
||||
if (this.stopped) {
|
||||
clearTimeout(this._heartbeatTimer);
|
||||
this._sequence = null;
|
||||
if (this.state === "stopped") {
|
||||
return;
|
||||
}
|
||||
if (fatalCloseCodes.has(code)) {
|
||||
this.stopped = true;
|
||||
this.handlers.onFatalClose?.(code, reason);
|
||||
this._setState("stopped");
|
||||
this.emit("fatalClose", code, reason);
|
||||
return;
|
||||
}
|
||||
this._setState("waiting");
|
||||
const delayMs = this.backoff.delay();
|
||||
this.logger.verbose(`Discord gateway closed with ${code}, reconnecting in ${Math.round(delayMs / 1e3)}s`);
|
||||
this.reconnectTimer = setTimeout(() => this.connect(), delayMs);
|
||||
this._logger.verbose(`Discord gateway closed with ${code}, reconnecting in ${Math.round(delayMs / 1e3)}s`);
|
||||
this._reconnectTimer = setTimeout(() => this._connect(), delayMs);
|
||||
}
|
||||
}
|
||||
@@ -79,11 +79,11 @@ async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {})
|
||||
plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids));
|
||||
}
|
||||
|
||||
plugin.apiBase = fake.apiBase;
|
||||
plugin.gatewayUrl = fake.gatewayUrl;
|
||||
plugin.rest.baseUrl = fake.apiBase;
|
||||
plugin.gateway.url = fake.gatewayUrl;
|
||||
controller.config.set("exp_discord_sync.bot_token", "token");
|
||||
controller.config.set("exp_discord_sync.guild_id", guildId);
|
||||
if (!plugin.gateway) {
|
||||
if (plugin.gateway.state === "stopped") {
|
||||
plugin.connect();
|
||||
}
|
||||
return { plugin, auth, controller, fake };
|
||||
@@ -206,7 +206,7 @@ t.test("syncing", t2 => {
|
||||
setRoles(controller, "Player1", [5]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
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)));
|
||||
});
|
||||
|
||||
@@ -241,7 +241,7 @@ t.test("syncing", t2 => {
|
||||
});
|
||||
const [plugin] = loaded.values();
|
||||
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)));
|
||||
});
|
||||
t2.end();
|
||||
|
||||
@@ -13,13 +13,13 @@ t.test("class DiscordRest", async t2 => {
|
||||
fake.members.set(memberId, new Set());
|
||||
|
||||
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.equal(await rest.getGuildMember(guildId, "1"), undefined);
|
||||
});
|
||||
|
||||
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);
|
||||
t3.same([...fake.members.get(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 => {
|
||||
const rest = new DiscordRest("token", fake.apiBase);
|
||||
const rest = new DiscordRest(() => "token", fake.apiBase);
|
||||
fake.requests.length = 0;
|
||||
fake.rateLimit = 2;
|
||||
const start = Date.now();
|
||||
@@ -37,21 +37,21 @@ t.test("class DiscordRest", async t2 => {
|
||||
});
|
||||
|
||||
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;
|
||||
await t3.rejects(rest.getGuildRoles(guildId), { status: 429 });
|
||||
fake.rateLimit = 0;
|
||||
});
|
||||
|
||||
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);
|
||||
t3.ok(err instanceof DiscordApiError);
|
||||
t3.equal(err.status, 401);
|
||||
});
|
||||
|
||||
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.rateLimit = 1;
|
||||
await Promise.all([rest.getGuildRoles(guildId), rest.getGuildMember(guildId, memberId)]);
|
||||
@@ -68,10 +68,9 @@ t.test("class DiscordGateway", async t2 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t3.teardown(fake.close);
|
||||
const events = [];
|
||||
const gateway = new DiscordGateway("token", gatewayIntents.GUILD_MEMBERS, logger, {
|
||||
onReady: () => events.push("ready"),
|
||||
onDispatch: (type, data) => events.push([type, data]),
|
||||
}, fake.gatewayUrl);
|
||||
const gateway = new DiscordGateway(() => "token", gatewayIntents.GUILD_MEMBERS, logger, fake.gatewayUrl);
|
||||
gateway.on("ready", () => events.push("ready"));
|
||||
gateway.on("dispatch", (type, data) => events.push([type, data]));
|
||||
t3.teardown(() => gateway.stop());
|
||||
gateway.start();
|
||||
await until(() => events.length);
|
||||
@@ -86,7 +85,8 @@ t.test("class DiscordGateway", async t2 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t3.teardown(fake.close);
|
||||
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 });
|
||||
t3.teardown(() => gateway.stop());
|
||||
gateway.start();
|
||||
@@ -102,13 +102,13 @@ t.test("class DiscordGateway", async t2 => {
|
||||
const fake = await startFakeDiscord({ closeCode: 4014 });
|
||||
t3.teardown(fake.close);
|
||||
let closed;
|
||||
const gateway = new DiscordGateway("token", 0, logger, {
|
||||
onFatalClose: (code, reason) => { closed = { code, reason }; },
|
||||
}, fake.gatewayUrl);
|
||||
const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
|
||||
gateway.on("fatalClose", (code, reason) => { closed = { code, reason }; });
|
||||
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
|
||||
gateway.start();
|
||||
await until(() => closed);
|
||||
t3.same(closed, { code: 4014, reason: "closed by fake" });
|
||||
t3.equal(gateway.state, "stopped");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
t3.equal(fake.identifies.length, 1, "did not reconnect");
|
||||
});
|
||||
@@ -117,7 +117,8 @@ t.test("class DiscordGateway", async t2 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t3.teardown(fake.close);
|
||||
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.start();
|
||||
await until(() => ready === 1);
|
||||
@@ -125,5 +126,53 @@ t.test("class DiscordGateway", async t2 => {
|
||||
await until(() => fake.sockets.size === 0);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
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");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user