Download src/lib/sync-engine.ts from Zero124/VR-MEDIA: direct link, hf CLI and curl.
- Browser
- Download file 19.5 kB
-
https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/sync-engine.ts
- Command line
-
hf download hf://spaces/Zero124/VR-MEDIA/src/lib/sync-engine.ts
-
curl -L -o sync-engine.ts https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/sync-engine.ts
19.5 kB
| // Incremental Offcloud sync ("delta sync"). | |
| // | |
| // Goals, in the order they matter: | |
| // 1. NEVER re-analyze content that is already indexed and ready to play. | |
| // A video that reached status "ready" is skipped forever unless its bytes | |
| // change (size/name) or the user explicitly forces a re-scan. | |
| // 2. Only brand-new Offcloud content is queued for the 11-layer detection. | |
| // 3. Content deleted from Offcloud disappears from the UI and the DEOVR feed | |
| // immediately (availability = "missing"), and is purged after a grace | |
| // period so a transient API hiccup can never wipe the library. | |
| // 4. No manual re-scan: an auto-sync loop polls Offcloud continuously. | |
| // 5. On every cold start (Space waking from sleep/pause) a FULL sync runs, so | |
| // the whole library is reconciled and loaded before the user arrives. | |
| // | |
| // Cheapness matters because the poll interval can be as low as 1 second: each | |
| // cycle fetches the Offcloud listing once, hashes it, and does zero database | |
| // writes when nothing changed. | |
| import { db } from "./db"; | |
| import { scanLibrary, type OffcloudFile } from "./offcloud"; | |
| import { ensureSchema } from "./migrate"; | |
| export type SyncMode = "delta" | "full"; | |
| export type SyncTrigger = "boot" | "auto" | "manual" | "force"; | |
| export type AutoSyncConfig = { | |
| /** Master switch for continuous polling. */ | |
| enabled: boolean; | |
| /** Seconds between polls. 1 is allowed; 5 is the sane default. */ | |
| intervalSeconds: number; | |
| /** Run a full reconcile when the server process starts. */ | |
| fullSyncOnBoot: boolean; | |
| /** | |
| * Hours to keep a video that vanished from Offcloud before deleting its row. | |
| * It is hidden from the UI and feed immediately either way. 0 = never delete. | |
| */ | |
| pruneAfterHours: number; | |
| }; | |
| export type SyncResult = { | |
| at: string; | |
| mode: SyncMode; | |
| trigger: SyncTrigger; | |
| /** False when the Offcloud listing was byte-identical to the previous poll. */ | |
| changed: boolean; | |
| offcloudMode: "real" | "mock"; | |
| discovered: number; | |
| added: number; | |
| updated: number; | |
| requeued: number; | |
| skippedReady: number; | |
| markedMissing: number; | |
| restored: number; | |
| pruned: number; | |
| durationMs: number; | |
| error?: string; | |
| }; | |
| export type SyncState = { | |
| running: boolean; | |
| loopArmed: boolean; | |
| lastSyncAt: string | null; | |
| lastChangeAt: string | null; | |
| lastResult: SyncResult | null; | |
| totalSyncs: number; | |
| consecutiveErrors: number; | |
| nextPollInSeconds: number | null; | |
| libraryFingerprint: string | null; | |
| }; | |
| export const AUTO_SYNC_SETTING = "auto_sync_config"; | |
| const LOG = "[sync]"; | |
| const MAX_BACKOFF_SECONDS = 60; | |
| export function getDefaultAutoSyncConfig(): AutoSyncConfig { | |
| return sanitizeAutoSyncConfig({ | |
| enabled: process.env.AUTO_SYNC_ENABLED !== "false", | |
| intervalSeconds: Number(process.env.AUTO_SYNC_INTERVAL_SECONDS || 5), | |
| fullSyncOnBoot: process.env.AUTO_SYNC_FULL_ON_BOOT !== "false", | |
| pruneAfterHours: Number(process.env.AUTO_SYNC_PRUNE_AFTER_HOURS || 24), | |
| }); | |
| } | |
| export function sanitizeAutoSyncConfig(input: Partial<AutoSyncConfig>): AutoSyncConfig { | |
| let interval = Number(input.intervalSeconds); | |
| if (!Number.isFinite(interval)) interval = 5; | |
| // 1s is the floor the user asked for; 3600s the ceiling. | |
| interval = Math.min(3600, Math.max(1, Math.round(interval))); | |
| let prune = Number(input.pruneAfterHours); | |
| if (!Number.isFinite(prune) || prune < 0) prune = 24; | |
| prune = Math.min(24 * 90, Math.round(prune)); | |
| return { | |
| enabled: input.enabled !== false, | |
| intervalSeconds: interval, | |
| fullSyncOnBoot: input.fullSyncOnBoot !== false, | |
| pruneAfterHours: prune, | |
| }; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Process-wide state (survives module re-evaluation / hot reload) | |
| // --------------------------------------------------------------------------- | |
| type Runtime = { | |
| timer: ReturnType<typeof setTimeout> | null; | |
| config: AutoSyncConfig | null; | |
| running: boolean; | |
| started: boolean; | |
| lastSyncAt: string | null; | |
| lastChangeAt: string | null; | |
| lastResult: SyncResult | null; | |
| totalSyncs: number; | |
| consecutiveErrors: number; | |
| fingerprint: string | null; | |
| nextPollAt: number | null; | |
| }; | |
| const globalRef = globalThis as unknown as { __vrmsSync?: Runtime }; | |
| function rt(): Runtime { | |
| if (!globalRef.__vrmsSync) { | |
| globalRef.__vrmsSync = { | |
| timer: null, | |
| config: null, | |
| running: false, | |
| started: false, | |
| lastSyncAt: null, | |
| lastChangeAt: null, | |
| lastResult: null, | |
| totalSyncs: 0, | |
| consecutiveErrors: 0, | |
| fingerprint: null, | |
| nextPollAt: null, | |
| }; | |
| } | |
| return globalRef.__vrmsSync; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Config persistence | |
| // --------------------------------------------------------------------------- | |
| export async function getAutoSyncConfig(): Promise<AutoSyncConfig> { | |
| const state = rt(); | |
| if (state.config) return state.config; | |
| try { | |
| const row = await db.setting.findUnique({ where: { key: AUTO_SYNC_SETTING } }); | |
| if (row?.value) { | |
| state.config = sanitizeAutoSyncConfig({ | |
| ...getDefaultAutoSyncConfig(), | |
| ...(JSON.parse(row.value) as Partial<AutoSyncConfig>), | |
| }); | |
| return state.config; | |
| } | |
| } catch { | |
| // DB cold — fall through to env defaults. | |
| } | |
| state.config = getDefaultAutoSyncConfig(); | |
| return state.config; | |
| } | |
| export async function updateAutoSyncConfig( | |
| patch: Partial<AutoSyncConfig> | |
| ): Promise<AutoSyncConfig> { | |
| const current = await getAutoSyncConfig(); | |
| const next = sanitizeAutoSyncConfig({ ...current, ...patch }); | |
| rt().config = next; | |
| try { | |
| const value = JSON.stringify(next); | |
| await db.setting.upsert({ | |
| where: { key: AUTO_SYNC_SETTING }, | |
| create: { key: AUTO_SYNC_SETTING, value }, | |
| update: { value }, | |
| }); | |
| } catch (err) { | |
| console.warn(`${LOG} could not persist auto-sync config:`, err); | |
| } | |
| scheduleNextPoll(0); | |
| return next; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Identity helpers | |
| // --------------------------------------------------------------------------- | |
| /** Stable identity of a file on Offcloud. */ | |
| function contentKeyOf(file: OffcloudFile): string { | |
| return `${file.offcloudId}::${file.name}`; | |
| } | |
| /** | |
| * Fingerprint of the *content*, not the URL. Offcloud stream URLs rotate, so | |
| * including them would make every poll look like a change and re-trigger | |
| * analysis — exactly what we are avoiding. | |
| */ | |
| function contentHashOf(file: OffcloudFile): string { | |
| return `${file.size}|${file.duration ?? ""}`; | |
| } | |
| /** Fingerprint of the whole listing, used to short-circuit unchanged polls. */ | |
| function libraryFingerprint(files: OffcloudFile[]): string { | |
| const parts = files | |
| .map((f) => `${contentKeyOf(f)}#${contentHashOf(f)}`) | |
| .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)}`; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // The sync itself | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Reconcile the local index with Offcloud. | |
| * | |
| * @param mode "delta" skips all work when the listing is unchanged. | |
| * "full" always reconciles (used on boot and manual scans). | |
| * @param force Re-queue detection even for videos already "ready". | |
| */ | |
| export async function syncOnce(options?: { | |
| mode?: SyncMode; | |
| trigger?: SyncTrigger; | |
| force?: boolean; | |
| }): Promise<SyncResult> { | |
| const mode = options?.mode ?? "delta"; | |
| const trigger = options?.trigger ?? "auto"; | |
| const force = options?.force === true; | |
| const state = rt(); | |
| const startedAt = Date.now(); | |
| const base: SyncResult = { | |
| at: new Date().toISOString(), | |
| mode, | |
| trigger, | |
| changed: false, | |
| offcloudMode: "real", | |
| discovered: 0, | |
| added: 0, | |
| updated: 0, | |
| requeued: 0, | |
| skippedReady: 0, | |
| markedMissing: 0, | |
| restored: 0, | |
| pruned: 0, | |
| durationMs: 0, | |
| }; | |
| if (state.running) { | |
| return { ...base, error: "A sync is already running", durationMs: 0 }; | |
| } | |
| state.running = true; | |
| try { | |
| await ensureSchema(); | |
| const config = await getAutoSyncConfig(); | |
| const { files, mode: scanMode } = await scanLibrary(); | |
| const offcloudMode: "real" | "mock" = scanMode === "error" ? "real" : scanMode; | |
| base.offcloudMode = offcloudMode; | |
| base.discovered = files.length; | |
| const fingerprint = libraryFingerprint(files); | |
| const unchanged = fingerprint === state.fingerprint; | |
| // Fast path: nothing on Offcloud changed and we are not forcing a full | |
| // reconcile. Zero writes — this is what makes 1-second polling viable. | |
| if (unchanged && mode === "delta" && !force) { | |
| 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 seenAt = new Date(); | |
| const seenKeys: string[] = []; | |
| let added = 0; | |
| let updated = 0; | |
| let requeued = 0; | |
| let skippedReady = 0; | |
| let restored = 0; | |
| for (const file of files) { | |
| const key = contentKeyOf(file); | |
| const hash = contentHashOf(file); | |
| seenKeys.push(key); | |
| const existing = await db.video.findFirst({ | |
| // Scope to Offcloud rows: TeraBox/Blomp ids live in the same table and | |
| // must never be matched (or reconciled) by this engine. | |
| where: { source: "offcloud", offcloudId: file.offcloudId, name: file.name }, | |
| }); | |
| if (!existing) { | |
| // Brand-new content — index it and queue the detection pipeline. | |
| const created = await db.video.create({ | |
| data: { | |
| source: "offcloud", | |
| offcloudId: file.offcloudId, | |
| 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"; | |
| // Always keep the stream URL and presence bookkeeping fresh: Offcloud URLs | |
| // expire, and this is cheap compared with re-analysis. | |
| await db.video.update({ | |
| where: { id: existing.id }, | |
| data: { | |
| streamUrl: file.streamUrl, | |
| folderPath: file.folderPath, | |
| 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" } : {}), | |
| }, | |
| }); | |
| updated++; | |
| if (wasMissing) restored++; | |
| if (alreadyReady && !bytesChanged && !force) { | |
| // The whole point: already loaded and playable, so do nothing. | |
| skippedReady++; | |
| continue; | |
| } | |
| if (await enqueue(existing.id)) requeued++; | |
| } | |
| // ---- Content deleted from Offcloud ----------------------------------- | |
| // Only trust deletions when we really talked to Offcloud. In mock mode, or | |
| // when the listing came back empty because of an API error, we leave the | |
| // library alone rather than hiding everything. | |
| let markedMissing = 0; | |
| let pruned = 0; | |
| const deletionsTrustworthy = scanMode === "real" && files.length > 0; | |
| if (deletionsTrustworthy) { | |
| const vanished = await db.video.findMany({ | |
| where: { | |
| // Source-scoped: an Offcloud poll only owns Offcloud rows. Without | |
| // this, every Blomp/TeraBox video would be marked missing on the | |
| // first poll because it was never in the Offcloud listing. | |
| source: "offcloud", | |
| 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 Offcloud — hidden from library and feed`); | |
| } | |
| // Purge rows that have been gone longer than the grace period. | |
| if (config.pruneAfterHours > 0) { | |
| const cutoff = new Date(Date.now() - config.pruneAfterHours * 3600_000); | |
| const { count } = await db.video.deleteMany({ | |
| where: { | |
| source: "offcloud", | |
| availability: "missing", | |
| missingSince: { lt: cutoff }, | |
| }, | |
| }); | |
| pruned = count; | |
| } | |
| } | |
| // Start the detection worker whenever anything is waiting - not only on the | |
| // poll that queued it. This lets a stalled queue recover by itself. | |
| const waiting = await db.queueItem.count({ where: { status: "queued" } }); | |
| if (waiting > 0) { | |
| const { ensureQueueProcessing } = await import("./scan-engine"); | |
| void ensureQueueProcessing(offcloudMode); | |
| } | |
| 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; | |
| if (changed) state.lastChangeAt = state.lastSyncAt; | |
| const result: SyncResult = { | |
| ...base, | |
| changed, | |
| added, | |
| updated, | |
| requeued, | |
| skippedReady, | |
| markedMissing, | |
| restored, | |
| pruned, | |
| durationMs: Date.now() - startedAt, | |
| }; | |
| state.lastResult = result; | |
| if (changed || mode === "full") { | |
| console.log( | |
| `${LOG} ${mode}/${trigger}: ${base.discovered} on Offcloud, +${added} new, ${skippedReady} already ready (skipped), ${requeued} queued, ${markedMissing} removed, ${pruned} purged (${result.durationMs}ms)` | |
| ); | |
| } | |
| return result; | |
| } catch (err) { | |
| const msg = err instanceof Error ? err.message : String(err); | |
| state.consecutiveErrors += 1; | |
| const result: SyncResult = { ...base, error: msg, durationMs: Date.now() - startedAt }; | |
| state.lastResult = result; | |
| console.warn(`${LOG} failed: ${msg}`); | |
| return result; | |
| } finally { | |
| state.running = false; | |
| } | |
| } | |
| /** Queue a video for detection unless it is already waiting. Returns true if queued. */ | |
| async function enqueue(videoId: string): Promise<boolean> { | |
| 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; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Auto-sync loop | |
| // --------------------------------------------------------------------------- | |
| function scheduleNextPoll(overrideSeconds?: number): void { | |
| const state = rt(); | |
| if (state.timer) { | |
| clearTimeout(state.timer); | |
| state.timer = null; | |
| } | |
| const config = state.config; | |
| if (!config || !config.enabled) { | |
| state.nextPollAt = null; | |
| return; | |
| } | |
| // Exponential backoff while Offcloud is unhappy, so a 1s interval cannot turn | |
| // into a hammering loop against a failing API. | |
| const backoff = | |
| state.consecutiveErrors > 0 | |
| ? Math.min( | |
| MAX_BACKOFF_SECONDS, | |
| config.intervalSeconds * Math.pow(2, Math.min(state.consecutiveErrors, 6)) | |
| ) | |
| : config.intervalSeconds; | |
| const seconds = overrideSeconds ?? backoff; | |
| state.nextPollAt = Date.now() + seconds * 1000; | |
| state.timer = setTimeout(async () => { | |
| try { | |
| await syncOnce({ mode: "delta", trigger: "auto" }); | |
| } catch { | |
| // syncOnce never throws, but stay defensive inside a timer. | |
| } | |
| scheduleNextPoll(); | |
| }, Math.max(250, seconds * 1000)); | |
| state.timer.unref?.(); | |
| } | |
| /** | |
| * Start continuous syncing. Called from src/instrumentation.ts on every server | |
| * boot — including when a Hugging Face Space wakes from sleep or pause, which | |
| * is exactly when the full reconcile is needed. | |
| */ | |
| export async function startAutoSync(): Promise<SyncState> { | |
| const state = rt(); | |
| const config = await getAutoSyncConfig(); | |
| state.config = config; | |
| if (!state.started) { | |
| state.started = true; | |
| console.log( | |
| `${LOG} auto-sync online — every ${config.intervalSeconds}s, prune after ${ | |
| config.pruneAfterHours || "never" | |
| }h` | |
| ); | |
| if (config.fullSyncOnBoot) { | |
| // Cold start / wake from sleep: reconcile and load the entire library. | |
| await syncOnce({ mode: "full", trigger: "boot" }).catch(() => {}); | |
| } | |
| } | |
| scheduleNextPoll(); | |
| return getSyncState(); | |
| } | |
| export function getSyncState(): SyncState { | |
| const state = rt(); | |
| return { | |
| running: state.running, | |
| loopArmed: Boolean(state.timer), | |
| lastSyncAt: state.lastSyncAt, | |
| lastChangeAt: state.lastChangeAt, | |
| lastResult: state.lastResult, | |
| totalSyncs: state.totalSyncs, | |
| consecutiveErrors: state.consecutiveErrors, | |
| nextPollInSeconds: state.nextPollAt | |
| ? Math.max(0, Math.round((state.nextPollAt - Date.now()) / 1000)) | |
| : null, | |
| libraryFingerprint: state.fingerprint, | |
| }; | |
| } | |
| /** Library counts for the sync status card. */ | |
| export async function getLibraryCounts() { | |
| const [available, missing, ready, pending, queued] = await Promise.all([ | |
| db.video.count({ where: { availability: "available" } }), | |
| db.video.count({ where: { availability: "missing" } }), | |
| db.video.count({ where: { availability: "available", status: "ready" } }), | |
| db.video.count({ where: { availability: "available", status: { in: ["pending", "scanning"] } } }), | |
| db.queueItem.count({ where: { status: { in: ["queued", "running"] } } }), | |
| ]); | |
| return { available, missing, ready, pending, queued }; | |
| } | |