diff --git a/exp_discord_auth/README.md b/exp_discord_auth/README.md index f2779963..342e553b 100644 --- a/exp_discord_auth/README.md +++ b/exp_discord_auth/README.md @@ -56,12 +56,12 @@ ExpDiscordAuth.get_linked(player) -- Prints the Discord account the player is li ## 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 -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("exp_discord_auth"); // undefined if exp_discord_auth is not loaded discordAuth.getLink("Player1"); // { id, name } of the Discord account, or undefined discordAuth.getAccount(discordId); // { id, name, playerNames }, or undefined discordAuth.getAccounts(); // every linked Discord account diff --git a/exp_discord_auth/controller.ts b/exp_discord_auth/controller.ts index 415e4a32..9caf8686 100644 --- a/exp_discord_auth/controller.ts +++ b/exp_discord_auth/controller.ts @@ -50,14 +50,7 @@ export class DiscordAuthHooks extends lib.AsyncHookCollection { readonly unlinked = this.newHook<[playerName: string, discordUser: DiscordUser]>(); } -const loaded = new WeakMap(); - 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; /** Logins which have been through Discord, by session id */ sessions = new Map(); @@ -118,9 +111,7 @@ export class ControllerPlugin { messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord), )); - const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, accounts); - loaded.set(controller, plugin); - return plugin; + return new ControllerPlugin(controller, context.logger, context.plugin.name, accounts); } async onSave() { diff --git a/exp_discord_auth/test/controller.test.js b/exp_discord_auth/test/controller.test.js index 8f194445..41ba8d7a 100644 --- a/exp_discord_auth/test/controller.test.js +++ b/exp_discord_auth/test/controller.test.js @@ -295,15 +295,6 @@ t.test("api for other plugins", t2 => { 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 => { const { plugin } = await startPlugin(t3); const session = await discordLogin(plugin, alice); diff --git a/exp_discord_sync/controller.ts b/exp_discord_sync/controller.ts index c2070932..1bb48069 100644 --- a/exp_discord_sync/controller.ts +++ b/exp_discord_sync/controller.ts @@ -1,7 +1,7 @@ import type { Controller, ControllerPluginContext } from "@clusterio/controller"; import * as lib from "@clusterio/lib"; 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 { DiscordApiError, DiscordGateway, DiscordRest, GuildMember, discordApi, discordGateway, gatewayIntents, @@ -29,13 +29,14 @@ export class ControllerPlugin { draining?: Promise; /** Roles of each user as last seen, so updates which don't touch roles are ignored */ userRoles = new Map(); - authAttached = false; private constructor( public controller: Controller, public logger: lib.Logger, public name: string, public mappings: lib.SubscribableDatastore, + /** Undefined if exp_discord_auth did not load, nothing is synced then */ + public discordAuth: DiscordAuth | undefined, ) {} static async fromContext(context: ControllerPluginContext) { @@ -47,7 +48,8 @@ export class ControllerPlugin { messages.RoleMappingRecord.fromJSON.bind(messages.RoleMappingRecord), )); - const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, mappings); + const discordAuth = await context.plugins.waitFor("exp_discord_auth"); + const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, mappings, discordAuth); plugin.sweepMappings(); for (const user of controller.users.values()) { 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.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)); plugin.connect(); return plugin; @@ -98,6 +102,10 @@ export class ControllerPlugin { if (!token || !guildId) { return; } + if (!this.discordAuth) { + 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); @@ -136,17 +144,6 @@ export class ControllerPlugin { 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) { if (!this.rest) { return; @@ -170,16 +167,9 @@ export class ControllerPlugin { private async processQueue() { 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) { this.syncAll = false; - for (const account of discordAuth.getAccounts()) { + for (const account of this.discordAuth?.getAccounts() ?? []) { 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. */ wantedRoleIds(discordId: string) { const wanted = new Set(); - const account = this.getDiscordAuth()?.getAccount(discordId); + const account = this.discordAuth?.getAccount(discordId); for (const playerName of account?.playerNames ?? []) { const user = this.controller.users.getByName(playerName); for (const roleId of user?.roleIds ?? []) { @@ -266,7 +256,7 @@ export class ControllerPlugin { } else { 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) { this.queue(link.id); } diff --git a/exp_discord_sync/test/controller.test.js b/exp_discord_sync/test/controller.test.js index 30f4e209..772aff76 100644 --- a/exp_discord_sync/test/controller.test.js +++ b/exp_discord_sync/test/controller.test.js @@ -1,7 +1,7 @@ import t from "tap"; +import { fileURLToPath } from "node:url"; import * as lib from "@clusterio/lib"; 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 entrypoint, { ControllerPlugin } from "../dist/node/controller.js"; import * as messages from "../dist/node/messages.js"; @@ -19,6 +19,14 @@ const logger = { 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; t.after(() => { 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. * - * 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] }; async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) { @@ -57,9 +65,15 @@ async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) 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()); - const auth = await DiscordAuth.fromContext({ plugin: { name: "exp_discord_auth" }, controller, logger }); t2.teardown(() => clearInterval(auth.cleanupInterval)); for (const [roleId, ids] of Object.entries(mappings)) { plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids)); @@ -86,7 +100,9 @@ async function settled(plugin) { t.test("entrypoint", async t2 => { const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() }); 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"]) { 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.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(); }); @@ -263,7 +299,7 @@ t.test("role mappings", t2 => { restarted.roles.set(role(5, "Moderator")); restarted.roles.set(role(6, "Trusted")); 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]), [ [5, [discordRoles.moderator]],