Skip to content

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

TypeScript

Hold the envelope.sent webhook until the invitation is out, and drop it if the send is undone

Claude5d2d36fc0a96
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index e7d1a0d..c283d9e 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -124,6 +124,7 @@ import {
import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";
import { hashAccessCode } from "./signer-checks.ts";
import { escapeHtml } from "./utils/html.ts";
+import { requestWebhookDrain } from "./webhooks/outbox.ts";
type CreateDraftEnvelopeOptions = {
database?: DbPool;
@@ -2700,6 +2701,16 @@ export async function sendDraftEnvelope(
`,
[envelopeId, sentAuditAt, input.senderEmail],
);
+ // The envelope.sent webhook was waiting for the invitation to go out
+ // (see below); it did not, so there is nothing to tell.
+ await tx.query(
+ `
+ DELETE FROM webhook_deliveries
+ WHERE envelope_id = $1 AND event_type = 'envelope.sent'
+ AND status = 'pending' AND attempts = 0
+ `,
+ [envelopeId],
+ );
}, database).catch((rollbackError) => {
console.error(
`Failed to roll back sent envelope ${envelopeId} after email delivery failure:`,
@@ -2720,6 +2731,8 @@ export async function sendDraftEnvelope(
},
database,
);
+ // Only now that the invitation is out is the envelope really sent.
+ requestWebhookDrain();
return sendEnvelopeResponseSchema.parse({
envelopeId,
diff --git a/src/lib/webhooks/deliver.ts b/src/lib/webhooks/deliver.ts
index cb8e75c..2843e7c 100644
--- a/src/lib/webhooks/deliver.ts
+++ b/src/lib/webhooks/deliver.ts
@@ -58,6 +58,7 @@ export type WebhookPayload = {
type ClaimedDelivery = {
attempts: number;
+ auditEventId: string | null;
auditCreatedAt: number | null;
auditMetadata: Record<string, unknown> | null;
createdAt: number;
@@ -164,6 +165,7 @@ async function claimDueDeliveries(
c.id,
c.event_type AS "eventType",
c.envelope_id AS "envelopeId",
+ c.audit_event_id AS "auditEventId",
c.signer_id AS "signerId",
c.payload,
c.attempts,
@@ -256,6 +258,21 @@ async function sendOne(
): Promise<"delivered" | "failed" | "dropped"> {
let body = delivery.payload;
+ // Its event was taken back (a send whose invitation could not go out).
+ if (
+ body === null &&
+ delivery.auditEventId &&
+ delivery.auditCreatedAt === null
+ ) {
+ await recordOutcome(
+ database,
+ delivery,
+ { kind: "dropped", reason: "The change it reported was undone." },
+ nowInSeconds(),
+ );
+ return "dropped";
+ }
+
if (body === null) {
const payload = await buildWebhookPayload(delivery, database);
diff --git a/src/lib/webhooks/outbox.ts b/src/lib/webhooks/outbox.ts
index bc4d900..1d61812 100644
--- a/src/lib/webhooks/outbox.ts
+++ b/src/lib/webhooks/outbox.ts
@@ -23,6 +23,11 @@ export function setWebhookDrainScheduler(scheduler: DrainScheduler | null) {
drainScheduler = scheduler ?? scheduleWebhookDrain;
}
+/** Starts sending what is due, after the response. */
+export function requestWebhookDrain() {
+ drainScheduler();
+}
+
export async function enqueueWebhookDeliveries(
input: {
auditEventId: string;
@@ -67,7 +72,10 @@ export async function enqueueWebhookDeliveries(
);
const queued = result.rowCount ?? 0;
- if (queued > 0) {
+ // A send is not finished until the invitation email has gone out, and
+ // is undone (with its delivery) if it cannot. sendDraftEnvelope starts
+ // sending once the email is out.
+ if (queued > 0 && input.event !== "sent") {
afterCommit(database, () => {
drainScheduler();
});
diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.ts
index 149dc0e..f4df16d 100644
--- a/src/lib/webhooks/webhooks.dbtest.ts
+++ b/src/lib/webhooks/webhooks.dbtest.ts
@@ -465,6 +465,43 @@ test("two drains at once never send the same delivery twice", async () => {
);
});
+test("a send whose invitation email fails leaves no envelope.sent webhook", async () => {
+ const admin = await createAdmin();
+ const { endpoint } = await addEndpoint(admin);
+ const outbox = process.env.EMAIL_CAPTURE_DIR;
+ const { writeFile } = await import("node:fs/promises");
+ const blocker = path.join(workDir, "not-a-directory");
+
+ // Capturing the email fails: its folder is a file.
+ await writeFile(blocker, "");
+ process.env.EMAIL_CAPTURE_DIR = path.join(blocker, "outbox");
+
+ try {
+ await assert.rejects(createEnvelope(admin));
+ } finally {
+ process.env.EMAIL_CAPTURE_DIR = outbox;
+ }
+
+ assert.equal((await deliveriesFor(endpoint.id)).length, 0);
+ await drainWebhookDeliveries({ database, env });
+ assert.equal(received.length, 0);
+});
+
+test("a delivery whose audit event was taken back is dropped", async () => {
+ const admin = await createAdmin();
+ const { endpoint } = await addEndpoint(admin, ["envelope.voided"]);
+ const envelope = await createEnvelope(admin);
+ const event = await recordAuditEvent(
+ { actorType: "sender", envelopeId: envelope.id, event: "voided" },
+ database,
+ );
+
+ await database.query(`delete from audit_events where id = $1`, [event.id]);
+ assert.equal((await drainWebhookDeliveries({ database, env })).dropped, 1);
+ assert.equal(received.length, 0);
+ assert.equal((await deliveriesFor(endpoint.id))[0]!.status, "failed");
+});
+
test("a delivery for an envelope deleted before its first try is dropped", async () => {
const admin = await createAdmin();
const { endpoint } = await addEndpoint(admin);