Skip to content

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

TypeScript

Record a signer's first view once, even when it is opened twice at once

Claude5d9e94ae094a
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 5a28d43..7f5f681 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -813,6 +813,13 @@ async function recordViewedEventOnce(
database: DbPool,
): Promise<void> {
await withTransaction(async (tx) => {
+ // Two first openings at once must not both pass the check below and
+ // record two first views (and send two signer.viewed webhooks). This
+ // lock is taken only here, before any other, so it cannot deadlock.
+ await tx.query(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
+ `signudoc:first-view:${context.signer.id ?? ""}`,
+ ]);
+
const existing = await queryOne<{ id: string }>(
tx,
`
diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.ts
index 00ae185..ab3e1ba 100644
--- a/src/lib/webhooks/webhooks.dbtest.ts
+++ b/src/lib/webhooks/webhooks.dbtest.ts
@@ -19,6 +19,8 @@ import {
import { withTransaction } from "../db/connection.ts";
import { openTestDatabase } from "../db/test-database.ts";
import { recordAuditEvent } from "../services/audit.ts";
+import { issueSigningLink } from "../services/signing-links.ts";
+import { getSigningPayloadForToken } from "../signing.ts";
import {
drainWebhookDeliveries,
MAX_ATTEMPTS,
@@ -751,3 +753,35 @@ test("a retry is dropped once its envelope is deleted, even after a first try",
assert.equal((await drainWebhookDeliveries({ database, env })).dropped, 1);
assert.equal(received.length, 1);
});
+
+test("two first openings at once record one view and queue one signer.viewed", async () => {
+ const actor = await createAdmin();
+ const endpoint = await addEndpoint(actor, ["signer.viewed"]);
+ const envelope = await createEnvelope(actor);
+ const signerId = envelope.signers[0]!.id;
+ const link = await issueSigningLink({ expiresInSeconds: 3600 }, { env });
+
+ await database.query(
+ `
+ update signers set signing_token_hash = $2, signing_token_expires_at = $3
+ where id = $1
+ `,
+ [signerId, link.tokenHash, link.exp],
+ );
+ await Promise.all(
+ Array.from({ length: 4 }, () =>
+ getSigningPayloadForToken(link.token, { database }),
+ ),
+ );
+
+ const views = await database.query<{ count: number }>(
+ `
+ select count(*)::int as count from audit_events
+ where envelope_id = $1 and event = 'viewed'
+ `,
+ [envelope.id],
+ );
+
+ assert.equal(views.rows[0]?.count, 1);
+ assert.equal((await deliveriesFor(endpoint.endpoint.id)).length, 1);
+});