Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Claim bulk-send batches with a saved token, not a session lock
Matt Van Horn9df9b945186d
diff --git a/db/migrations/20261118090000_bulk_send_batches.sql b/db/migrations/20261118090000_bulk_send_batches.sqlindex 253449c..0691bc3 100644--- a/db/migrations/20261118090000_bulk_send_batches.sql+++ b/db/migrations/20261118090000_bulk_send_batches.sql@@ -3,7 +3,13 @@---- The client gives each confirm a batch_key. The first request stores each-- row as it is sent. A later request with that key returns or finishes those--- stored results instead of sending the list again.+-- stored results instead of sending the list again. Skipped rows are not+-- stored: a retry works them out again from the same list.+--+-- claim_token and claimed_at mark the one request that is sending a batch.+-- They are a saved claim rather than a session lock so they work through+-- pooled connections, and a request that dies leaves a claim that goes+-- stale instead of one that is held forever.create table if not exists public.bulk_send_batches (id text primary key,@@ -11,6 +17,8 @@ create table if not exists public.bulk_send_batches (template_id text not null references public.templates(id) on delete cascade,batch_key text not null,request_fingerprint text not null,+ claim_token text,+ claimed_at bigint,created_at bigint not null default (extract(epoch from now())::bigint),constraint bulk_send_batches_user_key unique (user_id, batch_key));@@ -19,7 +27,7 @@ create table if not exists public.bulk_send_batch_rows (batch_id text not null references public.bulk_send_batches(id) on delete cascade,row_number integer not null,status text not null- check (status in ('processing', 'sent', 'skipped', 'failed')),+ check (status in ('processing', 'sent', 'failed')),envelope_id text references public.envelopes(id) on delete set null,reason text,primary key (batch_id, row_number)diff --git a/src/lib/bulk-send.dbtest.ts b/src/lib/bulk-send.dbtest.tsindex b4fbc78..df70bfd 100644--- a/src/lib/bulk-send.dbtest.ts+++ b/src/lib/bulk-send.dbtest.ts@@ -10,6 +10,8 @@ import type pg from "pg";import { ZodError } from "zod";import {+ BULK_SEND_CLAIM_STALE_SECONDS,+ bulkSendBatchBusyMessage,bulkSendBatchMismatchMessage,bulkSendFromTemplate,bulkSendInvitationUnconfirmedMessage,@@ -29,6 +31,8 @@ import {createStorageService,type StorageService,} from "./services/storage.ts";+import { duplicateCopyRecipientEmailMessage } from "./schemas/signer.ts";+import { eraseSignerData } from "./signer-data.ts";import { saveEnvelopeAsTemplate, TemplateError } from "./templates.ts";// Bulk send against a real Postgres: a CSV of people becomes envelopes@@ -927,3 +931,195 @@ test("an unexpected row failure is logged and kept for the sender", async () =>console.error = originalError;}});++test("a batch another request is sending is refused at once, and a stale claim is taken over", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\n`,+ );+ const first = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.equal(first.rows[0]?.status, "sent");++ const released = await database.query<{ claimToken: string | null }>(+ `select claim_token as "claimToken" from bulk_send_batches where user_id = $1 and batch_key = $2`,+ [userId, body.batchKey],+ );++ assert.equal(released.rows[0]?.claimToken, null);++ 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, body.batchKey],+ );++ await assert.rejects(+ bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ }),+ (error: unknown) =>+ error instanceof BulkSendError &&+ error.statusCode === 409 &&+ error.message === bulkSendBatchBusyMessage,+ );++ 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, first.rows[0]?.envelopeId);+ assert.equal(await countSent(userId), 1);+});++test("two confirms of one batch at once send each row once", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\nCara,cara-${randomUUID()}@example.test\n`,+ );+ const attempts = await Promise.allSettled([+ bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ }),+ bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ }),+ ]);++ for (const attempt of attempts) {+ if (attempt.status === "rejected") {+ assert.ok(attempt.reason instanceof BulkSendError);+ assert.equal(attempt.reason.message, bulkSendBatchBusyMessage);+ }+ }++ assert.ok(attempts.some((attempt) => attempt.status === "fulfilled"));+ assert.equal(await countSent(userId), 2);+});++test("skipped rows are returned but not saved to the batch", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const body = confirmBody(+ `name,email\nAnn,ann-${randomUUID()}@example.test\nBo,not-an-email\n`,+ );+ const first = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.deepEqual(+ first.rows.map((row) => row.status),+ ["sent", "skipped"],+ );++ const stored = await database.query<{ rowNumber: number; status: string }>(+ `+ select r.row_number as "rowNumber", r.status+ from bulk_send_batches b+ join bulk_send_batch_rows r on r.batch_id = b.id+ where b.user_id = $1 and b.batch_key = $2+ `,+ [userId, body.batchKey],+ );++ assert.deepEqual(stored.rows, [+ { rowNumber: first.rows[0]!.rowNumber, status: "sent" },+ ]);++ const retry = await bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ });++ assert.deepEqual(+ retry.rows.map((row) => [row.status, row.reason]),+ first.rows.map((row) => [row.status, row.reason]),+ );+ assert.equal(await countSent(userId), 1);+});++test("a repeated copy recipient is refused before the preview", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const before = await countEnvelopes(userId);+ const copyRecipients = [+ { email: "[email protected]", name: "Copy One" },+ { email: "[email protected]", name: "Copy Two" },+ ];+ const csv = `name,email\nAnn,ann-${randomUUID()}@example.test\n`;++ for (const body of [+ { copyRecipients, csv },+ confirmBody(csv, { copyRecipients }),+ ]) {+ await assert.rejects(+ bulkSendFromTemplate(userId, template.id, body, {+ ...options(),+ sender: senderFor(userId),+ }),+ (error: unknown) =>+ error instanceof ZodError &&+ error.issues[0]?.message === duplicateCopyRecipientEmailMessage,+ );+ }++ assert.equal(await countEnvelopes(userId), before);+});++test("erasing a signer clears a saved failure reason that names them", async () => {+ const userId = await createUser();+ const template = await createOneRoleTemplate(userId);+ const email = `ann-${randomUUID()}@example.test`;+ const result = await bulkSendFromTemplate(+ userId,+ template.id,+ confirmBody(`name,email\nAnn Example,${email}\n`),+ { ...options(), sender: senderFor(userId) },+ );+ const envelopeId = result.rows[0]?.envelopeId;++ assert.ok(envelopeId);++ await database.query(+ `+ update bulk_send_batch_rows+ set status = 'failed', reason = $2+ where envelope_id = $1+ `,+ [envelopeId, `Ann Example (${email}) needs an account on this site.`],+ );++ await eraseSignerData(email, email, database);++ const stored = await database.query<{ reason: string | null }>(+ `select reason from bulk_send_batch_rows where envelope_id = $1`,+ [envelopeId],+ );++ assert.equal(stored.rowCount, 1);+ assert.equal(stored.rows[0]?.reason, null);+});diff --git a/src/lib/bulk-send.ts b/src/lib/bulk-send.tsindex 8e1e2db..fff9964 100644--- a/src/lib/bulk-send.ts+++ b/src/lib/bulk-send.ts@@ -55,6 +55,9 @@ export const missingBulkSendBatchKeyMessage =export const bulkSendBatchMismatchMessage ="This batch key was used with a different list.";+export const bulkSendBatchBusyMessage =+ "This batch is still sending. Wait a moment, then confirm again to see its results.";+export const bulkSendInvitationUnconfirmedMessage ="This envelope was marked sent but the invitation was not recorded. Check your documents before sending this row again.";@@ -82,6 +85,7 @@ type BulkSendOptions = {};type StoredBatch = {+ claimToken: string;id: string;requestFingerprint: string;rows: Map<number, StoredBatchRow>;@@ -90,7 +94,7 @@ type StoredBatch = {type StoredBatchRow = {envelopeId: string | null;reason: string | null;- status: "failed" | "processing" | "sent" | "skipped";+ status: "failed" | "processing" | "sent";};type SendRowContext = {@@ -108,7 +112,14 @@ type SendRowContext = {userId: string;};-const TERMINAL_ROW_STATUSES = new Set(["failed", "sent", "skipped"]);+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.+ */+export const BULK_SEND_CLAIM_STALE_SECONDS = 5 * 60;function describeSendFailure(error: unknown): string {if (error instanceof ZodError) {@@ -231,53 +242,10 @@ function failedRow(};}-async function withBatchLock<T>(- pool: DbPool,- lockKey: string,- run: () => Promise<T>,-): Promise<T> {- const client = await pool.connect();-- try {- await client.query("SELECT pg_advisory_lock(hashtextextended($1, 19))", [- lockKey,- ]);-- try {- return await run();- } finally {- await client.query(- "SELECT pg_advisory_unlock(hashtextextended($1, 19))",- [lockKey],- );- }- } finally {- client.release();- }-}--async function loadBatch(- userId: string,- batchKey: string,+async function loadBatchRows(+ batchId: string,database: DbExecutor,-): Promise<StoredBatch | null> {- const batch = await queryOne<{- id: string;- requestFingerprint: string;- }>(- database,- `- SELECT id, request_fingerprint AS "requestFingerprint"- FROM bulk_send_batches- WHERE user_id = $1 AND batch_key = $2- `,- [userId, batchKey],- );-- if (!batch) {- return null;- }-+): Promise<Map<number, StoredBatchRow>> {const rows = await queryMany<{envelopeId: string | null;reason: string | null;@@ -294,98 +262,129 @@ async function loadBatch(FROM bulk_send_batch_rowsWHERE batch_id = $1`,- [batch.id],+ [batchId],);- return {- id: batch.id,- requestFingerprint: batch.requestFingerprint,- rows: new Map(- rows.map((row) => [- row.rowNumber,- {- envelopeId: row.envelopeId,- reason: row.reason,- status: row.status,- },- ]),- ),- };+ return new Map(+ rows.map((row) => [+ row.rowNumber,+ {+ envelopeId: row.envelopeId,+ reason: row.reason,+ status: row.status,+ },+ ]),+ );}-async function insertBatch(+/**+ * Creates the batch or takes it over, and claims it for this request. The+ * claim is a saved token, not a session lock, so it holds through pooled+ * connections and no connection waits on it. A batch another request is+ * still sending is refused at once; the sender can confirm again later and+ * get the stored results.+ */+async function claimBatch(userId: string,templateId: string,batchKey: string,requestFingerprint: string,database: DbExecutor,): Promise<StoredBatch> {- const id = randomUUID();-- await database.query(+ const claimToken = randomUUID();+ const claimed = await queryOne<{ id: string }>(+ database,`INSERT INTO bulk_send_batches (id,user_id,template_id,batch_key,- request_fingerprint+ request_fingerprint,+ claim_token,+ claimed_at)- VALUES ($1, $2, $3, $4, $5)+ VALUES ($1, $2, $3, $4, $5, $6, extract(epoch from now())::bigint)+ ON CONFLICT (user_id, batch_key) DO UPDATE SET+ claim_token = EXCLUDED.claim_token,+ claimed_at = EXCLUDED.claimed_at+ WHERE bulk_send_batches.request_fingerprint = EXCLUDED.request_fingerprint+ AND (+ bulk_send_batches.claim_token IS NULL+ OR bulk_send_batches.claimed_at < EXCLUDED.claimed_at - $7+ )+ RETURNING id`,- [id, userId, templateId, batchKey, requestFingerprint],+ [+ randomUUID(),+ userId,+ templateId,+ batchKey,+ requestFingerprint,+ claimToken,+ BULK_SEND_CLAIM_STALE_SECONDS,+ ],);- return { id, requestFingerprint, rows: new Map() };-}--async function ensureBatch(- userId: string,- templateId: string,- batchKey: string,- requestFingerprint: string,- database: DbExecutor,-): Promise<StoredBatch> {- const existing = await loadBatch(userId, batchKey, database);+ if (!claimed) {+ const existing = await queryOne<{ requestFingerprint: string }>(+ database,+ `+ SELECT request_fingerprint AS "requestFingerprint"+ FROM bulk_send_batches+ WHERE user_id = $1 AND batch_key = $2+ `,+ [userId, batchKey],+ );- if (existing) {- if (existing.requestFingerprint !== requestFingerprint) {+ if (existing && existing.requestFingerprint !== requestFingerprint) {throw new BulkSendError(bulkSendBatchMismatchMessage, 409);}- return existing;+ throw new BulkSendError(bulkSendBatchBusyMessage, 409);}- try {- return await insertBatch(- userId,- templateId,- batchKey,- requestFingerprint,- database,- );- } catch (error) {- if (- typeof error === "object" &&- error !== null &&- "code" in error &&- error.code === "23505"- ) {- const raced = await loadBatch(userId, batchKey, database);-- if (raced) {- if (raced.requestFingerprint !== requestFingerprint) {- throw new BulkSendError(bulkSendBatchMismatchMessage, 409);- }+ return {+ claimToken,+ id: claimed.id,+ requestFingerprint,+ rows: await loadBatchRows(claimed.id, database),+ };+}- return raced;- }- }+/** Keeps this request's claim fresh, or stops if another request took it. */+async function refreshBatchClaim(+ batch: StoredBatch,+ database: DbExecutor,+): Promise<void> {+ const refreshed = await database.query(+ `+ UPDATE bulk_send_batches+ SET claimed_at = extract(epoch from now())::bigint+ WHERE id = $1 AND claim_token = $2+ `,+ [batch.id, batch.claimToken],+ );- throw error;+ if (refreshed.rowCount === 0) {+ throw new BulkSendError(bulkSendBatchBusyMessage, 409);}}+async function releaseBatchClaim(+ batch: StoredBatch,+ database: DbExecutor,+): Promise<void> {+ await database.query(+ `+ UPDATE bulk_send_batches+ SET claim_token = NULL, claimed_at = NULL+ WHERE id = $1 AND claim_token = $2+ `,+ [batch.id, batch.claimToken],+ );+}+async function saveBatchRow(batchId: string,row: BulkSendRowResult,@@ -440,16 +439,6 @@ function restoreStoredRow(return sentRow(row, stored.envelopeId);}- if (stored.status === "skipped") {- return {- ...row,- envelopeId: null,- envelopePath: null,- reason: stored.reason,- status: "skipped",- };- }-return {...row,envelopeId: stored.envelopeId,@@ -678,14 +667,15 @@ export async function bulkSendFromTemplate(const signatureMeaning = parsedInput.signatureMeaning ?? null;const fingerprint = fingerprintBulkSendRequest(template.id, parsedInput);- return withBatchLock(database, `${userId}:${batchKey}`, async () => {- const batch = await ensureBatch(- userId,- template.id,- batchKey,- fingerprint,- database,- );+ const batch = await claimBatch(+ userId,+ template.id,+ batchKey,+ fingerprint,+ database,+ );++ try {const sent: BulkSendRowResult[] = [];for (const row of rows) {@@ -696,12 +686,17 @@ export async function bulkSendFromTemplate(continue;}+ // A skipped row is worked out again from the same list on a retry,+ // so it is not saved. That keeps a long list past the cap from+ // costing a write per row, and keeps the reasons, which can name the+ // person, out of the batch table.if (row.status !== "ok") {- await saveBatchRow(batch.id, row, "skipped", database);sent.push(row);continue;}+ await refreshBatchClaim(batch, database);+const progress = { envelopeId: stored?.envelopeId ?? null };try {@@ -745,5 +740,7 @@ export async function bulkSendFromTemplate(}return resultFor(sent);- });+ } finally {+ await releaseBatchClaim(batch, database);+ }}diff --git a/src/lib/schemas/bulk-send.ts b/src/lib/schemas/bulk-send.tsindex 46ad6ee..1405c8b 100644--- a/src/lib/schemas/bulk-send.ts+++ b/src/lib/schemas/bulk-send.ts@@ -6,6 +6,7 @@ import {} from "../types/domain.ts";import { emailSchema, nameSchema } from "./common.ts";import { deadlineDaysSchema, reminderIntervalDaysSchema } from "./envelope.ts";+import { duplicateCopyRecipientEmailMessage } from "./signer.ts";/** Enough for 200 rows with names, addresses and a title. */export const MAX_BULK_SEND_CSV_CHARS = 512 * 1024;@@ -21,6 +22,25 @@ export const bulkSendRequestSchema = z.object({copyRecipients: z.array(z.object({ email: emailSchema, name: nameSchema })).max(MAX_COPY_RECIPIENTS_PER_ENVELOPE)+ // Every envelope gets the same copy list, so a repeated address would+ // fail on every row once its draft exists. Refuse it before the preview.+ .superRefine((recipients, ctx) => {+ const emails = new Set<string>();++ for (const [index, recipient] of recipients.entries()) {+ const email = recipient.email.toLowerCase();++ if (emails.has(email)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: duplicateCopyRecipientEmailMessage,+ path: [index, "email"],+ });+ }++ emails.add(email);+ }+ }).optional(),csv: z.string().min(1).max(MAX_BULK_SEND_CSV_CHARS),expiresInDays: deadlineDaysSchema.optional(),diff --git a/src/lib/signer-data.ts b/src/lib/signer-data.tsindex 9501a91..34b41f4 100644--- a/src/lib/signer-data.ts+++ b/src/lib/signer-data.ts@@ -235,6 +235,19 @@ export async function eraseSignerData((row) => !erasedFromDrafts.stillDrafts.has(row.envelopeId),);+ // A send-to-many batch keeps why a row failed, and that reason can name+ // the signer (a Part 11 account problem does). Clear it for every+ // envelope they are on, before finished ones are deleted and the row+ // loses its link to them.+ await database.query(+ `+ UPDATE bulk_send_batch_rows+ SET reason = NULL+ WHERE reason IS NOT NULL AND envelope_id = ANY($1::text[])+ `,+ [[...new Set(envelopes.map((row) => row.envelopeId))]],+ );+const deletedEnvelopes = await deleteEnvelopesAndFiles([...new Set(finished.map((row) => row.envelopeId))],database,