feat: persist synced event-log history across server runs (SQLite relay)

The event relay was an in-memory array that started empty on every process, so
synced history vanished on every API-server restart. Persist it to a gitignored
.data/events.sqlite3 via node:sqlite like the blob store (EVENT_DB_PATH override;
seq rowid pull cursor; UNIQUE(authorPubkey,signature) push idempotency), keeping
the exact exported API. Synced history now survives restarts and keeps growing,
and a fresh device pulls the whole lived-in history on load; ShellLayout adds a
light 6s poll for live cross-device reflection. Adds a dev:all script, isolates
the two integration tests to a temp EVENT_DB_PATH, documents EVENT_DB_PATH.
This commit is contained in:
OmO Orchestrator committed 2026-11-20 02:30:03 -05:00
1 parent afa29a70f3
commit d22361a613
8 files changed
+189 -42

No files matched your search

+28 -12
View File
@@ -8,11 +8,21 @@ repo and Node's built-ins.
## What needs a server at all ## What needs a server at all
Almost everything in this app is a client-only PWA (identity, event log, Almost everything in this app is a client-only PWA (identity, event log,
ledger all live in the browser's IndexedDB). The one piece that needs a ledger all live in the browser's IndexedDB and keep working offline). Two
small long-running process is the blob store (`api/blob/*`), used for small pieces use the long-running API process, both persisting to local
cross-device mini-app sharing. `api/_lib/blobStore.ts` persists blobs to a SQLite files via Node's built-in `node:sqlite` module - no database server,
local SQLite file via Node's built-in `node:sqlite` module - no database no managed service, no signup required:
server, no managed service, no signup required for this storage path.
- the **blob store** (`api/blob/*`, `api/_lib/blobStore.ts`), for
cross-device mini-app sharing (`BLOB_DB_PATH`, default
`./.data/blobs.sqlite3`);
- the **signed-event relay** (`api/sync`, `api/_lib/eventRelayStore.ts`),
the best-effort cross-device sync for the event log. It survives restarts,
so synced history keeps accumulating and a fresh device pulls the whole
"lived-in" history on load (`EVENT_DB_PATH`, default
`./.data/events.sqlite3`). The relay only ever stores signature-verified
events and never blocks a local write - the event-log append/read/replay
path itself stays fully offline.
## 1. Build the frontend ## 1. Build the frontend
@@ -33,7 +43,10 @@ file directly with `node` (via its own `if (import.meta.url === ...)` entry
point) gives you a minimal production-equivalent entry point: point) gives you a minimal production-equivalent entry point:
```bash ```bash
PORT=3001 BLOB_DB_PATH=/var/lib/commons/blobs.sqlite3 node api/_lib/devServer.ts PORT=3001 \
BLOB_DB_PATH=/var/lib/commons/blobs.sqlite3 \
EVENT_DB_PATH=/var/lib/commons/events.sqlite3 \
node api/_lib/devServer.ts
``` ```
(This is the same command `npm run dev:api` already runs in this repo - (This is the same command `npm run dev:api` already runs in this repo -
@@ -67,6 +80,7 @@ After=network.target
WorkingDirectory=/opt/commons WorkingDirectory=/opt/commons
Environment=PORT=3001 Environment=PORT=3001
Environment=BLOB_DB_PATH=/var/lib/commons/blobs.sqlite3 Environment=BLOB_DB_PATH=/var/lib/commons/blobs.sqlite3
Environment=EVENT_DB_PATH=/var/lib/commons/events.sqlite3
ExecStart=/usr/bin/node api/_lib/prodServer.ts ExecStart=/usr/bin/node api/_lib/prodServer.ts
Restart=always Restart=always
User=commons User=commons
@@ -119,13 +133,15 @@ This mirrors `vercel.json`'s own routing convention (`/api/*` goes to the
API, everything else falls back to `index.html`) so the same build works API, everything else falls back to `index.html`) so the same build works
unchanged whether it's proxied this way or (still) deployed to Vercel. unchanged whether it's proxied this way or (still) deployed to Vercel.
## 4. The `BLOB_DB_PATH` env var and its persistent volume ## 4. The `BLOB_DB_PATH` / `EVENT_DB_PATH` env vars and their persistent volume
- Env var: `BLOB_DB_PATH` - Env vars: `BLOB_DB_PATH` (mini-app bundles) and `EVENT_DB_PATH`
- Default (if unset): `./.data/blobs.sqlite3`, resolved under the (signed-event relay). Both behave identically.
process's own working directory (`process.cwd()`) - a real file on - Defaults (if unset): `./.data/blobs.sqlite3` and `./.data/events.sqlite3`,
disk, not `os.tmpdir()`. This matches the repo's existing `.gitignore` resolved under the process's own working directory (`process.cwd()`) -
convention for local persistent state. real files on disk, not `os.tmpdir()`. This matches the repo's existing
`.gitignore` convention for local persistent state (the whole `.data/`
directory is gitignored).
- On a self-hosted box, point it at a path that survives restarts and - On a self-hosted box, point it at a path that survives restarts and
(if containerized) outlives the container filesystem - e.g. (if containerized) outlives the container filesystem - e.g.
`/var/lib/commons/blobs.sqlite3` on bare metal, or a bind-mounted host `/var/lib/commons/blobs.sqlite3` on bare metal, or a bind-mounted host
+13 -5
View File
@@ -87,15 +87,23 @@ to be independent.
```bash ```bash
npm install npm install
npm run dev # Vite dev server at http://localhost:5173 npm run dev # Vite dev server at http://localhost:5173
npm run dev:api # local API (blob store + signed-event relay) at :3001
npm run dev:all # both of the above together (recommended for a lived-in demo)
npm run build # tsc -b (type-check gate) && vite build -> dist/ npm run build # tsc -b (type-check gate) && vite build -> dist/
npm run test # vitest run npm run test # vitest run
npm run lint # oxlint npm run lint # oxlint
``` ```
The app is local-first: everything except the mini-app-sharing blob store The app is local-first: the identity, event log, ledger, and every
(`api/`, used only by the upload/QR flow) runs entirely in the browser mini-app's logic run entirely in the browser against IndexedDB (Dexie) and
against IndexedDB (Dexie). To run the blob API locally alongside the dev keep working with no server at all. The optional `api/` process adds two
server: `npm run dev:api`. best-effort pieces, both persisting to the gitignored `.data/` directory so
they survive restarts: the mini-app-sharing blob store (the upload/QR flow)
and a signed-event relay that syncs the event log across devices. With the
relay running, a fresh device pulls the accumulated history on load, so a
demo feels "lived in" and keeps growing as it is used. Run both servers
together with `npm run dev:all` (or each alone via `npm run dev` /
`npm run dev:api`).
## Authoring your own mini-app ## Authoring your own mini-app
+94 -25
View File
@@ -1,7 +1,10 @@
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import * as ed from "@noble/ed25519"; import * as ed from "@noble/ed25519";
/** /**
* In-process relay store for the generic signed-event sync endpoint * Persistent relay store for the generic signed-event sync endpoint
* (backend-expansion todo 2). This is a pure relay: it verifies every pushed * (backend-expansion todo 2). This is a pure relay: it verifies every pushed
* event's own signature before storing it, and never creates, mutates, or * event's own signature before storing it, and never creates, mutates, or
* counter-signs anything on anyone's behalf. It stores each entry exactly as * counter-signs anything on anyone's behalf. It stores each entry exactly as
@@ -9,12 +12,18 @@ import * as ed from "@noble/ed25519";
* back verbatim on pull, so a pulled entry replays on another device as its * back verbatim on pull, so a pulled entry replays on another device as its
* ORIGINAL author, never as the relay or the receiving device. * ORIGINAL author, never as the relay or the receiving device.
* *
* Mirroring `api/_lib/blobStore.ts`'s stub style: this todo's acceptance * Durability (2026-11-20): the relay now persists to a local SQLite file via
* criteria only require cross-device propagation within one running server * Node's built-in `node:sqlite` (`DatabaseSync`, stable since Node 22.5,
* (not cross-restart durability, unlike the blob store), so the backing store * present in this environment's Node 24), exactly like `api/_lib/blobStore.ts`
* is a plain module-level array that starts empty on each process. Tests that * - so synced history SURVIVES a server restart and keeps GROWING across runs
* need a clean slate between cases call `resetEventRelayStore()` - the * ("lived in" demos), instead of the old in-memory module array that started
* in-process analogue of the blob store's per-run `BLOB_STORE_DIR`. * empty on every process. No external account or credential is required: the
* db file is configurable via `EVENT_DB_PATH` and defaults to
* `.data/events.sqlite3` under the process cwd (this repo's `.gitignore`
* convention for local persistent state). Tests that need a clean slate point
* `EVENT_DB_PATH` at a temp dir and call `resetEventRelayStore()` between
* cases (the per-run isolation analogue the blob store does with
* `BLOB_DB_PATH`).
*/ */
/** The over-the-wire shape of one signed Event Log entry. `authorPubkey` and /** The over-the-wire shape of one signed Event Log entry. `authorPubkey` and
@@ -53,17 +62,48 @@ export class EventSignatureError extends Error {
const PUBKEY_HEX = /^[0-9a-f]{64}$/i; const PUBKEY_HEX = /^[0-9a-f]{64}$/i;
const SIGNATURE_HEX = /^[0-9a-f]{128}$/i; const SIGNATURE_HEX = /^[0-9a-f]{128}$/i;
let store: WireEventEntry[] = []; const DEFAULT_DB_PATH = join(process.cwd(), ".data", "events.sqlite3");
const seen = new Set<string>();
/** Clear the in-process store (test isolation; see module doc comment). */ // Resolved lazily (inside getDb(), on first call) rather than as a
export function resetEventRelayStore(): void { // module-load-time constant, so a test's `beforeAll` can point
store = []; // `EVENT_DB_PATH` at a temp dir before the first store access - the same
seen.clear(); // reason `blobStore.ts` resolves its path lazily.
function resolveDbPath(): string {
return process.env.EVENT_DB_PATH ?? DEFAULT_DB_PATH;
} }
function identity(entry: WireEventEntry): string { let db: DatabaseSync | undefined;
return `${entry.authorPubkey.toLowerCase()}:${entry.signature.toLowerCase()}`;
function getDb(): DatabaseSync {
if (db) {
return db;
}
const dbPath = resolveDbPath();
mkdirSync(dirname(dbPath), { recursive: true });
const opened = new DatabaseSync(dbPath);
// `seq` is the rowid alias and the relay's append-order cursor: it increases
// monotonically with insertion and, after a full `DELETE`, restarts at 1 (no
// AUTOINCREMENT), matching the old in-memory array index semantics. The
// UNIQUE(authorPubkey, signature) pair is the push-idempotency guard the old
// `seen` Set provided.
opened.exec(`
CREATE TABLE IF NOT EXISTS events (
seq INTEGER PRIMARY KEY,
payload TEXT NOT NULL,
authorPubkey TEXT NOT NULL,
signature TEXT NOT NULL,
lamportTs INTEGER NOT NULL,
UNIQUE(authorPubkey, signature)
)
`);
db = opened;
return opened;
}
/** Clear the relay's stored events (test isolation; see module doc comment).
* After deleting every row the `seq` cursor restarts at 1 on the next insert. */
export function resetEventRelayStore(): void {
getDb().exec("DELETE FROM events");
} }
function hexToBytes(hex: string): Uint8Array { function hexToBytes(hex: string): Uint8Array {
@@ -134,7 +174,8 @@ async function verifyWireEntry(entry: WireEventEntry): Promise<boolean> {
* ANY of them: a batch containing one malformed or forged entry is rejected * ANY of them: a batch containing one malformed or forged entry is rejected
* whole (throws), so a tampered event never lands in the store or a later * whole (throws), so a tampered event never lands in the store or a later
* pull. Valid entries already present (same authorPubkey+signature) are * pull. Valid entries already present (same authorPubkey+signature) are
* skipped, keeping push idempotent. Returns the count newly stored. * skipped via `INSERT OR IGNORE` on the UNIQUE pair, keeping push idempotent.
* Returns the count newly stored.
*/ */
export async function pushEvents(rawEntries: readonly unknown[]): Promise<number> { export async function pushEvents(rawEntries: readonly unknown[]): Promise<number> {
const validated: WireEventEntry[] = []; const validated: WireEventEntry[] = [];
@@ -146,21 +187,37 @@ export async function pushEvents(rawEntries: readonly unknown[]): Promise<number
validated.push(entry); validated.push(entry);
} }
const insert = getDb().prepare(
"INSERT OR IGNORE INTO events (payload, authorPubkey, signature, lamportTs) VALUES (?, ?, ?, ?)",
);
let added = 0; let added = 0;
for (const entry of validated) { for (const entry of validated) {
const id = identity(entry); const result = insert.run(
if (seen.has(id)) continue; JSON.stringify(entry.payload),
seen.add(id); entry.authorPubkey.toLowerCase(),
store.push(entry); entry.signature.toLowerCase(),
added++; entry.lamportTs,
);
if (Number(result.changes) === 1) added++;
} }
return added; return added;
} }
interface EventRow {
seq: number;
payload: string;
authorPubkey: string;
signature: string;
lamportTs: number;
}
/** /**
* Return every stored entry at or after `cursor` (an index into the relay's * Return every stored entry whose `seq` is greater than `cursor` (the relay's
* append order) together with the new cursor the caller should use next time. * monotonic append-order high-water mark) together with the new cursor the
* A missing/invalid cursor is treated as 0 (pull everything). * caller should use next time. A missing/invalid cursor is treated as 0 (pull
* everything). The returned cursor is the last entry's `seq`, or the given
* cursor unchanged when nothing new is available - so a subsequent pull with
* it returns only genuinely newer entries and survives a server restart.
*/ */
export function pullEvents(cursor: unknown): { export function pullEvents(cursor: unknown): {
entries: WireEventEntry[]; entries: WireEventEntry[];
@@ -170,5 +227,17 @@ export function pullEvents(cursor: unknown): {
typeof cursor === "number" && Number.isFinite(cursor) && cursor >= 0 typeof cursor === "number" && Number.isFinite(cursor) && cursor >= 0
? Math.floor(cursor) ? Math.floor(cursor)
: 0; : 0;
return { entries: store.slice(from), cursor: store.length }; const rows = getDb()
.prepare(
"SELECT seq, payload, authorPubkey, signature, lamportTs FROM events WHERE seq > ? ORDER BY seq ASC",
)
.all(from) as unknown as EventRow[];
const entries: WireEventEntry[] = rows.map((row) => ({
payload: JSON.parse(row.payload),
authorPubkey: row.authorPubkey,
signature: row.signature,
lamportTs: Number(row.lamportTs),
}));
const nextCursor = rows.length > 0 ? Number(rows[rows.length - 1].seq) : from;
return { entries, cursor: nextCursor };
} }
+8
View File
@@ -1,4 +1,7 @@
import type { AddressInfo } from "node:net"; import type { AddressInfo } from "node:net";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import * as ed from "@noble/ed25519"; import * as ed from "@noble/ed25519";
import { createApiServer } from "./_lib/devServer.ts"; import { createApiServer } from "./_lib/devServer.ts";
@@ -44,8 +47,11 @@ async function pushRaw(baseUrl: string, events: unknown[]): Promise<Response> {
describe("admin aggregate endpoint integration (todo 5)", () => { describe("admin aggregate endpoint integration (todo 5)", () => {
let server: ReturnType<typeof createApiServer>; let server: ReturnType<typeof createApiServer>;
let baseUrl: string; let baseUrl: string;
let storeDir: string;
beforeAll(async () => { beforeAll(async () => {
storeDir = await mkdtemp(join(tmpdir(), "commons-admin-test-"));
process.env.EVENT_DB_PATH = join(storeDir, "events.sqlite3");
server = createApiServer(); server = createApiServer();
await new Promise<void>((resolve) => server.listen(0, resolve)); await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo; const { port } = server.address() as AddressInfo;
@@ -54,6 +60,8 @@ describe("admin aggregate endpoint integration (todo 5)", () => {
afterAll(async () => { afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve())); await new Promise<void>((resolve) => server.close(() => resolve()));
delete process.env.EVENT_DB_PATH;
await rm(storeDir, { recursive: true, force: true });
}); });
beforeEach(() => { beforeEach(() => {
+8
View File
@@ -1,4 +1,7 @@
import type { AddressInfo } from "node:net"; import type { AddressInfo } from "node:net";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import * as ed from "@noble/ed25519"; import * as ed from "@noble/ed25519";
import { createApiServer } from "./_lib/devServer.ts"; import { createApiServer } from "./_lib/devServer.ts";
@@ -48,8 +51,11 @@ async function pushRaw(baseUrl: string, body: unknown): Promise<Response> {
describe("signed-event relay integration (todo 2)", () => { describe("signed-event relay integration (todo 2)", () => {
let server: ReturnType<typeof createApiServer>; let server: ReturnType<typeof createApiServer>;
let baseUrl: string; let baseUrl: string;
let storeDir: string;
beforeAll(async () => { beforeAll(async () => {
storeDir = await mkdtemp(join(tmpdir(), "commons-events-test-"));
process.env.EVENT_DB_PATH = join(storeDir, "events.sqlite3");
server = createApiServer(); server = createApiServer();
await new Promise<void>((resolve) => server.listen(0, resolve)); await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo; const { port } = server.address() as AddressInfo;
@@ -58,6 +64,8 @@ describe("signed-event relay integration (todo 2)", () => {
afterAll(async () => { afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve())); await new Promise<void>((resolve) => server.close(() => resolve()));
delete process.env.EVENT_DB_PATH;
await rm(storeDir, { recursive: true, force: true });
}); });
beforeEach(async () => { beforeEach(async () => {
+1
View File
@@ -6,6 +6,7 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"dev:api": "node api/_lib/devServer.ts", "dev:api": "node api/_lib/devServer.ts",
"dev:all": "node scripts/dev-all.mjs",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "oxlint", "lint": "oxlint",
"preview": "vite preview", "preview": "vite preview",
+24
View File
@@ -0,0 +1,24 @@
import { spawn } from "node:child_process";
const children = [
spawn("npm", ["run", "dev:api"], { stdio: "inherit", env: process.env }),
spawn("npm", ["run", "dev"], { stdio: "inherit", env: process.env }),
];
let shuttingDown = false;
function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
for (const child of children) {
child.kill(signal ?? "SIGTERM");
}
}
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
for (const child of children) {
child.on("exit", (code) => {
shutdown("SIGTERM");
process.exit(code ?? 0);
});
}
+13
View File
@@ -1,9 +1,13 @@
import { useEffect } from "react";
import { Link, Outlet, useLocation } from "react-router-dom"; import { Link, Outlet, useLocation } from "react-router-dom";
import { trySyncWithBackend } from "../lib/sync";
import { Icon } from "./icons"; import { Icon } from "./icons";
import { miniappRegistry } from "./miniappRegistry"; import { miniappRegistry } from "./miniappRegistry";
import styles from "./ShellLayout.module.css"; import styles from "./ShellLayout.module.css";
import { WalletCard } from "./WalletCard"; import { WalletCard } from "./WalletCard";
const SHELL_LIVE_SYNC_INTERVAL_MS = 6000;
function screenTitle(pathname: string): string | undefined { function screenTitle(pathname: string): string | undefined {
const miniappMatch = pathname.match(/^\/miniapp\/([^/]+)/); const miniappMatch = pathname.match(/^\/miniapp\/([^/]+)/);
if (miniappMatch) { if (miniappMatch) {
@@ -20,6 +24,15 @@ export function ShellLayout() {
const isHome = location.pathname === "/"; const isHome = location.pathname === "/";
const title = screenTitle(location.pathname); const title = screenTitle(location.pathname);
useEffect(() => {
void trySyncWithBackend();
const timer = setInterval(
() => void trySyncWithBackend(),
SHELL_LIVE_SYNC_INTERVAL_MS,
);
return () => clearInterval(timer);
}, []);
return ( return (
<div> <div>
<WalletCard compact={!isHome} /> <WalletCard compact={!isHome} />