Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Skip a webhook endpoint being removed instead of failing the change
Claude47a4267ce1f1
diff --git a/src/lib/api-keys.dbtest.ts b/src/lib/api-keys.dbtest.tsindex 2af693e..7269b54 100644--- a/src/lib/api-keys.dbtest.ts+++ b/src/lib/api-keys.dbtest.ts@@ -13,7 +13,7 @@ import {MAX_API_KEYS_PER_USER,revokeApiKey,} from "./api-keys.ts";-import { openTestDatabase } from "./db/test-database.ts";+import { openTestDatabase, waitUntilBlockedBy } from "./db/test-database.ts";import { setPersonRole } from "./people.ts";import { SYSTEM_AUDIT_LOCK_ID } from "./services/system-audit.ts";@@ -245,34 +245,6 @@ test("every key that is not revoked stays in the list, however many are revoked);});-/** Resolves once another session is waiting on a lock that `holder` has. */-async function waitUntilBlockedBy(holder: pg.PoolClient) {- const self = await holder.query<{ pid: number }>(- "select pg_backend_pid() as pid",- );- const holderPid = self.rows[0]?.pid;-- for (let attempt = 0; attempt < 500; attempt += 1) {- const waiting = await database.query(- `- select 1- from pg_stat_activity- where $1::integer = any(pg_blocking_pids(pid))- limit 1- `,- [holderPid],- );-- if (waiting.rowCount) {- return;- }-- await new Promise((resolve) => setTimeout(resolve, 10));- }-- throw new Error("Nothing started waiting on the held key row.");-}-test("removing an administrator takes the key rows before the audit lock, as revoking a key does", async () => {// revokeApiKey locks a key row and then the audit chain. Hold a key row// the way it does, and the role change must wait for it without already@@ -299,7 +271,7 @@ test("removing an administrator takes the key rows before the audit lock, as revdatabase,);- await waitUntilBlockedBy(holder);+ await waitUntilBlockedBy(database, holder);const free = await holder.query<{ locked: boolean }>(`select pg_try_advisory_xact_lock($1) as locked`,diff --git a/src/lib/db/test-database.ts b/src/lib/db/test-database.tsindex 15d65af..e7a5f46 100644--- a/src/lib/db/test-database.ts+++ b/src/lib/db/test-database.ts@@ -60,6 +60,41 @@ export async function openTestDatabase(): Promise<pg.Pool> {return new pg.Pool({ connectionString, max: 12 });}+/**+ * Resolves once another session is waiting on a lock that `holder` has,+ * so a test can check what that session holds while it waits. Fails if+ * none does within about five seconds.+ */+export async function waitUntilBlockedBy(+ database: pg.Pool,+ holder: pg.PoolClient,+): Promise<void> {+ const self = await holder.query<{ pid: number }>(+ "select pg_backend_pid() as pid",+ );+ const holderPid = self.rows[0]?.pid;++ for (let attempt = 0; attempt < 500; attempt += 1) {+ const waiting = await database.query(+ `+ select 1+ from pg_stat_activity+ where $1::integer = any(pg_blocking_pids(pid))+ limit 1+ `,+ [holderPid],+ );++ if (waiting.rowCount) {+ return;+ }++ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ throw new Error("Nothing started waiting on the held lock.");+}+type QueryFunction = (text: unknown, values?: unknown[]) => unknown;/**diff --git a/src/lib/webhooks/outbox.ts b/src/lib/webhooks/outbox.tsindex 33f7367..0efc63c 100644--- a/src/lib/webhooks/outbox.ts+++ b/src/lib/webhooks/outbox.ts@@ -98,6 +98,11 @@ export async function enqueueWebhookDeliveries(id, $1, $2, $3, $4, 'pending', 0, $5, $6, $6FROM webhook_endpointsWHERE enabled AND $1 = ANY(events)+ -- An endpoint being removed at this moment is waited for and then+ -- skipped, instead of failing this envelope's change on the foreign+ -- key once the removal commits. The lock also keeps a matching+ -- endpoint until this transaction ends.+ FOR KEY SHARE`,[type,diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.tsindex 028e637..3bab85c 100644--- a/src/lib/webhooks/webhooks.dbtest.ts+++ b/src/lib/webhooks/webhooks.dbtest.ts@@ -17,7 +17,7 @@ import {type ApiActor,} from "../api/envelopes.ts";import { withTransaction } from "../db/connection.ts";-import { openTestDatabase } from "../db/test-database.ts";+import { openTestDatabase, waitUntilBlockedBy } from "../db/test-database.ts";import { recordAuditEvent } from "../services/audit.ts";import { issueSigningLink } from "../services/signing-links.ts";import { getSigningPayloadForToken } from "../signing.ts";@@ -352,6 +352,49 @@ test("a delivery is written with its audit event, and not when that rolls back",assert.equal((await deliveriesFor(endpoint.id)).length, 1);});+test("an endpoint removed while an event is recorded is skipped, and the change still goes through", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin, ["envelope.voided"]);+ const envelope = await createEnvelope(admin);+ const remover = await database.connect();++ try {+ // An administrator removes the endpoint, not yet committed, just as+ // the envelope changes (here a void, as a signature would be).+ await remover.query("begin");+ await remover.query(`delete from webhook_endpoints where id = $1`, [+ endpoint.id,+ ]);++ const recorded = recordAuditEvent(+ {+ actorType: "sender",+ envelopeId: envelope.id,+ event: "voided",+ metadata: { reason: "Wrong client" },+ },+ database,+ );++ await waitUntilBlockedBy(database, remover);+ await remover.query("commit");++ // The change goes through; before, it failed on the foreign key.+ await recorded;+ } finally {+ remover.release();+ }++ assert.equal((await deliveriesFor(endpoint.id)).length, 0);++ const voided = await database.query(+ `select 1 from audit_events where envelope_id = $1 and event = 'voided'`,+ [envelope.id],+ );++ assert.equal(voided.rowCount, 1);+});+test("a delivery is signed, carries the envelope, and is marked delivered", async () => {const admin = await createAdmin();const { endpoint, secret } = await addEndpoint(admin);