music: nightly 3am full reindex (staged + atomic swap)

Self-scheduling timer in the sidecar (fresh setTimeout each night, so it always
fires at 3am local regardless of drift) runs reindexFull() — builds into a fresh
slot and swaps atomically only on success, never disrupting the live index.
Started at boot, cleared on shutdown. Logs the next scheduled time + each run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-27 16:30:42 +00:00
co-authored by Claude Opus 4.8
parent b1d1c91968
commit 1f21768c4c
2 changed files with 48 additions and 0 deletions
+5
View File
@@ -3,6 +3,7 @@ import { join } from 'node:path';
import type { SidecarCommand, SidecarEvent } from '../protocol';
import { createSidecarConnector } from '../connect';
import { streamAudioFile } from './stream-audio';
import { startNightlyReindex, stopNightlyReindex } from './nightly-reindex';
import {
reindexNow,
ensureCacheSetup,
@@ -74,6 +75,9 @@ const port = getFreePort();
// Ensure the cache is a symlink-to-slot before serving/building, so full reindexes can swap atomically.
await ensureCacheSetup();
// Nightly full reindex at 3am (staged + atomic swap).
startNightlyReindex();
const server = Bun.serve({
port,
hostname: '127.0.0.1',
@@ -267,6 +271,7 @@ const connection = createSidecarConnector({
function shutdown(signal: string) {
console.log(`[music] ${signal} received, shutting down...`);
stopNightlyReindex();
try {
server.stop(true);
} catch {
@@ -0,0 +1,43 @@
import { reindexFull } from './indexer';
// Nightly full-from-scratch reindex at 3am (server-local time). Uses reindexFull, so it builds into a
// fresh slot and atomically swaps it in only on success — the live index is never disrupted mid-build.
// Self-scheduling (a fresh setTimeout each night) rather than setInterval, so it always fires at 3am
// regardless of drift.
const REINDEX_HOUR = 3;
let timer: ReturnType<typeof setTimeout> | null = null;
function msUntilNextHour(hour: number): number {
const now = new Date();
const next = new Date(now);
next.setHours(hour, 0, 0, 0);
if (next <= now) next.setDate(next.getDate() + 1);
return next.getTime() - now.getTime();
}
export function startNightlyReindex(): void {
const schedule = () => {
const ms = msUntilNextHour(REINDEX_HOUR);
const at = new Date(Date.now() + ms);
console.log(`[music] nightly full reindex scheduled for ${at.toLocaleString()} (in ${(ms / 3_600_000).toFixed(1)}h)`);
timer = setTimeout(async () => {
console.log('[music] nightly full reindex starting');
try {
await reindexFull();
} catch (err) {
console.error('[music] nightly full reindex error:', err instanceof Error ? err.message : err);
}
schedule(); // reschedule for the following night
}, ms);
};
schedule();
}
export function stopNightlyReindex(): void {
if (timer) {
clearTimeout(timer);
timer = null;
}
}