Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Stop a bulk send that lost its batch claim before it saves or sends
Matt Van Hornf1dfb7ebcded
diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.tsindex df70bfd..33c17e5 100644--- a/src/lib/bulk-send.dbtest.ts+++ b/src/lib/bulk-send.dbtest.ts@@ -1123,3 +1123,139 @@ test("erasing a signer clears a saved failure reason that names them", async ()assert.equal(stored.rowCount, 1);assert.equal(stored.rows[0]?.reason, null);});++async function takeOverBatch(userId: string, batchKey: unknown) {+ await database.query(+ `+ update bulk_send_batches+ set claim_token = 'another-request',+ claimed_at = extract(epoch from now())::bigint+ where user_id = $1 and batch_key = $2+ `,+ [userId, batchKey],+ );+}++test("a request that loses its claim while making a draft saves and sends nothing", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\n`,+ );+ const envelopesBefore = await countEnvelopes(userId);+ // A retry takes the batch over while this request reads the template's+ // file, as it could if the read stalled past the claim's lifetime.+ const slowStorage: StorageService = {+ deleteObject: (key) => storageService.deleteObject(key),+ getObject: async (key) => {+ await takeOverBatch(userId, body.batchKey);+ return storageService.getObject(key);+ },+ getObjectStream: (key) => storageService.getObjectStream(key),+ headObject: (key) => storageService.headObject(key),+ putObject: (input) => storageService.putObject(input),+ };++ await assert.rejects(+ bulkSendFromTemplate(userId, template.id, body, {+ database,+ sender: senderFor(userId),+ storageService: slowStorage,+ }),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.statusCode === 409 &&+ error.message === bulkSendBatchBusyMessage,+ );++ const saved = await database.query(+ `+ select r.row_number+ from bulk_send_batch_rows r+ join bulk_send_batches b on b.id = r.batch_id+ where b.user_id = $1 and b.batch_key = $2+ `,+ [userId, body.batchKey],+ );++ assert.equal(saved.rowCount, 0);+ assert.equal(await countSent(userId), 0);+ assert.equal(await countEnvelopes(userId), envelopesBefore);+});++test("a request that loses its claim before sending does not send, and the retry sends the same envelope", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\n`,+ );+ // A retry takes the batch over right after the row's envelope is saved.+ const slowDatabase = new Proxy(database, {+ get(target, property, receiver) {+ if (property !== "query") {+ return Reflect.get(target, property, receiver);+ }++ return async (text: string, values?: unknown[]) => {+ const result = await target.query(text, values);++ if (+ typeof text === "string" &&+ text.includes("INSERT INTO bulk_send_batch_rows") &&+ values?.[2] === "processing"+ ) {+ await takeOverBatch(userId, body.batchKey);+ }++ return result;+ };+ },+ });++ await assert.rejects(+ bulkSendFromTemplate(userId, template.id, body, {+ database: slowDatabase,+ sender: senderFor(userId),+ storageService,+ }),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.message === bulkSendBatchBusyMessage,+ );++ const stored = await database.query<{+ envelopeId: string | null;+ status: string;+ }>(+ `+ select r.envelope_id as "envelopeId", r.status+ from bulk_send_batch_rows r+ join bulk_send_batches b on b.id = r.batch_id+ where b.user_id = $1 and b.batch_key = $2+ `,+ [userId, body.batchKey],+ );++ assert.equal(stored.rows[0]?.status, "processing");+ assert.ok(stored.rows[0]?.envelopeId);+ assert.equal(await countSent(userId), 0);++ await database.query(+ `+ update bulk_send_batches+ set claimed_at = extract(epoch from now())::bigint - $3+ where user_id = $1 and batch_key = $2+ `,+ [userId, body.batchKey, BULK_SEND_CLAIM_STALE_SECONDS + 1],+ );++ const retry = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.equal(retry.rows[0]?.status, "sent");+ assert.equal(retry.rows[0]?.envelopeId, stored.rows[0]?.envelopeId);+ assert.equal(await countSent(userId), 1);+ assert.equal(await countEnvelopes(userId), 2);+});diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.tsindex fff9964..2575623 100644--- a/src/lib/bulk-send.ts+++ b/src/lib/bulk-send.ts@@ -18,6 +18,7 @@ import {queryOne,} from "./db/connection.ts";import {+ deleteDraftEnvelope,EnvelopeMutationError,getPrepareEnvelopeDataForUser,replaceDraftEnvelopeSigners,@@ -71,6 +72,18 @@ export class BulkSendError extends Error {}}+/**+ * This request no longer holds the batch: it was too slow and a retry took+ * the claim over. It stops without saving or sending anything more, and the+ * request that holds the claim finishes the batch.+ */+class BulkSendClaimLostError extends BulkSendError {+ constructor() {+ super(bulkSendBatchBusyMessage, 409);+ this.name = "BulkSendClaimLostError";+ }+}+export type BulkSendSender = {email: string;ipAddress?: string | null;@@ -98,7 +111,7 @@ type StoredBatchRow = {};type SendRowContext = {- batchId: string;+ batch: StoredBatch;copyRecipients: NonNullable<BulkSendRequest["copyRecipients"]>;database: DbPool;expiresInDays: BulkSendRequest["expiresInDays"];@@ -116,8 +129,10 @@ const TERMINAL_ROW_STATUSES = new Set(["failed", "sent"]);/*** How long a claim on a batch lasts without being refreshed. The request- * sending a batch refreshes it before each row, so this only has to outlast- * one row. A request that dies leaves a claim a retry can take after this.+ * sending a batch refreshes it before each step of a row, so this only has+ * to outlast one step. A request that dies leaves a claim a retry can take+ * after this, and a request that loses its claim stops before it saves or+ * sends.*/export const BULK_SEND_CLAIM_STALE_SECONDS = 5 * 60;@@ -367,7 +382,7 @@ async function refreshBatchClaim();if (refreshed.rowCount === 0) {- throw new BulkSendError(bulkSendBatchBusyMessage, 409);+ throw new BulkSendClaimLostError();}}@@ -385,14 +400,26 @@ async function releaseBatchClaim();}+/**+ * Saves a row only while this request still holds the batch, and refreshes+ * the claim in the same statement. The claim update locks the batch, so a+ * retry taking the claim over either waits for this save and then sees the+ * row's envelope, or wins first and this save writes nothing.+ */async function saveBatchRow(- batchId: string,+ batch: StoredBatch,row: BulkSendRowResult,status: StoredBatchRow["status"],database: DbExecutor,): Promise<void> {- await database.query(+ const saved = await database.query(`+ WITH claim AS (+ UPDATE bulk_send_batches+ SET claimed_at = extract(epoch from now())::bigint+ WHERE id = $1 AND claim_token = $6+ RETURNING id+ )INSERT INTO bulk_send_batch_rows (batch_id,row_number,@@ -400,15 +427,27 @@ async function saveBatchRow(envelope_id,reason)- VALUES ($1, $2, $3, $4, $5)+ SELECT claim.id, $2, $3, $4, $5+ FROM claimON CONFLICT (batch_id, row_number)DO UPDATE SETstatus = EXCLUDED.status,envelope_id = EXCLUDED.envelope_id,reason = EXCLUDED.reason`,- [batchId, row.rowNumber, status, row.envelopeId, row.reason],+ [+ batch.id,+ row.rowNumber,+ status,+ row.envelopeId,+ row.reason,+ batch.claimToken,+ ],);++ if (saved.rowCount === 0) {+ throw new BulkSendClaimLostError();+ }}async function invitationWasRecorded(@@ -454,7 +493,7 @@ async function sendOneRow(context: SendRowContext,): Promise<BulkSendRowResult> {const {- batchId,+ batch,copyRecipients,database,expiresInDays,@@ -504,19 +543,41 @@ async function sendOneRow({ database, storageService },);+ try {+ await saveBatchRow(+ batch,+ { ...row, envelopeId: draft.envelopeId, reason: null },+ "processing",+ database,+ );+ } catch (error) {+ // Another request took the batch while this draft was being made. It+ // makes and sends its own envelope for this row, so this draft is+ // never sent and is removed.+ if (error instanceof BulkSendClaimLostError) {+ await deleteDraftEnvelope(userId, draft.envelopeId, {+ database,+ storageService,+ }).catch(() => undefined);+ }++ throw error;+ }+envelopeId = draft.envelopeId;progress.envelopeId = envelopeId;+ } else {+ await saveBatchRow(+ batch,+ { ...row, envelopeId, reason: null },+ "processing",+ database,+ );}- const processing = {- ...row,- envelopeId,- envelopePath: envelopePath(envelopeId),- };-- await saveBatchRow(batchId, processing, "processing", database);-if (needsSignerUpdate) {+ await refreshBatchClaim(batch, database);+const prepared = await getPrepareEnvelopeDataForUser(userId, envelopeId, {database,});@@ -546,6 +607,8 @@ async function sendOneRow(}}+ await refreshBatchClaim(batch, database);+try {await sendDraftEnvelope(userId,@@ -701,7 +764,7 @@ export async function bulkSendFromTemplate(try {const result = await sendOneRow(row, stored, {- batchId: batch.id,+ batch,copyRecipients,database,expiresInDays: parsedInput.expiresInDays,@@ -715,9 +778,13 @@ export async function bulkSendFromTemplate(userId,});- await saveBatchRow(batch.id, result, "sent", database);+ await saveBatchRow(batch, result, "sent", database);sent.push(result);} catch (error) {+ if (error instanceof BulkSendClaimLostError) {+ throw error;+ }+if (!isExpectedSendFailure(error)) {logRouteError(error, {category: "template_bulk_send_row_failure",@@ -734,7 +801,7 @@ export async function bulkSendFromTemplate(const failed = failedRow(row, progress.envelopeId, error);- await saveBatchRow(batch.id, failed, "failed", database);+ await saveBatchRow(batch, failed, "failed", database);sent.push(failed);}}