From 7ab38c2de421b140ac36279b52a3ff03203ae8d8 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Tue, 17 Nov 2026 06:13:20 +0100 Subject: [PATCH 1/2] fix(mirror): send the role and channel order in the shape Fluxer takes Fluxer answers PATCH /guilds/{id}/roles with 204 No Content, and the SDK's guild.setRolePositions() maps over that empty answer as if it were the role list, so the order was set and then reported as failed. The adapter now calls both order routes through the SDK's REST client. Discord numbers text and voice channels separately, so sorting a category by raw position could put a voice channel between text channels. Fluxer applies channel moves one at a time and refuses a move that leaves a voice channel above a text channel (400 Invalid form body). The order is now built the way Discord shows it (text-like first, then voice; loose channels before categories), sent text moves before voice moves, and positions count only the channels that exist on Fluxer. A refused order now says what Fluxer said, and that the copied roles keep waiting for their powerful permissions; Copy again sends it again. The bridge step sums itself up in one sentence across batches. --- docs/mirror.md | 13 +- src/mirror/engine.js | 98 +++++++++++--- src/mirror/errors.js | 15 ++- src/mirror/plan.js | 104 ++++++++++++-- src/mirror/target.js | 36 ++++- test/helpers/mirrorFakes.js | 76 ++++++++++- test/mirrorBridgeEngine.test.js | 32 ++++- test/mirrorFluxerContract.test.js | 143 ++++++++++++++++++++ test/mirrorOrder.test.js | 217 ++++++++++++++++++++++++++++++ test/mirrorTarget.test.js | 15 ++- 10 files changed, 703 insertions(+), 46 deletions(-) create mode 100644 test/mirrorFluxerContract.test.js create mode 100644 test/mirrorOrder.test.js diff --git a/docs/mirror.md b/docs/mirror.md index 7387ebe9..d7754aaa 100644 --- a/docs/mirror.md +++ b/docs/mirror.md @@ -70,7 +70,9 @@ so a message written on one side shows up on the other. Voice channels, categori Send Messages in both; bots are off; nobody is pinged across. The privacy rule is checked again whenever a paused link resumes and on every message: a channel that turns private later stops the link ("no longer open to the same people"). A pair that fails a rule is skipped, the reason - is in the report ("Linking channels through the bridge" and the notes), and the rest are linked. + is in the report ("Linking channels through the bridge" and the notes), and the rest are linked. The report sums + up the whole step in one sentence, for example "35 channels linked, 2 were linked already, 1 not linked (see the + notes)", also when the channels were linked in several batches. - **Safe to run again.** "Copy again" links only the pairs that have no link yet. A channel that an owner unlinked on the Bridge page stays unlinked, and a pair the owners bridged by hand is never taken over or changed (it is reported as skipped). A server can have at most 50 bridged channels this way (10 when @@ -176,7 +178,14 @@ update, and a drag that moves many channels becomes one reorder. (Administrator, Manage Roles and the like), because a new role starts at the bottom where a member with Manage Roles could hand it out; only after the order is set does Sylo give it its permissions. If a role ranks above Sylo's (the order cannot be set) the mirror pauses with the roles named, and the new role stays without its permissions until the - Fluxer owner has fixed it and the mirror is resumed. + Fluxer owner has fixed it and the mirror is resumed. If Fluxer refuses the order itself, the report shows "Role + order" as failed with Fluxer's reason, the roles stay without their powerful permissions, and **Copy again** sends + the order again (and then grants them). +- **The channel order is the one Discord shows.** Inside a category the text, announcement, forum and media channels + come first and the voice channels after them (Discord numbers the two kinds separately, and Fluxer does not allow a + voice channel above a text channel); at the top, the channels without a category come before the categories. + Channels made on the Fluxer server by its own people stay where they are. A refused channel order is reported with + Fluxer's reason, and **Copy again** tries it again. - **Limits.** Sylo plans with Fluxer's defaults (500 emoji and 500 stickers per server, 512 KB per emoji and per sticker). If Fluxer refuses more because of its own limit, Sylo stops that kind and lists the rest in the report. diff --git a/src/mirror/engine.js b/src/mirror/engine.js index 4816a141..77e5e87b 100644 --- a/src/mirror/engine.js +++ b/src/mirror/engine.js @@ -34,7 +34,14 @@ import { } from './bridgeLink.js'; import { MirrorError, MirrorPause, classifyError } from './errors.js'; import { checkOwnership } from './ownership.js'; -import { NOT_COPIED_MODULES, buildModuleSpec, buildPlan, channelOrder, copiedSets } from './plan.js'; +import { + NOT_COPIED_MODULES, + buildModuleSpec, + buildPlan, + channelOrder, + channelPositionUpdates, + copiedSets, +} from './plan.js'; import { snapshotDiscordGuild, snapshotFluxerGuild } from './snapshot.js'; import { createFluxerTarget } from './target.js'; import { @@ -882,6 +889,19 @@ export function createEngine(overrides = {}) { return done('copied', { notes: built.notes }); } + /** + * An order Fluxer refused, said plainly. Only a refusal of this one step is reworded: a rate limit, a network + * failure or a permission error goes on as it is (waited for, retried, or counted toward a pause). + */ + function orderRefused(err, what, after) { + const c = classifyError(err); + if (c.kind !== 'item' || err instanceof MirrorError) return err; + return new MirrorError( + `Fluxer did not take the ${what}: ${c.message.replace(/[.\s]+$/, '')}.${after}`, + 'item' + ); + } + async function reorder(ctx, which) { if (which === 'roles') { const order = roleOrderOf(ctx); @@ -902,7 +922,19 @@ export function createEngine(overrides = {}) { updates.push({ id: mapping.targetId, position: i + 1 }); } const notes = []; - if (updates.length > 0) await ctx.target.setRolePositions(updates); + // A failed order sets nothing: no mapping, no grants. The roles stay without their powerful permissions, and the + // step is planned again by "Copy again" (or the next role change on Discord). + if (updates.length > 0) { + try { + await ctx.target.setRolePositions(updates); + } catch (err) { + throw orderRefused( + err, + 'role order', + ' The copied roles stay without their powerful permissions until the order is set. Copy again tries it once more.' + ); + } + } await store.putMapping({ pairId: ctx.pair.id, kind: 'order', @@ -919,14 +951,19 @@ export function createEngine(overrides = {}) { const hash = specHash(layout); const m = await store.getMapping(ctx.pair.id, 'order', 'channels'); if (m && m.specHash === hash) return done('unchanged'); - const updates = []; + const targetIdOf = new Map(); for (const item of layout) { const mapping = await store.getMapping(ctx.pair.id, 'channel', item.id); - if (!mapping) continue; - const parent = item.parentId ? await store.getMapping(ctx.pair.id, 'channel', item.parentId) : null; - updates.push({ id: mapping.targetId, position: item.position, parentId: parent?.targetId ?? null }); + if (mapping?.targetId) targetIdOf.set(item.id, mapping.targetId); + } + const updates = channelPositionUpdates(layout, targetIdOf, ctx.target.listChannels()); + if (updates.length > 1) { + try { + await ctx.target.setChannelPositions(updates); + } catch (err) { + throw orderRefused(err, 'channel order', ' Copy again tries it once more.'); + } } - if (updates.length > 1) await ctx.target.setChannelPositions(updates); await store.putMapping({ pairId: ctx.pair.id, kind: 'order', @@ -1009,7 +1046,17 @@ export function createEngine(overrides = {}) { async function linkChannels(ctx, job) { const tried = new Set(job.payload?.tried ?? []); const res = await deps.linkMirroredChannels(ctx.pair.id, { skip: tried }); - const skippedPairs = res.skipped ?? []; + // The step can take several batches; each one says where the whole step stands, in one sentence. `tally` carries + // the counts from batch to batch: what this step linked, what was linked before it began (a later batch counts + // the links of the earlier ones as "already"), and the channels it could not link (each reported once). + const prev = job.payload?.tally ?? null; + const reported = new Set(prev?.notLinked ?? []); + const skippedPairs = (res.skipped ?? []).filter((s) => !reported.has(s.sourceId)); + const tally = { + linked: (prev?.linked ?? 0) + (res.linked ?? 0), + before: prev ? prev.before : (res.already ?? 0), + notLinked: [...reported, ...skippedPairs.map((s) => s.sourceId)], + }; const notes = skippedPairs.map((s) => ({ code: `bridge-${s.code}`, scope: 'channel', @@ -1025,19 +1072,24 @@ export function createEngine(overrides = {}) { kind: 'bridge', sourceId: job.sourceId, stepKey: job.stepKey, - payload: { ...job.payload, tried: [...tried, ...(res.tried ?? [])] }, + payload: { ...job.payload, tried: [...tried, ...(res.tried ?? [])], tally }, now: deps.now(), }); } + return done(linkSentence(tally, res), { notes, remote: res.linked > 0 }); + } + + /** The bridge step in one sentence: "35 channels linked, 2 were linked already, 1 not linked (see the notes)". */ + function linkSentence(tally, res) { + const channels = (n) => `${n} ${n === 1 ? 'channel' : 'channels'}`; + const following = res.remaining ?? 0; const parts = []; - if (res.linked > 0) parts.push(`${res.linked} channels linked`); - if ((res.already ?? 0) > 0) parts.push(`${res.already} already linked`); - if (skippedPairs.length > 0) parts.push(`${skippedPairs.length} not linked (see the notes)`); - if ((res.remaining ?? 0) > 0) parts.push(`${res.remaining} more follow`); - return done(parts.length ? parts.join(', ') : `not linked: ${res.reason ?? 'nothing to link'}`, { - notes, - remote: res.linked > 0, - }); + if (tally.linked > 0 || following > 0) + parts.push(`${channels(tally.linked)} linked${following > 0 ? ' so far' : ''}`); + if (tally.before > 0) parts.push(`${tally.before} ${tally.before === 1 ? 'was' : 'were'} linked already`); + if (tally.notLinked.length > 0) parts.push(`${tally.notLinked.length} not linked (see the notes)`); + if (following > 0) parts.push(`${following} more follow`); + return parts.length ? parts.join(', ') : `not linked: ${res.reason ?? 'nothing to link'}`; } async function perform(ctx, job) { @@ -1483,16 +1535,18 @@ export function createEngine(overrides = {}) { detail: j.detail, })); const notes = jobs.flatMap((j) => j.notes); - // The bridge step can take several runs (a batch of channels each): show them as one. + // The bridge step can take several runs (a batch of channels each): show them as one. Each batch's detail already + // sums up the whole step so far, so the latest one is the sentence to show. const links = jobs.filter((j) => j.op === 'link'); const open = links.find((j) => ['pending', 'running', 'failed'].includes(j.status)); const bridge = links.length ? { status: open ? open.status : links[links.length - 1].status, - detail: links - .map((j) => j.detail) - .filter(Boolean) - .join('; '), + detail: + links + .map((j) => j.detail) + .filter(Boolean) + .at(-1) ?? '', } : null; return { diff --git a/src/mirror/errors.js b/src/mirror/errors.js index 9ecccca5..054fca1e 100644 --- a/src/mirror/errors.js +++ b/src/mirror/errors.js @@ -40,12 +40,25 @@ export function isNotFound(err) { return /^(ROLE|CHANNEL|EMOJI|STICKER)_NOT_FOUND$/.test(String(err.code ?? '')); } +/** + * What Fluxer said about the fields of a refused request. A 400 says only "Invalid form body." in its message; the + * reasons are in `errors` ([{ path, message, code }]), which the SDK keeps on the error. + */ +function fieldErrors(err) { + const list = Array.isArray(err?.errors) ? err.errors : []; + const parts = list + .slice(0, 3) + .map((e) => [e?.path, e?.message ?? e?.code].filter(Boolean).join(': ')) + .filter(Boolean); + return parts.length ? ` (${parts.join('; ')})` : ''; +} + /** * @param {any} err * @returns {{ kind: ErrorKind, retryAfterMs?: number, message: string }} */ export function classifyError(err) { - const message = String(err?.message ?? err ?? 'Unknown error').slice(0, 300); + const message = `${String(err?.message ?? err ?? 'Unknown error')}${fieldErrors(err)}`.slice(0, 300); if (err instanceof MirrorError) return { kind: err.kind, message }; // The SDK wraps a failed look-up in an error that keeps the HTTP status only in `cause`. const status = Number(err?.statusCode ?? err?.status ?? err?.cause?.statusCode ?? err?.cause?.status ?? 0); diff --git a/src/mirror/plan.js b/src/mirror/plan.js index fee223c2..7e23df04 100644 --- a/src/mirror/plan.js +++ b/src/mirror/plan.js @@ -405,23 +405,103 @@ export function buildPlan({ return { steps, notes, summary: summarise(steps) }; } -/** The copied channels in the order they sit: for each parent, its children by position. */ +/** Discord's voice-like channels (a stage becomes a voice channel on Fluxer). */ +const VOICE_LIKE = new Set([DISCORD_CHANNEL.VOICE, DISCORD_CHANNEL.STAGE]); + +/** + * The copied channels in the order Discord shows them, as the list of moves sent to Fluxer. + * + * Discord numbers text-like and voice channels separately (a voice channel at position 0 and a text channel at + * position 0 can share a category), and shows the text-like ones first; so a channel's place is its kind first and + * its position second, never the position alone. At the top, the channels without a category come before the + * categories, as on Discord. + * + * The list is in the order the moves are sent: first everything at the top (categories carry their channels along), + * then the text-like channels of every category, then the voice channels. Fluxer applies the moves one at a time and + * refuses any move that leaves a voice channel above a text channel in a category; in this order every text-like + * channel is in place before a voice channel moves, so no step does. + * + * Each item: `position` is its index among its siblings (0 first); `voice` marks a voice channel in a category. + * @returns {Array<{ id: string, parentId: string | null, position: number, voice?: boolean }>} + */ export function channelOrder(source, copied) { const list = source.channels.filter((c) => copied.has(c.id)); - const out = []; - const groups = new Map(); + const isCategory = (c) => c.type === DISCORD_CHANNEL.CATEGORY; + const categories = new Set(list.filter(isCategory).map((c) => c.id)); + const rank = (c) => (VOICE_LIKE.has(c.type) ? 1 : 0); + const byLayout = (a, b) => rank(a) - rank(b) || byPosition(a, b); + const roots = []; + const children = new Map(); for (const c of list) { - const parent = c.parentId && copied.has(c.parentId) ? c.parentId : ''; - if (!groups.has(parent)) groups.set(parent, []); - groups.get(parent).push(c); + if (!isCategory(c) && c.parentId && categories.has(c.parentId)) { + if (!children.has(c.parentId)) children.set(c.parentId, []); + children.get(c.parentId).push(c); + } else { + roots.push(c); + } } - for (const [parent, children] of groups) { - children - .sort(byPosition) - .forEach((c, i) => out.push({ id: c.id, parentId: parent || null, position: i })); + const top = [ + ...roots.filter((c) => !isCategory(c)).sort(byLayout), + ...roots.filter(isCategory).sort(byPosition), + ]; + const out = top.map((c, i) => ({ id: c.id, parentId: null, position: i })); + const groups = top + .filter(isCategory) + .map((cat) => + (children.get(cat.id) ?? []) + .sort(byLayout) + .map((c, i) => ({ id: c.id, parentId: cat.id, position: i, voice: rank(c) === 1 })) + ); + for (const group of groups) out.push(...group.filter((c) => !c.voice)); + for (const group of groups) out.push(...group.filter((c) => c.voice)); + return out; +} + +/** Fluxer's voice channel type, and its category type: everything else sorts with the text channels. */ +const FLUXER_VOICE = 2; +const FLUXER_CATEGORY = 4; + +/** + * The moves for PATCH /guilds/{id}/channels, from channelOrder(): the Discord ids turned into Fluxer ids, and every + * position counted among the channels that are really there. A channel that has no copy on Fluxer (it could not be + * made) is left out and counts for nobody's position, and so is a channel whose category has no copy; otherwise a + * text channel could be placed after a voice channel, which Fluxer refuses. + * + * Channels on Fluxer that are not the mirror's stay where they are; a voice channel of the mirror's goes after every + * text-like channel of its category, the server's own ones included, so it never lands above one of them. + * @param {ReturnType} layout + * @param {Map} targetIdOf Discord channel id -> Fluxer channel id + * @param {Array<{ id: string, type: number, parentId: string | null }>} fluxerChannels what is on Fluxer now + * @returns {Array<{ id: string, position: number, parentId: string | null }>} + */ +export function channelPositionUpdates(layout, targetIdOf, fluxerChannels = []) { + const ours = new Set(targetIdOf.values()); + const foreignText = new Map(); + for (const c of fluxerChannels) { + if (ours.has(c.id) || !c.parentId || c.type === FLUXER_VOICE || c.type === FLUXER_CATEGORY) continue; + foreignText.set(c.parentId, (foreignText.get(c.parentId) ?? 0) + 1); + } + const placed = new Map(); // `${parent}|text` and `${parent}|voice` -> how many are placed + const count = (key) => placed.get(key) ?? 0; + const updates = []; + for (const item of layout) { + const id = targetIdOf.get(item.id); + if (!id) continue; + const parentId = item.parentId ? (targetIdOf.get(item.parentId) ?? null) : null; + if (item.parentId && !parentId) continue; + const group = parentId ?? ''; + let position; + if (item.voice) { + position = + count(`${group}|text`) + (foreignText.get(parentId) ?? 0) + count(`${group}|voice`); + placed.set(`${group}|voice`, count(`${group}|voice`) + 1); + } else { + position = count(`${group}|text`); + placed.set(`${group}|text`, position + 1); + } + updates.push({ id, position, parentId }); } - // Categories are ordered among themselves like any top-level channel. - return out.sort((a, b) => (a.parentId ?? '').localeCompare(b.parentId ?? '') || a.position - b.position); + return updates; } function slotsLeft(cap, targetCount, mapped) { diff --git a/src/mirror/target.js b/src/mirror/target.js index f4d7b307..8b8c3929 100644 --- a/src/mirror/target.js +++ b/src/mirror/target.js @@ -85,6 +85,13 @@ export function createFluxerTarget(guild) { const gone = () => Object.assign(new Error('Unknown channel or role'), { statusCode: 404 }); + // The SDK's REST client, for the routes whose SDK method does not fit Fluxer's answer. + const rest = () => { + const client = guild.client?.rest; + if (typeof client?.patch !== 'function') throw new Error('The Fluxer REST client is not available.'); + return client; + }; + return { kind: 'fluxer', id: String(guild.id), @@ -181,8 +188,18 @@ export function createFluxerTarget(guild) { if (!role) throw gone(); await role.delete('Mirrored from the Discord server'); }, + /** + * PATCH /guilds/{id}/roles with `[{ id, position }]`. Fluxer answers 204 No Content; the SDK's + * guild.setRolePositions() maps over the answer as if it were the role list (Discord's answer) and throws on it + * after the order was set, so the route is called through the SDK's REST client instead. The new positions reach + * the role cache through the gateway (GUILD_ROLE_UPDATE_BULK). + * @param {Array<{ id: string, position: number }>} updates + */ async setRolePositions(updates) { - await guild.setRolePositions(updates); + await rest().patch(`/guilds/${guild.id}/roles`, { + body: updates.map((u) => ({ id: String(u.id), position: Number(u.position) })), + auth: true, + }); }, // --- channels --- @@ -203,8 +220,23 @@ export function createFluxerTarget(guild) { if (!channel) throw gone(); await channel.delete({ reason: 'Mirrored from the Discord server' }); }, + /** + * PATCH /guilds/{id}/channels with `[{ id, position, parent_id, lock_permissions }]` (Fluxer answers 204). Fluxer + * applies the items one by one, in the order sent: `position` is the index among the channel's new siblings at + * that moment, and a move that leaves a voice channel above a text channel in a category is refused (400). The + * engine sends them in an order that keeps every step valid (see channelPositionUpdates in plan.js). + * @param {Array<{ id: string, position: number, parentId: string | null }>} updates + */ async setChannelPositions(updates) { - await guild.setChannelPositions(updates); + await rest().patch(`/guilds/${guild.id}/channels`, { + body: updates.map((u) => ({ + id: String(u.id), + position: Number(u.position), + parent_id: u.parentId == null ? null : String(u.parentId), + lock_permissions: false, + })), + auth: true, + }); }, // --- emoji and stickers --- diff --git a/test/helpers/mirrorFakes.js b/test/helpers/mirrorFakes.js index 3d392bea..9581f1bd 100644 --- a/test/helpers/mirrorFakes.js +++ b/test/helpers/mirrorFakes.js @@ -243,7 +243,8 @@ export function fakeFluxer({ name: spec.name, type: spec.type, parentId: spec.parentId ?? null, - position: 0, + // a new channel goes to the end + position: Math.max(0, ...[...guild.channels.values()].map((c) => c.position ?? 0)) + 1, }); done('createChannel', { spec, id: cid }); return cid; @@ -260,8 +261,11 @@ export function fakeFluxer({ if (!guild.channels.delete(cid)) throw gone('channel'); done('deleteChannel', { id: cid }); }, + // Like Fluxer (ChannelOperationsService.updateChannelPositionsByList): the moves are applied one at a time, and a + // move that leaves a voice channel above a text channel in a category is refused with a 400. async setChannelPositions(updates) { begin('setChannelPositions'); + for (const u of updates) moveChannel(guild, u); done('setChannelPositions', { updates }); }, async createEmoji({ name, image }) { @@ -311,6 +315,76 @@ export function fakeFluxer({ }; } +// --- Fluxer's channel ordering (packages/schema GuildChannelOrdering.ts and ChannelOperationsService.ts) ----------- + +const F_TEXT_LIKE = new Set([0, 5, 15, 16, 998]); +const fRank = (c) => (F_TEXT_LIKE.has(c.type) ? 0 : c.type === 2 ? 1 : 2); +const fByPosition = (a, b) => + (a.position ?? 0) - (b.position ?? 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); + +/** Fluxer's list order: the top level by position, each category followed by its channels, text-like ones first. */ +export function fluxerChannelList(channels) { + const all = [...channels.values()]; + const byId = new Map(all.map((c) => [c.id, c])); + const roots = all.filter((c) => !c.parentId || !byId.has(c.parentId)).sort(fByPosition); + const out = []; + for (const root of roots) { + out.push(root); + if (root.type !== 4) continue; + out.push( + ...all + .filter((c) => c.parentId === root.id) + .sort((a, b) => fRank(a) - fRank(b) || fByPosition(a, b)) + ); + } + out.push(...all.filter((c) => !out.includes(c)).sort(fByPosition)); + return out; +} + +const invalidForm = (path, code) => + Object.assign(new Error('Invalid form body.'), { + statusCode: 400, + code: 'INVALID_FORM_BODY', + errors: [{ path, message: code, code }], + }); + +/** One move of PATCH /guilds/{id}/channels, as Fluxer applies it. */ +function moveChannel(guild, u) { + const target = guild.channels.get(u.id); + if (!target) throw invalidForm('id', 'CHANNEL_NOT_FOUND'); + const parent = u.parentId === undefined ? (target.parentId ?? null) : u.parentId; + if (parent && guild.channels.get(parent)?.type !== 4) throw invalidForm('parent_id', 'INVALID_PARENT_CHANNEL'); + if (target.type === 4 && parent) throw invalidForm('parent_id', 'CATEGORIES_CANNOT_HAVE_PARENTS'); + const ordered = fluxerChannelList(guild.channels); + const block = new Set([target.id]); + if (target.type === 4) for (const c of ordered) if (c.parentId === target.id) block.add(c.id); + const siblings = ordered.filter((c) => (c.parentId ?? null) === parent && !block.has(c.id)); + const index = Math.min(Math.max(u.position ?? siblings.length, 0), siblings.length); + const preceding = index === 0 ? null : siblings[index - 1]; + const rest = ordered.filter((c) => !block.has(c.id)); + let at; + if (preceding?.type === 4) { + at = rest.findIndex((c) => c.id === preceding.id) + 1; + while (at < rest.length && rest[at].parentId === preceding.id) at += 1; + } else if (preceding) at = rest.findIndex((c) => c.id === preceding.id) + 1; + else at = parent ? rest.findIndex((c) => c.id === parent) + 1 : 0; + const moved = ordered.filter((c) => block.has(c.id)); + const final = [...rest.slice(0, at), ...moved, ...rest.slice(at)]; + const parentOf = (c) => (c.id === target.id ? parent : (c.parentId ?? null)); + if (parent) { + const group = final.filter((c) => parentOf(c) === parent); + const i = group.findIndex((c) => c.id === target.id); + const wrong = + (target.type === 2 && group[i + 1] && F_TEXT_LIKE.has(group[i + 1].type)) || + (F_TEXT_LIKE.has(target.type) && group[i - 1]?.type === 2); + if (wrong) throw invalidForm('preceding_sibling_id', 'VOICE_CHANNELS_CANNOT_BE_ABOVE_TEXT_CHANNELS'); + } + final.forEach((c, i) => { + c.parentId = parentOf(c); + c.position = i + 1; + }); +} + /** A fake clock and a sleep that moves it, so spacing and backoff are checked without waiting. */ export function fakeClock(start = 1_800_000_000_000) { const clock = { now: start, slept: [] }; diff --git a/test/mirrorBridgeEngine.test.js b/test/mirrorBridgeEngine.test.js index ed3a2760..06456f5d 100644 --- a/test/mirrorBridgeEngine.test.js +++ b/test/mirrorBridgeEngine.test.js @@ -72,8 +72,38 @@ test('when more channels wait than one run links, another run follows and does n assert.equal(report.bridge.status, 'done'); assert.equal( report.bridge.detail, - '2 channels linked, 1 already linked, 1 not linked (see the notes), 2 more follow; 2 channels linked, 3 already linked' + '4 channels linked, 1 was linked already, 1 not linked (see the notes)', + 'one sentence for the whole step: the links of the first batch are not counted as "already" again' ); + assert.deepEqual( + report.items.filter((i) => i.op === 'link').map((i) => i.detail), + [ + '2 channels linked so far, 1 was linked already, 1 not linked (see the notes), 2 more follow', + '4 channels linked, 1 was linked already, 1 not linked (see the notes)', + ] + ); + assert.equal( + report.notes.filter((n) => n.code === 'bridge-permissions').length, + 1, + 'a channel that was not linked is reported once' + ); +}); + +test('a copy that links 35 channels in two batches says so in one sentence', async () => { + const first = Array.from({ length: 25 }, (_, i) => `c${i}`); + const answers = [ + { linked: 25, already: 0, remaining: 10, tried: first, skipped: [] }, + { linked: 10, already: 25, remaining: 0, tried: [], skipped: [] }, + ]; + let n = 0; + const s = await scenario({ + withExpressions: false, + engineOpts: { linkMirroredChannels: async () => answers[n++] }, + }); + await s.engine.startCopy(s.pair.id); + await drain(s); + const report = await s.engine.report(await db.getPair(s.pair.id)); + assert.equal(report.bridge.detail, '35 channels linked'); }); test('a step that links nothing says why', async () => { diff --git a/test/mirrorFluxerContract.test.js b/test/mirrorFluxerContract.test.js new file mode 100644 index 00000000..12b5e904 --- /dev/null +++ b/test/mirrorFluxerContract.test.js @@ -0,0 +1,143 @@ +// The two order calls of the server mirror against Fluxer's real request shapes. The adapter (src/mirror/target.js) +// runs on the real SDK (a Guild of @fluxerjs/core and its REST client); only the network is swapped for a local HTTP +// server that records each request and answers as Fluxer does (fluxer_api GuildRoleController / GuildChannelController: +// 204 No Content on success, a 400 with `errors` when the form is refused). +// +// The route bodies, per Fluxer's schemas (packages/schema): +// PATCH /guilds/{id}/roles [{ id: snowflake, position?: int }] (at most 10000) +// PATCH /guilds/{id}/channels [{ id, position?: int >= 0, parent_id?: snowflake | null, +// preceding_sibling_id?: snowflake | null, lock_permissions?: bool }] +import test, { after, before } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import * as sdk from '@fluxerjs/core'; +import { createFluxerTarget } from '../src/mirror/target.js'; +import { classifyError } from '../src/mirror/errors.js'; + +const GUILD = '800000000000000050'; +const requests = []; +let answer = () => ({ status: 204 }); +let server; +let base; + +before(async () => { + server = http.createServer((req, res) => { + let raw = ''; + req.on('data', (chunk) => (raw += chunk)); + req.on('end', () => { + requests.push({ + method: req.method, + path: req.url, + auth: req.headers.authorization, + type: req.headers['content-type'], + raw, + }); + const { status, body } = answer(); + if (body === undefined) { + res.writeHead(status); + res.end(); + } else { + res.writeHead(status, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(body)); + } + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + base = `http://127.0.0.1:${server.address().port}/api`; +}); + +after(async () => { + await new Promise((resolve) => server.close(resolve)); +}); + +/** A Guild of the real SDK whose REST client talks to the recording server. */ +function sdkGuild() { + const client = new sdk.Client({}); + client.rest = new client.rest.constructor({ api: base, version: '1', retries: 0 }); + client.rest.setToken('test-token'); + return new sdk.Guild(client, { id: GUILD, name: 'Target' }); +} + +const last = () => requests.at(-1); + +test('the role order is one PATCH of [{ id, position }] to /guilds/{id}/roles, and a 204 is success', async () => { + answer = () => ({ status: 204 }); + const target = createFluxerTarget(sdkGuild()); + await target.setRolePositions([ + { id: '810000000000000002', position: 1 }, + { id: '810000000000000001', position: 2 }, + ]); + const req = last(); + assert.equal(req.method, 'PATCH'); + assert.equal(req.path, `/api/v1/guilds/${GUILD}/roles`); + assert.equal(req.auth, 'Bot test-token'); + assert.match(req.type, /application\/json/); + assert.equal( + req.raw, + '[{"id":"810000000000000002","position":1},{"id":"810000000000000001","position":2}]', + 'a bare array, string ids, integer positions, nothing else' + ); +}); + +test("the SDK's own guild.setRolePositions() throws on Fluxer's 204 (why the adapter calls the route itself)", async () => { + answer = () => ({ status: 204 }); + const guild = sdkGuild(); + const sentBefore = requests.length; + await assert.rejects(guild.setRolePositions([{ id: '810000000000000001', position: 1 }]), (err) => { + assert.ok(err instanceof TypeError); + assert.match(err.message, /reading 'map'/); + return true; + }); + assert.equal(requests.length, sentBefore + 1, 'the order did reach Fluxer before the SDK threw'); +}); + +test('the channel order is one PATCH of [{ id, position, parent_id, lock_permissions }] to /guilds/{id}/channels', async () => { + answer = () => ({ status: 204 }); + const target = createFluxerTarget(sdkGuild()); + await target.setChannelPositions([ + { id: '820000000000000001', position: 0, parentId: null }, + { id: '820000000000000002', position: 0, parentId: '820000000000000001' }, + { id: '820000000000000003', position: 1, parentId: '820000000000000001' }, + ]); + const req = last(); + assert.equal(req.method, 'PATCH'); + assert.equal(req.path, `/api/v1/guilds/${GUILD}/channels`); + assert.equal(req.auth, 'Bot test-token'); + assert.deepEqual(JSON.parse(req.raw), [ + { id: '820000000000000001', position: 0, parent_id: null, lock_permissions: false }, + { id: '820000000000000002', position: 0, parent_id: '820000000000000001', lock_permissions: false }, + { id: '820000000000000003', position: 1, parent_id: '820000000000000001', lock_permissions: false }, + ]); + for (const item of JSON.parse(req.raw)) { + assert.ok(Number.isInteger(item.position) && item.position >= 0, 'position is a non-negative integer'); + assert.equal(typeof item.id, 'string'); + } +}); + +test('a refused order is an item error that says what Fluxer refused', async () => { + answer = () => ({ + status: 400, + body: { + code: 'INVALID_FORM_BODY', + message: 'Invalid form body.', + errors: [ + { + path: 'preceding_sibling_id', + message: 'Voice channels cannot be above text channels.', + code: 'VOICE_CHANNELS_CANNOT_BE_ABOVE_TEXT_CHANNELS', + }, + ], + }, + }); + const target = createFluxerTarget(sdkGuild()); + await assert.rejects( + target.setChannelPositions([{ id: '820000000000000002', position: 0, parentId: null }]), + (err) => { + const c = classifyError(err); + assert.equal(c.kind, 'item'); + assert.match(c.message, /^Invalid form body\./); + assert.match(c.message, /preceding_sibling_id: Voice channels cannot be above text channels/); + return true; + } + ); +}); diff --git a/test/mirrorOrder.test.js b/test/mirrorOrder.test.js new file mode 100644 index 00000000..f15778ac --- /dev/null +++ b/test/mirrorOrder.test.js @@ -0,0 +1,217 @@ +// The role and channel order on Fluxer. Discord numbers text and voice channels separately, and Fluxer takes a channel +// order as moves applied one at a time, refusing any move that leaves a voice channel above a text channel in a +// category; the fake Fluxer (helpers/mirrorFakes.js) applies the moves the same way. A failed role order never lets +// a role get its powerful permissions, and "Copy again" tries a failed order again. +import './helpers/tmpDb.js'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as db from '../src/db/mirror.js'; +import { channelOrder, channelPositionUpdates } from '../src/mirror/plan.js'; +import { ELEVATED_FLUXER_MASK } from '../src/mirror/permissions.js'; +import { BIT, dChannel, fakeFluxer, fluxerChannelList } from './helpers/mirrorFakes.js'; +import { drain, scenario } from './helpers/mirrorScenario.js'; + +const MANAGE_ROLES = 1n << 28n; +const mapped = async (s, kind, id) => (await db.getMapping(s.pair.id, kind, id)).targetId; +const bitsOf = (s, id) => BigInt(s.fluxer.guild.roles.get(id)._permissions ?? 0); + +/** A category in which text and voice channels share position numbers, as Discord numbers them. */ +function mixedChannels(k) { + return [ + dChannel({ id: k.cat, name: 'Info', type: 4, rawPosition: 1 }), + dChannel({ id: '761000000000000001', name: 'general', type: 0, parentId: k.cat, rawPosition: 0 }), + dChannel({ id: '761000000000000002', name: 'Lounge', type: 2, parentId: k.cat, rawPosition: 0 }), + dChannel({ id: '761000000000000003', name: 'memes', type: 0, parentId: k.cat, rawPosition: 1 }), + dChannel({ id: '761000000000000004', name: 'Stage', type: 13, parentId: k.cat, rawPosition: 1 }), + dChannel({ id: '761000000000000005', name: 'news', type: 5, parentId: k.cat, rawPosition: 2 }), + dChannel({ id: k.cat2, name: 'More', type: 4, rawPosition: 0 }), + dChannel({ id: '761000000000000006', name: 'Talk', type: 2, parentId: k.cat2, rawPosition: 0 }), + dChannel({ id: '761000000000000007', name: 'help', type: 0, parentId: k.cat2, rawPosition: 3 }), + dChannel({ id: k.chat, name: 'welcome', type: 0, rawPosition: 5 }), + ]; +} + +const source = (channels) => ({ channels: channels.map((c) => ({ ...c, position: c.rawPosition })) }); + +test('the channel order is the one Discord shows: text-like before voice in a category, loose channels first', () => { + const k = { cat: '1', cat2: '2', chat: '3' }; + const channels = mixedChannels(k); + const layout = channelOrder(source(channels), new Set(channels.map((c) => c.id))); + const name = (id) => channels.find((c) => c.id === id).name; + assert.deepEqual( + layout.map((x) => [name(x.id), x.position, x.voice ?? null]), + [ + ['welcome', 0, null], // a channel without a category comes before the categories + ['More', 1, null], + ['Info', 2, null], + // the text-like channels of every category, then the voice channels + ['help', 0, false], + ['general', 0, false], + ['memes', 1, false], + ['news', 2, false], + ['Talk', 1, true], + ['Lounge', 3, true], + ['Stage', 4, true], + ] + ); +}); + +test('positions count only the channels that exist on Fluxer; a voice channel goes after the text channels already there', () => { + const layout = [ + { id: 'cat', parentId: null, position: 0 }, + { id: 't1', parentId: 'cat', position: 0, voice: false }, + { id: 't2', parentId: 'cat', position: 1, voice: false }, // could not be made on Fluxer + { id: 't3', parentId: 'cat', position: 2, voice: false }, + { id: 'v1', parentId: 'cat', position: 3, voice: true }, + { id: 'orphan', parentId: 'gone', position: 0, voice: false }, // its category has no copy + ]; + const ids = new Map([ + ['cat', 'C'], + ['t1', 'T1'], + ['t3', 'T3'], + ['v1', 'V1'], + ['orphan', 'O'], + ]); + const fluxer = [ + { id: 'C', type: 4, parentId: null }, + { id: 'T1', type: 0, parentId: 'C' }, + { id: 'T3', type: 0, parentId: 'C' }, + { id: 'V1', type: 2, parentId: 'C' }, + { id: 'MINE', type: 0, parentId: 'C' }, // made by someone on Fluxer + { id: 'MYVOICE', type: 2, parentId: 'C' }, + ]; + assert.deepEqual(channelPositionUpdates(layout, ids, fluxer), [ + { id: 'C', position: 0, parentId: null }, + { id: 'T1', position: 0, parentId: 'C' }, + { id: 'T3', position: 1, parentId: 'C' }, + { id: 'V1', position: 3, parentId: 'C' }, + ]); +}); + +test("the fake Fluxer refuses a voice channel above a text channel, like Fluxer (the old order's failure)", () => { + const f = fakeFluxer({ + existingChannels: [ + { id: '1', type: 4, parentId: null, position: 1 }, + { id: '2', type: 0, parentId: '1', position: 2 }, + { id: '3', type: 0, parentId: '1', position: 3 }, + { id: '4', type: 2, parentId: '1', position: 4 }, + ], + }); + // Discord's raw positions sorted together put the voice channel (position 0) between the two text channels. + return assert.rejects( + f.target.setChannelPositions([ + { id: '2', position: 0, parentId: '1' }, + { id: '4', position: 1, parentId: '1' }, + { id: '3', position: 2, parentId: '1' }, + ]), + (err) => err.statusCode === 400 && /Invalid form body/.test(err.message) + ); +}); + +test('a server whose categories mix text and voice channels is copied and ordered as on Discord', async () => { + const s = await scenario({ withExpressions: false }); + s.discord.channels.cache.clear(); + for (const c of mixedChannels(s.k)) s.discord.channels.cache.set(c.id, c); + await s.engine.startCopy(s.pair.id); + const end = await drain(s); + const report = await s.engine.report(end); + assert.deepEqual(report.failed, [], 'no step failed'); + assert.equal(s.fluxer.ops('setChannelPositions').length, 1); + const names = fluxerChannelList(s.fluxer.guild.channels).map((c) => c.name); + assert.deepEqual(names, [ + 'welcome', + 'More', + 'help', + 'Talk', + 'Info', + 'general', + 'memes', + 'news', + 'Lounge', + 'Stage', + ]); +}); + +test('a failed role order leaves every copied role without its powerful permissions, says so, and Copy again retries it', async () => { + const s = await scenario({ withExpressions: false }); + s.discord.roles.cache.get(s.k.member).permissions = { bitfield: MANAGE_ROLES | BIT.ViewChannel }; + s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator | BIT.ViewChannel }; + // What the SDK threw on Fluxer's 204 in the first live run. + s.fluxer.failOn('setRolePositions', new TypeError("Cannot read properties of undefined (reading 'map')")); + await s.engine.startCopy(s.pair.id); + let end = await drain(s); + + const roles = [await mapped(s, 'role', s.k.member), await mapped(s, 'role', s.k.mod)]; + for (const sourceId of [s.k.member, s.k.mod]) { + const m = await db.getMapping(s.pair.id, 'role', sourceId); + assert.equal(bitsOf(s, m.targetId) & ELEVATED_FLUXER_MASK, 0n, 'no powerful permission was granted'); + assert.equal(m.specHash, '', 'the role still waits for them'); + } + assert.ok(!(await db.getMapping(s.pair.id, 'order', 'roles')), 'the order is not marked as set'); + let report = await s.engine.report(end); + const failed = report.failed.find((i) => i.name === 'Role order'); + assert.ok(failed, 'the role order is reported as failed'); + assert.match(failed.detail, /^Fluxer did not take the role order: Cannot read properties/); + assert.match(failed.detail, /stay without their powerful permissions until the order is set/); + assert.match(failed.detail, /Copy again/); + const granted = s.fluxer + .ops('editRole') + .filter((c) => roles.includes(c.id) && BigInt(c.spec.permissions) & ELEVATED_FLUXER_MASK); + assert.equal(granted.length, 0, 'no grant was sent'); + + // Copy again: the order step is planned again, runs, and only then are the permissions granted. + const preview = await s.engine.previewPair(end); + assert.equal(preview.steps.find((x) => x.key === 'order-roles:roles').op, 'create'); + await s.engine.startCopy(s.pair.id); + end = await drain(s); + report = await s.engine.report(end); + assert.deepEqual(report.failed, []); + assert.equal(s.fluxer.ops('setRolePositions').length, 1); + assert.equal(bitsOf(s, roles[0]) & MANAGE_ROLES, MANAGE_ROLES); + assert.equal(bitsOf(s, roles[1]) & (1n << 3n), 1n << 3n); +}); + +test('a role order Fluxer refuses with a 400 says what Fluxer said, and grants nothing', async () => { + const s = await scenario({ withExpressions: false }); + s.discord.roles.cache.get(s.k.mod).permissions = { bitfield: BIT.Administrator }; + s.fluxer.failOn( + 'setRolePositions', + Object.assign(new Error('Invalid form body.'), { + statusCode: 400, + errors: [{ path: 'id', message: 'Invalid role ID', code: 'INVALID_ROLE_ID' }], + }) + ); + await s.engine.startCopy(s.pair.id); + const end = await drain(s); + assert.equal(end.status, 'live', 'one refused step does not pause the mirror'); + const failed = (await s.engine.report(end)).failed.find((i) => i.name === 'Role order'); + assert.match(failed.detail, /^Fluxer did not take the role order: Invalid form body\. \(id: Invalid role ID\)\./); + assert.equal(bitsOf(s, await mapped(s, 'role', s.k.mod)) & ELEVATED_FLUXER_MASK, 0n); +}); + +test('a failed channel order is reported plainly and Copy again tries it again', async () => { + const s = await scenario({ withExpressions: false }); + s.fluxer.failOn( + 'setChannelPositions', + Object.assign(new Error('Invalid form body.'), { statusCode: 400 }) + ); + await s.engine.startCopy(s.pair.id); + let end = await drain(s); + const failed = (await s.engine.report(end)).failed.find((i) => i.name === 'Channel order'); + assert.match(failed.detail, /^Fluxer did not take the channel order: Invalid form body\. Copy again/); + assert.equal(s.fluxer.ops('setChannelPositions').length, 0); + + await s.engine.startCopy(s.pair.id); + end = await drain(s); + assert.deepEqual((await s.engine.report(end)).failed, []); + assert.equal(s.fluxer.ops('setChannelPositions').length, 1, 'the order went through the second time'); +}); + +test('a rate limit on an order is waited out, not reported as a failure', async () => { + const s = await scenario({ withExpressions: false }); + s.fluxer.failOn('setChannelPositions', Object.assign(new Error('slow down'), { statusCode: 429, retryAfter: 2 })); + await s.engine.startCopy(s.pair.id); + const end = await drain(s); + assert.deepEqual((await s.engine.report(end)).failed, []); + assert.equal(s.fluxer.ops('setChannelPositions').length, 1); +}); diff --git a/test/mirrorTarget.test.js b/test/mirrorTarget.test.js index 1476700f..64e69c2e 100644 --- a/test/mirrorTarget.test.js +++ b/test/mirrorTarget.test.js @@ -26,7 +26,10 @@ function sdkGuild({ perms = [], admin = false, top = 7 } = {}) { roles: { highest: { id: '810000000000000000', position: top } }, }, }, - client: { channels: { fetch: async () => null } }, + client: { + channels: { fetch: async () => null }, + rest: { patch: async (route, opts) => log.push(['rest.patch', route, opts.body]) }, + }, createRole: async (body) => { log.push(['createRole', body]); const role = entity('role', { id: '810000000000000001', name: body.name, type: 'role' }); @@ -47,8 +50,6 @@ function sdkGuild({ perms = [], admin = false, top = 7 } = {}) { log.push(['createSticker', body]), entity('sticker', { id: '840000000000000001' }) ), - setRolePositions: async (u) => log.push(['setRolePositions', u]), - setChannelPositions: async (u) => log.push(['setChannelPositions', u]), edit: async (b) => log.push(['guild.edit', b]), fetchRole: async () => { throw Object.assign(new Error('Unknown Role'), { statusCode: 404 }); @@ -163,7 +164,11 @@ test('a channel keeps its overwrites as bigint allow and deny; only text and ann assert.deepEqual(log.at(-1), ['channel.delete', id, { reason: 'Mirrored from the Discord server' }]); await assert.rejects(target.deleteChannel('820000000000000099'), (e) => classifyError(e).kind === 'gone'); await target.setChannelPositions([{ id, position: 1, parentId: null }]); - assert.equal(log.at(-1)[0], 'setChannelPositions'); + assert.deepEqual(log.at(-1), [ + 'rest.patch', + `/guilds/${guild.id}/channels`, + [{ id, position: 1, parent_id: null, lock_permissions: false }], + ]); }); test('emoji, stickers, positions and the server itself go through the SDK with data URIs', async () => { @@ -182,7 +187,7 @@ test('emoji, stickers, positions and the server itself go through the SDK with d { name: 'hi', description: 'Hello', tags: ['a'], image: 'data:image/png;base64,AQID' }, ]); await target.setRolePositions([{ id: '1', position: 2 }]); - assert.deepEqual(log.at(-1), ['setRolePositions', [{ id: '1', position: 2 }]]); + assert.deepEqual(log.at(-1), ['rest.patch', `/guilds/${guild.id}/roles`, [{ id: '1', position: 2 }]]); await target.editGuild({ name: 'New', icon: 'data:image/png;base64,AQID' }); assert.deepEqual(log.at(-1), ['guild.edit', { name: 'New', icon: 'data:image/png;base64,AQID' }]); await assert.rejects( From af6be24ca4f6bad9375d3dd02d9bc88bc13889a1 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Tue, 17 Nov 2026 06:14:50 +0100 Subject: [PATCH 2/2] style: prettier --- src/mirror/plan.js | 3 +-- test/helpers/mirrorFakes.js | 7 +++---- test/mirrorOrder.test.js | 15 +++++++++------ 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/mirror/plan.js b/src/mirror/plan.js index 7e23df04..b3dae0e3 100644 --- a/src/mirror/plan.js +++ b/src/mirror/plan.js @@ -492,8 +492,7 @@ export function channelPositionUpdates(layout, targetIdOf, fluxerChannels = []) const group = parentId ?? ''; let position; if (item.voice) { - position = - count(`${group}|text`) + (foreignText.get(parentId) ?? 0) + count(`${group}|voice`); + position = count(`${group}|text`) + (foreignText.get(parentId) ?? 0) + count(`${group}|voice`); placed.set(`${group}|voice`, count(`${group}|voice`) + 1); } else { position = count(`${group}|text`); diff --git a/test/helpers/mirrorFakes.js b/test/helpers/mirrorFakes.js index 9581f1bd..f5f746c4 100644 --- a/test/helpers/mirrorFakes.js +++ b/test/helpers/mirrorFakes.js @@ -332,9 +332,7 @@ export function fluxerChannelList(channels) { out.push(root); if (root.type !== 4) continue; out.push( - ...all - .filter((c) => c.parentId === root.id) - .sort((a, b) => fRank(a) - fRank(b) || fByPosition(a, b)) + ...all.filter((c) => c.parentId === root.id).sort((a, b) => fRank(a) - fRank(b) || fByPosition(a, b)) ); } out.push(...all.filter((c) => !out.includes(c)).sort(fByPosition)); @@ -353,7 +351,8 @@ function moveChannel(guild, u) { const target = guild.channels.get(u.id); if (!target) throw invalidForm('id', 'CHANNEL_NOT_FOUND'); const parent = u.parentId === undefined ? (target.parentId ?? null) : u.parentId; - if (parent && guild.channels.get(parent)?.type !== 4) throw invalidForm('parent_id', 'INVALID_PARENT_CHANNEL'); + if (parent && guild.channels.get(parent)?.type !== 4) + throw invalidForm('parent_id', 'INVALID_PARENT_CHANNEL'); if (target.type === 4 && parent) throw invalidForm('parent_id', 'CATEGORIES_CANNOT_HAVE_PARENTS'); const ordered = fluxerChannelList(guild.channels); const block = new Set([target.id]); diff --git a/test/mirrorOrder.test.js b/test/mirrorOrder.test.js index f15778ac..bf0f61ae 100644 --- a/test/mirrorOrder.test.js +++ b/test/mirrorOrder.test.js @@ -185,16 +185,16 @@ test('a role order Fluxer refuses with a 400 says what Fluxer said, and grants n const end = await drain(s); assert.equal(end.status, 'live', 'one refused step does not pause the mirror'); const failed = (await s.engine.report(end)).failed.find((i) => i.name === 'Role order'); - assert.match(failed.detail, /^Fluxer did not take the role order: Invalid form body\. \(id: Invalid role ID\)\./); + assert.match( + failed.detail, + /^Fluxer did not take the role order: Invalid form body\. \(id: Invalid role ID\)\./ + ); assert.equal(bitsOf(s, await mapped(s, 'role', s.k.mod)) & ELEVATED_FLUXER_MASK, 0n); }); test('a failed channel order is reported plainly and Copy again tries it again', async () => { const s = await scenario({ withExpressions: false }); - s.fluxer.failOn( - 'setChannelPositions', - Object.assign(new Error('Invalid form body.'), { statusCode: 400 }) - ); + s.fluxer.failOn('setChannelPositions', Object.assign(new Error('Invalid form body.'), { statusCode: 400 })); await s.engine.startCopy(s.pair.id); let end = await drain(s); const failed = (await s.engine.report(end)).failed.find((i) => i.name === 'Channel order'); @@ -209,7 +209,10 @@ test('a failed channel order is reported plainly and Copy again tries it again', test('a rate limit on an order is waited out, not reported as a failure', async () => { const s = await scenario({ withExpressions: false }); - s.fluxer.failOn('setChannelPositions', Object.assign(new Error('slow down'), { statusCode: 429, retryAfter: 2 })); + s.fluxer.failOn( + 'setChannelPositions', + Object.assign(new Error('slow down'), { statusCode: 429, retryAfter: 2 }) + ); await s.engine.startCopy(s.pair.id); const end = await drain(s); assert.deepEqual((await s.engine.report(end)).failed, []);