openreader/compute/worker/src/pdf-artifact-persistence.ts
Richard R c0de2156fe 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.
2026-06-06 18:09:47 -06:00

18 lines
713 B
TypeScript

export async function persistParsedPdfWhileSourceExists(input: {
sourceObjectKey: string;
sourceExists: (key: string) => Promise<boolean>;
putParsedObject: () => Promise<string>;
deleteParsedObject: (key: string) => Promise<void>;
}): Promise<string> {
if (!await input.sourceExists(input.sourceObjectKey)) {
throw new Error('PDF source object was deleted before parsed output could be persisted');
}
const parsedObjectKey = await input.putParsedObject();
if (!await input.sourceExists(input.sourceObjectKey)) {
await input.deleteParsedObject(parsedObjectKey);
throw new Error('PDF source object was deleted while parsed output was being persisted');
}
return parsedObjectKey;
}