Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Retry a deleted envelope's files until they are gone
Claudee8a1cdce7b78
diff --git a/db/migrations/20261118100000_pending_file_deletions.sql b/db/migrations/20261118100000_pending_file_deletions.sqlnew file mode 100644index 0000000..d39b3b1--- /dev/null+++ b/db/migrations/20261118100000_pending_file_deletions.sql@@ -0,0 +1,14 @@+-- Stored files still to be deleted after their rows have gone. An+-- administrator's deletion of a finished envelope commits the row and the+-- record of its deletion first, then deletes the files; a file that could+-- not be deleted then (storage was down, the request stopped) stays named+-- here, and the daily cleanup tries it again until it is gone.++create table if not exists public.pending_file_deletions (+ storage_key text primary key,+ envelope_id text not null,+ queued_at bigint not null+);++create index if not exists pending_file_deletions_queued_at_idx+ on public.pending_file_deletions (queued_at);diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.tsindex 414c10d..743e688 100644--- a/src/lib/envelope-deletion.dbtest.ts+++ b/src/lib/envelope-deletion.dbtest.ts@@ -11,6 +11,7 @@ import type pg from "pg";import { openTestDatabase } from "./db/test-database.ts";import { deleteFinishedEnvelope } from "./envelope-deletion.ts";import { EnvelopeMutationError } from "./envelopes.ts";+import { runRetentionSweep } from "./retention.ts";import { getRecipientCertificateKey } from "./services/storage-keys.ts";import {createStorageService,@@ -155,6 +156,15 @@ async function envelopeExists(envelopeId: string) {return result.rowCount === 1;}+async function pendingFileDeletions(envelopeId: string) {+ const result = await database.query<{ storage_key: string }>(+ `select storage_key from pending_file_deletions where envelope_id = $1`,+ [envelopeId],+ );++ return result.rows.map((row) => row.storage_key);+}+async function filesExist(keys: readonly string[]) {return Promise.all(keys.map(async (key) => (await storageService.headObject(key)).exists),@@ -192,6 +202,7 @@ for (const status of ["completed", "declined", "voided"] as const) {await filesExist(envelope.stored),envelope.stored.map(() => false),);+ assert.deepEqual(await pendingFileDeletions(envelope.envelopeId), []);const [event] = await listSystemAuditEvents({ limit: 1 }, database);@@ -301,7 +312,7 @@ test("a reason that is not text, or too long, is refused", async () => {assert.equal(await envelopeExists(envelope.envelopeId), true);});-test("when a file cannot be deleted, the envelope is still deleted and recorded, and the file is logged", async () => {+test("when a file cannot be deleted, the envelope is still deleted and recorded, and the next cleanup deletes the file", async () => {const admin = await createUser("admin");const envelope = await createEnvelope(admin.userId, { status: "completed" });const failingStorage = {@@ -333,13 +344,27 @@ test("when a file cannot be deleted, the envelope is still deleted and recorded,assert.equal(event?.event, "envelope_deleted");assert.equal(event?.metadata?.envelopeId, envelope.envelopeId);- // Every file it held is named in the log, so it can be removed by hand.for (const key of envelope.stored) {assert.ok(logged.some((args) => String(args[0]).includes(key)),`expected ${key} to be logged`,);}+ assert.ok((await filesExist(envelope.stored)).every(Boolean));+ assert.ok(+ (await pendingFileDeletions(envelope.envelopeId)).length >=+ envelope.stored.length,+ );++ // Storage is back: the daily cleanup finishes the job.+ const summary = await runRetentionSweep({ database, storageService });++ assert.ok(summary.pendingFileDeletionsDone >= envelope.stored.length);+ assert.deepEqual(+ await filesExist(envelope.stored),+ envelope.stored.map(() => false),+ );+ assert.deepEqual(await pendingFileDeletions(envelope.envelopeId), []);});test("when the deletion fails before it commits, no file is touched", async () => {diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.tsindex 211127d..ded8d12 100644--- a/src/lib/envelope-deletion.ts+++ b/src/lib/envelope-deletion.ts@@ -5,7 +5,11 @@ import {withTransaction,} from "./db/connection.ts";import { EnvelopeMutationError } from "./envelopes.ts";-import { listEnvelopeStorageKeys } from "./retention.ts";+import {+ deletePendingFile,+ listEnvelopeStorageKeys,+ queueFileDeletions,+} from "./retention.ts";import {createStorageService,type StorageService,@@ -166,11 +170,18 @@ export async function deleteFinishedEnvelope(tx,);- // The row and the record of its deletion commit together. The files- // cannot roll back with them, so they go only after the commit: a file- // left behind by a failure is logged, never an envelope that lost its- // files without a record of why.+ // The row, the record of its deletion and the list of its files+ // commit together. The files cannot roll back with them, so they go+ // only after the commit; one that cannot be deleted then stays on the+ // list, and the daily cleanup tries it again.const storageKeys = await listEnvelopeStorageKeys(envelope.id, tx);++ await queueFileDeletions(+ envelope.id,+ storageKeys,+ Math.floor(Date.now() / 1000),+ tx,+ );const deleted = await tx.query(`DELETE FROM envelopes WHERE id = $1`, [envelope.id,]);@@ -185,12 +196,7 @@ export async function deleteFinishedEnvelope();for (const key of storageKeys) {- await storageService.deleteObject(key).catch((error: unknown) => {- console.error(- `Failed to delete stored file ${key} of deleted envelope ${deletedEnvelopeId}:`,- error,- );- });+ await deletePendingFile(key, database, storageService);}return { deletedEnvelopeId };diff --git a/src/lib/retention.ts b/src/lib/retention.tsindex a62e74b..15767fe 100644--- a/src/lib/retention.ts+++ b/src/lib/retention.ts@@ -63,6 +63,8 @@ export type RetentionSweepSummary = {finishedEnvelopeDeletionFailures: string[];finishedEnvelopesDeleted: number;finishedEnvelopeWarningsSent: number;+ /** Files of deleted envelopes that an earlier deletion could not remove. */+ pendingFileDeletionsDone: number;/** Trips to a signing provider ended because nobody came back. */providerSigningSessionsEnded: number;ranAt: number;@@ -949,6 +951,87 @@ export async function listEnvelopeStorageKeys();}+/** How many queued file deletions one cleanup tries, at most. */+const PENDING_FILE_DELETIONS_PER_SWEEP = 500;++/**+ * Names files to delete once the transaction that deletes their envelope+ * has committed. Until `deletePendingFile` removes one, the daily cleanup+ * keeps trying it.+ */+export async function queueFileDeletions(+ envelopeId: string,+ keys: readonly string[],+ now: number,+ database: DbExecutor,+): Promise<void> {+ if (keys.length === 0) {+ return;+ }++ await database.query(+ `+ INSERT INTO pending_file_deletions (storage_key, envelope_id, queued_at)+ SELECT key, $2, $3 FROM unnest($1::text[]) AS key+ ON CONFLICT (storage_key) DO NOTHING+ `,+ [keys, envelopeId, now],+ );+}++/**+ * Deletes one queued file and takes it off the queue. Returns false, after+ * logging, when it could not, so it stays queued for the next cleanup.+ */+export async function deletePendingFile(+ key: string,+ database: DbExecutor,+ storageService: StorageService,+): Promise<boolean> {+ try {+ // Deleting a file that is already gone succeeds.+ await storageService.deleteObject(key);+ await database.query(+ `DELETE FROM pending_file_deletions WHERE storage_key = $1`,+ [key],+ );++ return true;+ } catch (error) {+ console.error(+ `Failed to delete stored file ${key}; it stays queued for the next cleanup:`,+ error,+ );++ return false;+ }+}++async function deletePendingFiles(+ database: DbExecutor,+ storageService: StorageService,+): Promise<number> {+ const pending = await queryMany<{ storageKey: string }>(+ database,+ `+ SELECT storage_key AS "storageKey"+ FROM pending_file_deletions+ ORDER BY queued_at ASC, storage_key ASC+ LIMIT $1+ `,+ [PENDING_FILE_DELETIONS_PER_SWEEP],+ );+ let done = 0;++ for (const { storageKey } of pending) {+ if (await deletePendingFile(storageKey, database, storageService)) {+ done += 1;+ }+ }++ return done;+}+/** Deletes these envelopes and their stored files. Returns how many went. */export async function deleteEnvelopesAndFiles(envelopeIds: readonly string[],@@ -1016,10 +1099,16 @@ export async function runRetentionSweep({finishedEnvelopeDeletionFailures: [],finishedEnvelopesDeleted: 0,finishedEnvelopeWarningsSent: 0,+ pendingFileDeletionsDone: 0,providerSigningSessionsEnded: 0,ranAt: now,};+ summary.pendingFileDeletionsDone = await deletePendingFiles(+ database,+ storageService,+ );+summary.expiredRecipientDownloadTokensDeleted =await deleteExpiredRecipientDownloadTokens(now, database);summary.providerSigningSessionsEnded = await endAbandonedProviderSessions(