File size: 21,327 Bytes
5c0175e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | // 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<typeof setTimeout> | 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<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;
}
// ---------------------------------------------------------------------------
// 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<BlompSyncResult> {
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<BlompSyncState> {
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,
};
}
|