Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Re-check a scheduled deletion under the envelope lock before retention deletes
Claudec4e9aa15d3ca
diff --git a/src/lib/retention.ts b/src/lib/retention.tsindex 109904f..1875c0f 100644--- a/src/lib/retention.ts+++ b/src/lib/retention.ts@@ -733,6 +733,49 @@ type FinishedEnvelopeRow = EnvelopeArtifactRow & {title: string;};+/**+ * Deletes a finished envelope's row for the retention period, unless it+ * has moved on or an administrator's scheduled deletion now stands, and+ * queues its files for deletion once this commits. Locks the envelope row+ * as scheduling a deletion does.+ */+async function deleteFinishedEnvelopeRow(+ envelope: FinishedEnvelopeRow,+ keys: readonly string[],+ now: number,+ scheduledDeletionsExist: boolean,+ tx: DbExecutor,+): Promise<boolean> {+ const locked = await tx.query(+ `SELECT 1 FROM envelopes WHERE id = $1 AND status = $2 FOR UPDATE`,+ [envelope.id, envelope.status],+ );++ if (locked.rowCount !== 1) {+ return false;+ }++ if (scheduledDeletionsExist) {+ const scheduled = await tx.query(+ `+ SELECT 1+ FROM scheduled_envelope_deletions+ WHERE envelope_id = $1 AND cancelled_at IS NULL+ `,+ [envelope.id],+ );++ if (scheduled.rowCount === 1) {+ return false;+ }+ }++ await queueFileDeletions(envelope.id, keys, now, tx);+ await tx.query(`DELETE FROM envelopes WHERE id = $1`, [envelope.id]);++ return true;+}+async function hasScheduledDeletionsTable(database: DbExecutor,): Promise<boolean> {@@ -752,15 +795,20 @@ async function hasScheduledDeletionsTable(async function listFinishedEnvelopesToHandle({deleteBefore,+ scheduledDeletionsExist,warnBefore,warnedBefore,- }: { deleteBefore: number; warnBefore: number; warnedBefore: number },+ }: {+ deleteBefore: number;+ scheduledDeletionsExist: boolean;+ warnBefore: number;+ warnedBefore: number;+ },database: DbExecutor,): Promise<FinishedEnvelopeRow[]> {// An administrator's scheduled deletion has its own notice and wait,- // which this timer must not cut short. A database the new migration has- // not reached yet has no such deletions, and its retention keeps working.- const scheduledDeletionClause = (await hasScheduledDeletionsTable(database))+ // which this timer must not cut short.+ const scheduledDeletionClause = scheduledDeletionsExist? `AND NOT EXISTS (SELECT 1FROM scheduled_envelope_deletions s@@ -860,9 +908,13 @@ async function applyRetentionPeriod() {const warnBefore =now - (retentionDays - RETENTION_WARNING_DAYS) * DAY_IN_SECONDS;+ // A database the scheduled-deletion migration has not reached yet has+ // no such deletions, and its retention keeps working.+ const scheduledDeletionsExist = await hasScheduledDeletionsTable(database);const candidates = await listFinishedEnvelopesToHandle({deleteBefore: now - retentionDays * DAY_IN_SECONDS,+ scheduledDeletionsExist,warnBefore,warnedBefore: now - RETENTION_MIN_NOTICE_DAYS * DAY_IN_SECONDS,},@@ -897,22 +949,33 @@ async function applyRetentionPeriod(continue;}- // Files first: a failure leaves the row, so the next run retries.- await deleteStorageKeys(- buildEnvelopeStorageKeys(- envelope,- fieldImagesByEnvelopeId.get(envelope.id) ?? [],- ),- storageService,- );-- const deleted = await database.query(- `DELETE FROM envelopes WHERE id = $1 AND status = $2`,- [envelope.id, envelope.status],+ const keys = buildEnvelopeStorageKeys(+ envelope,+ fieldImagesByEnvelopeId.get(envelope.id) ?? [],);+ // The row goes first, in one transaction with the files' place on+ // the queue, then the files. An administrator scheduling the+ // envelope's deletion holds the same lock, so one of the two sees+ // the other: a request made since the list was read keeps it.+ const removeRow = (tx: DbExecutor) =>+ deleteFinishedEnvelopeRow(+ envelope,+ keys,+ now,+ scheduledDeletionsExist,+ tx,+ );+ const deleted = isPool(database)+ ? await withTransaction(removeRow, database)+ : await removeRow(database);- if (deleted.rowCount === 1) {+ if (deleted) {summary.finishedEnvelopesDeleted += 1;++ for (const key of keys) {+ await deletePendingFile(key, database, storageService);+ }+await deleteThumbnailStoredMeanwhile(envelope, storageService);}} catch (error) {diff --git a/src/lib/signature-evidence.dbtest.ts b/src/lib/signature-evidence.dbtest.tsindex 6d80fb3..04511e2 100644--- a/src/lib/signature-evidence.dbtest.ts+++ b/src/lib/signature-evidence.dbtest.ts@@ -431,3 +431,80 @@ test("retention keeps working on a database the scheduled-deletion migration hasassert.equal(await envelopeOwner(record), null);});++test("a deletion scheduled after the retention period's list was read still keeps the envelope", async () => {+ const owner = await createUser();+ const now = 2_000_000_000;+ const day = 24 * 60 * 60;+ const record = await createEnvelope(+ owner,+ "completed",+ "[email protected]",+ now - 400 * day,+ );+ const emailService = {+ send: async (message: { to: string }) => ({+ accepted: [message.to],+ rejected: [],+ }),+ sendBatch: async () => [],+ } as unknown as EmailService;++ await database.query(+ `update envelopes set retention_warned_at = $1 where id = $2`,+ [now - 60 * day, record],+ );+ await database.query(+ `insert into app_settings (id, signup_mode, retention_days, created_at, updated_at)+ values (true, 'closed', 30, 1, 1)+ on conflict (id) do update set retention_days = 30`,+ );++ // Once the sweep has read which envelopes are due, an administrator+ // schedules this one's deletion.+ let scheduled = false;+ const watched = new Proxy(database, {+ get(target, property) {+ if (property === "query") {+ return async (...args: Parameters<pg.Pool["query"]>) => {+ const result = await (+ target.query as (...a: unknown[]) => Promise<unknown>+ )(...args);++ if (+ !scheduled &&+ typeof args[0] === "string" &&+ args[0].includes("retention_warned_at AS")+ ) {+ scheduled = true;+ await target.query(+ `+ insert into scheduled_envelope_deletions (+ envelope_id, requested_by_user_id, requested_by_email,+ requested_at, delete_after, sender_notified_at+ ) values ($1, $2, '[email protected]', $3, $4, $3)+ `,+ [record, owner, now, now + 14 * day],+ );+ }++ return result;+ };+ }++ const value: unknown = Reflect.get(target, property);++ return typeof value === "function" ? value.bind(target) : value;+ },+ });++ await runRetentionSweep({+ database: watched,+ emailService,+ now,+ storageService: storage(),+ });++ assert.equal(scheduled, true);+ assert.equal(await envelopeOwner(record), owner);+});