Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Turn away a setup submission that arrives while another is running
Claude8d3771f5fa95
diff --git a/src/lib/setup.dbtest.ts b/src/lib/setup.dbtest.tsindex a53d878..25fa831 100644--- a/src/lib/setup.dbtest.ts+++ b/src/lib/setup.dbtest.ts@@ -13,7 +13,7 @@ import {readStoredSettings,saveSettings,} from "./settings.ts";-import { completeSetup } from "./setup.ts";+import { completeSetup, SetupError } from "./setup.ts";// First-run setup and the sign-up rule against a real Postgres, where the// order in which things become visible to other connections is the point.@@ -144,6 +144,46 @@ test("a setup that fails halfway leaves sign-up closed, not open", async () => {assert.deepEqual(afterTheAccount, [{ status: "unclaimed" }, "closed", false]);});+test(+ "submissions that arrive together get one winner, and the rest are turned away at once",+ { timeout: 20_000 },+ async () => {+ // As many at once as the pool has connections. If the losers waited+ // for the winner, each would hold a connection while it did, and the+ // winner would have none left to create the account with.+ const submissions = Array.from({ length: 12 }, (_, index) =>+ completeSetup(+ { ...setupInput, email: `owner${index}@acme.com` },+ {+ createAdminAccount: async ({ email }) => ({+ userId: await insertUser(email),+ }),+ database,+ env,+ },+ ),+ );+ const outcomes = await Promise.allSettled(submissions);+ const winners = outcomes.filter(+ (outcome) => outcome.status === "fulfilled",+ );+ const refusals = outcomes.flatMap((outcome) =>+ outcome.status === "rejected" ? [outcome.reason as unknown] : [],+ );++ assert.equal(winners.length, 1);+ assert.equal(refusals.length, 11);++ for (const refusal of refusals) {+ assert.ok(refusal instanceof SetupError);+ assert.equal(refusal.statusCode, 409);+ }++ assert.equal(await countUsers(), 1);+ assert.deepEqual(await readSetupState(database), { status: "complete" });+ },+);+test("an install from before settings existed stays open until it is claimed", async () => {await insertUser("[email protected]");diff --git a/src/lib/setup.ts b/src/lib/setup.tsindex d2fdba3..10f35a9 100644--- a/src/lib/setup.ts+++ b/src/lib/setup.ts@@ -245,9 +245,21 @@ export async function completeSetup(try {const result = await withTransaction(async (tx) => {- await tx.query("select pg_advisory_xact_lock($1)", [- SETUP_ADVISORY_LOCK_ID,- ]);+ // Taken without waiting. A submission that waited would sit on a+ // database connection for as long as the one ahead of it runs, and+ // that one needs a second connection to create the account. Enough+ // of them waiting would leave it none.+ const lock = await tx.query<{ locked: boolean }>(+ "select pg_try_advisory_xact_lock($1) as locked",+ [SETUP_ADVISORY_LOCK_ID],+ );++ if (lock.rows[0]?.locked !== true) {+ throw new SetupError(+ "Setup is already running. Try again in a moment.",+ 409,+ );+ }const state = await readSetupState(tx);