Skip to content

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

TypeScript

Let later deletion emails and deletions pass ones that keep failing

Claudec6bc9c0b7893
diff --git a/db/migrations/20261118110000_scheduled_envelope_deletions.sql b/db/migrations/20261118110000_scheduled_envelope_deletions.sql
index 5a9a912..d7daed3 100644
--- a/db/migrations/20261118110000_scheduled_envelope_deletions.sql
+++ b/db/migrations/20261118110000_scheduled_envelope_deletions.sql
@@ -24,7 +24,11 @@ create table if not exists public.scheduled_envelope_deletions (
cancelled_at bigint,
cancelled_by_user_id text,
cancelled_by_email text,
- cancel_notified_at bigint
+ cancel_notified_at bigint,
+ -- When the daily cleanup last tried this request's email or deletion.
+ -- The ones never tried, then the longest waiting, go first, so a few
+ -- that keep failing cannot hold back the rest.
+ last_attempt_at bigint
);
create index if not exists scheduled_envelope_deletions_due_idx
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.ts
index fface8a..a7f4f4d 100644
--- a/src/lib/envelope-deletion.dbtest.ts
+++ b/src/lib/envelope-deletion.dbtest.ts
@@ -15,6 +15,7 @@ import {
ENVELOPE_DELETION_WAIT_DAYS,
getScheduledEnvelopeDeletion,
runScheduledEnvelopeDeletions,
+ SCHEDULED_DELETIONS_PER_RUN,
scheduleEnvelopeDeletion,
} from "./envelope-deletion.ts";
import { EnvelopeMutationError } from "./envelopes.ts";
@@ -754,6 +755,79 @@ test("a cancellation email still owed is not sent once the deletion is scheduled
assert.equal(emailsTo(second.owner.email).length, 2);
});
+test("notices that keep failing go behind the others, so later senders are still told", async () => {
+ sent = [];
+ const admin = await createUser("admin");
+ const unreachable = await createUser("user");
+ const reachable = await createUser("user");
+ // Long ago, so these come before anything else waiting.
+ const start = 500_000_000;
+
+ // A full batch of requests whose sender's email keeps bouncing…
+ await database.query(
+ `
+ with made as (
+ insert into envelopes (
+ id, user_id, title, status, source_pdf_key, source_pdf_filename,
+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at,
+ completed_at
+ )
+ select
+ gen_random_uuid()::text, $1, 'Lease', 'completed',
+ 'users/' || $1 || '/envelopes/' || n || '/source.pdf', 'lease.pdf',
+ 4, 1, $2, $3, $3
+ from generate_series(1, $4::int) as n
+ returning id
+ )
+ insert into scheduled_envelope_deletions (
+ envelope_id, requested_by_user_id, requested_by_email, requested_at,
+ delete_after
+ )
+ select id, $5, $6, $3, $3 + $7 from made
+ `,
+ [
+ unreachable.userId,
+ SOURCE_HASH,
+ start,
+ SCHEDULED_DELETIONS_PER_RUN,
+ admin.userId,
+ admin.email,
+ WAIT,
+ ],
+ );
+ // …and one asked for after them.
+ const later = await createEnvelope(reachable.userId, { status: "completed" });
+
+ await quietly(() =>
+ scheduleAs(admin, later.envelopeId, undefined, {
+ emailService: createOutbox(true),
+ now: start + 1,
+ }),
+ );
+
+ const bouncing = createOutbox();
+ const outbox: EmailService = {
+ ...bouncing,
+ async send(message, options) {
+ if (message.to === unreachable.email) {
+ throw new Error("Mailbox unavailable.");
+ }
+
+ return bouncing.send(message, options);
+ },
+ };
+
+ // The first run tries the oldest ones; the next reaches the later sender.
+ await quietly(() => runDaily(start + DAY, outbox));
+ await quietly(() => runDaily(start + 2 * DAY, outbox));
+
+ assert.equal(emailsTo(reachable.email).length, 1);
+ assert.ok(
+ (await getScheduledEnvelopeDeletion(later.envelopeId, database))
+ ?.deleteAfter,
+ );
+});
+
test("a cancelled deletion can be scheduled again", async () => {
const admin = await createUser("admin");
const envelope = await createEnvelope(admin.userId, { status: "voided" });
diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.ts
index d64682d..b51813d 100644
--- a/src/lib/envelope-deletion.ts
+++ b/src/lib/envelope-deletion.ts
@@ -39,7 +39,7 @@ export const ENVELOPE_DELETION_WAIT_DAYS = 14;
const DAY_IN_SECONDS = 24 * 60 * 60;
/** How many due deletions, and sender notices, one daily run handles. */
-const SCHEDULED_DELETIONS_PER_RUN = 100;
+export const SCHEDULED_DELETIONS_PER_RUN = 100;
type FinishedEnvelopeRow = {
evidenceSha256: string | null;
@@ -415,7 +415,8 @@ export async function scheduleEnvelopeDeletion(
cancelled_at = NULL,
cancelled_by_user_id = NULL,
cancelled_by_email = NULL,
- cancel_notified_at = NULL
+ cancel_notified_at = NULL,
+ last_attempt_at = NULL
WHERE scheduled_envelope_deletions.cancelled_at IS NOT NULL
`,
[
@@ -720,33 +721,39 @@ const CANCELLED_KEPT_SECONDS = DAY_IN_SECONDS;
/** After this, a cancellation notice that keeps failing is given up. */
const CANCELLED_GIVE_UP_SECONDS = 30 * DAY_IN_SECONDS;
-/** Whether the notice a row was read as owing is still owed, as it is now. */
-async function isNoticeStillOwed(
+/**
+ * Claims a notice the row was read as owing, if it is still owed as things
+ * are now: a request rescheduled or cancelled since the list was read is
+ * owed something else, or nothing. The attempt is recorded either way it
+ * ends, so a notice that keeps failing goes behind the others next time.
+ */
+async function claimOwedNotice(
row: PendingNoticeRow,
+ now: number,
database: DbExecutor,
): Promise<boolean> {
const result =
row.cancelledAt === null
? await database.query(
`
- SELECT 1
- FROM scheduled_envelope_deletions
+ UPDATE scheduled_envelope_deletions
+ SET last_attempt_at = $3
WHERE envelope_id = $1
AND requested_at = $2
AND cancelled_at IS NULL
AND sender_notified_at IS NULL
`,
- [row.envelopeId, row.requestedAt],
+ [row.envelopeId, row.requestedAt, now],
)
: await database.query(
`
- SELECT 1
- FROM scheduled_envelope_deletions
+ UPDATE scheduled_envelope_deletions
+ SET last_attempt_at = $3
WHERE envelope_id = $1
AND cancelled_at = $2
AND cancel_notified_at IS NULL
`,
- [row.envelopeId, row.cancelledAt],
+ [row.envelopeId, row.cancelledAt, now],
);
return result.rowCount === 1;
@@ -798,7 +805,9 @@ export async function runScheduledEnvelopeDeletions({
AND e.user_id <> s.requested_by_user_id
AND e.user_id <> s.cancelled_by_user_id
)
- ORDER BY s.requested_at ASC
+ -- Never tried first, then the longest since the last try, so notices
+ -- that keep failing cannot hold back the rest.
+ ORDER BY s.last_attempt_at ASC NULLS FIRST, s.requested_at ASC
LIMIT ${String(SCHEDULED_DELETIONS_PER_RUN)}
`,
[now - CANCELLED_GIVE_UP_SECONDS],
@@ -807,9 +816,7 @@ export async function runScheduledEnvelopeDeletions({
for (const row of owed) {
try {
- // The list was read before any of it was sent: a request rescheduled
- // or cancelled since then is owed something else, or nothing.
- if (!(await isNoticeStillOwed(row, database))) {
+ if (!(await claimOwedNotice(row, now, database))) {
continue;
}
@@ -872,7 +879,7 @@ export async function runScheduledEnvelopeDeletions({
WHERE cancelled_at IS NULL
AND sender_notified_at IS NOT NULL
AND delete_after <= $1
- ORDER BY delete_after ASC, envelope_id ASC
+ ORDER BY last_attempt_at ASC NULLS FIRST, delete_after ASC, envelope_id ASC
LIMIT ${String(SCHEDULED_DELETIONS_PER_RUN)}
`,
[now],
@@ -880,6 +887,13 @@ export async function runScheduledEnvelopeDeletions({
for (const { envelopeId } of due) {
try {
+ // Recorded before trying, so a deletion that keeps failing goes
+ // behind the others next time.
+ await database.query(
+ `UPDATE scheduled_envelope_deletions SET last_attempt_at = $2 WHERE envelope_id = $1`,
+ [envelopeId, now],
+ );
+
if (
await deleteScheduledEnvelope(envelopeId, {
database,