Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

fix(retention): queue and retry failed account and draft file deletions (#217)

Kevin Rose7f5b85c6a27d
diff --git a/src/lib/retention-job.dbtest.ts b/src/lib/retention-job.dbtest.ts
index 6553928..b5f91c3 100644
--- a/src/lib/retention-job.dbtest.ts
+++ b/src/lib/retention-job.dbtest.ts
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
-import { createHash } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -10,26 +10,150 @@ import type pg from "pg";
import { openTestDatabase } from "./db/test-database.ts";
import {
RETENTION_ADVISORY_LOCK_ID,
+ retentionJobFailed,
runRetentionJob,
} from "./retention-job.ts";
-import { createStorageService } from "./services/storage.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import {
+ buildEnvelopeOriginalPdfKey,
+ buildEnvelopeThumbnailKey,
+ buildTemplatePdfKey,
+} from "./services/storage-keys.ts";
-// The cleanup job's hourly ration and its lock, against a real Postgres.
+// The cleanup job's hourly ration, its lock, and durable file-deletion
+// retries for closed accounts and stale drafts, against a real Postgres.
// Run with `npm run test:db`.
const RATION_KEY = createHash("sha256").update("job:retention").digest("hex");
let database: pg.Pool;
let storageDir: string;
+let storageService: StorageService;
+const createdUsers: string[] = [];
+const createdPendingKeys: string[] = [];
-function run(caller: "anonymous" | "authorized") {
+function run(
+ caller: "anonymous" | "authorized",
+ customStorage: StorageService = storageService,
+) {
return runRetentionJob({
caller,
database,
- storageService: createStorageService({
- env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
- }),
+ storageService: customStorage,
+ });
+}
+
+function createFailingStorage(base: StorageService): StorageService {
+ return {
+ ...base,
+ deleteObject: async () => {
+ throw new Error("Storage is unavailable.");
+ },
+ };
+}
+
+async function createUser() {
+ const id = randomUUID();
+
+ createdUsers.push(id);
+ await database.query(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ values ($1, $2, $3, 'user', true)
+ `,
+ [id, `Person ${id.slice(0, 4)}`, `${id}@example.test`],
+ );
+
+ return id;
+}
+
+async function createDraftWithPdf(userId: string, updatedAt: number) {
+ const id = randomUUID();
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId: id, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId: id,
+ sourcePdfKey,
+ userId,
+ });
+
+ createdPendingKeys.push(sourcePdfKey, thumbnailKey);
+ await storageService.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key: sourcePdfKey,
+ });
+ await database.query(
+ `
+ insert into envelopes (
+ id, user_id, title, status, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, source_pdf_hash, created_at, updated_at
+ ) values ($1, $2, 'Draft', 'draft', $3, 'draft.pdf', 4, 1, $4, $5, $5)
+ `,
+ [id, userId, sourcePdfKey, "a".repeat(64), updatedAt],
+ );
+
+ return { id, sourcePdfKey, thumbnailKey };
+}
+
+async function createTemplateWithPdf(userId: string) {
+ const id = randomUUID();
+ const sourcePdfKey = buildTemplatePdfKey({ templateId: id, userId });
+
+ createdPendingKeys.push(sourcePdfKey);
+ await storageService.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key: sourcePdfKey,
});
+ await database.query(
+ `
+ insert into templates (
+ id, user_id, name, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, roles, fields
+ ) values ($1, $2, 'Template', $3, 'template.pdf', 4, 1, $4::jsonb, '[]'::jsonb)
+ `,
+ [id, userId, sourcePdfKey, JSON.stringify([{ id: "r1", name: "Signer" }])],
+ );
+
+ return { id, sourcePdfKey };
+}
+
+async function closeAccountDue(userId: string) {
+ await database.query(
+ `
+ insert into account_closure_requests
+ (user_id, requested_at, export_expires_at, purge_after_at, updated_at)
+ values ($1, 1, 1, 1, 1)
+ `,
+ [userId],
+ );
+}
+
+async function pendingRowsForKeys(keys: readonly string[]) {
+ const result = await database.query<{ storage_key: string }>(
+ `select storage_key from pending_file_deletions where storage_key = any($1)`,
+ [keys],
+ );
+
+ return result.rows.map((row) => row.storage_key);
+}
+
+async function quietly<T>(work: () => Promise<T>): Promise<T> {
+ const originalError = console.error;
+ const originalInfo = console.info;
+
+ console.error = () => {};
+ console.info = () => {};
+
+ try {
+ return await work();
+ } finally {
+ console.error = originalError;
+ console.info = originalInfo;
+ }
}
async function clearRation() {
@@ -41,10 +165,20 @@ async function clearRation() {
before(async () => {
database = await openTestDatabase();
storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-retention-"));
+ storageService = createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },
+ });
});
after(async () => {
await clearRation();
+ await database.query(
+ `delete from pending_file_deletions where storage_key = any($1)`,
+ [createdPendingKeys],
+ );
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
await database.end();
await rm(storageDir, { force: true, recursive: true });
});
@@ -75,6 +209,7 @@ test("a caller with the secret is not rationed, and gets the summary", async ()
if (second.status === "ran") {
assert.deepEqual(second.summary.accountPurgeFailures, []);
assert.deepEqual(second.summary.draftDeletionFailures, []);
+ assert.deepEqual(second.summary.pendingFileDeletionFailures, []);
}
});
@@ -116,3 +251,205 @@ test("while one run holds the lock, another steps aside", async () => {
// none of its own behind.
assert.equal((await run("authorized")).status, "ran");
});
+
+test("a closed-account purge with working storage deletes its files on the first run", async () => {
+ const now = Math.floor(Date.now() / 1000);
+ const userId = await createUser();
+ const draft = await createDraftWithPdf(userId, now);
+ const template = await createTemplateWithPdf(userId);
+
+ await closeAccountDue(userId);
+
+ const outcome = await quietly(() => run("authorized"));
+
+ assert.equal(outcome.status, "ran");
+
+ if (outcome.status === "ran") {
+ assert.ok(outcome.summary.accountsPurged >= 1);
+ assert.ok(!outcome.summary.accountPurgeFailures.includes(userId));
+ assert.equal(retentionJobFailed(outcome), false);
+ }
+
+ assert.equal(
+ (await storageService.headObject(draft.sourcePdfKey)).exists,
+ false,
+ );
+ assert.equal(
+ (await storageService.headObject(template.sourcePdfKey)).exists,
+ false,
+ );
+ assert.deepEqual(
+ await pendingRowsForKeys([
+ draft.sourcePdfKey,
+ draft.thumbnailKey,
+ template.sourcePdfKey,
+ ]),
+ [],
+ );
+});
+
+test("a closed-account purge whose files cannot be deleted reports failure and retries after storage recovers", async () => {
+ const now = Math.floor(Date.now() / 1000);
+ const userId = await createUser();
+ const draft = await createDraftWithPdf(userId, now);
+ const template = await createTemplateWithPdf(userId);
+ const keys = [draft.sourcePdfKey, draft.thumbnailKey, template.sourcePdfKey];
+
+ await closeAccountDue(userId);
+
+ const first = await quietly(() =>
+ run("authorized", createFailingStorage(storageService)),
+ );
+
+ assert.equal(first.status, "ran");
+
+ if (first.status === "ran") {
+ assert.ok(first.summary.accountsPurged >= 1);
+ assert.ok(first.summary.accountPurgeFailures.includes(userId));
+ assert.equal(retentionJobFailed(first), true);
+ }
+
+ assert.equal(
+ (
+ await database.query(`select 1 from public."user" where id = $1`, [
+ userId,
+ ])
+ ).rowCount,
+ 0,
+ );
+ assert.deepEqual((await pendingRowsForKeys(keys)).sort(), [...keys].sort());
+ assert.equal(
+ (await storageService.headObject(draft.sourcePdfKey)).exists,
+ true,
+ );
+ assert.equal(
+ (await storageService.headObject(template.sourcePdfKey)).exists,
+ true,
+ );
+
+ // While storage is still down, retrying queued deletions still fails the run.
+ const stillDown = await quietly(() =>
+ run("authorized", createFailingStorage(storageService)),
+ );
+
+ assert.equal(stillDown.status, "ran");
+
+ if (stillDown.status === "ran") {
+ assert.ok(
+ stillDown.summary.pendingFileDeletionFailures.includes(
+ draft.sourcePdfKey,
+ ),
+ );
+ assert.ok(
+ stillDown.summary.pendingFileDeletionFailures.includes(
+ template.sourcePdfKey,
+ ),
+ );
+ assert.equal(retentionJobFailed(stillDown), true);
+ }
+
+ // Storage recovers: the next daily run retries and removes both files.
+ const next = await quietly(() => run("authorized", storageService));
+
+ assert.equal(next.status, "ran");
+
+ if (next.status === "ran") {
+ assert.ok(next.summary.pendingFileDeletionsDone >= keys.length);
+ assert.equal(retentionJobFailed(next), false);
+ }
+
+ assert.equal(
+ (await storageService.headObject(draft.sourcePdfKey)).exists,
+ false,
+ );
+ assert.equal(
+ (await storageService.headObject(template.sourcePdfKey)).exists,
+ false,
+ );
+ assert.deepEqual(await pendingRowsForKeys(keys), []);
+});
+
+test("a stale-draft purge with working storage deletes its file on the first run", async () => {
+ const userId = await createUser();
+ const draft = await createDraftWithPdf(userId, 1);
+
+ const outcome = await quietly(() => run("authorized"));
+
+ assert.equal(outcome.status, "ran");
+
+ if (outcome.status === "ran") {
+ assert.ok(outcome.summary.draftsDeleted >= 1);
+ assert.ok(!outcome.summary.draftDeletionFailures.includes(draft.id));
+ assert.equal(retentionJobFailed(outcome), false);
+ }
+
+ assert.equal(
+ (await storageService.headObject(draft.sourcePdfKey)).exists,
+ false,
+ );
+ assert.deepEqual(
+ await pendingRowsForKeys([draft.sourcePdfKey, draft.thumbnailKey]),
+ [],
+ );
+});
+
+test("a stale-draft purge whose files cannot be deleted stays queued and retries after storage recovers", async () => {
+ const userId = await createUser();
+ const draft = await createDraftWithPdf(userId, 1);
+ const keys = [draft.sourcePdfKey, draft.thumbnailKey];
+
+ const first = await quietly(() =>
+ run("authorized", createFailingStorage(storageService)),
+ );
+
+ assert.equal(first.status, "ran");
+
+ if (first.status === "ran") {
+ assert.ok(first.summary.draftsDeleted >= 1);
+ assert.ok(first.summary.draftDeletionFailures.includes(draft.id));
+ assert.equal(retentionJobFailed(first), true);
+ }
+
+ assert.equal(
+ (await database.query(`select 1 from envelopes where id = $1`, [draft.id]))
+ .rowCount,
+ 0,
+ );
+ assert.deepEqual((await pendingRowsForKeys(keys)).sort(), [...keys].sort());
+ assert.equal(
+ (await storageService.headObject(draft.sourcePdfKey)).exists,
+ true,
+ );
+
+ // While storage is still down, retrying queued deletions still fails the run.
+ const stillDown = await quietly(() =>
+ run("authorized", createFailingStorage(storageService)),
+ );
+
+ assert.equal(stillDown.status, "ran");
+
+ if (stillDown.status === "ran") {
+ assert.ok(
+ stillDown.summary.pendingFileDeletionFailures.includes(
+ draft.sourcePdfKey,
+ ),
+ );
+ assert.equal(retentionJobFailed(stillDown), true);
+ }
+
+ // Storage recovers: the next daily run retries and removes the file.
+ const next = await quietly(() => run("authorized", storageService));
+
+ assert.equal(next.status, "ran");
+
+ if (next.status === "ran") {
+ assert.ok(next.summary.pendingFileDeletionsDone >= keys.length);
+ assert.equal(retentionJobFailed(next), false);
+ }
+
+ assert.equal(
+ (await storageService.headObject(draft.sourcePdfKey)).exists,
+ false,
+ );
+ assert.deepEqual(await pendingRowsForKeys(keys), []);
+});
diff --git a/src/lib/retention-job.test.ts b/src/lib/retention-job.test.ts
index 40d8aaf..05bbf2c 100644
--- a/src/lib/retention-job.test.ts
+++ b/src/lib/retention-job.test.ts
@@ -1,13 +1,610 @@
import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
import { test } from "node:test";
+import type { QueryResult, QueryResultRow } from "pg";
+
+import type { DbPool } from "./db/connection.ts";
import {
identifyRetentionCaller,
isCronLockedOutByOlderSecret,
+ retentionJobFailed,
+ retentionSweepFailed,
+ runRetentionJob,
} from "./retention-job.ts";
+import {
+ runRetentionSweep,
+ STALE_DRAFT_RETENTION_DAYS,
+ type RetentionSweepSummary,
+} from "./retention.ts";
+import {
+ createStorageService,
+ type StorageService,
+} from "./services/storage.ts";
+import {
+ buildEnvelopeCertificateKey,
+ buildEnvelopeOriginalPdfKey,
+ buildEnvelopeSignedPdfKey,
+ buildEnvelopeThumbnailKey,
+ buildSignatureImageKey,
+ buildTemplatePdfKey,
+ getRecipientCertificateKey,
+} from "./services/storage-keys.ts";
// Running the job itself, with its lock and its hourly ration, is checked
-// against a real Postgres in retention-job.dbtest.ts.
+// against a real Postgres in retention-job.dbtest.ts. The tests below also
+// exercise the retry queue and failure reporting end-to-end with an in-memory
+// transactional pool and local file storage.
+
+type FakeUserRow = {
+ email: string;
+ id: string;
+ role: "admin" | "user";
+};
+
+type FakeClosureRow = {
+ exportExpiresAt: number;
+ purgeAfterAt: number;
+ requestedAt: number;
+ updatedAt: number;
+ userId: string;
+};
+
+type FakeEnvelopeRow = {
+ evidenceKey: string | null;
+ id: string;
+ part11: boolean;
+ signedPdfKey: string | null;
+ sourcePdfKey: string;
+ status: "completed" | "declined" | "draft" | "sent" | "voided";
+ updatedAt: number;
+ userId: string;
+};
+
+type FakeTemplateRow = {
+ id: string;
+ sourcePdfKey: string;
+ userId: string;
+};
+
+type FakePendingDeletionRow = {
+ envelopeId: string;
+ lastTriedAt: number | null;
+ queuedAt: number;
+ storageKey: string;
+};
+
+type FakeFieldImageRow = {
+ envelopeId: string;
+ imageKey: string;
+};
+
+type FakeState = {
+ closures: FakeClosureRow[];
+ envelopes: FakeEnvelopeRow[];
+ fieldImages: FakeFieldImageRow[];
+ pendingFileDeletions: FakePendingDeletionRow[];
+ templates: FakeTemplateRow[];
+ users: FakeUserRow[];
+};
+
+function cloneState(state: FakeState): FakeState {
+ return {
+ closures: state.closures.map((row) => ({ ...row })),
+ envelopes: state.envelopes.map((row) => ({ ...row })),
+ fieldImages: state.fieldImages.map((row) => ({ ...row })),
+ pendingFileDeletions: state.pendingFileDeletions.map((row) => ({ ...row })),
+ templates: state.templates.map((row) => ({ ...row })),
+ users: state.users.map((row) => ({ ...row })),
+ };
+}
+
+function queryResult<T extends QueryResultRow>(
+ rows: T[],
+ rowCount = rows.length,
+): QueryResult<T> {
+ return {
+ command: "",
+ fields: [],
+ oid: 0,
+ rowCount,
+ rows,
+ };
+}
+
+type FakeDatabaseHooks = {
+ beforeQuery?: (
+ sql: string,
+ values: readonly unknown[],
+ state: FakeState,
+ ) => void;
+};
+
+function createFakeRetentionPool(
+ initial: Partial<FakeState> = {},
+ hooks: FakeDatabaseHooks = {},
+) {
+ let committed: FakeState = {
+ closures: [],
+ envelopes: [],
+ fieldImages: [],
+ pendingFileDeletions: [],
+ templates: [],
+ users: [],
+ ...initial,
+ };
+ const executedTransactions: string[][] = [];
+
+ function runQuery(
+ state: FakeState,
+ text: string,
+ values: readonly unknown[] = [],
+ ): QueryResult<QueryResultRow> {
+ const sql = text.replace(/\s+/g, " ").trim();
+
+ hooks.beforeQuery?.(sql, values, state);
+
+ if (sql.toLowerCase().startsWith("select pg_try_advisory_xact_lock")) {
+ return queryResult([{ locked: true }]);
+ }
+
+ if (sql.toLowerCase().startsWith("select pg_advisory_xact_lock")) {
+ return queryResult([]);
+ }
+
+ if (
+ sql.startsWith("SELECT ") &&
+ sql.includes("FROM pending_file_deletions")
+ ) {
+ const limit = Number(values[0] ?? 500);
+ const ordered = [...state.pendingFileDeletions]
+ .sort((a, b) => {
+ if (a.lastTriedAt === null && b.lastTriedAt !== null) {
+ return -1;
+ }
+
+ if (a.lastTriedAt !== null && b.lastTriedAt === null) {
+ return 1;
+ }
+
+ if (
+ a.lastTriedAt !== null &&
+ b.lastTriedAt !== null &&
+ a.lastTriedAt !== b.lastTriedAt
+ ) {
+ return a.lastTriedAt - b.lastTriedAt;
+ }
+
+ if (a.queuedAt !== b.queuedAt) {
+ return a.queuedAt - b.queuedAt;
+ }
+
+ return a.storageKey.localeCompare(b.storageKey);
+ })
+ .slice(0, limit)
+ .map((row) => ({ storageKey: row.storageKey }));
+
+ return queryResult(ordered);
+ }
+
+ if (sql.startsWith("INSERT INTO pending_file_deletions")) {
+ if (sql.includes("unnest($1::text[], $2::text[])")) {
+ const keys = values[0] as string[];
+ const envelopeIds = values[1] as string[];
+ const queuedAt = Number(values[2]);
+
+ for (let i = 0; i < keys.length; i += 1) {
+ const storageKey = keys[i]!;
+ const envelopeId = envelopeIds[i]!;
+
+ if (
+ !state.pendingFileDeletions.some(
+ (row) => row.storageKey === storageKey,
+ )
+ ) {
+ state.pendingFileDeletions.push({
+ envelopeId,
+ lastTriedAt: null,
+ queuedAt,
+ storageKey,
+ });
+ }
+ }
+
+ return queryResult([], keys.length);
+ }
+
+ const keys = values[0] as string[];
+ const envelopeId = String(values[1]);
+ const queuedAt = Number(values[2]);
+
+ for (const storageKey of keys) {
+ if (
+ !state.pendingFileDeletions.some(
+ (row) => row.storageKey === storageKey,
+ )
+ ) {
+ state.pendingFileDeletions.push({
+ envelopeId,
+ lastTriedAt: null,
+ queuedAt,
+ storageKey,
+ });
+ }
+ }
+
+ return queryResult([], keys.length);
+ }
+
+ if (sql.startsWith("DELETE FROM pending_file_deletions")) {
+ const storageKey = String(values[0]);
+ const before = state.pendingFileDeletions.length;
+
+ state.pendingFileDeletions = state.pendingFileDeletions.filter(
+ (row) => row.storageKey !== storageKey,
+ );
+
+ return queryResult([], before - state.pendingFileDeletions.length);
+ }
+
+ if (sql.startsWith("UPDATE pending_file_deletions SET last_tried_at")) {
+ const storageKey = String(values[0]);
+ const triedAt = Number(values[1]);
+ let updated = 0;
+
+ for (const row of state.pendingFileDeletions) {
+ if (row.storageKey === storageKey) {
+ row.lastTriedAt = triedAt;
+ updated += 1;
+ }
+ }
+
+ return queryResult([], updated);
+ }
+
+ if (
+ sql.includes("FROM envelopes WHERE status = 'draft' AND updated_at < $1")
+ ) {
+ const staleBefore = Number(values[0]);
+ const rows = state.envelopes
+ .filter((row) => row.status === "draft" && row.updatedAt < staleBefore)
+ .map((row) => ({ ...row }));
+
+ return queryResult(rows);
+ }
+
+ if (sql.includes("FROM fields WHERE envelope_id IN")) {
+ const ids = new Set(values.map(String));
+ const rows = state.fieldImages
+ .filter((row) => ids.has(row.envelopeId))
+ .map((row) => ({ ...row }));
+
+ return queryResult(rows);
+ }
+
+ if (sql.includes("FROM \"user\" u WHERE u.id <> $1 AND u.role = 'admin'")) {
+ const exceptUserId = String(values[0]);
+ const closingIds = new Set(state.closures.map((row) => row.userId));
+ const keeper = state.users.find(
+ (row) =>
+ row.id !== exceptUserId &&
+ row.role === "admin" &&
+ !closingIds.has(row.id),
+ );
+
+ return queryResult(keeper ? [{ id: keeper.id }] : []);
+ }
+
+ if (sql.startsWith("UPDATE envelopes e SET user_id = k.id")) {
+ const keeperId = String(values[0]);
+ const userId = String(values[1]);
+ const finishedStatuses = values[2] as string[];
+ const closingIds = new Set(state.closures.map((row) => row.userId));
+ const keeper = state.users.find(
+ (row) =>
+ row.id === keeperId &&
+ row.role === "admin" &&
+ !closingIds.has(row.id),
+ );
+
+ if (!keeper) {
+ return queryResult([], 0);
+ }
+
+ let moved = 0;
+
+ for (const envelope of state.envelopes) {
+ if (
+ envelope.userId === userId &&
+ (finishedStatuses.includes(envelope.status) ||
+ (envelope.part11 && envelope.status !== "draft"))
+ ) {
+ envelope.userId = keeper.id;
+ moved += 1;
+ }
+ }
+
+ return queryResult([], moved);
+ }
+
+ if (
+ sql.includes("FROM account_closure_requests WHERE purge_after_at <= $1")
+ ) {
+ const now = Number(values[0]);
+ const rows = state.closures
+ .filter((row) => row.purgeAfterAt <= now)
+ .map((row) => ({ ...row }));
+
+ return queryResult(rows);
+ }
+
+ if (
+ sql ===
+ "SELECT 1 FROM envelopes WHERE id = $1 AND user_id = $2 AND status = 'draft' AND updated_at = $3 FOR UPDATE"
+ ) {
+ const [id, userId, updatedAt] = values;
+ const found = state.envelopes.some(
+ (row) =>
+ row.id === id &&
+ row.userId === userId &&
+ row.status === "draft" &&
+ row.updatedAt === updatedAt,
+ );
+
+ return queryResult(found ? [{ "?column?": 1 }] : []);
+ }
+
+ if (
+ sql ===
+ "DELETE FROM envelopes WHERE id = $1 AND user_id = $2 AND status = 'draft' AND updated_at = $3"
+ ) {
+ const [id, userId, updatedAt] = values;
+ const before = state.envelopes.length;
+
+ state.envelopes = state.envelopes.filter(
+ (row) =>
+ !(
+ row.id === id &&
+ row.userId === userId &&
+ row.status === "draft" &&
+ row.updatedAt === updatedAt
+ ),
+ );
+
+ return queryResult([], before - state.envelopes.length);
+ }
+
+ if (sql === 'SELECT id FROM "user" WHERE id = $1 FOR UPDATE') {
+ const user = state.users.find((row) => row.id === values[0]);
+
+ return queryResult(user ? [{ id: user.id }] : []);
+ }
+
+ if (
+ sql === "SELECT id FROM envelopes WHERE user_id = $1 FOR NO KEY UPDATE"
+ ) {
+ const rows = state.envelopes
+ .filter((row) => row.userId === values[0])
+ .map((row) => ({ id: row.id }));
+
+ return queryResult(rows);
+ }
+
+ if (
+ sql.includes(
+ "SELECT count(*)::text AS count FROM envelopes WHERE user_id = $1",
+ )
+ ) {
+ const userId = String(values[0]);
+ const finishedStatuses = values[1] as string[];
+ const count = state.envelopes.filter(
+ (row) =>
+ row.userId === userId &&
+ (finishedStatuses.includes(row.status) ||
+ (row.part11 && row.status !== "draft")),
+ ).length;
+
+ return queryResult([{ count: String(count) }]);
+ }
+
+ if (sql.includes("FROM envelopes WHERE user_id = $1 ORDER BY")) {
+ const rows = state.envelopes
+ .filter((row) => row.userId === values[0])
+ .map((row) => ({ ...row }));
+
+ return queryResult(rows);
+ }
+
+ if (
+ sql ===
+ 'SELECT id, source_pdf_key AS "sourcePdfKey" FROM templates WHERE user_id = $1'
+ ) {
+ const rows = state.templates
+ .filter((row) => row.userId === values[0])
+ .map((row) => ({ id: row.id, sourcePdfKey: row.sourcePdfKey }));
+
+ return queryResult(rows);
+ }
+
+ if (sql === 'SELECT email FROM "user" WHERE id = $1') {
+ const user = state.users.find((row) => row.id === values[0]);
+
+ return queryResult(user ? [{ email: user.email }] : []);
+ }
+
+ if (sql === "SELECT id FROM api_keys WHERE user_id = $1 FOR UPDATE") {
+ return queryResult([]);
+ }
+
+ if (sql.includes("FROM system_audit_events")) {
+ return queryResult([]);
+ }
+
+ if (sql.startsWith("INSERT INTO system_audit_events")) {
+ return queryResult([], 1);
+ }
+
+ if (sql === 'DELETE FROM "user" WHERE id = $1') {
+ const userId = String(values[0]);
+ const before = state.users.length;
+
+ state.users = state.users.filter((row) => row.id !== userId);
+ state.closures = state.closures.filter((row) => row.userId !== userId);
+ state.envelopes = state.envelopes.filter((row) => row.userId !== userId);
+ state.templates = state.templates.filter((row) => row.userId !== userId);
+
+ return queryResult([], before - state.users.length);
+ }
+
+ // Read-only / no-op tables touched by the rest of runRetentionJob.
+ if (
+ sql.includes("recipient_download_tokens") ||
+ sql.includes("provider_signing_sessions") ||
+ sql.includes("app_settings") ||
+ sql.includes("rate_limits") ||
+ sql.includes("api_idempotency_keys") ||
+ sql.includes("webhook_deliveries") ||
+ sql.includes("scheduled_envelope_deletions") ||
+ sql.includes("FROM envelopes e")
+ ) {
+ return queryResult([], 0);
+ }
+
+ throw new Error(`Unexpected SQL in fake retention pool: ${sql}`);
+ }
+
+ const pool = {
+ totalCount: 1,
+ async connect() {
+ let inTx = false;
+ let txState: FakeState | null = null;
+ let txStatements: string[] = [];
+
+ return {
+ async query(text: string, values?: readonly unknown[]) {
+ const normalized = text.trim().toUpperCase();
+
+ if (normalized === "BEGIN") {
+ inTx = true;
+ txState = cloneState(committed);
+ txStatements = [];
+ return queryResult([]);
+ }
+
+ if (normalized === "COMMIT") {
+ if (txState) {
+ committed = txState;
+ executedTransactions.push(txStatements);
+ }
+
+ inTx = false;
+ txState = null;
+ txStatements = [];
+ return queryResult([]);
+ }
+
+ if (normalized === "ROLLBACK") {
+ inTx = false;
+ txState = null;
+ txStatements = [];
+ return queryResult([]);
+ }
+
+ if (inTx && txState) {
+ txStatements.push(text.replace(/\s+/g, " ").trim());
+ return runQuery(txState, text, values);
+ }
+
+ return runQuery(committed, text, values);
+ },
+ release() {
+ inTx = false;
+ txState = null;
+ },
+ };
+ },
+ async query(text: string, values?: readonly unknown[]) {
+ return runQuery(committed, text, values);
+ },
+ };
+
+ return {
+ executedTransactions,
+ getState: () => committed,
+ pool: pool as unknown as DbPool,
+ };
+}
+
+function wrapStorage(
+ base: StorageService,
+ shouldFail: (key: string) => boolean,
+) {
+ const deleteAttempts: string[] = [];
+ const storageService: StorageService = {
+ ...base,
+ async deleteObject(key) {
+ deleteAttempts.push(key);
+
+ if (shouldFail(key)) {
+ throw new Error(`Storage outage while deleting ${key}`);
+ }
+
+ return base.deleteObject(key);
+ },
+ };
+
+ return { deleteAttempts, storageService };
+}
+
+async function withSilentConsole<T>(run: () => Promise<T>): Promise<T> {
+ const originalError = console.error;
+ const originalInfo = console.info;
+
+ console.error = () => {};
+ console.info = () => {};
+
+ try {
+ return await run();
+ } finally {
+ console.error = originalError;
+ console.info = originalInfo;
+ }
+}
+
+async function withTempStorage<T>(
+ run: (storage: StorageService) => Promise<T>,
+): Promise<T> {
+ const dir = await mkdtemp(path.join(tmpdir(), "signudoc-retention-unit-"));
+
+ try {
+ const storage = createStorageService({
+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: dir },
+ });
+
+ return await run(storage);
+ } finally {
+ await rm(dir, { force: true, recursive: true });
+ }
+}
+
+function emptySummary(): RetentionSweepSummary {
+ return {
+ accountPurgeFailures: [],
+ accountsPurged: 0,
+ draftDeletionFailures: [],
+ draftsDeleted: 0,
+ expiredRecipientDownloadTokensDeleted: 0,
+ finishedEnvelopeDeletionFailures: [],
+ finishedEnvelopesDeleted: 0,
+ finishedEnvelopeWarningsSent: 0,
+ pendingFileDeletionFailures: [],
+ pendingFileDeletionsDone: 0,
+ providerSigningSessionsEnded: 0,
+ ranAt: 1,
+ };
+}
test("with no secret configured, anyone may ask and nobody is trusted", () => {
assert.equal(identifyRetentionCaller(null, {}), "anonymous");
@@ -73,3 +670,851 @@ test("with both set, either secret works", () => {
);
assert.equal(identifyRetentionCaller("Bearer wrong", env), "denied");
});
+
+test("retentionSweepFailed flags account, draft, finished envelope, and pending file retry failures", () => {
+ assert.equal(retentionSweepFailed(emptySummary()), false);
+ assert.equal(
+ retentionSweepFailed({ ...emptySummary(), accountPurgeFailures: ["u1"] }),
+ true,
+ );
+ assert.equal(
+ retentionSweepFailed({ ...emptySummary(), draftDeletionFailures: ["e1"] }),
+ true,
+ );
+ assert.equal(
+ retentionSweepFailed({
+ ...emptySummary(),
+ finishedEnvelopeDeletionFailures: ["e2"],
+ }),
+ true,
+ );
+ assert.equal(
+ retentionSweepFailed({
+ ...emptySummary(),
+ pendingFileDeletionFailures: ["users/u1/envelopes/e1/original.pdf"],
+ }),
+ true,
+ );
+});
+
+test("closed-account purge with working storage removes files on the first run and leaves no pending rows", async () => {
+ await withTempStorage(async (storage) => {
+ const now = Math.floor(Date.now() / 1000);
+ const userId = "user-account-control";
+ const envelopeId = "env-account-control";
+ const templateId = "tpl-account-control";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId,
+ sourcePdfKey,
+ userId,
+ });
+ const templateKey = buildTemplatePdfKey({ templateId, userId });
+
+ for (const key of [sourcePdfKey, thumbnailKey, templateKey]) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ closures: [
+ {
+ exportExpiresAt: 1,
+ purgeAfterAt: 1,
+ requestedAt: 1,
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: now,
+ userId,
+ },
+ ],
+ templates: [{ id: templateId, sourcePdfKey: templateKey, userId }],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ });
+
+ const outcome = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(outcome.status, "ran");
+ assert.equal(retentionJobFailed(outcome), false);
+ assert.equal(outcome.summary.accountsPurged, 1);
+ assert.deepEqual(outcome.summary.accountPurgeFailures, []);
+ assert.deepEqual(outcome.summary.pendingFileDeletionFailures, []);
+ assert.equal(db.getState().users.length, 0);
+ assert.equal(db.getState().envelopes.length, 0);
+ assert.equal(db.getState().templates.length, 0);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+
+ for (const key of [sourcePdfKey, thumbnailKey, templateKey]) {
+ assert.equal((await storage.headObject(key)).exists, false);
+ }
+ });
+});
+
+test("closed-account purge queues files transactionally on outage, reports incomplete, and retries on recovery", async () => {
+ await withTempStorage(async (storage) => {
+ const now = Math.floor(Date.now() / 1000);
+ const userId = "user-account-outage";
+ const envelopeId = "env-account-outage";
+ const templateId = "tpl-account-outage";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId,
+ sourcePdfKey,
+ userId,
+ });
+ const templateKey = buildTemplatePdfKey({ templateId, userId });
+ const allKeys = [sourcePdfKey, thumbnailKey, templateKey];
+
+ for (const key of allKeys) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ closures: [
+ {
+ exportExpiresAt: 1,
+ purgeAfterAt: 1,
+ requestedAt: 1,
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: now,
+ userId,
+ },
+ ],
+ templates: [{ id: templateId, sourcePdfKey: templateKey, userId }],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ });
+
+ const failing = wrapStorage(storage, () => true);
+
+ const first = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: failing.storageService,
+ }),
+ );
+
+ assert.equal(first.status, "ran");
+ assert.equal(first.summary.accountsPurged, 1);
+ assert.deepEqual(first.summary.accountPurgeFailures, [userId]);
+ assert.equal(retentionJobFailed(first), true);
+
+ // Queueing and user removal committed in the same transaction.
+ const accountTx = db.executedTransactions.find((tx) =>
+ tx.some((sql) => sql === 'DELETE FROM "user" WHERE id = $1'),
+ );
+
+ assert.ok(accountTx, "expected a transaction deleting the account");
+ assert.ok(
+ accountTx.some((sql) =>
+ sql.startsWith("INSERT INTO pending_file_deletions"),
+ ),
+ "expected pending_file_deletions insert in the same transaction",
+ );
+
+ // Each file was tried once (not double-attempted) and stayed queued.
+ assert.deepEqual([...failing.deleteAttempts].sort(), [...allKeys].sort());
+ assert.equal(db.getState().users.length, 0);
+ assert.deepEqual(
+ db
+ .getState()
+ .pendingFileDeletions.map((row) => ({
+ envelopeId: row.envelopeId,
+ storageKey: row.storageKey,
+ tried: row.lastTriedAt !== null,
+ }))
+ .sort((a, b) => a.storageKey.localeCompare(b.storageKey)),
+ [
+ { envelopeId, storageKey: sourcePdfKey, tried: true },
+ { envelopeId, storageKey: thumbnailKey, tried: true },
+ {
+ envelopeId: `template:${templateId}`,
+ storageKey: templateKey,
+ tried: true,
+ },
+ ].sort((a, b) => a.storageKey.localeCompare(b.storageKey)),
+ );
+
+ for (const key of allKeys) {
+ assert.equal((await storage.headObject(key)).exists, true);
+ }
+
+ // A second run while storage is still down still reports failure.
+ const stillDown = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: failing.storageService,
+ }),
+ );
+
+ assert.equal(stillDown.status, "ran");
+ assert.equal(stillDown.summary.pendingFileDeletionsDone, 0);
+ assert.deepEqual(
+ [...stillDown.summary.pendingFileDeletionFailures].sort(),
+ [...allKeys].sort(),
+ );
+ assert.equal(retentionJobFailed(stillDown), true);
+
+ // Storage recovers: the next run deletes all queued files and clears rows.
+ const recovered = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(recovered.status, "ran");
+ assert.equal(recovered.summary.pendingFileDeletionsDone, allKeys.length);
+ assert.deepEqual(recovered.summary.pendingFileDeletionFailures, []);
+ assert.deepEqual(recovered.summary.accountPurgeFailures, []);
+ assert.equal(retentionJobFailed(recovered), false);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+
+ for (const key of allKeys) {
+ assert.equal((await storage.headObject(key)).exists, false);
+ }
+ });
+});
+
+test("closed-account purge under partial storage outage deletes healthy files and retries only the failed key", async () => {
+ await withTempStorage(async (storage) => {
+ const now = Math.floor(Date.now() / 1000);
+ const userId = "user-partial";
+ const envelopeId = "env-partial";
+ const templateId = "tpl-partial";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId,
+ sourcePdfKey,
+ userId,
+ });
+ const templateKey = buildTemplatePdfKey({ templateId, userId });
+
+ for (const key of [sourcePdfKey, thumbnailKey, templateKey]) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ closures: [
+ {
+ exportExpiresAt: 1,
+ purgeAfterAt: 1,
+ requestedAt: 1,
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: now,
+ userId,
+ },
+ ],
+ templates: [{ id: templateId, sourcePdfKey: templateKey, userId }],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ });
+
+ const partialStorage = wrapStorage(storage, (key) => key === sourcePdfKey);
+ const first = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: partialStorage.storageService,
+ }),
+ );
+
+ assert.equal(first.status, "ran");
+ assert.equal(retentionJobFailed(first), true);
+ assert.deepEqual(first.summary.accountPurgeFailures, [userId]);
+ assert.equal((await storage.headObject(sourcePdfKey)).exists, true);
+ assert.equal((await storage.headObject(thumbnailKey)).exists, false);
+ assert.equal((await storage.headObject(templateKey)).exists, false);
+ assert.deepEqual(
+ db.getState().pendingFileDeletions.map((row) => row.storageKey),
+ [sourcePdfKey],
+ );
+
+ const recovered = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(recovered.status, "ran");
+ assert.equal(recovered.summary.pendingFileDeletionsDone, 1);
+ assert.equal(retentionJobFailed(recovered), false);
+ assert.equal((await storage.headObject(sourcePdfKey)).exists, false);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+ });
+});
+
+test("stale-draft purge with working storage removes files on the first run and leaves no pending rows", async () => {
+ await withTempStorage(async (storage) => {
+ const userId = "user-draft-control";
+ const envelopeId = "env-draft-control";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId,
+ sourcePdfKey,
+ userId,
+ });
+
+ for (const key of [sourcePdfKey, thumbnailKey]) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ users: [
+ { email: "[email protected]", id: userId, role: "user" },
+ ],
+ });
+
+ const outcome = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(outcome.status, "ran");
+ assert.equal(retentionJobFailed(outcome), false);
+ assert.equal(outcome.summary.draftsDeleted, 1);
+ assert.deepEqual(outcome.summary.draftDeletionFailures, []);
+ assert.equal(db.getState().envelopes.length, 0);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+ assert.equal((await storage.headObject(sourcePdfKey)).exists, false);
+ assert.equal((await storage.headObject(thumbnailKey)).exists, false);
+ });
+});
+
+test("stale-draft purge queues files transactionally on outage, reports incomplete, and retries on recovery", async () => {
+ await withTempStorage(async (storage) => {
+ const userId = "user-draft-outage";
+ const envelopeId = "env-draft-outage";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId,
+ sourcePdfKey,
+ userId,
+ });
+ const allKeys = [sourcePdfKey, thumbnailKey];
+
+ for (const key of allKeys) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ });
+
+ const failing = wrapStorage(storage, () => true);
+
+ const first = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: failing.storageService,
+ }),
+ );
+
+ assert.equal(first.status, "ran");
+ assert.equal(first.summary.draftsDeleted, 1);
+ assert.deepEqual(first.summary.draftDeletionFailures, [envelopeId]);
+ assert.equal(retentionJobFailed(first), true);
+
+ const draftTx = db.executedTransactions.find((tx) =>
+ tx.some((sql) => sql.startsWith("DELETE FROM envelopes WHERE id = $1")),
+ );
+
+ assert.ok(draftTx, "expected a transaction deleting the stale draft");
+ assert.ok(
+ draftTx.some((sql) =>
+ sql.startsWith("INSERT INTO pending_file_deletions"),
+ ),
+ "expected pending_file_deletions insert in the same transaction",
+ );
+
+ // Each file was tried once and remains queued with last_tried_at set.
+ assert.deepEqual([...failing.deleteAttempts].sort(), [...allKeys].sort());
+ assert.equal(db.getState().envelopes.length, 0);
+ assert.deepEqual(
+ db
+ .getState()
+ .pendingFileDeletions.map((row) => ({
+ envelopeId: row.envelopeId,
+ storageKey: row.storageKey,
+ tried: row.lastTriedAt !== null,
+ }))
+ .sort((a, b) => a.storageKey.localeCompare(b.storageKey)),
+ allKeys
+ .map((storageKey) => ({ envelopeId, storageKey, tried: true }))
+ .sort((a, b) => a.storageKey.localeCompare(b.storageKey)),
+ );
+
+ for (const key of allKeys) {
+ assert.equal((await storage.headObject(key)).exists, true);
+ }
+
+ // Continued outage still fails the run via pendingFileDeletionFailures.
+ const stillDown = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: failing.storageService,
+ }),
+ );
+
+ assert.equal(stillDown.status, "ran");
+ assert.equal(stillDown.summary.pendingFileDeletionsDone, 0);
+ assert.deepEqual(
+ [...stillDown.summary.pendingFileDeletionFailures].sort(),
+ [...allKeys].sort(),
+ );
+ assert.equal(retentionJobFailed(stillDown), true);
+
+ // Recovery run deletes queued files and returns clean success.
+ const recovered = await withSilentConsole(() =>
+ runRetentionJob({
+ caller: "authorized",
+ database: db.pool,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(recovered.status, "ran");
+ assert.equal(recovered.summary.pendingFileDeletionsDone, allKeys.length);
+ assert.deepEqual(recovered.summary.pendingFileDeletionFailures, []);
+ assert.deepEqual(recovered.summary.draftDeletionFailures, []);
+ assert.equal(retentionJobFailed(recovered), false);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+
+ for (const key of allKeys) {
+ assert.equal((await storage.headObject(key)).exists, false);
+ }
+ });
+});
+
+test("a stale draft edited before its transaction locks it is neither queued nor deleted", async () => {
+ await withTempStorage(async (storage) => {
+ const now = 2_000_000_000;
+ const staleAt = now - (STALE_DRAFT_RETENTION_DAYS + 5) * 24 * 60 * 60;
+ const userId = "user-draft-raced";
+ const envelopeId = "env-draft-raced";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key: sourcePdfKey,
+ });
+
+ const db = createFakeRetentionPool(
+ {
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: staleAt,
+ userId,
+ },
+ ],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ },
+ {
+ beforeQuery(sql, _values, state) {
+ if (sql.includes("SELECT 1 FROM envelopes WHERE id = $1")) {
+ const target = state.envelopes.find((row) => row.id === envelopeId);
+
+ if (target) {
+ target.updatedAt = now;
+ }
+ }
+ },
+ },
+ );
+
+ const summary = await withSilentConsole(() =>
+ runRetentionSweep({ database: db.pool, now, storageService: storage }),
+ );
+
+ assert.equal(summary.draftsDeleted, 0);
+ assert.deepEqual(summary.draftDeletionFailures, []);
+ assert.equal(retentionSweepFailed(summary), false);
+ assert.equal(db.getState().envelopes.length, 1);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+ assert.equal((await storage.headObject(sourcePdfKey)).exists, true);
+ });
+});
+
+test("a rolled-back account deletion leaves no pending_file_deletions rows behind", async () => {
+ await withTempStorage(async (storage) => {
+ const now = 2_000_000_000;
+ const userId = "user-rollback";
+ const envelopeId = "env-rollback";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key: sourcePdfKey,
+ });
+
+ const db = createFakeRetentionPool(
+ {
+ closures: [
+ {
+ exportExpiresAt: 1,
+ purgeAfterAt: 1,
+ requestedAt: 1,
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey,
+ status: "draft",
+ updatedAt: now,
+ userId,
+ },
+ ],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ },
+ {
+ beforeQuery(sql) {
+ if (sql === 'DELETE FROM "user" WHERE id = $1') {
+ throw new Error("Simulated DB failure on delete");
+ }
+ },
+ },
+ );
+
+ const summary = await withSilentConsole(() =>
+ runRetentionSweep({ database: db.pool, now, storageService: storage }),
+ );
+
+ assert.equal(summary.accountsPurged, 0);
+ assert.deepEqual(summary.accountPurgeFailures, [userId]);
+ assert.equal(retentionSweepFailed(summary), true);
+ assert.equal(db.getState().users.length, 1);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+ assert.equal((await storage.headObject(sourcePdfKey)).exists, true);
+ });
+});
+
+test("self-hosted account purge hands over finished envelopes without queueing their files, while queueing draft files", async () => {
+ await withTempStorage(async (storage) => {
+ const now = 2_000_000_000;
+ const adminId = "admin-keeper";
+ const leaverId = "user-with-finished";
+ const finishedId = "env-finished-kept";
+ const draftId = "env-draft-removed";
+ const finishedPdfKey = buildEnvelopeOriginalPdfKey({
+ envelopeId: finishedId,
+ userId: leaverId,
+ });
+ const draftPdfKey = buildEnvelopeOriginalPdfKey({
+ envelopeId: draftId,
+ userId: leaverId,
+ });
+ const draftThumbKey = buildEnvelopeThumbnailKey({
+ envelopeId: draftId,
+ sourcePdfKey: draftPdfKey,
+ userId: leaverId,
+ });
+
+ for (const key of [finishedPdfKey, draftPdfKey, draftThumbKey]) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ closures: [
+ {
+ exportExpiresAt: 1,
+ purgeAfterAt: 1,
+ requestedAt: 1,
+ updatedAt: 1,
+ userId: leaverId,
+ },
+ ],
+ envelopes: [
+ {
+ evidenceKey: null,
+ id: finishedId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey: finishedPdfKey,
+ status: "completed",
+ updatedAt: now,
+ userId: leaverId,
+ },
+ {
+ evidenceKey: null,
+ id: draftId,
+ part11: false,
+ signedPdfKey: null,
+ sourcePdfKey: draftPdfKey,
+ status: "draft",
+ updatedAt: now,
+ userId: leaverId,
+ },
+ ],
+ users: [
+ { email: "[email protected]", id: adminId, role: "admin" },
+ { email: "[email protected]", id: leaverId, role: "user" },
+ ],
+ });
+
+ const failing = wrapStorage(storage, () => true);
+ const first = await withSilentConsole(() =>
+ runRetentionSweep({
+ database: db.pool,
+ now,
+ storageService: failing.storageService,
+ }),
+ );
+
+ assert.equal(first.accountsPurged, 1);
+ assert.deepEqual(first.accountPurgeFailures, [leaverId]);
+ assert.equal(retentionSweepFailed(first), true);
+
+ // Completed envelope moved to the admin and its file was never queued.
+ const handedOver = db
+ .getState()
+ .envelopes.find((row) => row.id === finishedId);
+
+ assert.equal(handedOver?.userId, adminId);
+ assert.deepEqual(
+ db
+ .getState()
+ .pendingFileDeletions.map((row) => row.storageKey)
+ .sort(),
+ [draftPdfKey, draftThumbKey].sort(),
+ );
+
+ // Recovery deletes the draft files while preserving the handed-over file.
+ const recovered = await withSilentConsole(() =>
+ runRetentionSweep({
+ database: db.pool,
+ now: now + 86_400,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(recovered.pendingFileDeletionsDone, 2);
+ assert.equal(retentionSweepFailed(recovered), false);
+ assert.equal((await storage.headObject(finishedPdfKey)).exists, true);
+ assert.equal((await storage.headObject(draftPdfKey)).exists, false);
+ assert.equal((await storage.headObject(draftThumbKey)).exists, false);
+ });
+});
+
+test("hosted-mode account purge queues all envelope artifacts including signed PDF, certificates, and drawn signatures", async () => {
+ const previousHostedMode = process.env.HOSTED_MODE;
+
+ process.env.HOSTED_MODE = "1";
+
+ try {
+ await withTempStorage(async (storage) => {
+ const now = 2_000_000_000;
+ const userId = "user-hosted-outage";
+ const envelopeId = "env-hosted-completed";
+ const sourcePdfKey = buildEnvelopeOriginalPdfKey({ envelopeId, userId });
+ const thumbnailKey = buildEnvelopeThumbnailKey({
+ envelopeId,
+ sourcePdfKey,
+ userId,
+ });
+ const signedPdfKey = buildEnvelopeSignedPdfKey({ envelopeId, userId });
+ const evidenceKey = buildEnvelopeCertificateKey({
+ audience: "internal",
+ envelopeId,
+ userId,
+ });
+ const recipientCertKey = getRecipientCertificateKey(evidenceKey);
+ const signatureImageKey = buildSignatureImageKey({
+ envelopeId,
+ fieldId: "field-1",
+ submissionId: "sub-1",
+ userId,
+ });
+ const allKeys = [
+ sourcePdfKey,
+ thumbnailKey,
+ signedPdfKey,
+ evidenceKey,
+ recipientCertKey,
+ signatureImageKey,
+ ];
+
+ for (const key of allKeys) {
+ await storage.putObject({
+ body: new Uint8Array([37, 80, 68, 70]),
+ contentType: "application/pdf",
+ key,
+ });
+ }
+
+ const db = createFakeRetentionPool({
+ closures: [
+ {
+ exportExpiresAt: 1,
+ purgeAfterAt: 1,
+ requestedAt: 1,
+ updatedAt: 1,
+ userId,
+ },
+ ],
+ envelopes: [
+ {
+ evidenceKey,
+ id: envelopeId,
+ part11: false,
+ signedPdfKey,
+ sourcePdfKey,
+ status: "completed",
+ updatedAt: now,
+ userId,
+ },
+ ],
+ fieldImages: [{ envelopeId, imageKey: signatureImageKey }],
+ users: [{ email: "[email protected]", id: userId, role: "user" }],
+ });
+
+ const failing = wrapStorage(storage, () => true);
+ const first = await withSilentConsole(() =>
+ runRetentionSweep({
+ database: db.pool,
+ now,
+ storageService: failing.storageService,
+ }),
+ );
+
+ assert.equal(first.accountsPurged, 1);
+ assert.deepEqual(first.accountPurgeFailures, [userId]);
+ assert.equal(retentionSweepFailed(first), true);
+ assert.deepEqual(
+ db
+ .getState()
+ .pendingFileDeletions.map((row) => row.storageKey)
+ .sort(),
+ [...allKeys].sort(),
+ );
+
+ const recovered = await withSilentConsole(() =>
+ runRetentionSweep({
+ database: db.pool,
+ now: now + 86_400,
+ storageService: storage,
+ }),
+ );
+
+ assert.equal(recovered.pendingFileDeletionsDone, allKeys.length);
+ assert.equal(retentionSweepFailed(recovered), false);
+ assert.deepEqual(db.getState().pendingFileDeletions, []);
+
+ for (const key of allKeys) {
+ assert.equal((await storage.headObject(key)).exists, false);
+ }
+ });
+ } finally {
+ if (previousHostedMode === undefined) {
+ delete process.env.HOSTED_MODE;
+ } else {
+ process.env.HOSTED_MODE = previousHostedMode;
+ }
+ }
+});
diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.ts
index d8b1e6d..a275e39 100644
--- a/src/lib/retention-job.ts
+++ b/src/lib/retention-job.ts
@@ -239,7 +239,8 @@ export function retentionSweepFailed(summary: RetentionSweepSummary): boolean {
return (
summary.accountPurgeFailures.length > 0 ||
summary.draftDeletionFailures.length > 0 ||
- summary.finishedEnvelopeDeletionFailures.length > 0
+ summary.finishedEnvelopeDeletionFailures.length > 0 ||
+ summary.pendingFileDeletionFailures.length > 0
);
}
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index 6844ccb..b2b388e 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -63,7 +63,9 @@ export type RetentionSweepSummary = {
finishedEnvelopeDeletionFailures: string[];
finishedEnvelopesDeleted: number;
finishedEnvelopeWarningsSent: number;
- /** Files of deleted envelopes that an earlier deletion could not remove. */
+ /** Queued files of deleted records that could not be removed on retry. */
+ pendingFileDeletionFailures: string[];
+ /** Files of deleted records that an earlier deletion could not remove. */
pendingFileDeletionsDone: number;
/** Trips to a signing provider ended because nobody came back. */
providerSigningSessionsEnded: number;
@@ -543,11 +545,12 @@ function isPool(database: DbExecutor): database is ReturnType<typeof getDb> {
}
/**
- * Deletes the account with everything that hangs on it, and returns the
- * files those rows pointed at. Returns null when the account is already
- * gone. With `keepFinishedEnvelopes`, finished envelopes are handed to an
- * administrator first, and the account stays (AccountPurgeDeferredError)
- * when there is none to take them.
+ * Deletes the account with everything that hangs on it, queues the files
+ * those rows pointed at in `pending_file_deletions` in the same
+ * transaction, and returns those keys. Returns null when the account is
+ * already gone. With `keepFinishedEnvelopes`, finished envelopes are handed
+ * to an administrator first, and the account stays
+ * (AccountPurgeDeferredError) when there is none to take them.
*
* The account's row is locked before the files are listed. Saving a
* template or uploading a document writes a row that points at the account,
@@ -600,27 +603,31 @@ async function deleteAccountRows(
envelopes.map((envelope) => envelope.id),
database,
);
- const storageKeys = new Set<string>();
+ const storageKeys = new Map<string, string>();
for (const envelope of envelopes) {
for (const key of buildEnvelopeStorageKeys(
envelope,
fieldImagesByEnvelopeId.get(envelope.id) ?? [],
)) {
- storageKeys.add(key);
+ if (!storageKeys.has(key)) {
+ storageKeys.set(key, envelope.id);
+ }
}
}
// Templates go with the account: their rows with the user's row below,
// their documents here.
- const templates = await queryMany<{ sourcePdfKey: string }>(
+ const templates = await queryMany<{ id: string; sourcePdfKey: string }>(
database,
- `SELECT source_pdf_key AS "sourcePdfKey" FROM templates WHERE user_id = $1`,
+ `SELECT id, source_pdf_key AS "sourcePdfKey" FROM templates WHERE user_id = $1`,
[userId],
);
for (const template of templates) {
- storageKeys.add(template.sourcePdfKey);
+ if (!storageKeys.has(template.sourcePdfKey)) {
+ storageKeys.set(template.sourcePdfKey, `template:${template.id}`);
+ }
}
// The access it ends is worth a line in the install's trail, which lands
@@ -658,6 +665,15 @@ async function deleteAccountRows(
database,
);
+ await queuePendingFileDeletions(
+ [...storageKeys.entries()].map(([storageKey, envelopeId]) => ({
+ envelopeId,
+ storageKey,
+ })),
+ now,
+ database,
+ );
+
await database.query(
`
DELETE FROM "user"
@@ -666,7 +682,7 @@ async function deleteAccountRows(
[userId],
);
- return [...storageKeys];
+ return [...storageKeys.keys()];
}
async function purgeQueuedAccount(
@@ -675,14 +691,15 @@ async function purgeQueuedAccount(
database: DbExecutor,
storageService: StorageService,
env: EnvSource = process.env,
-): Promise<boolean> {
+): Promise<{ filesLeft: boolean; purged: boolean }> {
// On a self-hosted install the finished envelopes stay with the
// organization. Hosted mode keeps nothing of a closed account.
const keepFinishedEnvelopes = !isHostedMode(env);
// One transaction, so the locks on the account and its envelopes hold
- // from the hand-over and the list of its files to the delete. A caller
- // that hands in its own connection decides where its transaction ends.
+ // from the hand-over and the list of its files to the delete, and the
+ // queued file deletions commit with the row removal. A caller that hands
+ // in its own connection decides where its transaction ends.
const storageKeys = isPool(database)
? await withTransaction(
(tx) => deleteAccountRows(userId, now, keepFinishedEnvelopes, tx),
@@ -691,52 +708,100 @@ async function purgeQueuedAccount(
: await deleteAccountRows(userId, now, keepFinishedEnvelopes, database);
if (!storageKeys) {
- return false;
+ return { filesLeft: false, purged: false };
}
- // Only once the rows are gone for good.
- await deleteStorageKeys(storageKeys, storageService).catch((error) => {
- console.error(
- `Failed to delete storage artifacts for purged account ${userId}:`,
- error,
- );
- });
+ // Only once the rows are gone for good. A file that cannot be deleted
+ // stays queued in pending_file_deletions for the next sweep, and this run
+ // is reported as failed for it.
+ let filesLeft = false;
- return true;
+ for (const key of storageKeys) {
+ if (!(await deletePendingFile(key, database, storageService))) {
+ filesLeft = true;
+ }
+ }
+
+ return { filesLeft, purged: true };
}
-async function purgeStaleDraftEnvelope(
+/**
+ * Deletes a stale draft's row if it has not been touched since it was
+ * listed, and queues its files for deletion in the same transaction.
+ */
+async function deleteStaleDraftRow(
envelope: EnvelopeArtifactRow,
- database: DbExecutor,
- storageService: StorageService,
- fieldImagesByEnvelopeId: ReadonlyMap<string, readonly string[]>,
+ keys: readonly string[],
+ now: number,
+ tx: DbExecutor,
): Promise<boolean> {
- const deleteResult = await database.query(
+ const locked = await tx.query(
`
- DELETE FROM envelopes
+ SELECT 1
+ FROM envelopes
WHERE id = $1
AND user_id = $2
AND status = 'draft'
AND updated_at = $3
+ FOR UPDATE
`,
[envelope.id, envelope.userId, envelope.updatedAt],
);
- if (deleteResult.rowCount !== 1) {
+ if (locked.rowCount !== 1) {
return false;
}
- await deleteStorageKeys(
- buildEnvelopeStorageKeys(
- envelope,
- fieldImagesByEnvelopeId.get(envelope.id) ?? [],
- ),
- storageService,
+ await queueFileDeletions(envelope.id, keys, now, tx);
+ await tx.query(
+ `
+ DELETE FROM envelopes
+ WHERE id = $1
+ AND user_id = $2
+ AND status = 'draft'
+ AND updated_at = $3
+ `,
+ [envelope.id, envelope.userId, envelope.updatedAt],
);
return true;
}
+async function purgeStaleDraftEnvelope(
+ envelope: EnvelopeArtifactRow,
+ now: number,
+ database: DbExecutor,
+ storageService: StorageService,
+ fieldImagesByEnvelopeId: ReadonlyMap<string, readonly string[]>,
+): Promise<{ deleted: boolean; filesLeft: boolean }> {
+ const keys = buildEnvelopeStorageKeys(
+ envelope,
+ fieldImagesByEnvelopeId.get(envelope.id) ?? [],
+ );
+ // The row goes first, in one transaction with its files on the queue,
+ // then the files. A storage failure or crash after commit leaves the
+ // keys queued for the next sweep.
+ const removeRow = (tx: DbExecutor) =>
+ deleteStaleDraftRow(envelope, keys, now, tx);
+ const deleted = isPool(database)
+ ? await withTransaction(removeRow, database)
+ : await removeRow(database);
+
+ if (!deleted) {
+ return { deleted: false, filesLeft: false };
+ }
+
+ let filesLeft = false;
+
+ for (const key of keys) {
+ if (!(await deletePendingFile(key, database, storageService))) {
+ filesLeft = true;
+ }
+ }
+
+ return { deleted: true, filesLeft };
+}
+
type FinishedEnvelopeRow = EnvelopeArtifactRow & {
finishedAt: number;
ownerEmail: string;
@@ -1061,6 +1126,30 @@ export async function listEnvelopeStorageKeys(
/** How many queued file deletions one cleanup tries, at most. */
const PENDING_FILE_DELETIONS_PER_SWEEP = 500;
+async function queuePendingFileDeletions(
+ entries: readonly { envelopeId: string; storageKey: string }[],
+ now: number,
+ database: DbExecutor,
+): Promise<void> {
+ if (entries.length === 0) {
+ return;
+ }
+
+ await database.query(
+ `
+ INSERT INTO pending_file_deletions (storage_key, envelope_id, queued_at)
+ SELECT storage_key, envelope_id, $3
+ FROM unnest($1::text[], $2::text[]) AS pending(storage_key, envelope_id)
+ ON CONFLICT (storage_key) DO NOTHING
+ `,
+ [
+ entries.map((entry) => entry.storageKey),
+ entries.map((entry) => entry.envelopeId),
+ now,
+ ],
+ );
+}
+
/**
* Names files to delete once the transaction that deletes their envelope
* has committed. Until `deletePendingFile` removes one, the daily cleanup
@@ -1127,12 +1216,11 @@ export async function deletePendingFile(
}
}
-/** Tries the queued file deletions, least recently tried first. */
-export async function deletePendingFiles(
+async function retryPendingFiles(
database: DbExecutor,
storageService: StorageService,
limit = PENDING_FILE_DELETIONS_PER_SWEEP,
-): Promise<number> {
+): Promise<{ done: number; failures: string[] }> {
const pending = await queryMany<{ storageKey: string }>(
database,
`
@@ -1144,13 +1232,27 @@ export async function deletePendingFiles(
[limit],
);
let done = 0;
+ const failures: string[] = [];
for (const { storageKey } of pending) {
if (await deletePendingFile(storageKey, database, storageService)) {
done += 1;
+ } else {
+ failures.push(storageKey);
}
}
+ return { done, failures };
+}
+
+/** Tries the queued file deletions, least recently tried first. */
+export async function deletePendingFiles(
+ database: DbExecutor,
+ storageService: StorageService,
+ limit = PENDING_FILE_DELETIONS_PER_SWEEP,
+): Promise<number> {
+ const { done } = await retryPendingFiles(database, storageService, limit);
+
return done;
}
@@ -1221,15 +1323,16 @@ export async function runRetentionSweep({
finishedEnvelopeDeletionFailures: [],
finishedEnvelopesDeleted: 0,
finishedEnvelopeWarningsSent: 0,
+ pendingFileDeletionFailures: [],
pendingFileDeletionsDone: 0,
providerSigningSessionsEnded: 0,
ranAt: now,
};
- summary.pendingFileDeletionsDone = await deletePendingFiles(
- database,
- storageService,
- );
+ const pendingFileResults = await retryPendingFiles(database, storageService);
+
+ summary.pendingFileDeletionsDone = pendingFileResults.done;
+ summary.pendingFileDeletionFailures = pendingFileResults.failures;
summary.expiredRecipientDownloadTokensDeleted =
await deleteExpiredRecipientDownloadTokens(now, database);
@@ -1241,15 +1344,20 @@ export async function runRetentionSweep({
for (const envelope of staleDrafts) {
try {
- const deleted = await purgeStaleDraftEnvelope(
+ const result = await purgeStaleDraftEnvelope(
envelope,
+ now,
database,
storageService,
staleDraftFieldImagesByEnvelopeId,
);
- if (deleted) {
+ if (result.deleted) {
summary.draftsDeleted += 1;
+
+ if (result.filesLeft) {
+ summary.draftDeletionFailures.push(envelope.id);
+ }
}
} catch (error) {
summary.draftDeletionFailures.push(envelope.id);
@@ -1262,15 +1370,19 @@ export async function runRetentionSweep({
for (const closureRequest of dueAccountClosures) {
try {
- const deleted = await purgeQueuedAccount(
+ const result = await purgeQueuedAccount(
closureRequest.userId,
now,
database,
storageService,
);
- if (deleted) {
+ if (result.purged) {
summary.accountsPurged += 1;
+
+ if (result.filesLeft) {
+ summary.accountPurgeFailures.push(closureRequest.userId);
+ }
}
} catch (error) {
summary.accountPurgeFailures.push(closureRequest.userId);