openreader/tests/unit/blob-upload-finalize-docx.vitest.spec.ts
Richard R e670c38523
Refactor user data cleanup and TTS storage flows (#105)
* 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.
2026-06-07 13:33:20 -06:00

154 lines
5.5 KiB
TypeScript

import { createHash } from 'node:crypto';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { NextRequest } from 'next/server';
const hoisted = vi.hoisted(() => ({
requireAuthContext: vi.fn(),
registerUploadedDocument: vi.fn(),
convertDocxBufferToPdfBuffer: vi.fn(),
headTempDocumentBlob: vi.fn(),
getTempDocumentBlob: vi.fn(),
getTempDocumentFinalizeReceipt: vi.fn(),
putTempDocumentFinalizeReceipt: vi.fn(),
deleteTempDocumentUpload: vi.fn(),
headDocumentBlob: vi.fn(),
copyTempDocumentBlobToDocument: vi.fn(),
putDocumentBlob: vi.fn(),
}));
vi.mock('@/lib/server/auth/auth', () => ({
requireAuthContext: hoisted.requireAuthContext,
}));
vi.mock('@/lib/server/documents/register-upload', () => ({
registerUploadedDocument: hoisted.registerUploadedDocument,
}));
vi.mock('@/lib/server/documents/blob-lease', () => ({
withDocumentBlobLease: vi.fn(async (_documentId: string, fn: () => Promise<unknown>) => fn()),
}));
vi.mock('@/lib/server/documents/docx-convert', () => ({
convertDocxBufferToPdfBuffer: hoisted.convertDocxBufferToPdfBuffer,
}));
vi.mock('@/lib/server/documents/blobstore', () => ({
TEMP_DOCUMENT_UPLOAD_TTL_MS: 24 * 60 * 60 * 1000,
copyTempDocumentBlobToDocument: hoisted.copyTempDocumentBlobToDocument,
deleteTempDocumentUpload: hoisted.deleteTempDocumentUpload,
getTempDocumentBlob: hoisted.getTempDocumentBlob,
getTempDocumentFinalizeReceipt: hoisted.getTempDocumentFinalizeReceipt,
headDocumentBlob: hoisted.headDocumentBlob,
headTempDocumentBlob: hoisted.headTempDocumentBlob,
isMissingBlobError: vi.fn((error: unknown) => {
const maybe = error as { code?: string } | undefined;
return maybe?.code === 'NoSuchKey';
}),
isPreconditionFailed: vi.fn(() => false),
isValidTempUploadToken: vi.fn(() => true),
putDocumentBlob: hoisted.putDocumentBlob,
putTempDocumentFinalizeReceipt: hoisted.putTempDocumentFinalizeReceipt,
}));
vi.mock('@/lib/server/testing/test-namespace', () => ({
getOpenReaderTestNamespace: vi.fn(() => null),
}));
vi.mock('@/lib/server/storage/s3', () => ({
isS3Configured: vi.fn(() => true),
}));
vi.mock('@/lib/server/logger', () => ({
errorToLog: vi.fn((error: unknown) => error),
serverLogger: {
warn: vi.fn(),
error: vi.fn(),
},
}));
describe('POST /api/documents/blob/upload/finalize DOCX flow', () => {
beforeEach(() => {
hoisted.requireAuthContext.mockReset();
hoisted.registerUploadedDocument.mockReset();
hoisted.convertDocxBufferToPdfBuffer.mockReset();
hoisted.headTempDocumentBlob.mockReset();
hoisted.getTempDocumentBlob.mockReset();
hoisted.getTempDocumentFinalizeReceipt.mockReset();
hoisted.putTempDocumentFinalizeReceipt.mockReset();
hoisted.deleteTempDocumentUpload.mockReset();
hoisted.headDocumentBlob.mockReset();
hoisted.copyTempDocumentBlobToDocument.mockReset();
hoisted.putDocumentBlob.mockReset();
hoisted.requireAuthContext.mockResolvedValue({ userId: 'user-1' });
hoisted.getTempDocumentFinalizeReceipt.mockResolvedValue(null);
hoisted.headTempDocumentBlob.mockResolvedValue({
contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
contentLength: 12,
lastModified: Date.now(),
});
hoisted.getTempDocumentBlob.mockResolvedValue(Buffer.from('docx-bytes'));
hoisted.convertDocxBufferToPdfBuffer.mockResolvedValue(Buffer.from('pdf-bytes'));
hoisted.headDocumentBlob
.mockRejectedValueOnce({ code: 'NoSuchKey' })
.mockResolvedValue({
contentLength: Buffer.byteLength('pdf-bytes'),
contentType: 'application/pdf',
eTag: 'etag-1',
});
hoisted.registerUploadedDocument.mockImplementation(async (input: { documentId: string; name: string; type: string; size: number; lastModified: number }) => ({
id: input.documentId,
name: input.name,
type: input.type,
size: input.size,
lastModified: input.lastModified,
scope: 'user',
}));
hoisted.putTempDocumentFinalizeReceipt.mockResolvedValue(undefined);
hoisted.deleteTempDocumentUpload.mockResolvedValue(undefined);
});
test('converts raw DOCX during finalize and registers a PDF', async () => {
const { POST } = await import('../../src/app/api/documents/blob/upload/finalize/route');
const request = new NextRequest('http://localhost/api/documents/blob/upload/finalize', {
method: 'POST',
body: JSON.stringify({
uploads: [{
token: '123e4567-e89b-12d3-a456-426614174000',
name: 'Report.docx',
type: 'docx',
lastModified: 1700000000000,
}],
}),
headers: {
'Content-Type': 'application/json',
},
});
const response = await POST(request);
const expectedId = createHash('sha256').update(Buffer.from('pdf-bytes')).digest('hex');
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({
stored: [{
id: expectedId,
name: 'Report.pdf',
type: 'pdf',
}],
});
expect(hoisted.convertDocxBufferToPdfBuffer).toHaveBeenCalledTimes(1);
expect(hoisted.putDocumentBlob).toHaveBeenCalledWith(
expectedId,
Buffer.from('pdf-bytes'),
'application/pdf',
null,
{ ifNoneMatch: true },
);
expect(hoisted.copyTempDocumentBlobToDocument).not.toHaveBeenCalled();
expect(hoisted.registerUploadedDocument).toHaveBeenCalledWith(expect.objectContaining({
documentId: expectedId,
name: 'Report.pdf',
type: 'pdf',
}));
});
});