Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: track GC sweep timers in scheduler (#4890)

Adam Eivyfb5e50f40ae1
diff --git a/server/services/imageCleanTmpGc.js b/server/services/imageCleanTmpGc.js
index f5668fdf17..6f377d8b37 100644
--- a/server/services/imageCleanTmpGc.js
+++ b/server/services/imageCleanTmpGc.js
@@ -18,6 +18,7 @@ import { readdir, stat, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import { PATHS } from '../lib/fileUtils.js';
import { listJobs } from './mediaJobQueue/index.js';
+import { createSweepScheduler } from './sweepScheduler.js';
// Grace window before a temp clean file is eligible for deletion, measured
// against mtime. An hour is generous next to the seconds-to-minutes a GPU clean
@@ -60,9 +61,6 @@ export function collectActiveCleanBasenames(jobs = []) {
// the dir bounded without busywork.
const SWEEP_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
-let sweepTimer = null;
-let initialSweepTimer = null;
-
/**
* Delete every file under `tmpDir` older than `maxAgeMs`. Returns
* `{ deleted, keptYoung }`. A missing dir yields all-zero. Pure over its args so
@@ -101,34 +99,20 @@ export async function sweepImageCleanTmp({
}
/**
- * Start the periodic sweep. Fires once ~5 min after boot (off the startup hot
- * path) then hourly. Idempotent — a second call is a no-op.
+ * Log the domain summary for one scheduler-owned sweep.
*/
-export function startImageCleanTmpGc() {
- if (sweepTimer) return;
-
- const runSweep = () => {
- sweepImageCleanTmp()
- .then(({ deleted }) => {
- if (deleted > 0) console.log(`🧹 Image-clean temp GC: removed ${deleted} stale file(s)`);
- })
- .catch((err) => console.error(`❌ Image-clean temp GC sweep failed: ${err.message}`));
- };
-
- initialSweepTimer = setTimeout(() => { initialSweepTimer = null; runSweep(); }, 5 * 60 * 1000);
- initialSweepTimer.unref?.();
- sweepTimer = setInterval(runSweep, SWEEP_INTERVAL_MS);
- sweepTimer.unref?.();
-}
+const runSweep = async () => {
+ const { deleted } = await sweepImageCleanTmp();
+ if (deleted > 0) console.log(`🧹 Image-clean temp GC: removed ${deleted} stale file(s)`);
+};
-/** Stop the periodic sweep (used by tests / graceful shutdown). */
-export function stopImageCleanTmpGc() {
- if (initialSweepTimer) {
- clearTimeout(initialSweepTimer);
- initialSweepTimer = null;
- }
- if (sweepTimer) {
- clearInterval(sweepTimer);
- sweepTimer = null;
- }
-}
+export const {
+ start: startImageCleanTmpGc,
+ stop: stopImageCleanTmpGc,
+} = createSweepScheduler({
+ id: 'image-clean-tmp-gc',
+ intervalMs: SWEEP_INTERVAL_MS,
+ initialDelayMs: 5 * 60 * 1000,
+ handler: runSweep,
+ source: 'imageCleanTmpGc',
+});
diff --git a/server/services/imageRefsGc.js b/server/services/imageRefsGc.js
index c2938b7451..7d63415508 100644
--- a/server/services/imageRefsGc.js
+++ b/server/services/imageRefsGc.js
@@ -32,14 +32,14 @@
* reference sheets (`universe-…`, `sheet-…`) and any other file in the dir are
* never matched.
*
- * Runs OUTSIDE the Express request lifecycle (a `setInterval` from index.js),
- * so this module wraps its sweep in try/catch and logs single-line per the repo
- * logging convention — an uncaught throw here would crash the process.
+ * Runs OUTSIDE the Express request lifecycle through eventScheduler, which
+ * catches handler failures and records them in scheduler history.
*/
import { readdir, stat, unlink } from 'fs/promises';
import { join, basename } from 'path';
import { PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+import { createSweepScheduler } from './sweepScheduler.js';
// `init-<uuid>` / `ref-<uuid>` with a decodable image extension — the exact
// staged-upload discriminator migration 085 uses. The UUID shape is loose on
@@ -56,9 +56,6 @@ export const ORPHAN_REF_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
// so a slow cadence is fine — daily keeps `data/image-refs` bounded without churn.
const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
-let sweepTimer = null;
-let initialSweepTimer = null;
-
/**
* Scan every gallery sidecar and collect the set of `data/image-refs` basenames
* any kept image still references (`initImageFilename` + `referenceImageFilenames`).
@@ -140,40 +137,22 @@ export async function sweepOrphanRefImages({
}
/**
- * Start the periodic sweep. Fires once on a short delay after boot (so a long
- * grace window doesn't mean accumulation waits a full day after a restart) then
- * on SWEEP_INTERVAL_MS. Idempotent — a second call is a no-op.
+ * Log the domain summary for one scheduler-owned sweep.
*/
-export function startImageRefsGc() {
- if (sweepTimer) return;
-
- const runSweep = () => {
- sweepOrphanRefImages()
- .then(({ deleted }) => {
- if (deleted > 0) {
- console.log(`🧹 Image-refs GC: removed ${deleted} orphan staged upload(s)`);
- }
- })
- .catch((err) => console.error(`❌ Image-refs GC sweep failed: ${err.message}`));
- };
-
- // Initial pass ~5 min after boot — off the startup hot path, but soon enough
- // that a restart doesn't reset the cleanup clock. Keep the handle so
- // stopImageRefsGc() can cancel it if shutdown lands inside the window.
- initialSweepTimer = setTimeout(() => { initialSweepTimer = null; runSweep(); }, 5 * 60 * 1000);
- initialSweepTimer.unref?.();
- sweepTimer = setInterval(runSweep, SWEEP_INTERVAL_MS);
- sweepTimer.unref?.();
-}
-
-/** Stop the periodic sweep (used by tests / graceful shutdown). */
-export function stopImageRefsGc() {
- if (initialSweepTimer) {
- clearTimeout(initialSweepTimer);
- initialSweepTimer = null;
- }
- if (sweepTimer) {
- clearInterval(sweepTimer);
- sweepTimer = null;
+const runSweep = async () => {
+ const { deleted } = await sweepOrphanRefImages();
+ if (deleted > 0) {
+ console.log(`🧹 Image-refs GC: removed ${deleted} orphan staged upload(s)`);
}
-}
+};
+
+export const {
+ start: startImageRefsGc,
+ stop: stopImageRefsGc,
+} = createSweepScheduler({
+ id: 'image-refs-gc',
+ intervalMs: SWEEP_INTERVAL_MS,
+ initialDelayMs: 5 * 60 * 1000,
+ handler: runSweep,
+ source: 'imageRefsGc',
+});
diff --git a/server/services/importerOrphanGc.js b/server/services/importerOrphanGc.js
index 8a5acb1b17..4b0de85eee 100644
--- a/server/services/importerOrphanGc.js
+++ b/server/services/importerOrphanGc.js
@@ -26,14 +26,14 @@
* - The age gate is measured from `updatedAt` (the most recent touch), so a
* user mid-flight on a fresh analyze is never swept out from under them.
*
- * Runs OUTSIDE the Express request lifecycle (a `setInterval` from index.js),
- * so this module wraps its sweep in try/catch and logs single-line per the
- * repo logging convention — an uncaught throw here would crash the process.
+ * Runs OUTSIDE the Express request lifecycle through eventScheduler, which
+ * catches handler failures and records them in scheduler history.
*/
import { listUniverses, deleteUniverse } from './universeBuilder.js';
import { listSeries, deleteSeries } from './pipeline/series.js';
import { listAllIssues } from './pipeline/issues.js';
+import { createSweepScheduler } from './sweepScheduler.js';
// Grace window before an abandoned, never-committed shell is eligible for GC.
// Measured against `updatedAt`. Generous on purpose — the cost of an orphan
@@ -45,9 +45,6 @@ export const ORPHAN_SHELL_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
// so a slow cadence is fine — daily keeps `data/` tidy without churn.
const SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
-let sweepTimer = null;
-let initialSweepTimer = null;
-
const ageMs = (record, now) => {
const ts = Date.parse(record?.updatedAt || record?.createdAt || '');
return Number.isFinite(ts) ? now - ts : NaN;
@@ -139,40 +136,22 @@ export async function sweepOrphanShells({ now = Date.now(), maxAgeMs = ORPHAN_SH
}
/**
- * Start the periodic sweep. Fires once on a short delay after boot (so a long
- * grace window doesn't mean orphans wait a full day after a restart) then on
- * SWEEP_INTERVAL_MS. Idempotent — a second call is a no-op.
+ * Log the domain summary for one scheduler-owned sweep.
*/
-export function startOrphanShellGc() {
- if (sweepTimer) return;
-
- const runSweep = () => {
- sweepOrphanShells()
- .then(({ deletedSeries, deletedUniverses }) => {
- if (deletedSeries.length > 0 || deletedUniverses.length > 0) {
- console.log(`🧹 Importer orphan GC: removed ${deletedSeries.length} series + ${deletedUniverses.length} universe shells`);
- }
- })
- .catch((err) => console.error(`❌ Importer orphan GC sweep failed: ${err.message}`));
- };
-
- // Initial pass ~5 min after boot — outside the startup hot path, but soon
- // enough that a restart doesn't reset the cleanup clock. Keep the handle so
- // stopOrphanShellGc() can cancel it if shutdown lands inside the 5-min window.
- initialSweepTimer = setTimeout(() => { initialSweepTimer = null; runSweep(); }, 5 * 60 * 1000);
- initialSweepTimer.unref?.();
- sweepTimer = setInterval(runSweep, SWEEP_INTERVAL_MS);
- sweepTimer.unref?.();
-}
-
-/** Stop the periodic sweep (used by tests / graceful shutdown). */
-export function stopOrphanShellGc() {
- if (initialSweepTimer) {
- clearTimeout(initialSweepTimer);
- initialSweepTimer = null;
- }
- if (sweepTimer) {
- clearInterval(sweepTimer);
- sweepTimer = null;
+const runSweep = async () => {
+ const { deletedSeries, deletedUniverses } = await sweepOrphanShells();
+ if (deletedSeries.length > 0 || deletedUniverses.length > 0) {
+ console.log(`🧹 Importer orphan GC: removed ${deletedSeries.length} series + ${deletedUniverses.length} universe shells`);
}
-}
+};
+
+export const {
+ start: startOrphanShellGc,
+ stop: stopOrphanShellGc,
+} = createSweepScheduler({
+ id: 'importer-orphan-gc',
+ intervalMs: SWEEP_INTERVAL_MS,
+ initialDelayMs: 5 * 60 * 1000,
+ handler: runSweep,
+ source: 'importerOrphanGc',
+});
diff --git a/server/services/sweepScheduler.js b/server/services/sweepScheduler.js
new file mode 100644
index 0000000000..6b4e5004dc
--- /dev/null
+++ b/server/services/sweepScheduler.js
@@ -0,0 +1,39 @@
+/**
+ * Shared eventScheduler registration for periodic garbage-collection sweeps.
+ *
+ * Each GC gets one delayed boot pass plus one recurring interval. Keeping both
+ * in eventScheduler makes them cancellable and visible in scheduler history.
+ */
+
+import { cancel, getEvent, schedule } from './eventScheduler.js';
+
+const INITIAL_SUFFIX = ':initial';
+
+export function createSweepScheduler({ id, intervalMs, initialDelayMs, handler, source }) {
+ const initialId = `${id}${INITIAL_SUFFIX}`;
+
+ return {
+ start() {
+ if (getEvent(id)?.active) return;
+
+ schedule({
+ id: initialId,
+ type: 'once',
+ delayMs: initialDelayMs,
+ handler,
+ metadata: { source },
+ });
+ schedule({
+ id,
+ type: 'interval',
+ intervalMs,
+ handler,
+ metadata: { source },
+ });
+ },
+ stop() {
+ cancel(initialId);
+ cancel(id);
+ },
+ };
+}
diff --git a/server/services/sweepScheduler.test.js b/server/services/sweepScheduler.test.js
new file mode 100644
index 0000000000..198709c755
--- /dev/null
+++ b/server/services/sweepScheduler.test.js
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const cancelMock = vi.fn();
+const getEventMock = vi.fn();
+const scheduleMock = vi.fn();
+
+vi.mock('./eventScheduler.js', () => ({
+ cancel: (...args) => cancelMock(...args),
+ getEvent: (...args) => getEventMock(...args),
+ schedule: (...args) => scheduleMock(...args),
+}));
+
+const { createSweepScheduler } = await import('./sweepScheduler.js');
+
+beforeEach(() => {
+ cancelMock.mockClear();
+ getEventMock.mockReset();
+ scheduleMock.mockClear();
+});
+
+const build = () => createSweepScheduler({
+ id: 'demo-gc',
+ intervalMs: 60_000,
+ initialDelayMs: 5_000,
+ handler: vi.fn(),
+ source: 'demoGc',
+});
+
+describe('createSweepScheduler', () => {
+ it('registers a delayed boot sweep and a recurring interval', () => {
+ const handler = vi.fn();
+ const scheduler = createSweepScheduler({
+ id: 'demo-gc',
+ intervalMs: 60_000,
+ initialDelayMs: 5_000,
+ handler,
+ source: 'demoGc',
+ });
+
+ scheduler.start();
+
+ expect(scheduleMock).toHaveBeenCalledTimes(2);
+ expect(scheduleMock.mock.calls.map(([event]) => event)).toEqual([
+ {
+ id: 'demo-gc:initial',
+ type: 'once',
+ delayMs: 5_000,
+ handler,
+ metadata: { source: 'demoGc' },
+ },
+ {
+ id: 'demo-gc',
+ type: 'interval',
+ intervalMs: 60_000,
+ handler,
+ metadata: { source: 'demoGc' },
+ },
+ ]);
+ });
+
+ it('keeps start idempotent while the interval is active', () => {
+ getEventMock.mockReturnValue({ active: true });
+
+ build().start();
+
+ expect(scheduleMock).not.toHaveBeenCalled();
+ });
+
+ it('cancels both the delayed and recurring events', () => {
+ build().stop();
+
+ expect(cancelMock.mock.calls).toEqual([
+ ['demo-gc:initial'],
+ ['demo-gc'],
+ ]);
+ });
+});