Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Hold the request while its daily email goes out
Claudecca1f9f84374
diff --git a/src/lib/envelope-deletion.dbtest.ts b/src/lib/envelope-deletion.dbtest.tsindex a7f4f4d..f2937af 100644--- a/src/lib/envelope-deletion.dbtest.ts+++ b/src/lib/envelope-deletion.dbtest.ts@@ -755,6 +755,57 @@ test("a cancellation email still owed is not sent once the deletion is scheduledassert.equal(emailsTo(second.owner.email).length, 2);});+test("a deletion scheduled again while its cancellation email is going out waits, so its own notice comes after", async () => {+ sent = [];+ const admin = await createUser("admin");+ const owner = await createUser("user");+ const envelope = await createEnvelope(owner.userId, { status: "completed" });+ const start = 1_100_000_000;++ await scheduleAs(admin, envelope.envelopeId, undefined, { now: start });+ await quietly(() =>+ cancelAs(admin, envelope.envelopeId, {+ emailService: createOutbox(true),+ now: start + 1,+ }),+ );++ // As the daily run sends the cancellation, an administrator schedules it+ // again; that waits for the email, then sends its own.+ const outbox = createOutbox();+ let rescheduling: Promise<unknown> | undefined;+ const reschedulingOutbox: EmailService = {+ ...outbox,+ async send(message, options) {+ if (!rescheduling && message.to === owner.email) {+ rescheduling = scheduleAs(admin, envelope.envelopeId, "Again.", {+ now: start + DAY,+ });+ await delay(300);+ }++ return outbox.send(message, options);+ },+ };++ await runDaily(start + DAY, reschedulingOutbox);+ await rescheduling;++ assert.deepEqual(+ emailsTo(owner.email)+ .map((message) => message.subject)+ .slice(1),+ [+ '"Lease" will not be deleted',+ `"Lease" will be deleted on ${new Date((start + DAY + WAIT) * 1000).toISOString().slice(0, 10)}`,+ ],+ );+ assert.equal(+ (await getScheduledEnvelopeDeletion(envelope.envelopeId, database))?.reason,+ "Again.",+ );+});+test("notices that keep failing go behind the others, so later senders are still told", async () => {sent = [];const admin = await createUser("admin");diff --git a/src/lib/envelope-deletion.ts b/src/lib/envelope-deletion.tsindex b51813d..6e2b2b2 100644--- a/src/lib/envelope-deletion.ts+++ b/src/lib/envelope-deletion.ts@@ -722,38 +722,40 @@ const CANCELLED_KEPT_SECONDS = DAY_IN_SECONDS;const CANCELLED_GIVE_UP_SECONDS = 30 * DAY_IN_SECONDS;/**- * 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.+ * Locks the request for 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 lock is held while the+ * email goes out, so a reschedule or cancellation waits for it and its own+ * email comes after.*/-async function claimOwedNotice(+async function lockOwedNotice(row: PendingNoticeRow,- now: number,- database: DbExecutor,+ tx: DbExecutor,): Promise<boolean> {const result =row.cancelledAt === null- ? await database.query(+ ? await tx.query(`- UPDATE scheduled_envelope_deletions- SET last_attempt_at = $3+ SELECT 1+ FROM scheduled_envelope_deletionsWHERE envelope_id = $1AND requested_at = $2AND cancelled_at IS NULLAND sender_notified_at IS NULL+ FOR UPDATE`,- [row.envelopeId, row.requestedAt, now],+ [row.envelopeId, row.requestedAt],)- : await database.query(+ : await tx.query(`- UPDATE scheduled_envelope_deletions- SET last_attempt_at = $3+ SELECT 1+ FROM scheduled_envelope_deletionsWHERE envelope_id = $1AND cancelled_at = $2AND cancel_notified_at IS NULL+ FOR UPDATE`,- [row.envelopeId, row.cancelledAt, now],+ [row.envelopeId, row.cancelledAt],);return result.rowCount === 1;@@ -816,28 +818,40 @@ export async function runScheduledEnvelopeDeletions({for (const row of owed) {try {- if (!(await claimOwedNotice(row, now, database))) {- continue;- }+ // Recorded first, and kept if the email fails, so a notice 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`,+ [row.envelopeId, now],+ );- service ??= createEmailService();-- if (row.cancelledAt === null) {- await sendDeletionNotice(row, now, database, service);- } else {- await sendCancellationNotice(- {- ...row,- cancelledAt: row.cancelledAt,- cancelledByEmail: row.cancelledByEmail ?? "",- },- now,- database,- service,- );+ const emailService = (service ??= createEmailService());+ const notified = await withTransaction(async (tx) => {+ if (!(await lockOwedNotice(row, tx))) {+ return false;+ }++ if (row.cancelledAt === null) {+ await sendDeletionNotice(row, now, tx, emailService);+ } else {+ await sendCancellationNotice(+ {+ ...row,+ cancelledAt: row.cancelledAt,+ cancelledByEmail: row.cancelledByEmail ?? "",+ },+ now,+ tx,+ emailService,+ );+ }++ return true;+ }, database);++ if (notified) {+ summary.noticesSent += 1;}-- summary.noticesSent += 1;} catch (error) {summary.noticeFailures.push(row.envelopeId);console.error(