Dough Git

commit

Whelps

commit
927e527364727e79df97e9cdddeba86f3196e32c
author
Clove Twilight <[email protected]>
date
2026-11-13 15:26

diff --git a/src/lib/server/discord/bot.ts b/src/lib/server/discord/bot.ts
index 4b6236a..163bb22 100644
--- a/src/lib/server/discord/bot.ts
+++ b/src/lib/server/discord/bot.ts
@@ -7,7 +7,7 @@ import { Client, Events, MessageFlags, type Interaction } from 'discord.js';
 import { getConfig } from '../config.ts';
 import { getFinding, listUnnotifiedFindings, setFindingDiscordMessage } from '../db/findings.ts';
 import { onFindingEvent } from '../events.ts';
-import { createLogger } from '../logger.ts';
+import { createLogger, sleep } from '../logger.ts';
 import { performModerationAction, type ModerationDecision } from '../moderation/actions.ts';
 import { buttonPrefix, renderFinding } from './render.ts';
 
@@ -140,28 +140,68 @@ async function handleInteraction(interaction: Interaction): Promise<void> {
 	await refreshNotification(findingId);
 }
 
-export async function startDiscordBot(): Promise<void> {
-	const { discordToken, discordUserId } = getConfig();
-
-	if (!discordToken || !discordUserId) {
-		logger.warn('DISCORD_BOT_TOKEN or DISCORD_USER_ID missing; Discord is disabled');
-		return;
-	}
-
+function createClient(): Client {
 	// Buttons and direct messages need no privileged gateway intents
-	client = new Client({ intents: [] });
+	const newClient = new Client({ intents: [] });
 
-	client.once(Events.ClientReady, (readyClient) => {
+	newClient.once(Events.ClientReady, (readyClient) => {
 		logger.info(`Connected as ${readyClient.user.tag}`);
 
 		void flushNotifications().catch((error) => logger.warn('Catch-up failed', error));
 	});
 
-	client.on(Events.InteractionCreate, (interaction) => {
+	newClient.on(Events.InteractionCreate, (interaction) => {
 		void handleInteraction(interaction).catch((error) => logger.error('Interaction failed', error));
 	});
 
-	client.on(Events.Error, (error) => logger.error('Gateway error', error));
+	newClient.on(Events.Error, (error) => logger.error('Gateway error', error));
+
+	return newClient;
+}
+
+const retryDelaysSeconds = [5, 15, 30, 60];
+
+// Each start gets a new number, so a stop or restart ends any older login loop
+let loginGeneration = 0;
+
+function isBadToken(error: unknown): boolean {
+	return (error as { code?: string } | null)?.code === 'TokenInvalid';
+}
+
+// Keeps trying until Discord accepts the login, e.g. when the service starts before the network
+async function loginWithRetry(discordToken: string, generation: number): Promise<void> {
+	for (let attempt = 0; generation === loginGeneration; attempt += 1) {
+		const candidate = createClient();
+
+		client = candidate;
+
+		try {
+			await candidate.login(discordToken);
+			return;
+		} catch (error) {
+			await candidate.destroy().catch(() => undefined);
+
+			if (isBadToken(error)) {
+				logger.error('DISCORD_BOT_TOKEN was rejected; Discord is disabled', error);
+				return;
+			}
+
+			const delaySeconds = retryDelaysSeconds[Math.min(attempt, retryDelaysSeconds.length - 1)];
+
+			logger.warn(`Discord login failed; retrying in ${delaySeconds}s`, error);
+
+			await sleep(delaySeconds * 1000);
+		}
+	}
+}
+
+export function startDiscordBot(): void {
+	const { discordToken, discordUserId } = getConfig();
+
+	if (!discordToken || !discordUserId) {
+		logger.warn('DISCORD_BOT_TOKEN or DISCORD_USER_ID missing; Discord is disabled');
+		return;
+	}
 
 	onFindingEvent('findingCreated', (findingId) => {
 		void sendNotification(findingId).catch((error) =>
@@ -175,10 +215,15 @@ export async function startDiscordBot(): Promise<void> {
 		);
 	});
 
-	await client.login(discordToken);
+	loginGeneration += 1;
+
+	// Not awaited: the scanner and dashboard start while Discord is still connecting
+	void loginWithRetry(discordToken, loginGeneration);
 }
 
 export async function stopDiscordBot(): Promise<void> {
+	loginGeneration += 1;
+
 	await client?.destroy();
 	client = undefined;
 }
diff --git a/src/lib/server/network.test.ts b/src/lib/server/network.test.ts
new file mode 100644
index 0000000..1f0fa72
--- /dev/null
+++ b/src/lib/server/network.test.ts
@@ -0,0 +1,61 @@
+/* src/lib/server/network.test.ts
+ * MIT — (c) Doughmination System®
+ */
+
+import assert from 'node:assert/strict';
+import { describe, test } from 'node:test';
+
+import { waitForNetwork } from './network.ts';
+
+describe('waitForNetwork', () => {
+	test('returns at once when the network answers', async () => {
+		let probeCount = 0;
+
+		const ready = await waitForNetwork({
+			isCancelled: () => false,
+			delaysSeconds: [0.001],
+			probe: async () => {
+				probeCount += 1;
+			}
+		});
+
+		assert.equal(ready, true);
+		assert.equal(probeCount, 1);
+	});
+
+	test('keeps trying until the network answers', async () => {
+		let probeCount = 0;
+
+		const ready = await waitForNetwork({
+			isCancelled: () => false,
+			delaysSeconds: [0.001, 0.002],
+			probe: async () => {
+				probeCount += 1;
+
+				if (probeCount < 5) {
+					throw new Error('fetch failed');
+				}
+			}
+		});
+
+		assert.equal(ready, true);
+		assert.equal(probeCount, 5);
+	});
+
+	test('gives up quietly when cancelled', async () => {
+		let probeCount = 0;
+
+		const ready = await waitForNetwork({
+			isCancelled: () => probeCount >= 2,
+			delaysSeconds: [0.001],
+			probe: async () => {
+				probeCount += 1;
+
+				throw new Error('fetch failed');
+			}
+		});
+
+		assert.equal(ready, false);
+		assert.equal(probeCount, 2);
+	});
+});
diff --git a/src/lib/server/network.ts b/src/lib/server/network.ts
new file mode 100644
index 0000000..f810f63
--- /dev/null
+++ b/src/lib/server/network.ts
@@ -0,0 +1,59 @@
+/* src/lib/server/network.ts
+ * MIT — (c) Doughmination System®
+ */
+
+import { createLogger, describeError, sleep } from './logger.ts';
+
+const logger = createLogger('network');
+
+// The two services the tracker cannot work without; neither probe needs a token
+const probeUrls = ['https://api.github.com/', 'https://discord.com/api/v10/gateway'];
+
+const probeTimeoutMs = 8_000;
+
+// Staggered waits between attempts; the last one repeats until the network answers
+const defaultDelaysSeconds = [2, 5, 10, 20, 40, 60];
+
+// Any HTTP answer at all proves the host is reachable; only a thrown error means it is not
+async function probeAll(): Promise<void> {
+	for (const url of probeUrls) {
+		const response = await fetch(url, {
+			method: 'HEAD',
+			signal: AbortSignal.timeout(probeTimeoutMs)
+		});
+
+		await response.body?.cancel();
+	}
+}
+
+export interface WaitForNetworkOptions {
+	isCancelled: () => boolean;
+	probe?: () => Promise<void>;
+	delaysSeconds?: number[];
+}
+
+// Resolves true once the network answers, or false if cancelled while waiting
+export async function waitForNetwork(options: WaitForNetworkOptions): Promise<boolean> {
+	const probe = options.probe ?? probeAll;
+	const delaysSeconds = options.delaysSeconds ?? defaultDelaysSeconds;
+
+	for (let attempt = 0; !options.isCancelled(); attempt += 1) {
+		try {
+			await probe();
+
+			if (attempt > 0) {
+				logger.info(`Network is up after ${attempt + 1} attempts`);
+			}
+
+			return !options.isCancelled();
+		} catch (error) {
+			const delaySeconds = delaysSeconds[Math.min(attempt, delaysSeconds.length - 1)];
+
+			logger.warn(`Network not ready (${describeError(error)}); trying again in ${delaySeconds}s`);
+
+			await sleep(delaySeconds * 1000);
+		}
+	}
+
+	return false;
+}
diff --git a/src/lib/server/runtime.ts b/src/lib/server/runtime.ts
index e86e8d4..646df2b 100644
--- a/src/lib/server/runtime.ts
+++ b/src/lib/server/runtime.ts
@@ -8,6 +8,7 @@ import { flushNotifications, startDiscordBot, stopDiscordBot } from './discord/b
 import { removeFindingListeners } from './events.ts';
 import { checkToken } from './github/token.ts';
 import { createLogger } from './logger.ts';
+import { waitForNetwork } from './network.ts';
 import { startScanner, stopScanner } from './moderation/scanner.ts';
 
 const logger = createLogger('runtime');
@@ -42,6 +43,8 @@ function hookShutdown(): void {
 }
 
 async function stop(): Promise<void> {
+	startGeneration += 1;
+
 	stopScanner();
 	removeFindingListeners();
 	await stopDiscordBot();
@@ -60,12 +63,30 @@ export async function startServices(): Promise<void> {
 
 	logger.info(config.dryRun ? 'Dry run is ON: GitHub will not be changed' : 'Dry run is OFF');
 
-	// Not awaited: a slow or failing GitHub must not delay the dashboard or the bot
+	startGeneration += 1;
+
+	// Not awaited: the dashboard opens at once, even while the network is still down
+	void startNetworkServices(startGeneration);
+}
+
+// Each start gets a new number, so a stop or restart ends any older wait
+let startGeneration = 0;
+
+// Everything that talks to GitHub or Discord waits here until the network answers
+async function startNetworkServices(generation: number): Promise<void> {
+	const ready = await waitForNetwork({
+		isCancelled: () => generation !== startGeneration
+	});
+
+	if (!ready) {
+		return;
+	}
+
 	void checkToken();
 
-	await startDiscordBot().catch((error) => logger.error('Discord failed to start', error));
+	startDiscordBot();
 
-	if (config.scannerEnabled) {
+	if (getConfig().scannerEnabled) {
 		startScanner(flushNotifications);
 	} else {
 		logger.info('Scanner disabled (SCANNER_ENABLED=false)');