// Incremental Blomp sync ("delta sync"). // // Blomp is reconciled on its own schedule so connecting the account is enough: // no manual "Scan Blomp" is needed. The loop aims for the same behaviour as the // Offcloud sync: // // 1. New objects in the container are indexed and queued for detection. // 2. Existing videos keep their analysis. Only the stream URL and presence // bookkeeping are refreshed, so a poll is cheap. // 3. Objects deleted from Blomp are hidden immediately (availability = // "missing") and purged after the shared grace period. // 4. Objects that reappear are restored automatically. // 5. On boot, or right after the account is connected, a full reconcile runs. // // Deletions are only trusted when the listing actually returned objects. That // mirrors the Offcloud engine: a transient empty/failed listing must never wipe // the whole library. // // The default poll interval is 60 seconds because Blomp's listing endpoint is // rate-limited; BLOMP_SYNC_INTERVAL_SECONDS can override it (15s minimum). import { db } from "./db"; import { getBlompConfig, scanBlompLibrary } from "./blomp"; import { applyBlompCustomThumbnails } from "./custom-thumbs"; import type { CustomThumbImage } from "./custom-thumbs"; import { ensureSchema } from "./migrate"; import { getAutoSyncConfig } from "./sync-engine"; import type { SourceFile } from "./types"; export type BlompSyncMode = "delta" | "full"; export type BlompSyncTrigger = "boot" | "auto" | "manual"; export type BlompSyncResult = { at: string; mode: BlompSyncMode; trigger: BlompSyncTrigger; configured: boolean; /** False when the Blomp listing was byte-identical to the previous poll. */ changed: boolean; container: string | null; root: string; discovered: number; added: number; updated: number; requeued: number; skippedReady: number; markedMissing: number; restored: number; pruned: number; /** Custom thumbnails currently matched to Blomp videos. */ thumbsMatched: number; /** Custom thumbnail matches written this run (new or changed images). */ thumbsApplied: number; /** Custom thumbnail matches withdrawn this run (images gone upstream). */ thumbsRemoved: number; durationMs: number; error?: string; }; export type BlompSyncState = { running: boolean; loopArmed: boolean; enabled: boolean; intervalSeconds: number; lastSyncAt: string | null; totalSyncs: number; consecutiveErrors: number; nextPollInSeconds: number | null; lastResult: BlompSyncResult | null; libraryFingerprint: string | null; }; const LOG = "[blomp-sync]"; const DEFAULT_INTERVAL_SECONDS = 60; const MIN_INTERVAL_SECONDS = 15; const MAX_BACKOFF_SECONDS = 300; function configuredIntervalSeconds(): number { const raw = Number(process.env.BLOMP_SYNC_INTERVAL_SECONDS || DEFAULT_INTERVAL_SECONDS); if (!Number.isFinite(raw)) return DEFAULT_INTERVAL_SECONDS; return Math.min(3600, Math.max(MIN_INTERVAL_SECONDS, Math.round(raw))); } function autoSyncDisabled(): boolean { return (process.env.BLOMP_SYNC_ENABLED ?? "").trim().toLowerCase() === "false"; } // --------------------------------------------------------------------------- // Process-wide state (survives module re-evaluation / hot reload) // --------------------------------------------------------------------------- type Runtime = { timer: ReturnType | null; started: boolean; running: boolean; intervalSeconds: number; lastSyncAt: string | null; lastResult: BlompSyncResult | null; totalSyncs: number; consecutiveErrors: number; nextPollAt: number | null; fingerprint: string | null; }; const globalRef = globalThis as unknown as { __vrmsBlompSync?: Runtime }; function rt(): Runtime { if (!globalRef.__vrmsBlompSync) { globalRef.__vrmsBlompSync = { timer: null, started: false, running: false, intervalSeconds: configuredIntervalSeconds(), lastSyncAt: null, lastResult: null, totalSyncs: 0, consecutiveErrors: 0, nextPollAt: null, fingerprint: null, }; } return globalRef.__vrmsBlompSync; } // --------------------------------------------------------------------------- // Identity helpers // --------------------------------------------------------------------------- /** Stable identity of a Blomp object. */ function contentKeyOf(file: SourceFile): string { return file.sourceId; } /** * Fingerprint of the bytes, not the URL. Blomp's storage URL can rotate with * the auth token, so including streamUrl would make every poll look changed. */ function contentHashOf(file: SourceFile): string { return `${file.size}|${file.addedAt ? file.addedAt.toISOString() : ""}`; } /** Fingerprint of the drive images too — uploading a thumbnail must wake the * delta sync even when no video changed. */ function imageFingerprintOf(image: CustomThumbImage): string { return `img:${image.container}/${image.objectName}#${image.bytes}|${image.lastModified ?? ""}`; } function libraryFingerprint(files: SourceFile[], images: CustomThumbImage[]): string { const parts = files .map((f) => `${contentKeyOf(f)}#${contentHashOf(f)}`) .concat(images.map(imageFingerprintOf)) .sort(); let h1 = 0x811c9dc5; let h2 = 0x01000193; const joined = parts.join("\n"); for (let i = 0; i < joined.length; i++) { const c = joined.charCodeAt(i); h1 = (h1 ^ c) * 0x01000193 >>> 0; h2 = (h2 + c * 31) >>> 0; } return `${parts.length}-${h1.toString(16)}${h2.toString(16)}`; } /** Queue a video for detection unless it is already waiting. Returns true if queued. */ async function enqueue(videoId: string): Promise { const existing = await db.queueItem.findFirst({ where: { videoId, status: { in: ["queued", "running"] } }, }); if (existing) return false; await db.queueItem.create({ data: { videoId, status: "queued", currentStep: null, stepProgress: 0 }, }); return true; } // --------------------------------------------------------------------------- // The sync itself // --------------------------------------------------------------------------- /** * Reconcile the local index with Blomp. * * @param mode "delta" skips all work when the listing is unchanged. * "full" always reconciles (used on boot and manual runs). * @param force Re-queue detection even for videos already marked ready. */ export async function syncBlompOnce(options?: { mode?: BlompSyncMode; trigger?: BlompSyncTrigger; force?: boolean; }): Promise { const mode = options?.mode ?? "delta"; const trigger = options?.trigger ?? "auto"; const force = options?.force === true; const state = rt(); const startedAt = Date.now(); const base: BlompSyncResult = { at: new Date().toISOString(), mode, trigger, configured: false, changed: false, container: null, root: "", discovered: 0, added: 0, updated: 0, requeued: 0, skippedReady: 0, markedMissing: 0, restored: 0, pruned: 0, thumbsMatched: 0, thumbsApplied: 0, thumbsRemoved: 0, durationMs: 0, }; if (state.running) { return { ...base, error: "A Blomp sync is already running", durationMs: 0 }; } state.running = true; try { await ensureSchema(); const cfg = await getBlompConfig(); base.configured = cfg.configured; base.root = cfg.root; // Not connected (yet): report it, keep the library untouched and wait for // the next poll. Connecting the account triggers an immediate sync. if (!cfg.configured) { state.lastSyncAt = new Date().toISOString(); state.totalSyncs += 1; state.consecutiveErrors = 0; const result = { ...base, durationMs: Date.now() - startedAt }; state.lastResult = result; return result; } const scan = await scanBlompLibrary(); base.container = scan.container; base.root = scan.root; base.discovered = scan.files.length; if (scan.error) throw new Error(scan.error); const fingerprint = libraryFingerprint(scan.files, scan.images); const unchanged = fingerprint === state.fingerprint; // Fast path: listing identical, no writes at all. if (unchanged && mode === "delta" && !force) { // Even an unchanged listing can hide work for the auto thumbnail // uploader: a video whose detection finished after the last pass, or a // retry whose backoff elapsed. Keep the pass ticking (it is a no-op // when nothing is eligible). if (scan.files.length > 0) { try { const { runBlompThumbUploadPass } = await import("./thumb-uploader"); void runBlompThumbUploadPass({ folders: scan.folders, imageFolders: scan.images.map((image) => image.folderPath), trigger, }).catch(() => {}); } catch { // Module load issue — the next poll retries. } } state.lastSyncAt = new Date().toISOString(); state.totalSyncs += 1; state.consecutiveErrors = 0; const result = { ...base, changed: false, durationMs: Date.now() - startedAt }; state.lastResult = result; return result; } const autoSync = await getAutoSyncConfig(); const seenAt = new Date(); let added = 0; let updated = 0; let requeued = 0; let skippedReady = 0; let restored = 0; for (const file of scan.files) { const key = contentKeyOf(file); const hash = contentHashOf(file); const existing = await db.video.findFirst({ where: { source: "blomp", sourceId: file.sourceId }, }); if (!existing) { // Brand-new object — index it and queue the detection pipeline so it // becomes playable in the library and the DEOVR feed. const created = await db.video.create({ data: { source: "blomp", sourceId: file.sourceId, sourcePath: file.sourcePath ?? null, // offcloudId is required in the legacy schema; it mirrors the // provider id for non-Offcloud rows. offcloudId: file.sourceId, name: file.name, folderPath: file.folderPath, streamUrl: file.streamUrl, size: file.size, duration: file.duration ?? null, addedAt: file.addedAt ?? null, status: "pending", availability: "available", lastSeenAt: seenAt, contentKey: key, contentHash: hash, }, }); await enqueue(created.id); added++; requeued++; continue; } const bytesChanged = existing.contentHash != null && existing.contentHash !== hash; const wasMissing = existing.availability !== "available"; const alreadyReady = existing.status === "ready"; // Refresh the object URL and presence bookkeeping on every poll. This is // cheap and keeps playback working when Blomp rotates the storage URL. await db.video.update({ where: { id: existing.id }, data: { name: file.name, folderPath: file.folderPath, sourcePath: file.sourcePath ?? existing.sourcePath, streamUrl: file.streamUrl || existing.streamUrl, size: file.size, addedAt: file.addedAt ?? existing.addedAt, availability: "available", missingSince: null, lastSeenAt: seenAt, contentKey: key, contentHash: hash, // Status is deliberately untouched: a "ready" video stays ready. ...(bytesChanged || force ? { status: "pending", errorMessage: null } : {}), }, }); updated++; if (wasMissing) restored++; if (alreadyReady && !bytesChanged && !force) { skippedReady++; continue; } if (await enqueue(existing.id)) requeued++; } // ---- Objects deleted from Blomp -------------------------------------- // Only trust deletions when the listing actually returned objects, exactly // like the Offcloud engine: a failed/empty response must not hide the // library. Anything that vanished is hidden immediately. let markedMissing = 0; let pruned = 0; const deletionsTrustworthy = scan.files.length > 0; if (deletionsTrustworthy) { const vanished = await db.video.findMany({ where: { source: "blomp", availability: "available", OR: [{ lastSeenAt: null }, { lastSeenAt: { lt: seenAt } }], }, select: { id: true, name: true }, }); if (vanished.length > 0) { await db.video.updateMany({ where: { id: { in: vanished.map((v) => v.id) } }, data: { availability: "missing", missingSince: seenAt }, }); // Drop any pending analysis for content that no longer exists. await db.queueItem.deleteMany({ where: { videoId: { in: vanished.map((v) => v.id) }, status: { in: ["queued", "running"] }, }, }); markedMissing = vanished.length; console.log( `${LOG} ${markedMissing} item(s) removed from Blomp — hidden from library and feed` ); } // Purge rows that have been gone longer than the grace period. if (autoSync.pruneAfterHours > 0) { const cutoff = new Date(Date.now() - autoSync.pruneAfterHours * 3600_000); const { count } = await db.video.deleteMany({ where: { source: "blomp", availability: "missing", missingSince: { lt: cutoff }, }, }); pruned = count; } } // ---- Custom thumbnails (user-uploaded images matched by name) -------- // Runs after the video reconcile so brand-new videos are matched in the // same pass. An empty image listing only withdraws matches when the // container actually returned objects — mirroring the deletion paranoia // above. let thumbsMatched = 0; let thumbsApplied = 0; let thumbsRemoved = 0; try { const listingTrustworthy = scan.files.length > 0 || scan.images.length > 0; const thumbs = await applyBlompCustomThumbnails(scan.images, { trustEmpty: listingTrustworthy, }); if (!thumbs.skipped) { thumbsMatched = thumbs.matched; thumbsApplied = thumbs.applied; thumbsRemoved = thumbs.removed; } } catch (err) { // Never fail the whole sync over thumbnails. console.warn( `${LOG} custom thumbnail matching failed: ${ err instanceof Error ? err.message : String(err) }` ); } // ---- Auto thumbnail upload (generate posters, push to Blomp) -------- // Fire-and-forget: every Blomp video without a thumbnail gets a // generated poster pushed into the title-matched folder (never creating // folders). When the pass uploads something it schedules an immediate // re-sync, so the new images are matched without waiting for the next // poll. if (scan.files.length > 0) { try { const { runBlompThumbUploadPass } = await import("./thumb-uploader"); void runBlompThumbUploadPass({ folders: scan.folders, imageFolders: scan.images.map((image) => image.folderPath), trigger, }).catch(() => {}); } catch (err) { console.warn(`${LOG} auto thumbnail pass could not start:`, err); } } // Start/continue the detection worker whenever anything is waiting. Doing // this every poll makes the queue self-healing after a crash or restart. const waiting = await db.queueItem.count({ where: { status: "queued" } }); if (waiting > 0) { const { ensureQueueProcessing } = await import("./scan-engine"); void ensureQueueProcessing("real"); } state.fingerprint = fingerprint; state.lastSyncAt = new Date().toISOString(); state.totalSyncs += 1; state.consecutiveErrors = 0; const changed = added > 0 || requeued > 0 || markedMissing > 0 || restored > 0 || pruned > 0 || thumbsApplied > 0 || thumbsRemoved > 0; const result: BlompSyncResult = { ...base, changed, added, updated, requeued, skippedReady, markedMissing, restored, pruned, thumbsMatched, thumbsApplied, thumbsRemoved, durationMs: Date.now() - startedAt, }; state.lastResult = result; if (changed || mode === "full") { console.log( `${LOG} ${mode}/${trigger}: ${base.discovered} on Blomp (${base.root}), +${added} new, ${skippedReady} already ready (skipped), ${requeued} queued, ${markedMissing} removed, ${pruned} purged, ${thumbsMatched} custom thumbnails (${thumbsApplied} applied, ${thumbsRemoved} withdrawn) (${result.durationMs}ms)` ); } return result; } catch (err) { const msg = err instanceof Error ? err.message : String(err); state.consecutiveErrors += 1; const result: BlompSyncResult = { ...base, error: msg, durationMs: Date.now() - startedAt }; state.lastResult = result; // Missing items are never touched here: a failed listing is not a deletion. console.warn(`${LOG} failed: ${msg}`); return result; } finally { state.running = false; } } // --------------------------------------------------------------------------- // Auto-sync loop // --------------------------------------------------------------------------- /** * Run a delta sync "soon": wait out any in-flight sync, then reconcile once. * Used by the auto thumbnail uploader right after it pushed new posters, so * the images are matched to their videos within seconds instead of waiting * for the next poll. */ export function syncBlompSoon(attempt = 0): void { const state = rt(); if (state.running) { if (attempt < 10) setTimeout(() => syncBlompSoon(attempt + 1), 3000); return; } const timer = setTimeout(() => { void syncBlompOnce({ mode: "delta", trigger: "auto" }).catch(() => {}); }, 1500); timer.unref?.(); } function scheduleNextPoll(overrideSeconds?: number): void { const state = rt(); if (state.timer) { clearTimeout(state.timer); state.timer = null; } if (autoSyncDisabled()) { state.nextPollAt = null; return; } const backoff = state.consecutiveErrors > 0 ? Math.min( MAX_BACKOFF_SECONDS, state.intervalSeconds * Math.pow(2, Math.min(state.consecutiveErrors, 5)) ) : state.intervalSeconds; const seconds = overrideSeconds ?? backoff; state.nextPollAt = Date.now() + seconds * 1000; state.timer = setTimeout(async () => { try { // The Library sync switch is the master switch for all sources. const config = await getAutoSyncConfig(); if (config.enabled) { await syncBlompOnce({ mode: "delta", trigger: "auto" }); } } catch { // syncBlompOnce never throws, but stay defensive inside a timer. } scheduleNextPoll(); }, Math.max(1000, seconds * 1000)); state.timer.unref?.(); } /** * Start continuous Blomp syncing. Called from src/instrumentation.ts on every * server boot; also safe to call from a route (idempotent). An immediate full * reconcile runs when the account is configured. */ export async function startBlompSync(): Promise { const state = rt(); state.intervalSeconds = configuredIntervalSeconds(); if (!state.started) { state.started = true; console.log( `${LOG} auto-sync online — every ${state.intervalSeconds}s${ autoSyncDisabled() ? " (disabled by BLOMP_SYNC_ENABLED)" : "" }` ); if (!autoSyncDisabled()) { // Do not block server startup on the first reconcile. void syncBlompOnce({ mode: "full", trigger: "boot" }).catch(() => {}); } } // Polling the status endpoint must not keep postponing the next poll, so only // arm the timer when there is none. if (!state.timer) scheduleNextPoll(); return getBlompSyncState(); } export function getBlompSyncState(): BlompSyncState { const state = rt(); return { running: state.running, loopArmed: Boolean(state.timer), enabled: !autoSyncDisabled(), intervalSeconds: state.intervalSeconds, lastSyncAt: state.lastSyncAt, totalSyncs: state.totalSyncs, consecutiveErrors: state.consecutiveErrors, nextPollInSeconds: state.nextPollAt ? Math.max(0, Math.round((state.nextPollAt - Date.now()) / 1000)) : null, lastResult: state.lastResult, libraryFingerprint: state.fingerprint, }; }