diff --git a/src/features/scheduled-announcements/service.ts b/src/features/scheduled-announcements/service.ts index bd2a758..0329a24 100644 --- a/src/features/scheduled-announcements/service.ts +++ b/src/features/scheduled-announcements/service.ts @@ -84,6 +84,10 @@ export function createScheduledAnnouncementsService( let entries: ScheduledAnnouncementEntry[] = []; let timer: NodeJS.Timeout | null = null; let stopped = false; + // The idle re-check runs every 60s; log only the transition into idle so a + // quiet schedule does not flood the log (~1440 lines/day) and evict useful + // history from retention. + let idleNotified = false; function resolveChannel(channelId: string): Promise { if (options.resolveChannel) { @@ -158,7 +162,10 @@ export function createScheduledAnnouncementsService( const next = pickNextFires(entries, now, 1)[0] ?? null; if (!next) { - logger.info("No enabled entries left to schedule; entering idle loop."); + if (!idleNotified) { + logger.info("No enabled entries left to schedule; entering idle loop."); + idleNotified = true; + } // Re-check periodically so config edits followed by a restart can be // picked up; also handles a future case where entries get re-enabled // via edit-and-restart. @@ -166,6 +173,8 @@ export function createScheduledAnnouncementsService( return; } + idleNotified = false; + const rawDelayMs = next.fireAt.getTime() - now.getTime(); const delayMs = Math.max(0, rawDelayMs); const safeDelayMs = Math.min(delayMs, MAX_SET_TIMEOUT_DELAY_MS); diff --git a/src/features/timekeeper/service.ts b/src/features/timekeeper/service.ts index c0f7d9d..5f9d293 100644 --- a/src/features/timekeeper/service.ts +++ b/src/features/timekeeper/service.ts @@ -33,7 +33,11 @@ import { } from "./engagement.js"; import type { PlaybackTimeouts } from "./playback-budget.js"; import { resolvePlaybackTimeouts } from "./playback-budget.js"; -import { getCurrentOrNextDailyStartAt, getTimekeeperPreparationStartAt } from "./schedule.js"; +import { + getCurrentOrNextDailyStartAt, + getNextDailyStartAt, + getTimekeeperPreparationStartAt, +} from "./schedule.js"; import { clampTimeToEvent, createSessionClock, @@ -70,6 +74,25 @@ let activePaused = false; let activeSkipResolver: (() => void) | null = null; let pendingScheduledStartAt: Date | null = null; let skipFlag = false; +// Incremented every time a session run starts or is aborted. The event loop +// captures the value at start and aborts once it no longer matches, which is +// how the watchdog stops a wedged runSession without waiting for it to settle. +let sessionGeneration = 0; +// The in-flight voice connection, tracked at module level so the watchdog can +// destroy it when the owning runSession is wedged inside an unbounded await. +let activeVoiceConnection: Awaited> | null = null; + +/** + * Upper bound for each pre-flight step in `runSession` (channel resolution, + * voice connect, engagement load). Discord REST / storage calls have no + * built-in timeout; without this a wedged gateway leaves the session — and + * therefore the whole daily scheduler — silently stuck forever. + */ +const PREFLIGHT_STEP_TIMEOUT_MS = 30_000; +/** Hard cap for the whole voice-connect sequence including stage retries. */ +const VOICE_CONNECT_TIMEOUT_MS = 5 * 60_000; +/** Extra wall-clock allowed past the nominal session length before the watchdog fires. */ +const SESSION_WATCHDOG_MARGIN_MS = 10 * 60_000; /** * Snapshot of the currently running (or just-scheduled) timekeeper session. @@ -203,6 +226,8 @@ export function __resetTimekeeperRuntimeState(): void { activeSkipResolver = null; pendingScheduledStartAt = null; skipFlag = false; + sessionGeneration += 1; + activeVoiceConnection = null; } /** @@ -230,18 +255,63 @@ export async function cancelActiveSession( status: options.status ?? "interrupted", }); + // Invalidate any in-flight runSession so its event loop aborts at the next + // generation check instead of continuing to play audio after cancellation. + sessionGeneration += 1; + const wedgedConnection = activeVoiceConnection; + activeVoiceConnection = null; + if (wedgedConnection) { + safeDestroy(wedgedConnection); + } + + resetSessionRuntimeState(); + pendingScheduledStartAt = null; + return true; +} + +/** + * Clear the per-session runtime singletons without touching scheduler state + * (`pendingScheduledStartAt` belongs to `scheduleNextSession`). Shared by the + * normal session tail, cancellation, and the watchdog abort path. + */ +function resetSessionRuntimeState(): void { activeSession = null; activeTimeline = []; activeClock = null; - // Mirror the normal completion path's reset so a cancelled session does - // not leak pause/skip state into the next one. Without this the next - // session starts already paused (suppressing every phase-ending-soon - // announcement) and a pending skip resolver hangs forever. activePaused = false; activeSkipResolver = null; skipFlag = false; - pendingScheduledStartAt = null; - return true; +} + +/** + * Force-abort a session whose `runSession` promise has not settled within the + * watchdog budget. Bumps the generation so the orphaned loop exits at its next + * check, destroys the tracked voice connection to unblock any voice awaits, + * persists the interrupted session when one exists, and resets module state so + * the scheduler can arm the next day cleanly. + */ +async function abortWedgedSession(): Promise { + sessionGeneration += 1; + + const wedgedConnection = activeVoiceConnection; + activeVoiceConnection = null; + if (wedgedConnection) { + safeDestroy(wedgedConnection); + } + + const session = activeSession; + if (session) { + try { + await markSessionInterrupted(session, { + reason: "watchdog", + status: "interrupted", + }); + } catch (error) { + logger.error({ err: error }, "failed to persist interrupted session during watchdog abort"); + } + } + + resetSessionRuntimeState(); } /** @@ -341,7 +411,12 @@ export function registerTimekeeper( return { detachConsent }; } -function scheduleNextSession(client: Client, config: TimekeeperConfig, botConfig: BotConfig): void { +function scheduleNextSession( + client: Client, + config: TimekeeperConfig, + botConfig: BotConfig, + notBeforeStartAt: Date | null = null, +): void { if (!isTimekeeperConfigured(config)) { logger.warn( "Timekeeper is disabled. Set voiceChannelId and textChannelId in timekeeper config.", @@ -350,12 +425,23 @@ function scheduleNextSession(client: Client, config: TimekeeperConfig, botConfig return; } - const nextStartAt = getCurrentOrNextDailyStartAt( + let nextStartAt = getCurrentOrNextDailyStartAt( new Date(), config.startHourJst, config.startMinuteJst, config.phases, ); + // A session that just ran (or failed) for `notBeforeStartAt` must not be + // re-armed for the same slot: during the pre-start window the candidate + // would be identical, producing a zero-delay hot loop of immediate + // retries. Skipping to the next day keeps one attempt per day. + if (notBeforeStartAt && nextStartAt.getTime() <= notBeforeStartAt.getTime()) { + nextStartAt = getNextDailyStartAt( + new Date(notBeforeStartAt.getTime() + 1), + config.startHourJst, + config.startMinuteJst, + ); + } const preparationStartAt = getTimekeeperPreparationStartAt(nextStartAt); const delayMs = Math.max(0, preparationStartAt.getTime() - Date.now()); pendingScheduledStartAt = nextStartAt; @@ -368,24 +454,56 @@ function scheduleNextSession(client: Client, config: TimekeeperConfig, botConfig "next timekeeper session scheduled", ); + const sessionBudgetMs = getSessionDurationMinutes(config) * 60_000; + const watchdogMs = sessionBudgetMs + SESSION_WATCHDOG_MARGIN_MS; + setTimeout(() => { + logger.info( + { startAt: nextStartAt.toISOString(), watchdogMs }, + "timekeeper session timer fired", + ); + + // Reschedule exactly once whether the session settles normally, throws, + // or is force-aborted by the watchdog. Without this guard a wedged + // runSession would leave the daily schedule permanently disarmed. + let rescheduled = false; + const rescheduleOnce = () => { + if (rescheduled) { + return; + } + rescheduled = true; + pendingScheduledStartAt = null; + scheduleNextSession(client, config, botConfig, nextStartAt); + }; + + const watchdog = setTimeout(() => { + logger.error( + { startAt: nextStartAt.toISOString(), watchdogMs }, + "timekeeper session watchdog expired; aborting wedged session", + ); + void abortWedgedSession().then(rescheduleOnce, (error: unknown) => { + logger.error({ err: error }, "watchdog abort failed; rescheduling anyway"); + rescheduleOnce(); + }); + }, watchdogMs); + void runSession(client, config, botConfig, nextStartAt) .catch((error: unknown) => { logger.error({ err: error }, "timekeeper session failed"); }) .finally(() => { - pendingScheduledStartAt = null; - scheduleNextSession(client, config, botConfig); + clearTimeout(watchdog); + rescheduleOnce(); }); }, delayMs); } +function getSessionDurationMinutes(config: TimekeeperConfig): number { + return config.phases.reduce((total, phase) => total + phase.durationMinutes, 0); +} + function isWithinSessionWindow(now: Date, startAt: Date, config: TimekeeperConfig): boolean { - const totalDurationMinutes = config.phases.reduce( - (total, phase) => total + phase.durationMinutes, - 0, - ); - const sessionEndAt = new Date(startAt.getTime() + totalDurationMinutes * 60_000); + const sessionEndAt = new Date(startAt.getTime() + getSessionDurationMinutes(config) * 60_000); return now >= startAt && now < sessionEndAt; } @@ -395,8 +513,18 @@ async function runSession( botConfig: BotConfig, startAt: Date, ): Promise { - const voiceChannel = await resolveVoiceChannel(client, config.voiceChannelId); - const textChannel = await resolveTextChannel(client, config.textChannelId); + const generation = ++sessionGeneration; + + const voiceChannel = await withTimeout( + resolveVoiceChannel(client, config.voiceChannelId), + PREFLIGHT_STEP_TIMEOUT_MS, + "resolve voice channel", + ); + const textChannel = await withTimeout( + resolveTextChannel(client, config.textChannelId), + PREFLIGHT_STEP_TIMEOUT_MS, + "resolve text channel", + ); if (!voiceChannel) { throw new Error(`Voice channel not found: ${config.voiceChannelId}`); @@ -406,11 +534,12 @@ async function runSession( throw new Error(`Text channel not found: ${config.textChannelId}`); } - const connection = await connectForPlayback( + const connection = await connectWithTimeout( voiceChannel, client, botConfig.voiceConnectionTimeoutMs, ); + activeVoiceConnection = connection; const player = createAudioPlayer({ behaviors: { @@ -421,127 +550,192 @@ async function runSession( attachVoiceDebugging(connection, player); connection.subscribe(player); - const timeline = buildTimekeeperTimeline(startAt, config); - const now = new Date(); - const startIndex = findTimelineStartIndex(timeline, now); + try { + const timeline = buildTimekeeperTimeline(startAt, config); + const now = new Date(); + const startIndex = findTimelineStartIndex(timeline, now); + + if (startIndex === -1) { + logger.info("session has already ended; skipping playback"); + return; + } - if (startIndex === -1) { - logger.info("session has already ended; skipping playback"); - connection.destroy(); - return; - } + const firstEvent = timeline[startIndex]; + if (firstEvent && firstEvent.at > now) { + logger.info( + { label: firstEvent.label, at: firstEvent.at.toISOString() }, + "starting from upcoming phase", + ); + } else if (firstEvent) { + logger.info( + { label: firstEvent.label, startedAt: firstEvent.at.toISOString() }, + "resuming from current phase", + ); + } - const firstEvent = timeline[startIndex]; - if (firstEvent && firstEvent.at > now) { - logger.info( - { label: firstEvent.label, at: firstEvent.at.toISOString() }, - "starting from upcoming phase", - ); - } else if (firstEvent) { - logger.info( - { label: firstEvent.label, startedAt: firstEvent.at.toISOString() }, - "resuming from current phase", + activeTimeline = timeline; + activeSession = await withTimeout( + createSessionEngagement(startAt.toISOString()), + PREFLIGHT_STEP_TIMEOUT_MS, + "create session engagement", ); - } - activeTimeline = timeline; - activeSession = await createSessionEngagement(startAt.toISOString()); + const minuteMs = process.env.TIMEKEEPER_RUN_ON_READY === "true" ? 1_000 : 60_000; + const clock = createSessionClock(timeline, startAt, startIndex, minuteMs, Date.now()); + activeClock = clock; + const timelineNow = getTimelineNow(clock, Date.now()); - const minuteMs = process.env.TIMEKEEPER_RUN_ON_READY === "true" ? 1_000 : 60_000; - const clock = createSessionClock(timeline, startAt, startIndex, minuteMs, Date.now()); - activeClock = clock; - const timelineNow = getTimelineNow(clock, Date.now()); + if (startIndex > 0) { + await postMissedProgressMessages(textChannel, timeline, startIndex, timelineNow); + } - if (startIndex > 0) { - await postMissedProgressMessages(textChannel, timeline, startIndex, timelineNow); - } + const progressTasks: Promise[] = []; - const progressTasks: Promise[] = []; + const eventsToRun = timeline.slice(startIndex); + for (const [index, event] of eventsToRun.entries()) { + const beforeWaitMs = Date.now(); + const waitMs = getDelayFor(clock, event.at, beforeWaitMs); + logger.info( + { + order: event.order, + kind: event.kind, + scheduledAt: event.at.toISOString(), + now: new Date(beforeWaitMs).toISOString(), + waitMs, + }, + "event waiting", + ); - const eventsToRun = timeline.slice(startIndex); - for (const [index, event] of eventsToRun.entries()) { - const beforeWaitMs = Date.now(); - const waitMs = getDelayFor(clock, event.at, beforeWaitMs); - logger.info( - { - order: event.order, - kind: event.kind, - scheduledAt: event.at.toISOString(), - now: new Date(beforeWaitMs).toISOString(), - waitMs, - }, - "event waiting", - ); + if (waitMs > 0) { + await awaitInterruptibleDelay(waitMs); + } - if (waitMs > 0) { - await awaitInterruptibleDelay(waitMs); - } + // The watchdog (or a cancellation) bumps sessionGeneration while this + // loop is suspended; bail out at the next event boundary instead of + // continuing to play audio for a session that no longer owns the state. + if (generation !== sessionGeneration) { + logger.info({ order: event.order }, "session superseded; aborting event loop"); + return; + } - // A moderator-issued `/timekeeper skip` interrupts the wait above. If - // the skip landed between this event's `at` and the next event's `at`, - // treat that as a no-op for *this* iteration; the next loop iteration - // will fire its event on schedule from its own `getDelayFor` call. + // A moderator-issued `/timekeeper skip` interrupts the wait above. If + // the skip landed between this event's `at` and the next event's `at`, + // treat that as a no-op for *this* iteration; the next loop iteration + // will fire its event on schedule from its own `getDelayFor` call. - if (isTimekeeperSessionPaused() && event.kind === "phase-ending-soon") { - logger.info({ order: event.order }, "suppressing paused phase-ending-soon"); - continue; - } + if (isTimekeeperSessionPaused() && event.kind === "phase-ending-soon") { + logger.info({ order: event.order }, "suppressing paused phase-ending-soon"); + continue; + } - const firedAtMs = Date.now(); - logger.info( - { - order: event.order, - kind: event.kind, - scheduledAt: event.at.toISOString(), - actualAt: new Date(firedAtMs).toISOString(), - latenessMs: firedAtMs - event.at.getTime(), - }, - "event firing", - ); + const firedAtMs = Date.now(); + logger.info( + { + order: event.order, + kind: event.kind, + scheduledAt: event.at.toISOString(), + actualAt: new Date(firedAtMs).toISOString(), + latenessMs: firedAtMs - event.at.getTime(), + }, + "event firing", + ); - if (!existsSync(event.audioPath)) { - throw new Error(`Audio file not found: ${event.audioPath}`); - } + if (!existsSync(event.audioPath)) { + throw new Error(`Audio file not found: ${event.audioPath}`); + } - // Bound this announcement to the time left before the next event, so a - // stalled player cannot overrun the gap and make the next event fire - // immediately after this one. - const nextEvent = eventsToRun[index + 1]; - const msUntilNextEvent = nextEvent ? getDelayFor(clock, nextEvent.at, Date.now()) : null; - - const { progressTask } = await playAnnouncement( - connection, - client, - voiceChannel, - player, - textChannel, - event, - clock, - resolvePlaybackTimeouts(msUntilNextEvent), - ); + // Bound this announcement to the time left before the next event, so a + // stalled player cannot overrun the gap and make the next event fire + // immediately after this one. + const nextEvent = eventsToRun[index + 1]; + const msUntilNextEvent = nextEvent ? getDelayFor(clock, nextEvent.at, Date.now()) : null; + + const { progressTask } = await playAnnouncement( + connection, + client, + voiceChannel, + player, + textChannel, + event, + clock, + resolvePlaybackTimeouts(msUntilNextEvent), + generation, + ); - if (progressTask) { - progressTasks.push(progressTask); + if (progressTask) { + progressTasks.push(progressTask); + } } - } - await Promise.allSettled(progressTasks); - if (activeSession) { - await persistSessionAttendance(activeSession, formatSessionDate(startAt)); - } - const fortuneSummaries = activeSession ? await buildFortuneSummary(activeSession) : null; - if (fortuneSummaries) { - for (const summary of fortuneSummaries) { - await textChannel.send(summary); + await Promise.allSettled(progressTasks); + if (activeSession) { + await persistSessionAttendance(activeSession, formatSessionDate(startAt)); + } + const fortuneSummaries = activeSession ? await buildFortuneSummary(activeSession) : null; + if (fortuneSummaries) { + for (const summary of fortuneSummaries) { + await textChannel.send(summary); + } + } + } finally { + if (generation === sessionGeneration) { + resetSessionRuntimeState(); + pendingScheduledStartAt = null; } + activeVoiceConnection = null; + safeDestroy(connection); + } +} + +/** + * Reject `promise` after `ms` so an unbounded Discord REST / storage await + * cannot wedge the session (and with it the daily scheduler) silently. + */ +function withTimeout(promise: Promise, ms: number, label: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error(`${label} timed out after ${ms}ms`)); + }, ms); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (error: unknown) => { + clearTimeout(timer); + reject(error); + }, + ); + }); +} + +/** + * `connectForPlayback` is internally bounded per attempt but its stage + * prepare path still awaits Discord REST calls (suppress / members fetch) + * that can hang. Cap the whole sequence; if the cap fires, destroy whatever + * connection the abandoned attempt eventually produces. + */ +async function connectWithTimeout( + voiceChannel: VoiceBasedChannel, + client: Client, + perAttemptTimeoutMs: number, +): Promise>> { + let expired = false; + const connectionPromise = connectForPlayback(voiceChannel, client, perAttemptTimeoutMs).then( + (connection) => { + if (expired) { + safeDestroy(connection); + } + return connection; + }, + ); + + try { + return await withTimeout(connectionPromise, VOICE_CONNECT_TIMEOUT_MS, "voice connect"); + } catch (error) { + expired = true; + throw error; } - activeSession = null; - activeTimeline = []; - activeClock = null; - activePaused = false; - activeSkipResolver = null; - skipFlag = false; - connection.destroy(); } async function playAnnouncement( @@ -553,6 +747,7 @@ async function playAnnouncement( event: TimekeeperTimelineEvent, clock: SessionClock, timeouts: PlaybackTimeouts, + generation: number, ): Promise { await refreshStageSpeakerBeforePlayback(client, voiceChannel); connection.setSpeaking(true); @@ -570,7 +765,7 @@ async function playAnnouncement( content: initialMessage, components: buildCheckInComponents(event), }); - progressTask = updateProgressMessage(sentMessage, event, clock); + progressTask = updateProgressMessage(sentMessage, event, clock, generation); } logger.info( @@ -817,6 +1012,7 @@ async function updateProgressMessage( message: EditableTextMessage, event: TimekeeperTimelineEvent, clock: SessionClock, + generation: number, ): Promise { if (!event.durationMinutes) { return; @@ -832,6 +1028,12 @@ async function updateProgressMessage( await delay(waitMs); } + // Stop editing once the session has been superseded (watchdog abort or + // cancellation); the orphaned updater must not keep writing to Discord. + if (generation !== sessionGeneration) { + return; + } + const nextMessage = buildProgressMessage( event, targetAt, diff --git a/tests/scheduled-announcements.test.ts b/tests/scheduled-announcements.test.ts index a604040..e8f96d5 100644 --- a/tests/scheduled-announcements.test.ts +++ b/tests/scheduled-announcements.test.ts @@ -669,4 +669,36 @@ describe("scheduled-announcements service", () => { setTimeoutSpy.mockRestore(); service.stop(); }); + + it("logs the idle transition once instead of every re-check tick", async () => { + writeFileSync(filePath, JSON.stringify({ entries: [] }), "utf8"); + + const client = { channels: { fetch: vi.fn() } } as unknown as Parameters< + typeof createScheduledAnnouncementsService + >[0]; + const infoMessages: string[] = []; + + const service = createScheduledAnnouncementsService(client, { + loadOptions: { filePath }, + logger: { + info: (message) => infoMessages.push(message), + warn: () => undefined, + error: () => undefined, + }, + }); + + service.start(); + await service.ready(); + + // The idle re-check fires every 60s; several ticks must not repeat the + // "entering idle loop" line (it flooded ~1440 lines/day in production). + for (let tick = 0; tick < 5; tick += 1) { + await vi.advanceTimersByTimeAsync(60_000); + } + + const idleLogs = infoMessages.filter((message) => message.includes("entering idle loop")); + expect(idleLogs).toHaveLength(1); + + service.stop(); + }); }); diff --git a/tests/timekeeper-watchdog.test.ts b/tests/timekeeper-watchdog.test.ts new file mode 100644 index 0000000..328d3bb --- /dev/null +++ b/tests/timekeeper-watchdog.test.ts @@ -0,0 +1,196 @@ +import { EventEmitter } from "node:events"; + +import type { VoiceConnection } from "@discordjs/voice"; +import * as voice from "@discordjs/voice"; +import type { Client } from "discord.js"; +import { ChannelType, Events } from "discord.js"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + __resetTimekeeperRuntimeState, + getTimekeeperSessionSnapshot, + registerTimekeeper, +} from "../src/features/timekeeper/service.js"; + +// The scheduler under test is module-private; drive it through the public +// registerTimekeeper + ClientReady path with a fake client, exactly like the +// composition root does in production. +vi.mock("@discordjs/voice", () => ({ + AudioPlayerStatus: { + AutoPaused: "autopaused", + Buffering: "buffering", + Idle: "idle", + Paused: "paused", + Playing: "playing", + }, + createAudioPlayer: vi.fn(() => ({ + play: vi.fn(), + state: { status: "idle" }, + stop: vi.fn(), + })), + createAudioResource: vi.fn(() => ({})), + entersState: vi.fn(), + joinVoiceChannel: vi.fn(), + NoSubscriberBehavior: { Pause: "pause" }, + VoiceConnectionStatus: { + Destroyed: "destroyed", + Ready: "ready", + Signalling: "signalling", + }, +})); + +// Voice-state snapshots pull extra Discord REST calls; stub the debug hooks so +// the test only exercises the scheduler/session lifecycle. +vi.mock("../src/features/timekeeper/voice-debug.js", () => ({ + attachVoiceDebugging: vi.fn(), + logVoiceStateSnapshot: vi.fn(), +})); + +// Engagement persistence would hit the storage driver (real fs I/O cannot +// complete inside fake-time advancement, tripping the pre-flight timeout); +// stub both entry points so tests exercise only the scheduler/session loop. +vi.mock("../src/features/timekeeper/engagement.js", async (importOriginal) => { + const actual = (await importOriginal()) as Record; + return { + ...actual, + createSessionEngagement: vi.fn((id: string) => + Promise.resolve({ + attendanceDatesByUserId: new Map(), + checkInsByUserId: new Map(), + driver: {} as never, + id, + }), + ), + markSessionInterrupted: vi.fn(() => Promise.resolve()), + }; +}); + +const mockedJoinVoiceChannel = vi.mocked(voice.joinVoiceChannel); +const mockedEntersState = vi.mocked(voice.entersState) as unknown as ReturnType< + typeof vi.fn<(target: unknown, status: unknown, timeoutMs?: number) => Promise> +>; + +function buildFakeClient(options: { hangChannelFetch?: boolean } = {}): Client { + const emitter = new EventEmitter(); + // timekeeperConfig uses the same channel id for voice and text; a single + // dual-purpose fake satisfies both resolvers for any fetched id. + const channel = { + guild: { + id: "guild-id", + members: { fetch: vi.fn(() => Promise.resolve(null)) }, + voiceAdapterCreator: () => ({}) as never, + }, + id: "channel-id", + isTextBased: () => true, + isVoiceBased: () => true, + send: vi.fn(() => Promise.resolve({ edit: vi.fn(() => Promise.resolve()) })), + type: ChannelType.GuildVoice, + }; + + const fetch = vi.fn(() => { + if (options.hangChannelFetch) { + return new Promise(() => {}); + } + return Promise.resolve(channel); + }); + + return Object.assign(emitter, { + channels: { fetch }, + user: { id: "bot-user-id" }, + }) as unknown as Client; +} + +function buildVoiceConnection(): VoiceConnection { + return { + destroy: vi.fn(), + setSpeaking: vi.fn(), + subscribe: vi.fn(), + } as unknown as VoiceConnection; +} + +const botConfig = { voiceConnectionTimeoutMs: 5_000 } as never; + +beforeEach(() => { + mockedJoinVoiceChannel.mockReset(); + mockedEntersState.mockReset(); + __resetTimekeeperRuntimeState(); + vi.useFakeTimers(); + // Anchor the clock so the next 21:00 JST session is ~2h away: a short, + // deterministic schedule delay instead of up to ~24h. + vi.setSystemTime(new Date("2026-11-22T10:00:00Z")); // 19:00 JST +}); + +afterEach(() => { + vi.useRealTimers(); + __resetTimekeeperRuntimeState(); +}); + +/** Flush microtasks between timer advances. */ +async function tick(ms: number): Promise { + await vi.advanceTimersByTimeAsync(ms); + await Promise.resolve(); +} + +describe("timekeeper scheduler resilience", () => { + it("reschedules the next day when a pre-flight REST call hangs", async () => { + // Reproduces the production wedge: channels.fetch never settles (zombie + // gateway). The pre-flight timeout must fail the session loudly AND the + // scheduler must arm the following day instead of stopping forever. + const client = buildFakeClient({ hangChannelFetch: true }); + registerTimekeeper(client, { botConfig }); + (client as unknown as EventEmitter).emit(Events.ClientReady); + await tick(0); + + expect(getTimekeeperSessionSnapshot().pendingStartAt?.toISOString()).toBe( + "2026-11-22T12:00:00.000Z", + ); + + // Advance past the schedule delay (prep starts 20:57 JST = 11:57Z), then + // past the 30s pre-flight timeout that rejects the wedged fetch. + await tick(118 * 60_000); + await tick(60_000); + + expect(getTimekeeperSessionSnapshot().pendingStartAt?.toISOString()).toBe( + "2026-11-23T12:00:00.000Z", + ); + // The session never reached the voice layer. + expect(mockedJoinVoiceChannel).not.toHaveBeenCalled(); + }); + + it("watchdog aborts a wedged session and re-arms the daily schedule", async () => { + const connection = buildVoiceConnection(); + mockedJoinVoiceChannel.mockReturnValue(connection); + // Voice connect resolves; the audio player's Idle transition never does, + // so playAnnouncement stays suspended inside the session — the exact + // shape of an unbounded await the watchdog exists for. + mockedEntersState.mockImplementation((_target: unknown, status: unknown) => + status === "idle" ? new Promise(() => {}) : Promise.resolve(), + ); + + const client = buildFakeClient(); + registerTimekeeper(client, { botConfig }); + (client as unknown as EventEmitter).emit(Events.ClientReady); + await tick(0); + + // Fire the scheduled session (prep 11:57Z, start 12:00Z). + await tick(118 * 60_000); + // Let the first event reach the wedged Idle wait. + await tick(5 * 60_000); + expect(mockedJoinVoiceChannel).toHaveBeenCalledTimes(1); + + // Session budget is 100min + 10min margin; push past the watchdog. + await tick(115 * 60_000); + + // The wedged connection must be destroyed and the schedule re-armed for + // the next day — this is the assertion that would have caught the + // production incident. + expect(connection.destroy as ReturnType).toHaveBeenCalled(); + expect(getTimekeeperSessionSnapshot().pendingStartAt?.toISOString()).toBe( + "2026-11-23T12:00:00.000Z", + ); + + // ~22h later the re-armed timer must fire a second session. + await tick(23 * 60 * 60_000); + expect(mockedJoinVoiceChannel).toHaveBeenCalledTimes(2); + }); +});