Skip to content

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

TypeScript

Lock the envelope row no harder than an update does

Claudee0576bd99902
diff --git a/src/lib/automatic-reminders.dbtest.ts b/src/lib/automatic-reminders.dbtest.ts
index 79b842f..c1a4455 100644
--- a/src/lib/automatic-reminders.dbtest.ts
+++ b/src/lib/automatic-reminders.dbtest.ts
@@ -4,13 +4,17 @@ import { after, before, test } from "node:test";
import type pg from "pg";
-import { openTestDatabase } from "./db/test-database.ts";
+import {
+ openTestDatabase,
+ recordAuditEventWhileWaitedOn,
+} from "./db/test-database.ts";
import { runEnvelopeSchedule } from "./envelope-schedule.ts";
import {
changeEnvelopeDeadline,
changeEnvelopeReminders,
EnvelopeMutationError,
} from "./envelopes.ts";
+import { sendAutomaticEnvelopeReminder } from "./reminders.ts";
import { verifyAuditChain } from "./services/audit.ts";
import type {
EmailService,
@@ -292,6 +296,39 @@ test("a deadline moved while a reminder's email fails stays moved", async () =>
assert.equal(signer.signing_token_expires_at, newDeadline);
});
+test("a reminder and a signer opening the page do not lock each other out", async () => {
+ const due = await createSentEnvelope({ reminderIntervalDays: 1 });
+ const { sent, service } = recordingEmailService();
+
+ const reminded = await recordAuditEventWhileWaitedOn(
+ database,
+ {
+ actorType: "signer",
+ envelopeId: due.envelopeId,
+ event: "viewed",
+ metadata: { signerId: due.signerId },
+ },
+ () =>
+ sendAutomaticEnvelopeReminder(due.envelopeId, {
+ database,
+ emailService: service,
+ nowUnixTimestamp: SENT_AT + DAY,
+ }),
+ );
+
+ assert.equal(reminded, true);
+ assert.equal(
+ sent.filter((message) => message.to.startsWith(due.signerId)).length,
+ 1,
+ );
+ assert.deepEqual(await auditEvents(due.envelopeId), [
+ "viewed",
+ "reminded_auto",
+ "email_sent",
+ ]);
+ assert.equal((await verifyAuditChain(due.envelopeId, database)).ok, true);
+});
+
test("a run that is out of time leaves the rest for the next one", async () => {
const due = await createSentEnvelope({ reminderIntervalDays: 1 });
const { sent, service } = recordingEmailService();
diff --git a/src/lib/db/test-database.ts b/src/lib/db/test-database.ts
index 9df8a15..66afff1 100644
--- a/src/lib/db/test-database.ts
+++ b/src/lib/db/test-database.ts
@@ -1,6 +1,11 @@
import pg from "pg";
import { runMigrations } from "../../../db/migrate.mjs";
+import {
+ lockEnvelopeAuditChain,
+ recordAuditEvent,
+ type RecordAuditEventInput,
+} from "../services/audit.ts";
// For the tests that need a real Postgres (npm run test:db). They use the
// same disposable database as the end-to-end test and bring its schema up
@@ -54,3 +59,59 @@ export async function openTestDatabase(): Promise<pg.Pool> {
return new pg.Pool({ connectionString, max: 12 });
}
+
+/**
+ * Records an audit event the way a signer opening the signing page does,
+ * timed against something else that writes to the same envelope: the
+ * event's transaction takes the envelope's audit chain, `start()` gets
+ * under way until it has to wait for that chain, and only then is the event
+ * stored.
+ *
+ * Storing it checks the event's foreign key, which needs a share of the
+ * envelope's row. So if `start()` holds that row too tightly while it
+ * waits, each waits for the other, Postgres cancels one of them, and this
+ * rejects.
+ */
+export async function recordAuditEventWhileWaitedOn<T>(
+ database: pg.Pool,
+ event: RecordAuditEventInput,
+ start: () => Promise<T>,
+): Promise<T> {
+ const client = await database.connect();
+
+ try {
+ await client.query("begin");
+ await lockEnvelopeAuditChain(event.envelopeId, client);
+
+ const started = start();
+
+ // Looked at below. Until then a rejection must not go unhandled.
+ started.catch(() => undefined);
+
+ for (let attempt = 0; ; attempt += 1) {
+ const waiting = await database.query(
+ `select 1 from pg_locks where locktype = 'advisory' and not granted limit 1`,
+ );
+
+ if (waiting.rowCount) {
+ break;
+ }
+
+ if (attempt === 500) {
+ throw new Error("Nothing came to wait for the audit chain.");
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+
+ await recordAuditEvent(event, client);
+ await client.query("commit");
+
+ return await started;
+ } catch (error) {
+ await client.query("rollback").catch(() => undefined);
+ throw error;
+ } finally {
+ client.release();
+ }
+}
diff --git a/src/lib/envelope-deadline.dbtest.ts b/src/lib/envelope-deadline.dbtest.ts
index 95690a7..3f9b7ca 100644
--- a/src/lib/envelope-deadline.dbtest.ts
+++ b/src/lib/envelope-deadline.dbtest.ts
@@ -4,7 +4,10 @@ import { after, before, test } from "node:test";
import type pg from "pg";
-import { openTestDatabase } from "./db/test-database.ts";
+import {
+ openTestDatabase,
+ recordAuditEventWhileWaitedOn,
+} from "./db/test-database.ts";
import { formatDeadline } from "./envelope-deadline.ts";
import { runEnvelopeSchedule } from "./envelope-schedule.ts";
import { changeEnvelopeDeadline, EnvelopeMutationError } from "./envelopes.ts";
@@ -445,6 +448,36 @@ test("a deadline moved during the run is not told or noted as passed", async ()
}
});
+test("a change of deadline and a signer opening the page do not lock each other out", async () => {
+ const { envelopeId, signerId, userId } = await createSentEnvelope({
+ expiresAt: unixNow() + DAY,
+ });
+
+ const changed = await recordAuditEventWhileWaitedOn(
+ database,
+ {
+ actorType: "signer",
+ envelopeId,
+ event: "viewed",
+ metadata: { signerId },
+ },
+ () =>
+ changeEnvelopeDeadline(
+ userId,
+ envelopeId,
+ { expiresInDays: 7, senderEmail: "[email protected]" },
+ { database },
+ ),
+ );
+
+ assert.equal((await readEnvelope(envelopeId)).expires_at, changed.expiresAt);
+ assert.deepEqual(await auditEvents(envelopeId), [
+ "viewed",
+ "deadline_changed",
+ ]);
+ assert.equal((await verifyAuditChain(envelopeId, database)).ok, true);
+});
+
test("a deadline moved while a signer submits reaches the next signer", async () => {
const now = unixNow();
const { envelopeId, signerId, token, userId } = await createSentEnvelope({
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 6e02bd1..f3dc686 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -2055,7 +2055,10 @@ export async function changeEnvelopeDeadline(
SELECT expires_at AS "expiresAt", status
FROM envelopes
WHERE id = $1 AND user_id = $2
- FOR UPDATE
+ -- The lock an UPDATE takes, not FOR UPDATE: storing an audit event
+ -- needs a share of this row for its foreign key, and FOR UPDATE
+ -- would deadlock with a signer opening the signing page.
+ FOR NO KEY UPDATE
`,
[envelopeId, userId],
);
diff --git a/src/lib/reminders.ts b/src/lib/reminders.ts
index dc521ca..6a911b0 100644
--- a/src/lib/reminders.ts
+++ b/src/lib/reminders.ts
@@ -135,6 +135,12 @@ export class ReminderMutationError extends Error {
* The envelope, and only for its owner when a user is given. With a lock,
* inside a transaction, the envelope's row is held until the transaction
* ends, so its deadline cannot be moved in between.
+ *
+ * The lock is the one an UPDATE takes (NO KEY UPDATE), not the stronger
+ * FOR UPDATE. Storing an audit event checks its foreign key, which needs a
+ * share of this row while it holds the envelope's audit chain. FOR UPDATE
+ * would refuse that share, and a reminder waiting for the chain would then
+ * deadlock with a signer opening the signing page.
*/
async function getReminderEnvelope(
envelopeId: string,
@@ -159,7 +165,7 @@ async function getReminderEnvelope(
JOIN "user" u ON u.id = e.user_id
WHERE e.id = $1
AND ($2::text IS NULL OR e.user_id = $2)
- ${lock ? "FOR UPDATE OF e" : ""}
+ ${lock ? "FOR NO KEY UPDATE OF e" : ""}
`,
[envelopeId, userId],
);