Drafts of every record, previewed on the real page

Migration 077 keeps one draft per record of any entity. Saving a draft
checks it by applying it in a transaction that is rolled back; Preview
opens the record's page in a tab that sends X-Draft-Preview, and the
server answers those reads from a second connection holding the applied
draft, then rolls back, so nobody else sees it. Publish is the ordinary
save, which drops the draft. tx() now nests as a savepoint.

Also commits TODO.md: the answered questions, and parts 1 to 3 moved to
Done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aidan Dona 2026-10-16 18:21:53 -05:00
parent e4c7e165d1
commit a6c66d4607
13 changed files with 576 additions and 65 deletions

View file

@ -36,27 +36,67 @@ export async function openDatabase(path) {
db.exec("PRAGMA busy_timeout = 5000");
db.driverName = "node:sqlite";
// A draft's preview opens its own connection to the same file (drafts.js).
db.path = path;
return db;
}
/* ── Transactions ──────────────────────────────────────────────
node:sqlite has no db.transaction(), so do it by hand. Runs
fn() and commits, or rolls back and rethrows.
fn() and commits, or rolls back and rethrows. Inside another
tx() (or rolledBack(), below) it's a savepoint instead, so a
save can run inside a transaction that's then thrown away:
how a draft is checked and previewed (drafts.js).
───────────────────────────────────────────────────────────── */
export function tx(db, fn) {
db.exec("BEGIN");
const depth = db.txDepth ?? 0;
const savepoint = `tx_${depth}`;
db.exec(depth ? `SAVEPOINT ${savepoint}` : "BEGIN");
db.txDepth = depth + 1;
try {
const result = fn();
db.exec("COMMIT");
db.exec(depth ? `RELEASE ${savepoint}` : "COMMIT");
return result;
} catch (err) {
try {
db.exec("ROLLBACK");
db.exec(depth ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
} catch {
/* already rolled back */
}
throw err;
} finally {
db.txDepth = depth;
}
}
/* Runs fn() in a transaction that is always rolled back, whatever
fn() does: its writes are seen only by fn() itself. fn() may wait,
so only on a connection of its own (a draft's preview, drafts.js):
on the main one, another request would see the writes meanwhile. */
export async function rolledBack(db, fn) {
if (db.txDepth) throw new Error("rolledBack() can't run inside a transaction.");
db.exec("BEGIN");
db.txDepth = 1;
try {
return await fn();
} finally {
db.txDepth = 0;
db.exec("ROLLBACK");
}
}
/* The same for a synchronous fn(), which nothing else can run
during, so the main connection is fine (checking a draft). */
export function rolledBackSync(db, fn) {
if (db.txDepth) throw new Error("rolledBackSync() can't run inside a transaction.");
db.exec("BEGIN");
db.txDepth = 1;
try {
return fn();
} finally {
db.txDepth = 0;
db.exec("ROLLBACK");
}
}

156
server/src/drafts.js Normal file
View file

@ -0,0 +1,156 @@
/* ═══════════════════════════════════════════════════════════════
DRAFTS (077_drafts.sql)
A record's changes saved without going live: one per record, of
any entity the admin edits. The draft is the editor's whole form,
exactly what a save would send, so publishing is that save
(PATCH, routes/admin-entities.js), which then drops the draft.
Nothing applies a draft for real until it's published. Twice it's
applied and thrown away:
checking when it's saved, in a transaction on the main
connection that's always rolled back
(rolledBackSync): updateRow is synchronous, so no
other request can see it, and a draft that a save
would refuse is refused now, with the same errors
preview a public API read sent with X-Draft-Preview:
<entity>/<id> by a signed-in viewer and up runs on a
connection of its own (the same file), inside a
transaction holding the applied draft, rolled back
when the answer is made (previewDrafts). The site
draws the real page from it, with no code of its own
for previews. WAL keeps that connection's writes
unseen by everyone else; it holds the write lock
meanwhile, a few milliseconds, which other writes
wait out (busy_timeout).
The draft is applied over the live record as it is now, so a
save made since the draft was started is overwritten when it's
published; the editor says when that's so (stale).
═══════════════════════════════════════════════════════════════ */
import { currentUser, hasRole } from "./auth.js";
import { openDatabase, rolledBack, rolledBackSync } from "./db.js";
import { HttpError, normalizeId, updateRow } from "./admin-crud.js";
import { ENTITIES } from "./admin-schema.js";
/* Who may preview a draft: anyone who can read the admin. */
export const PREVIEWS = "viewer";
export const entityNamed = (key) => (Object.hasOwn(ENTITIES, key) ? ENTITIES[key] : null);
const liveStamp = (db, entity, id) =>
entity.concurrency
? db
.prepare(`SELECT ${entity.concurrency} AS stamp FROM ${entity.table} WHERE ${entity.idColumn} = ?`)
.get(normalizeId(entity, id))?.stamp
: undefined;
/* Writes the draft over the live record, its concurrency stamp taken
from the live row so the check passes. Call inside a rolled-back
transaction, or as the real publish. */
function apply(db, entity, id, payload) {
const stamp = liveStamp(db, entity, id);
return updateRow(db, entity, id, entity.concurrency ? { ...payload, [entity.concurrency]: stamp } : payload);
}
export function readDraft(db, key, id) {
const entity = entityNamed(key);
const row = db
.prepare(
`SELECT d.*, u.name AS updated_by_name, u.email AS updated_by_email
FROM drafts d LEFT JOIN admin_users u ON u.id = d.updated_by
WHERE d.entity = ? AND d.record_id = ?`,
)
.get(key, String(id));
if (!row) return null;
const live = entity ? liveStamp(db, entity, id) : undefined;
return {
payload: JSON.parse(row.payload),
created_at: row.created_at,
updated_at: row.updated_at,
updated_by: row.updated_by_name ?? row.updated_by_email ?? null,
// The live record was saved after the draft was started.
stale: Boolean(entity?.concurrency && row.base_updated_at && live && live !== row.base_updated_at),
};
}
/* The ids of an entity's records that have a draft, for its list. */
export const draftIds = (db, key) =>
db.prepare(`SELECT record_id FROM drafts WHERE entity = ?`).all(key).map((row) => row.record_id);
/* Checks the draft by applying it and throwing that away, then keeps
it. An HttpError from the check (422 with fields, say) refuses it. */
export function saveDraft(db, key, id, payload, userId) {
const entity = entityNamed(key);
if (!entity) throw new HttpError(404, "Unknown entity.");
if (!payload || typeof payload !== "object") throw new HttpError(400, "Expected the record's form.");
rolledBackSync(db, () => apply(db, entity, id, payload));
const existing = db.prepare(`SELECT base_updated_at FROM drafts WHERE entity = ? AND record_id = ?`).get(key, String(id));
const base = existing ? existing.base_updated_at : (payload[entity.concurrency] ?? null);
db.prepare(
`INSERT INTO drafts (entity, record_id, payload, base_updated_at, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (entity, record_id) DO UPDATE
SET payload = excluded.payload, updated_by = excluded.updated_by, updated_at = datetime('now')`,
).run(key, String(id), JSON.stringify(payload), base, userId, userId);
return readDraft(db, key, id);
}
export function dropDraft(db, key, id) {
db.prepare(`DELETE FROM drafts WHERE entity = ? AND record_id = ?`).run(key, String(id));
}
/* Middleware for the public API: a GET carrying X-Draft-Preview from
a signed-in viewer and up is answered with that draft applied. Any
other request, or a draft that isn't there, goes on as usual. */
export async function previewDrafts(c, next) {
if (c.req.method !== "GET" || /^\/api\/(admin|auth|account)(\/|$)/.test(c.req.path)) return next();
await answer(c, next);
// A public read may be kept a minute (shape.js, CACHE): never hand
// the live copy to a preview tab, or a preview's to anyone.
c.res.headers.append("Vary", "X-Draft-Preview");
}
async function answer(c, next) {
const wanted = c.req.header("x-draft-preview");
if (!wanted) return next();
const main = c.get("db");
if (!hasRole(currentUser(main, c), PREVIEWS)) return next();
const slash = wanted.indexOf("/");
const key = wanted.slice(0, slash);
let id;
try {
id = decodeURIComponent(wanted.slice(slash + 1));
} catch {
return next();
}
const entity = entityNamed(key);
const draft = slash > 0 && entity ? readDraft(main, key, id) : null;
if (!draft) return next();
const db = await openDatabase(main.path);
try {
await rolledBack(db, async () => {
// A draft the record has outgrown (a field it no longer has,
// say) shows the live page rather than an error; saving it in
// the editor says what's wrong.
try {
apply(db, entity, id, draft.payload);
} catch (err) {
console.warn(`draft preview ${key}/${id} not applied: ${err.message}`);
}
c.set("db", db);
await next();
});
} finally {
db.close();
}
// Only for this tab, never kept.
c.res.headers.set("Cache-Control", "no-store");
}

View file

@ -50,6 +50,7 @@ import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
import { ENTITIES } from "./admin-schema.js";
import { previewDrafts } from "./drafts.js";
const HOST = process.env.HOST ?? "127.0.0.1";
const PORT = Number(process.env.PORT ?? 3001);
@ -180,6 +181,10 @@ app.use("*", async (c, next) => {
await next();
});
// A draft's preview (drafts.js): a public read from a signed-in
// viewer with X-Draft-Preview answers with that draft applied.
app.use("/api/*", previewDrafts);
app.get("/api/health", (c) =>
c.json({ ok: true, schema: version, driver: db.driverName }),
);

View file

@ -0,0 +1,25 @@
-- ═══════════════════════════════════════════════════════════════
-- 077 DRAFTS
--
-- A record's changes saved without going live: one draft per
-- record, of any entity the admin edits (events, people, pages,
-- Navigation...). payload is the editor's whole form, as a save
-- would send it; publishing is that save, which then drops the
-- draft. Anyone who can edit the record can save, preview, publish
-- or discard it (drafts.js).
--
-- base_updated_at is the record's updated_at when the draft was
-- started, so the editor can say the live record changed since.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE drafts (
entity TEXT NOT NULL, -- the descriptor key, eg. 'events'
record_id TEXT NOT NULL,
payload TEXT NOT NULL CHECK (json_valid(payload)),
base_updated_at TEXT,
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (entity, record_id)
) STRICT;

View file

@ -6,7 +6,11 @@
GET /api/admin/:entity/:id row with side tables and children
POST /api/admin/:entity create
PATCH /api/admin/:entity/:id replace the row and its children
(publishing a draft too: it's dropped)
DELETE /api/admin/:entity/:id
GET /api/admin/:entity/:id/draft its draft, or null (drafts.js)
PUT /api/admin/:entity/:id/draft save the form as its draft
DELETE /api/admin/:entity/:id/draft discard it
Mounted alongside the existing admin router, which keeps the
feedback routes. Both sit under the same requireAuth.
@ -29,6 +33,7 @@ import {
deleteRow,
} from "../admin-crud.js";
import { NO_STORE } from "../shape.js";
import { draftIds, dropDraft, readDraft, saveDraft } from "../drafts.js";
const entities = new Hono();
@ -84,7 +89,8 @@ entities.get("/options", (c) => {
entities.get("/:entity", (c) => {
const entity = entityOr404(c);
const { rows, total } = listRows(c.get("db"), entity, c.req.query());
return c.json({ rows, total }, 200, NO_STORE);
// Which of them have a draft waiting, for the list to mark.
return c.json({ rows, total, drafts: draftIds(c.get("db"), entity.key) }, 200, NO_STORE);
});
entities.get("/:entity/:id", (c) => {
@ -103,6 +109,8 @@ entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
// Saved for real: any draft of it is published, or overtaken.
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
return c.json({ row }, 200, NO_STORE);
});
@ -111,10 +119,34 @@ entities.delete("/:entity/:id", requireRole("admin"), (c) => {
const entity = entityOr404(c);
const id = c.req.param("id");
deleteRow(c.get("db"), entity, id);
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
/* ── Drafts (drafts.js) ──────────────────────────────────────── */
entities.get("/:entity/:id/draft", (c) => {
const entity = entityOr404(c);
return c.json({ draft: readDraft(c.get("db"), entity.key, c.req.param("id")) }, 200, NO_STORE);
});
entities.put("/:entity/:id/draft", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const draft = saveDraft(c.get("db"), entity.key, id, await json(c), c.get("user").id);
console.log(`${entity.key} ${id} draft saved by ${c.get("user").email}`);
return c.json({ draft }, 200, NO_STORE);
});
entities.delete("/:entity/:id/draft", requireRole("editor"), (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
dropDraft(c.get("db"), entity.key, id);
console.log(`${entity.key} ${id} draft discarded by ${c.get("user").email}`);
return c.body(null, 204);
});
async function json(c) {
try {
return await c.req.json();