Wait for exp_discord_auth with plugins.waitFor

Clusterio 2.1.2 loads plugins concurrently and lets them wait for each
other, so exp_discord_sync gets exp_discord_auth in its entrypoint and
attaches the link hooks there instead of looking it up on the first
sync. Without exp_discord_auth it logs an error and does not connect.

DiscordAuth.get() and its WeakMap had no other users and are removed,
the README shows waitFor instead. The sync tests load both plugins
through lib.PluginLoader with sync listed first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-23 16:28:00 +00:00
1 parent 2c55cb796e
commit cf968c02bb
5 files changed
+60 -52

No files matched your search

+3 -3
View File
@@ -56,12 +56,12 @@ ExpDiscordAuth.get_linked(player) -- Prints the Discord account the player is li
## Other plugins ## Other plugins
Controller plugins can read links and react to them. Import the plugin class from the controller entrypoint and look it up with the controller. Controller plugins can read links and react to them. Wait for the plugin from your entrypoint, the class is only needed for its type.
```ts ```ts
import { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js"; import type { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
const discordAuth = DiscordAuth.get(controller); // undefined if exp_discord_auth is not loaded const discordAuth = await plugins.waitFor<DiscordAuth>("exp_discord_auth"); // undefined if exp_discord_auth is not loaded
discordAuth.getLink("Player1"); // { id, name } of the Discord account, or undefined discordAuth.getLink("Player1"); // { id, name } of the Discord account, or undefined
discordAuth.getAccount(discordId); // { id, name, playerNames }, or undefined discordAuth.getAccount(discordId); // { id, name, playerNames }, or undefined
discordAuth.getAccounts(); // every linked Discord account discordAuth.getAccounts(); // every linked Discord account
+1 -10
View File
@@ -50,14 +50,7 @@ export class DiscordAuthHooks extends lib.AsyncHookCollection {
readonly unlinked = this.newHook<[playerName: string, discordUser: DiscordUser]>(); readonly unlinked = this.newHook<[playerName: string, discordUser: DiscordUser]>();
} }
const loaded = new WeakMap<Controller, ControllerPlugin>();
export class ControllerPlugin { export class ControllerPlugin {
/** The plugin loaded on a controller, for other plugins to read links from. */
static get(controller: Controller) {
return loaded.get(controller);
}
hooks: DiscordAuthHooks; hooks: DiscordAuthHooks;
/** Logins which have been through Discord, by session id */ /** Logins which have been through Discord, by session id */
sessions = new Map<string, Session>(); sessions = new Map<string, Session>();
@@ -118,9 +111,7 @@ export class ControllerPlugin {
messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord), messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord),
)); ));
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, accounts); return new ControllerPlugin(controller, context.logger, context.plugin.name, accounts);
loaded.set(controller, plugin);
return plugin;
} }
async onSave() { async onSave() {
-9
View File
@@ -295,15 +295,6 @@ t.test("api for other plugins", t2 => {
return calls; return calls;
} }
t2.test("static get() returns the plugin loaded on a controller", async t3 => {
const { plugin, controller } = await startPlugin(t3);
t3.equal(ControllerPlugin.get(controller), plugin);
const other = new Controller(logger, [], new lib.ControllerConfig("controller", {
"controller.database_directory": t3.testdir(),
}));
t3.equal(ControllerPlugin.get(other), undefined);
});
t2.test(".getLink(), .getAccount() and .getAccounts() read links", async t3 => { t2.test(".getLink(), .getAccount() and .getAccounts() read links", async t3 => {
const { plugin } = await startPlugin(t3); const { plugin } = await startPlugin(t3);
const session = await discordLogin(plugin, alice); const session = await discordLogin(plugin, alice);
+14 -24
View File
@@ -1,7 +1,7 @@
import type { Controller, ControllerPluginContext } from "@clusterio/controller"; import type { Controller, ControllerPluginContext } from "@clusterio/controller";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import * as path from "node:path"; import * as path from "node:path";
import { 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, discordApi, discordGateway, gatewayIntents,
@@ -29,13 +29,14 @@ export class ControllerPlugin {
draining?: Promise<void>; draining?: Promise<void>;
/** Roles of each user as last seen, so updates which don't touch roles are ignored */ /** Roles of each user as last seen, so updates which don't touch roles are ignored */
userRoles = new Map<string, string>(); userRoles = new Map<string, string>();
authAttached = false;
private constructor( private constructor(
public controller: Controller, public controller: Controller,
public logger: lib.Logger, public logger: lib.Logger,
public name: string, public name: string,
public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>, public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>,
/** Undefined if exp_discord_auth did not load, nothing is synced then */
public discordAuth: DiscordAuth | undefined,
) {} ) {}
static async fromContext(context: ControllerPluginContext) { static async fromContext(context: ControllerPluginContext) {
@@ -47,7 +48,8 @@ export class ControllerPlugin {
messages.RoleMappingRecord.fromJSON.bind(messages.RoleMappingRecord), messages.RoleMappingRecord.fromJSON.bind(messages.RoleMappingRecord),
)); ));
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, mappings); const discordAuth = await context.plugins.waitFor<DiscordAuth>("exp_discord_auth");
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, mappings, discordAuth);
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));
@@ -67,6 +69,8 @@ export class ControllerPlugin {
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.unlinked.attach(plugin.name, (_playerName, discordUser) => plugin.queue(discordUser.id));
plugin.connect(); plugin.connect();
return plugin; return plugin;
@@ -98,6 +102,10 @@ export class ControllerPlugin {
if (!token || !guildId) { if (!token || !guildId) {
return; return;
} }
if (!this.discordAuth) {
this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced");
return;
}
this.guildId = guildId; this.guildId = guildId;
this.rest = new DiscordRest(token, this.apiBase); this.rest = new DiscordRest(token, this.apiBase);
@@ -136,17 +144,6 @@ export class ControllerPlugin {
Syncing Syncing
*/ */
/** exp_discord_auth may load after this plugin, so it is looked up when first needed. */
getDiscordAuth() {
const discordAuth = DiscordAuth.get(this.controller);
if (discordAuth && !this.authAttached) {
this.authAttached = true;
discordAuth.hooks.linked.attach(this.name, (_playerName, discordUser) => this.queue(discordUser.id));
discordAuth.hooks.unlinked.attach(this.name, (_playerName, discordUser) => this.queue(discordUser.id));
}
return discordAuth;
}
queue(discordId: string) { queue(discordId: string) {
if (!this.rest) { if (!this.rest) {
return; return;
@@ -170,16 +167,9 @@ export class ControllerPlugin {
private async processQueue() { private async processQueue() {
while (this.syncAll || this.pending.size) { while (this.syncAll || this.pending.size) {
const discordAuth = this.getDiscordAuth();
if (!discordAuth) {
this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced");
this.pending.clear();
this.syncAll = false;
return;
}
if (this.syncAll) { if (this.syncAll) {
this.syncAll = false; this.syncAll = false;
for (const account of discordAuth.getAccounts()) { for (const account of this.discordAuth?.getAccounts() ?? []) {
this.pending.add(account.id); this.pending.add(account.id);
} }
} }
@@ -217,7 +207,7 @@ export class ControllerPlugin {
/** The mapped Discord roles for the clusterio roles of every player linked to the account. */ /** The mapped Discord roles for the clusterio roles of every player linked to the account. */
wantedRoleIds(discordId: string) { wantedRoleIds(discordId: string) {
const wanted = new Set<string>(); const wanted = new Set<string>();
const account = this.getDiscordAuth()?.getAccount(discordId); const account = this.discordAuth?.getAccount(discordId);
for (const playerName of account?.playerNames ?? []) { for (const playerName of account?.playerNames ?? []) {
const user = this.controller.users.getByName(playerName); const user = this.controller.users.getByName(playerName);
for (const roleId of user?.roleIds ?? []) { for (const roleId of user?.roleIds ?? []) {
@@ -266,7 +256,7 @@ export class ControllerPlugin {
} else { } else {
this.userRoles.set(user.id, key); this.userRoles.set(user.id, key);
} }
const link = this.rest ? this.getDiscordAuth()?.getLink(user.name) : undefined; const link = this.rest ? this.discordAuth?.getLink(user.name) : undefined;
if (link) { if (link) {
this.queue(link.id); this.queue(link.id);
} }
+42 -6
View File
@@ -1,7 +1,7 @@
import t from "tap"; import t from "tap";
import { fileURLToPath } from "node:url";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { Controller } from "@clusterio/controller"; import { Controller } from "@clusterio/controller";
import { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
import { plugin as discordAuthDeclaration } from "@expcluster/discord-auth/dist/node/index.js"; import { plugin as discordAuthDeclaration } from "@expcluster/discord-auth/dist/node/index.js";
import entrypoint, { ControllerPlugin } from "../dist/node/controller.js"; import entrypoint, { ControllerPlugin } from "../dist/node/controller.js";
import * as messages from "../dist/node/messages.js"; import * as messages from "../dist/node/messages.js";
@@ -19,6 +19,14 @@ const logger = {
warn: msg => warnings.push(msg), warn: msg => warnings.push(msg),
}; };
/** Plugin infos as the controller has them, sync is listed before auth */
const packagePath = relative => fileURLToPath(new URL(relative, import.meta.url));
const pluginInfos = [
{ ...pluginDeclaration, packagePath: packagePath("../package.json") },
{ ...discordAuthDeclaration, packagePath: packagePath("../../exp_discord_auth/package.json") },
];
const noPlugins = { waitFor: async () => undefined, checkInstalled: () => false, checkEnabled: () => false };
lib.logger.silent = true; lib.logger.silent = true;
t.after(() => { t.after(() => {
lib.logger.silent = false; lib.logger.silent = false;
@@ -32,7 +40,7 @@ const role = (id, name) => new lib.Role(id, name, "", new Set());
/** /**
* exp_discord_sync and exp_discord_auth on a real controller, talking to a fake Discord. * exp_discord_sync and exp_discord_auth on a real controller, talking to a fake Discord.
* *
* Sync loads before auth to cover auth being looked up late. * Loaded the way the controller loads them, with sync listed before auth.
*/ */
const defaultMappings = { 5: [discordRoles.moderator], 6: [discordRoles.trusted] }; const defaultMappings = { 5: [discordRoles.moderator], 6: [discordRoles.trusted] };
async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) { async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) {
@@ -57,9 +65,15 @@ async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {})
controller.users.createUser(name); controller.users.createUser(name);
} }
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord_sync" }, controller, logger }); const { loaded } = await lib.PluginLoader.load({
type: "controller",
context: { controller, metrics: undefined },
logger,
installed: pluginInfos,
load: pluginInfos,
});
const [plugin, auth] = loaded.values();
t2.teardown(() => plugin.disconnect()); t2.teardown(() => plugin.disconnect());
const auth = await DiscordAuth.fromContext({ plugin: { name: "exp_discord_auth" }, controller, logger });
t2.teardown(() => clearInterval(auth.cleanupInterval)); t2.teardown(() => clearInterval(auth.cleanupInterval));
for (const [roleId, ids] of Object.entries(mappings)) { for (const [roleId, ids] of Object.entries(mappings)) {
plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids)); plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids));
@@ -86,7 +100,9 @@ async function settled(plugin) {
t.test("entrypoint", async t2 => { t.test("entrypoint", async t2 => {
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() }); const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
const controller = new Controller(logger, [], controllerConfig); const controller = new Controller(logger, [], controllerConfig);
await entrypoint({ controller, logger, plugin: { name: "exp_discord_sync" }, metrics: undefined }); await entrypoint({
controller, logger, plugin: { name: "exp_discord_sync" }, metrics: undefined, plugins: noPlugins,
});
for (const hook of ["save", "shutdown", "controllerConfigFieldChanged"]) { for (const hook of ["save", "shutdown", "controllerConfigFieldChanged"]) {
t2.ok([...controller.hooks[hook].attached].includes("exp_discord_sync"), `attached to ${hook}`); t2.ok([...controller.hooks[hook].attached].includes("exp_discord_sync"), `attached to ${hook}`);
} }
@@ -208,6 +224,26 @@ t.test("syncing", t2 => {
t3.same(fake.requests, []); t3.same(fake.requests, []);
t3.ok(await plugin.handleGuildRoleListRequest().catch(err => err) instanceof lib.UnavailableError); t3.ok(await plugin.handleGuildRoleListRequest().catch(err => err) instanceof lib.UnavailableError);
}); });
t2.test("nothing is synced without exp_discord_auth", async t3 => {
const controller = new Controller(logger, [], new lib.ControllerConfig("controller", {
"controller.database_directory": t3.testdir(),
}));
controller.config.set("exp_discord_sync.bot_token", "token");
controller.config.set("exp_discord_sync.guild_id", guildId);
warnings.length = 0;
const { loaded } = await lib.PluginLoader.load({
type: "controller",
context: { controller, metrics: undefined },
logger,
installed: pluginInfos,
load: [pluginInfos[0]],
});
const [plugin] = loaded.values();
t3.equal(plugin.discordAuth, undefined);
t3.equal(plugin.gateway, undefined, "does not connect");
t3.ok(warnings.some(msg => /exp_discord_auth is not loaded/.test(msg)));
});
t2.end(); t2.end();
}); });
@@ -263,7 +299,7 @@ t.test("role mappings", t2 => {
restarted.roles.set(role(5, "Moderator")); restarted.roles.set(role(5, "Moderator"));
restarted.roles.set(role(6, "Trusted")); restarted.roles.set(role(6, "Trusted"));
const reloaded = await ControllerPlugin.fromContext({ const reloaded = await ControllerPlugin.fromContext({
plugin: { name: "exp_discord_sync" }, controller: restarted, logger, plugin: { name: "exp_discord_sync" }, controller: restarted, logger, plugins: noPlugins,
}); });
t3.same([...reloaded.mappings.values()].map(m => [m.id, m.discordRoleIds]), [ t3.same([...reloaded.mappings.values()].map(m => [m.id, m.discordRoleIds]), [
[5, [discordRoles.moderator]], [5, [discordRoles.moderator]],