Skip to content

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

TypeScript

Keep a save's settings from being cached over by the old row

Matthew Jacksonc8cbe4047e6d
diff --git a/src/lib/settings.dbtest.ts b/src/lib/settings.dbtest.ts
new file mode 100644
index 0000000..d36b8d5
--- /dev/null
+++ b/src/lib/settings.dbtest.ts
@@ -0,0 +1,56 @@
+import assert from "node:assert/strict";
+import { after, before, beforeEach, test } from "node:test";
+
+import type pg from "pg";
+
+import { replaceDbPoolForTests, withTransaction } from "./db/connection.ts";
+import { openTestDatabase } from "./db/test-database.ts";
+import {
+ getSettings,
+ invalidateSettingsCache,
+ saveSettings,
+} from "./settings.ts";
+
+// The settings cache against a real Postgres: a save made inside a
+// transaction has to show on this instance as soon as it commits, even when
+// another request read the settings while the transaction was still open.
+// Run with `npm run test:db`.
+
+let database: pg.Pool;
+let replaced: pg.Pool | null = null;
+
+before(async () => {
+ database = await openTestDatabase();
+ replaced = replaceDbPoolForTests(database);
+});
+
+beforeEach(async () => {
+ await database.query("delete from public.app_settings");
+ invalidateSettingsCache();
+});
+
+after(async () => {
+ await database.query("delete from public.app_settings");
+ invalidateSettingsCache();
+
+ if (replaced) {
+ replaceDbPoolForTests(replaced);
+ }
+
+ await database.end();
+});
+
+test("a read during an open save does not keep the old settings after commit", async () => {
+ await saveSettings({ requireTwoFactor: false, signupMode: "open" });
+ invalidateSettingsCache();
+
+ await withTransaction(async (tx) => {
+ await saveSettings({ requireTwoFactor: true }, tx);
+
+ // Another request renders a page while the save is still open: it
+ // sees the committed (old) row.
+ assert.equal((await getSettings()).requireTwoFactor, false);
+ }, database);
+
+ assert.equal((await getSettings()).requireTwoFactor, true);
+});
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 5a03a25..60d856a 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -1,5 +1,6 @@
import { buildBranding, type Branding } from "./branding.ts";
import {
+ afterCommit,
type DbExecutor,
type DbPool,
getDb,
@@ -448,7 +449,9 @@ async function saveSettingsLocked(
],
);
- invalidateSettingsCache();
+ // Inside a transaction, clear once it commits: a page that read the old row
+ // in between would otherwise keep it cached.
+ afterCommit(database, invalidateSettingsCache);
return row ? mapSettingsRow(row) : next;
}