* refactor(user): overhaul user data cleanup and export for cascading deletes and TTS segment support Revise user data cleanup logic to ensure proper cascading deletion of user-related database rows and S3 objects, including shared document and preview artifacts. Introduce explicit checks for last ownership before removing shared resources. Add TTS segment cache and audio cleanup to document and user deletion flows. Expand user data export to include TTS segment entries and audio, job events, document settings, and linked auth sessions. Update schema with ON DELETE CASCADE for userTtsChars and userJobEvents. Add new migration scripts and comprehensive unit tests for cleanup and export scenarios. * test(user): expand cleanup and export coverage for shared docs and TTS segment files Add tests for user data cleanup with shared document ownership and for TTS segment variant export scenarios, including cases with duplicate audio keys and storage disabled. Refactor cleanup logic to use document row types and transactional ownership removal with last-owner checks. Update TTS segment cache clearing to report deleted segment count by unique entry. Adjust export logic to always include all TTS segment variants and conditionally export file buckets based on storage availability. Update migration to use NOT VALID/VALIDATE for new cascading constraints. * refactor(documents): centralize owned document deletion and add mutation locking Introduce `deleteOwnedDocument` utility to encapsulate all logic for removing a user's ownership of a document, including TTS segment cache cleanup, preview artifact removal, and S3 blob deletion for last-owner cases. Add `withDocumentMutationLock` to serialize concurrent mutations on the same document, using advisory locks in Postgres and a local queue fallback. Refactor all API routes and user data flows to use these utilities, ensuring transactional safety and preventing race conditions during document deletion or transfer. Update tests for new flows and add coverage for document cleanup sequencing and locking behavior. * feat(data): enhance anonymous claim to support document settings and TTS segment copy Expand the anonymous data claim process to include document settings transfer and TTS segment S3 prefix copying. Remove foreign key constraints from user_tts_chars to allow non-user buckets. Update claim modal and onboarding flow to display claimed document settings. Refactor TTS char count transfer to merge all dates and fix upsert logic. Add S3 copy utility for TTS segments and corresponding tests. Update migrations and schema to reflect relaxed constraints. * refactor(data): improve error handling and rollback for document and TTS segment operations Enhance robustness of document deletion and TTS segment transfer by improving error logging, partial rollback, and degraded state reporting. Add best-effort cleanup and recovery mechanisms to prevent orphaned data and ensure diagnostic information is captured for unexpected failures. Update user data cleanup to log and swallow restoration errors without masking primary failures. Refine claim logic to handle unmapped TTS audio keys safely. * refactor(data): unify document mutation locking and transaction handling Replace mutation-lock with document-lock to centralize document mutation serialization and database transaction management. Introduce runInDbTransaction utility to abstract SQLite/Postgres transaction differences. Update document deletion, user data cleanup, and rate limiter logic to delegate transaction handling and locking to shared helpers. Remove dialect-specific branching and inline transaction logic for improved maintainability and testability. BREAKING CHANGE: withDocumentMutationLock is removed in favor of withDocumentLock and runInDbTransaction * fix(documents): improve rollback error handling in deleteOwnedDocument Enhance error handling during document deletion by ensuring that failures in restoring document ownership do not obscure the original error. Log degraded events when ownership restoration fails after a deletion error, providing additional context for debugging and monitoring. This change improves reliability and traceability of document deletion operations. * feat(tasks): introduce scheduled task engine and admin UI for background jobs Add a general-purpose scheduled task system with a persistent registry and status tracking, supporting background maintenance jobs such as orphaned blob reaping, expired upload cleanup, job event pruning, and TTS usage retention. Implement a new `scheduled_tasks` table, task engine, and handlers for each maintenance operation. Integrate an admin UI panel for monitoring, manual runs, and configuration of tasks. Update document and user data cleanup flows to delegate shared blob and preview deletion to the scheduled reaper. Add Vercel cron integration for serverless environments. BREAKING CHANGE: Document and user storage cleanup now relies on background scheduled tasks for shared blob and preview deletion; immediate inline deletion is no longer performed. * refactor(user): streamline document and TTS segment transfer logic Simplify user document transfer by consolidating storage and metadata handling. Remove inline deletion of shared blobs; only metadata is moved, and TTS segment transfer is controlled via options. Add `skipStorage` option for test scenarios to bypass storage operations. Update tests to reflect new transfer behavior. * chore(instrumentation): delegate node-specific setup to separate module Move Node.js-specific instrumentation logic to a dedicated file. Update registration to dynamically import the node module only when running in a Node.js environment. This separation clarifies environment-specific behavior and improves maintainability. * ci(config): update scheduled task cron to run daily at midnight Change cron schedule for /api/admin/tasks/tick from hourly to once daily at midnight to reduce task frequency and align with updated operational requirements. * refactor(tasks): enforce positive interval and improve scheduled task updates Add database-level check constraints to ensure scheduled task intervals are always positive for both Postgres and SQLite. Update admin API and UI to support sub-minute intervals and stricter validation. Refactor scheduled task update logic to upsert rows, ensuring tasks can be updated even if not yet present in the database. Improve temporary upload cleanup to delete in paginated batches. Enhance tests to cover new constraints and update behaviors. * chore(docker): remove ffmpeg-static from runtime dependencies in image build Eliminate ffmpeg-static from the production node_modules during Docker image assembly to streamline the deployment artifact and avoid bundling unused binaries. * refactor(admin): redesign task panel UI with Card layout and running indicator Replace the bordered div layout in AdminTasksPanel with the Card component for improved visual hierarchy. Add a dynamic running indicator using a custom RunningDot component to clearly show active tasks. Update control alignment and button states for better usability. Remove Badge-based status display in favor of a more streamlined appearance. * 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. * refactor(admin): add loading skeleton to tasks panel for improved UX Introduce a TasksSkeleton component to display animated placeholders while scheduled tasks are loading. Replace direct rendering of empty task rows with the skeleton when data is pending, enhancing perceived responsiveness and user experience in the admin tasks panel. * test: clean up playwright anonymous users * test: make blob lease expiry deterministic * fix(documents): improve blob lease release error handling and test stale lease scenario Handle errors during blob lease release by logging warnings instead of allowing them to mask original results. Update unit tests to verify that releasing a stale lease does not affect a replacement lease. * refactor(documents): implement exponential backoff with jitter for blob lease retries Replace fixed retry delay with capped exponential backoff and jitter to reduce contention and thundering herd effect when acquiring document blob leases. This improves lease acquisition fairness and efficiency under high load.
243 lines
8 KiB
TypeScript
243 lines
8 KiB
TypeScript
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
|
import Database from 'better-sqlite3';
|
|
import { drizzle } from 'drizzle-orm/better-sqlite3';
|
|
import { eq } from 'drizzle-orm';
|
|
import * as sqliteSchema from '../../src/db/schema_sqlite';
|
|
|
|
// Back the engine with a real in-memory SQLite so the CAS claim, due-detection,
|
|
// and nextRunAt arithmetic are exercised against real SQL rather than mocks.
|
|
const holder = vi.hoisted(() => ({ db: null as unknown as ReturnType<typeof drizzle> }));
|
|
vi.mock('@/db', () => ({
|
|
get db() {
|
|
return holder.db;
|
|
},
|
|
}));
|
|
|
|
// Keep the error-path test from printing the expected failure to the console.
|
|
vi.mock('@/lib/server/errors/logging', () => ({ logDegraded: vi.fn() }));
|
|
|
|
import { runDueTasks, updateTask } from '../../src/lib/server/tasks/engine';
|
|
import type { TaskRegistry } from '../../src/lib/server/tasks/types';
|
|
|
|
const tasks = sqliteSchema.scheduledTasks;
|
|
|
|
const CREATE_TABLE = `CREATE TABLE scheduled_tasks (
|
|
key text PRIMARY KEY NOT NULL,
|
|
enabled integer DEFAULT true NOT NULL,
|
|
interval_ms integer NOT NULL,
|
|
last_status text DEFAULT 'idle' NOT NULL,
|
|
lease_owner text,
|
|
last_run_at integer,
|
|
last_duration_ms integer,
|
|
last_error text,
|
|
last_result_json text,
|
|
next_run_at integer,
|
|
run_requested integer DEFAULT false NOT NULL,
|
|
running_since integer,
|
|
updated_at integer DEFAULT (cast(unixepoch('subsecond') * 1000 as integer)) NOT NULL,
|
|
CONSTRAINT scheduled_tasks_interval_ms_positive CHECK(interval_ms > 0)
|
|
);`;
|
|
|
|
const KEY = 'test-task';
|
|
|
|
async function seedRow(overrides: Partial<typeof tasks.$inferInsert>) {
|
|
await holder.db.insert(tasks).values({
|
|
key: KEY,
|
|
enabled: true,
|
|
intervalMs: 1000,
|
|
lastStatus: 'idle',
|
|
nextRunAt: Date.now() - 1,
|
|
runRequested: false,
|
|
...overrides,
|
|
});
|
|
}
|
|
|
|
async function readRow() {
|
|
const rows = await holder.db.select().from(tasks).where(eq(tasks.key, KEY));
|
|
return rows[0];
|
|
}
|
|
|
|
function registryWith(run: () => Promise<{ summary?: string } | void>): TaskRegistry {
|
|
return { [KEY]: { name: 'Test task', defaultIntervalMs: 1000, run } };
|
|
}
|
|
|
|
beforeEach(() => {
|
|
const sqlite = new Database(':memory:');
|
|
sqlite.exec(CREATE_TABLE);
|
|
holder.db = drizzle(sqlite, { schema: sqliteSchema });
|
|
});
|
|
|
|
describe('scheduled task engine', () => {
|
|
test('runs a due task and records success + next run', async () => {
|
|
const handler = vi.fn(async () => ({ summary: 'did 3 things' }));
|
|
await seedRow({ nextRunAt: Date.now() - 1 });
|
|
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
|
|
expect(handler).toHaveBeenCalledTimes(1);
|
|
const row = await readRow();
|
|
expect(row.lastStatus).toBe('ok');
|
|
expect(row.lastRunAt).not.toBeNull();
|
|
expect(row.lastResultJson).toBe('did 3 things');
|
|
expect(row.runningSince).toBeNull();
|
|
expect(Number(row.nextRunAt)).toBeGreaterThan(Date.now());
|
|
});
|
|
|
|
test('does not run a task that is not yet due', async () => {
|
|
const handler = vi.fn(async () => undefined);
|
|
await seedRow({ nextRunAt: Date.now() + 60_000, lastStatus: 'idle' });
|
|
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
|
|
expect(handler).not.toHaveBeenCalled();
|
|
expect((await readRow()).lastStatus).toBe('idle');
|
|
});
|
|
|
|
test('runs when a manual run is requested even if not due', async () => {
|
|
const handler = vi.fn(async () => ({ summary: 'manual' }));
|
|
await seedRow({ nextRunAt: Date.now() + 60_000, runRequested: true });
|
|
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
|
|
expect(handler).toHaveBeenCalledTimes(1);
|
|
const row = await readRow();
|
|
expect(row.lastStatus).toBe('ok');
|
|
expect(row.runRequested).toBe(false);
|
|
});
|
|
|
|
test('records errors without throwing', async () => {
|
|
const handler = vi.fn(async () => {
|
|
throw new Error('boom');
|
|
});
|
|
await seedRow({ nextRunAt: Date.now() - 1 });
|
|
|
|
await expect(runDueTasks({ registry: registryWith(handler) })).resolves.toBeUndefined();
|
|
|
|
const row = await readRow();
|
|
expect(row.lastStatus).toBe('error');
|
|
expect(row.lastError).toContain('boom');
|
|
});
|
|
|
|
test('single-flight: skips a task already marked running', async () => {
|
|
const handler = vi.fn(async () => undefined);
|
|
await seedRow({ nextRunAt: Date.now() - 1, lastStatus: 'running', runningSince: Date.now() });
|
|
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
|
|
expect(handler).not.toHaveBeenCalled();
|
|
expect((await readRow()).lastStatus).toBe('running');
|
|
});
|
|
|
|
test('runs a requested task even when disabled', async () => {
|
|
const handler = vi.fn(async () => undefined);
|
|
await seedRow({ nextRunAt: Date.now() + 60_000, enabled: false, runRequested: true });
|
|
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
|
|
expect(handler).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
test('preserves a manual rerun requested while a task is running', async () => {
|
|
const handler = vi.fn(async () => {
|
|
await holder.db
|
|
.update(tasks)
|
|
.set({ runRequested: true })
|
|
.where(eq(tasks.key, KEY));
|
|
});
|
|
await seedRow({ nextRunAt: Date.now() - 1 });
|
|
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
|
|
expect(handler).toHaveBeenCalledTimes(1);
|
|
expect((await readRow()).runRequested).toBe(true);
|
|
});
|
|
|
|
test('does not let a stale runner overwrite its replacement run', async () => {
|
|
let resolveFirst!: (value: { summary: string }) => void;
|
|
const firstResult = new Promise<{ summary: string }>((resolve) => {
|
|
resolveFirst = resolve;
|
|
});
|
|
const handler = vi.fn()
|
|
.mockImplementationOnce(() => firstResult)
|
|
.mockResolvedValueOnce({ summary: 'replacement' });
|
|
await seedRow({ nextRunAt: Date.now() - 1 });
|
|
|
|
let now = Date.now();
|
|
const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);
|
|
const firstRun = runDueTasks({ registry: registryWith(handler) });
|
|
await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(1));
|
|
|
|
now += 2 * 60 * 60 * 1000;
|
|
await runDueTasks({ registry: registryWith(handler) });
|
|
expect((await readRow()).lastResultJson).toBe('replacement');
|
|
|
|
resolveFirst({ summary: 'stale original' });
|
|
await firstRun;
|
|
expect((await readRow()).lastResultJson).toBe('replacement');
|
|
nowSpy.mockRestore();
|
|
});
|
|
|
|
test('starts independent due tasks concurrently', async () => {
|
|
const started: string[] = [];
|
|
let release!: () => void;
|
|
const gate = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const registry: TaskRegistry = {
|
|
first: {
|
|
name: 'First',
|
|
defaultIntervalMs: 1000,
|
|
run: async () => {
|
|
started.push('first');
|
|
await gate;
|
|
},
|
|
},
|
|
second: {
|
|
name: 'Second',
|
|
defaultIntervalMs: 1000,
|
|
run: async () => {
|
|
started.push('second');
|
|
await gate;
|
|
},
|
|
},
|
|
};
|
|
|
|
const running = runDueTasks({ registry });
|
|
await vi.waitFor(() => expect(started).toEqual(['first', 'second']));
|
|
release();
|
|
await running;
|
|
});
|
|
|
|
test('aborts and records an error when a task exceeds its runtime limit', async () => {
|
|
const handler = vi.fn(async ({ signal }: { signal: AbortSignal }) => {
|
|
await new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }));
|
|
});
|
|
await seedRow({ nextRunAt: Date.now() - 1 });
|
|
const registry: TaskRegistry = {
|
|
[KEY]: { name: 'Timed task', defaultIntervalMs: 1000, maxRunMs: 5, run: handler },
|
|
};
|
|
|
|
await runDueTasks({ registry });
|
|
|
|
expect(handler).toHaveBeenCalledTimes(1);
|
|
expect((await readRow()).lastError).toContain('runtime limit');
|
|
});
|
|
|
|
test('rejects non-positive intervals at the database boundary', async () => {
|
|
await expect(seedRow({ intervalMs: 0 })).rejects.toThrow();
|
|
});
|
|
|
|
test('updates a registered task even when its row has not been seeded', async () => {
|
|
await updateTask('prune-job-events', { enabled: false, intervalMs: 12_345 });
|
|
|
|
const [row] = await holder.db
|
|
.select()
|
|
.from(tasks)
|
|
.where(eq(tasks.key, 'prune-job-events'));
|
|
expect(row).toEqual(expect.objectContaining({
|
|
enabled: false,
|
|
intervalMs: 12_345,
|
|
lastStatus: 'idle',
|
|
}));
|
|
});
|
|
});
|