openreader/tests/unit/document-blob-lease.vitest.spec.ts
Richard R 848ee4faad feat(tasks): add document blob lease for safe orphan reaping and improve scheduled task robustness
Introduce a document blob lease mechanism to prevent race conditions between document registration and orphaned blob cleanup. The new `document_blob_leases` table ensures that only one process can claim a document blob for mutation or deletion at a time. Update the orphan reaper to acquire a lease before deleting blobs and to re-check for ownership after acquiring the lease, avoiding accidental deletion of in-flight uploads.

Enhance scheduled task infrastructure with per-task fencing tokens to prevent stale runners from overwriting newer results, enforce runtime limits with abort signals, and expose scheduler mode and minimum interval to the admin panel and API. Adjust task handlers to accept a context with abort support, and update documentation and environment variable references for the new cron secret and scheduling behavior.

BREAKING CHANGE: Scheduled tasks now require a `document_blob_leases` table and updated handler signatures. Vercel deployments must set `CRON_SECRET` for scheduled maintenance.
2026-06-07 12:08:57 -06:00

47 lines
1.6 KiB
TypeScript

import { beforeEach, describe, expect, test, vi } from 'vitest';
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import * as sqliteSchema from '../../src/db/schema_sqlite';
const holder = vi.hoisted(() => ({ db: null as unknown as ReturnType<typeof drizzle> }));
vi.mock('@/db', () => ({
get db() {
return holder.db;
},
}));
import { tryAcquireDocumentBlobLease } from '../../src/lib/server/documents/blob-lease';
beforeEach(() => {
const sqlite = new Database(':memory:');
sqlite.exec(`CREATE TABLE document_blob_leases (
document_id text PRIMARY KEY NOT NULL,
lease_owner text NOT NULL,
lease_until_ms integer NOT NULL
);`);
holder.db = drizzle(sqlite, { schema: sqliteSchema });
});
describe('document blob lease', () => {
test('allows only one owner until the lease is released', async () => {
const first = await tryAcquireDocumentBlobLease('doc-1');
const blocked = await tryAcquireDocumentBlobLease('doc-1');
expect(first).not.toBeNull();
expect(blocked).toBeNull();
await first?.release();
await expect(tryAcquireDocumentBlobLease('doc-1')).resolves.not.toBeNull();
});
test('allows an expired lease to be reclaimed', async () => {
const first = await tryAcquireDocumentBlobLease('doc-1', { leaseMs: 1 });
expect(first).not.toBeNull();
await new Promise((resolve) => setTimeout(resolve, 2));
const replacement = await tryAcquireDocumentBlobLease('doc-1');
expect(replacement).not.toBeNull();
expect(replacement?.owner).not.toBe(first?.owner);
});
});