Public: anyone can read this; the crew can change it.

The cache spectrum, chosen on purpose: in-process snapshots, SQLite, the edge's own cache, and a global read-cheap config pushed to the edge in seconds; offered to apps #1368

Closed opened this in answer to
Closed without merging

scout/forge:scout/1138-the-cache-spectrum-chosen-on-purpose-in → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +1311 −3
docs/CACHE.md added +72
@@ -0,0 +1,72 @@
1 # The cache spectrum
2
3 Each kind of data lives on one rung, chosen on purpose. Climb only when the
4 rung below is too slow for who reads it; never keep the same fact as truth on
5 two rungs.
6
7 | Rung | What lives there | Read cost | Changes | Truth? |
8 |---|---|---|---|---|
9 | **git** | code, `forge.json`, the repository's own files | a `git` read | a push | yes — the only truth (CLAUDE.md, invariant 4) |
10 | **SQLite** | the derived index (issues, pulls, events), config rows and their ledger (`config`, `config_change`), sessions | one indexed query | every action | derived from git, except config and sessions |
11 | **process** | the current config snapshot of each scope, held by every forge process | a map lookup | refreshed on the `config.set` bus event, or by a half-second poll for another process's write | a copy of SQLite |
12 | **edge** | the signed snapshot file, at a stable URL and (behind Cloudflare) in KV | none of the forge's | published within seconds of a write | a copy of SQLite |
13 | **validator** | `ETag` + `If-None-Match`: the client keeps the body, the forge answers `304` | a lookup | per request | n/a |
14
15 ## Which data, which rung
16
17 - **Flags, settings, the forge's and an app's config** — small, read
18 everywhere, written rarely: the **config store** (`src/core/config.ts`).
19 Truth in SQLite, copy in every process, signed copy on the edge. Values
20 are public by contract; secrets go in the secret store, never here.
21 - **Pages, lists, issues, pulls** — large, personal, changing: SQLite, with
22 `fragment` or `config` validators. Not the edge.
23 - **Content-addressed assets** (`/assets/<hash>.css`) — `immutable`.
24 - **Repository contents** — git, read through the pooled `cat-file` readers.
25
26 ## One helper per kind
27
28 `Cache-Control` and `ETag` come from `cacheHeaders(kind, etag)` and
29 `cached(...)` in `src/http/respond.ts`; a route names the kind and never
30 writes the header. The table `CACHE_CONTROL` is the single source and
31 `test/config-store.test.ts` checks this page against it.
32
33 | Kind | `Cache-Control` | `ETag` | Used for |
34 |---|---|---|---|
35 | `immutable` | `public, max-age=31536000, immutable` | optional | hashed assets |
36 | `edge` | `public, max-age=5, stale-while-revalidate=30` | snapshot id | the published snapshot, the forge's public config |
37 | `config` | `private, no-cache` | snapshot id | an app's config for its signed-in reader |
38 | `fragment` | `private, max-age=30` | optional | rendered fragments for one reader |
39 | `live` | `no-store` | never | anything that must not be kept |
40
41 Routes that predate the helper still set their own headers
42 (`web/pages/*`, `apps/proxy.ts`); they move to a kind as they are touched.
43
44 ## The edge rung
45
46 Every write produces one snapshot id. Each process that learns of it
47 publishes `<data>/edge/config/<name>.json`, an Ed25519-signed
48 `{ payload, sig }`, served at `/edge/config/<name>.json` (`forge`, or
49 `app-<id>` for an app whose repository anyone can read). The public key is
50 at `/edge/config/key.pem`. With `FORGE_CF_ACCOUNT`, `FORGE_CF_KV_NAMESPACE`
51 and `FORGE_CF_API_TOKEN` set, the same bytes are also `PUT` to that KV
52 namespace under the same name, so a Worker reads flags without the forge.
53
54 **A stale edge is visible.** Every response carries `X-Forge-Config`, the id
55 of the snapshot this forge holds; compare it with the `snapshot` in the file
56 you have (`isStale` in `src/cloud/edge.ts`).
57
58 ## Apps
59
60 `GET /api/v1/apps/:slug/config` (any credential that can read the app, so
61 the read-only token an app starts with) returns
62 `{ snapshot, version, values, updated_at }` with the id as `ETag`; send it
63 back as `If-None-Match` for a `304`. `PATCH` with `{ "set": { key: value |
64 null }, "why": "…" }` needs an admin token and repository admin. The edge
65 file of a public app is the same data without the forge.
66
67 ## Checking the choice
68
69 `GET /api/v1/cache` (admin) returns this process's hit/miss counts per rung:
70 `process` (snapshot already held), `sqlite` (loaded or refreshed), `edge`
71 (published file served), `validator` (`304`s). The counters are in memory
72 and reset with the process.
forge.json +2 −1
@@ -1,6 +1,7 @@
11 {
22 "egress": [
3 "api.anthropic.com"
3 "api.anthropic.com",
4 "api.cloudflare.com"
45 ],
56 "app": {
67 "run": "bun run src/main.ts",
scripts/gate.ts +1
@@ -40,6 +40,7 @@ export const GATE: readonly string[] = [
4040 "test/crew-brief-audience.test.ts",
4141 "test/crew.test.ts",
4242 "test/commit-identity.test.ts",
43 "test/config-store.test.ts",
4344 "test/enterable-apps.test.ts",
4445 "test/event-order.test.ts",
4546 "test/refresh-meta.test.ts",
src/app.ts +23 −1
@@ -12,6 +12,8 @@ import { mkdirSync } from "node:fs";
1212 import { join, resolve } from "node:path";
1313 import { migrations } from "./core/schema.ts";
1414 import { dropLegacyNewAccountGuards } from "./core/schema.ts";
15 import { ConfigStore } from "./core/config.ts";
16 import { EdgePublisher, kvFromEnv } from "./cloud/edge.ts";
1517 import { EventBus } from "./core/events.ts";
1618 import { follow } from "./core/following.ts";
1719 import { enqueueForEvent } from "./core/webhooks.ts";
@@ -134,6 +136,10 @@ export interface App {
134136 readonly log: Log;
135137 readonly reposRoot: string;
136138 readonly socketPath: string;
139 /** Small read-mostly values, held in memory (`core/config.ts`). */
140 readonly configs: ConfigStore;
141 /** Where config snapshots are published for the edge (`cloud/edge.ts`); made on first use. */
142 edge(): EdgePublisher;
137143 /** Where the internal listener answers: `socketPath`, or a loopback port (`git/hook-address.ts`). */
138144 readonly hookAddress: { current: string };
139145 /** Per-boot secret every internal request must carry (`FORGE_HOOK_SECRET` in a hook's env). */
@@ -166,11 +172,26 @@ export function createApp(config: ForgeConfig): App {
166172 // and the forks whose default branch is still a copy of this one's.
167173 follow({ db, reposRoot, bus });
168174
175 const log = createLog("forge");
176 const configs = new ConfigStore(db, bus);
177 let publisher: EdgePublisher | undefined;
178 const edge = (): EdgePublisher =>
179 (publisher ??= new EdgePublisher(dataDir, { kv: kvFromEnv(process.env) }));
180 // A snapshot this process newly holds is published within the same tick
181 // (the file) and the next round trip (KV).
182 configs.onChange((snap) => {
183 edge()
184 .publish(snap)
185 .catch((error) => log.error("edge publish failed", { error: String(error) }));
186 });
187
169188 return {
170189 config: { ...config, dataDir },
190 configs,
191 edge,
171192 db,
172193 bus,
173 log: createLog("forge"),
194 log,
174195 reposRoot,
175196 // This process's own: two forges share a data directory for the length
176197 // of a release, and each spawns git with its own socket in the env.
@@ -183,6 +204,7 @@ export function createApp(config: ForgeConfig): App {
183204 // otherwise. One data dir is one forge, so closing the forge is where
184205 // that is said.
185206 closeReadersUnder(reposRoot);
207 configs.stop();
186208 db.close();
187209 },
188210 };
src/apps/scaffold.ts +122
@@ -48,6 +48,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
4848 },
4949 { path: "design/tokens.json", content: TOKENS_JSON },
5050 { path: "src/env.ts", content: ENV_TS },
51 { path: "src/flags.ts", content: FLAGS_TS },
5152 { path: "src/who.ts", content: WHO_TS },
5253 { path: "src/can.ts", content: CAN_TS },
5354 { path: "src/contract.ts", content: CONTRACT_TS },
@@ -69,6 +70,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
6970 { path: "static/app.css", content: APP_CSS },
7071 { path: "static/live.js", content: LIVE_JS },
7172 { path: "src/who.test.ts", content: WHO_TEST },
73 { path: "src/flags.test.ts", content: FLAGS_TEST },
7274 { path: "src/db.test.ts", content: DB_TEST },
7375 { path: "src/actions.test.ts", content: ACTIONS_TEST },
7476 { path: "src/contract.test.ts", content: CONTRACT_TEST },
@@ -264,6 +266,9 @@ preview at its own address, deployed from your branch as you push.
264266 and nothing more: the terminal gates its reads and writes exactly as the
265267 page does (\`FORGE_APP_USER_ROLE\` is the forge's word on who is there), and a
266268 write made there reaches web viewers live like any other.
269 - Flags and settings live in the forge's config store, not in code or the
270 database: \`flag(name, fallback)\` from \`src/flags.ts\` is a lookup in a
271 snapshot held in memory (\`docs/CACHE.md\` in the forge). Values are public.
267272 - Keep it dependency-free unless a dependency is clearly worth it, and say
268273 why in the pull. A dependency is code you now maintain.
269274 - When you are done, push and stop. Your last message becomes the pull's
@@ -408,6 +413,123 @@ export const publicOrigin: string = new URL(
408413 export const forgeUrl: string | undefined = process.env.FORGE_URL;
409414 /** The key the forge signs identities with (\`who.ts\`). Unset, everyone is anonymous. */
410415 export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? "";
416 /** Where the forge's API is, and the read-only token the forge gave this process (\`flags.ts\`). */
417 export const forgeApiUrl: string | undefined = process.env.FORGE_API_URL;
418 export const forgeToken: string | undefined = process.env.FORGE_TOKEN;
419 `;
420
421 // Flags: the forge's config store, held in memory (docs/CACHE.md).
422 const FLAGS_TS = `/**
423 * Flags and settings from the forge's config store (\`GET
424 * /api/v1/apps/<slug>/config\`). The current snapshot is held in memory, so
425 * \`flag()\` is a map lookup that never waits on the network; \`refresh()\`
426 * revalidates with the snapshot id as the ETag (a 304 costs the forge one
427 * lookup), and \`start()\` does it every few seconds. Values are public by
428 * contract: no secrets here. Change them with \`PATCH\` and a \`why\`.
429 * Without a forge to ask, every flag is its fallback.
430 */
431
432 import { forgeApiUrl, forgeToken, publicOrigin } from "./env.ts";
433
434 export type FlagValue = string | number | boolean | null | FlagValue[] | { [k: string]: FlagValue };
435
436 /** \`<slug>.<domain>\` or \`<slug>--<n>.<domain>\`: the app's slug. */
437 export function slugOf(origin: string): string {
438 return new URL(origin).hostname.split(".")[0]!.split("--")[0]!;
439 }
440
441 export class Flags {
442 /** The id of the snapshot held; changes with every write. \`"0"\` before the first answer. */
443 snapshot = "0";
444 private values: Record<string, FlagValue> = {};
445 private timer: ReturnType<typeof setInterval> | undefined;
446
447 constructor(
448 private readonly url: string | undefined,
449 private readonly token: string | undefined,
450 private readonly slug: string,
451 private readonly fetcher: typeof fetch = fetch,
452 ) {}
453
454 flag<T extends FlagValue>(name: string, fallback: T): T {
455 const value = this.values[name];
456 return value === undefined ? fallback : (value as T);
457 }
458
459 /** Ask the forge whether the snapshot moved; true when this call changed it. */
460 async refresh(): Promise<boolean> {
461 if (this.url === undefined || this.token === undefined) return false;
462 try {
463 const res = await this.fetcher(\`\${this.url}/apps/\${this.slug}/config\`, {
464 headers: {
465 authorization: \`Bearer \${this.token}\`,
466 ...(this.snapshot === "0" ? {} : { "if-none-match": \`"\${this.snapshot}"\` }),
467 },
468 });
469 if (res.status !== 200) return false;
470 const body = (await res.json()) as { snapshot?: unknown; values?: unknown };
471 if (typeof body.snapshot !== "string" || typeof body.values !== "object" || body.values === null)
472 return false;
473 this.values = body.values as Record<string, FlagValue>;
474 this.snapshot = body.snapshot;
475 return true;
476 } catch {
477 // The forge being away keeps the last snapshot; flags are never a reason to fail a request.
478 return false;
479 }
480 }
481
482 start(ms = 5000): void {
483 if (this.timer !== undefined) return;
484 void this.refresh();
485 this.timer = setInterval(() => void this.refresh(), ms);
486 this.timer.unref?.();
487 }
488 }
489
490 export const flags = new Flags(forgeApiUrl, forgeToken, slugOf(publicOrigin));
491 `;
492
493 const FLAGS_TEST = `import { expect, test } from "bun:test";
494 import { Flags, slugOf } from "./flags.ts";
495
496 const forge = (snapshot: string, values: object, seen: string[]): typeof fetch =>
497 (async (_url: string, init: RequestInit) => {
498 const sent = (init.headers as Record<string, string>)["if-none-match"];
499 seen.push(sent ?? "");
500 if (sent === \`"\${snapshot}"\`) return new Response(null, { status: 304 });
501 return Response.json({ snapshot, values });
502 }) as unknown as typeof fetch;
503
504 test("a flag is its fallback until the forge answers, then the held value", async () => {
505 const seen: string[] = [];
506 const f = new Flags("http://forge/api/v1", "t", "notes", forge("s1", { beta: true }, seen));
507 expect(f.flag<boolean>("beta", false)).toBe(false);
508 expect(await f.refresh()).toBe(true);
509 expect(f.flag<boolean>("beta", false)).toBe(true);
510 expect(f.snapshot).toBe("s1");
511 });
512
513 test("an unchanged snapshot is revalidated, not re-read", async () => {
514 const seen: string[] = [];
515 const f = new Flags("http://forge/api/v1", "t", "notes", forge("s1", { a: 1 }, seen));
516 await f.refresh();
517 expect(await f.refresh()).toBe(false);
518 expect(seen).toEqual(["", '"s1"']);
519 });
520
521 test("no forge, or a forge that is down, leaves the fallbacks", async () => {
522 expect(await new Flags(undefined, undefined, "notes").refresh()).toBe(false);
523 const down = (async () => { throw new Error("away"); }) as unknown as typeof fetch;
524 const f = new Flags("http://forge/api/v1", "t", "notes", down);
525 expect(await f.refresh()).toBe(false);
526 expect(f.flag("x", 3)).toBe(3);
527 });
528
529 test("the slug is the hostname's first label, without a preview number", () => {
530 expect(slugOf("https://notes.apps.example")).toBe("notes");
531 expect(slugOf("https://notes--3.apps.example")).toBe("notes");
532 });
411533 `;
412534
413535 // Identity: the forge's signed headers, or anon.
src/cloud/edge.ts added +182
@@ -0,0 +1,182 @@
1 /**
2 * The edge rung of the cache spectrum (`docs/CACHE.md`): the config store's
3 * snapshots, published where readers need not touch the forge.
4 *
5 * Every snapshot becomes one signed file, `<data>/edge/<name>.json`, served
6 * at the stable URL `/edge/config/<name>.json` (and any CDN in front caches
7 * that URL). Where the forge runs behind Cloudflare, the same bytes are also
8 * written to a KV namespace, so Workers read flags at the edge itself.
9 *
10 * The file is `{ payload, sig }`: `payload` is the snapshot as a JSON
11 * string, `sig` an Ed25519 signature over exactly those bytes, so nothing
12 * between the forge and the reader can alter it. The public key is served at
13 * `/edge/config/key.pem`; the private key lives in the data directory and
14 * never leaves it.
15 *
16 * A stale edge is visible: every forge response carries `X-Forge-Config`,
17 * the id of the snapshot the forge holds, and `isStale` compares it with the
18 * id a reader has.
19 */
20
21 import {
22 createPrivateKey,
23 createPublicKey,
24 generateKeyPairSync,
25 sign,
26 verify,
27 type KeyObject,
28 } from "node:crypto";
29 import {
30 chmodSync,
31 existsSync,
32 mkdirSync,
33 readFileSync,
34 renameSync,
35 writeFileSync,
36 } from "node:fs";
37 import { join } from "node:path";
38 import { id } from "../kernel/id.ts";
39 import type { ConfigValue, Snapshot } from "../core/config.ts";
40
41 export interface KvTarget {
42 readonly account: string;
43 readonly namespace: string;
44 readonly token: string;
45 }
46
47 /** The Cloudflare KV target from the environment, when all three are set. */
48 export function kvFromEnv(env: Record<string, string | undefined>): KvTarget | undefined {
49 const account = (env.FORGE_CF_ACCOUNT ?? "").trim();
50 const namespace = (env.FORGE_CF_KV_NAMESPACE ?? "").trim();
51 const token = (env.FORGE_CF_API_TOKEN ?? "").trim();
52 const safe = /^[0-9a-zA-Z]{1,64}$/;
53 if (!safe.test(account) || !safe.test(namespace) || token === "") return undefined;
54 return { account, namespace, token };
55 }
56
57 /** The file name a scope is published under, or undefined for a bad scope. */
58 export function edgeName(scope: string): string | undefined {
59 if (scope === "forge") return "forge";
60 const m = /^app\/([0-9a-z]{1,40})$/.exec(scope);
61 return m ? `app-${m[1]}` : undefined;
62 }
63
64 export interface EdgeFile {
65 readonly payload: string;
66 readonly sig: string;
67 }
68
69 export interface Published {
70 readonly scope: string;
71 readonly snapshot: string;
72 readonly version: number;
73 readonly values: Record<string, ConfigValue>;
74 readonly at: string;
75 }
76
77 function loadKey(dir: string): { priv: KeyObject; publicPem: string } {
78 const path = join(dir, "signing.pem");
79 if (!existsSync(path)) {
80 mkdirSync(dir, { recursive: true });
81 const { privateKey } = generateKeyPairSync("ed25519");
82 const tmp = join(dir, `signing.${id()}.tmp`);
83 writeFileSync(tmp, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 0o600 });
84 chmodSync(tmp, 0o600);
85 // rename wins the race between two processes booting together
86 if (!existsSync(path)) renameSync(tmp, path);
87 }
88 const priv = createPrivateKey(readFileSync(path));
89 const publicPem = createPublicKey(priv).export({ type: "spki", format: "pem" }).toString();
90 return { priv, publicPem };
91 }
92
93 /** Sign a snapshot into the file the edge serves. */
94 export function signSnapshot(priv: KeyObject, snap: Snapshot): EdgeFile {
95 const published: Published = {
96 scope: snap.scope,
97 snapshot: snap.id,
98 version: snap.version,
99 values: { ...snap.values },
100 at: snap.updatedAt,
101 };
102 const payload = JSON.stringify(published);
103 return { payload, sig: sign(null, Buffer.from(payload), priv).toString("base64") };
104 }
105
106 /** The snapshot a file carries, if its signature holds under `publicPem`. */
107 export function verifyEdgeFile(file: unknown, publicPem: string): Published | undefined {
108 if (typeof file !== "object" || file === null) return undefined;
109 const { payload, sig } = file as Record<string, unknown>;
110 if (typeof payload !== "string" || typeof sig !== "string") return undefined;
111 try {
112 const good = verify(null, Buffer.from(payload), createPublicKey(publicPem), Buffer.from(sig, "base64"));
113 return good ? (JSON.parse(payload) as Published) : undefined;
114 } catch {
115 return undefined;
116 }
117 }
118
119 /**
120 * Whether a reader's copy lags the forge: `seen` is the `X-Forge-Config`
121 * (or snapshot id) it has, `current` what the forge holds now. Nothing seen
122 * is `unknown`, not fresh.
123 */
124 export function isStale(
125 seen: string | null | undefined,
126 current: string,
127 ): "fresh" | "stale" | "unknown" {
128 if (seen === null || seen === undefined || seen === "") return "unknown";
129 return seen === current ? "fresh" : "stale";
130 }
131
132 export class EdgePublisher {
133 readonly dir: string;
134 readonly publicPem: string;
135 private readonly priv: KeyObject;
136
137 constructor(
138 dataDir: string,
139 private readonly options: { kv?: KvTarget | undefined; fetch?: typeof fetch | undefined } = {},
140 ) {
141 this.dir = join(dataDir, "edge");
142 const key = loadKey(this.dir);
143 this.priv = key.priv;
144 this.publicPem = key.publicPem;
145 mkdirSync(join(this.dir, "config"), { recursive: true });
146 writeFileSync(join(this.dir, "config", "key.pem"), this.publicPem);
147 }
148
149 pathOf(scope: string): string | undefined {
150 const name = edgeName(scope);
151 return name === undefined ? undefined : join(this.dir, "config", `${name}.json`);
152 }
153
154 /** Write the signed file (atomically), then KV when configured. */
155 async publish(snap: Snapshot): Promise<void> {
156 const path = this.pathOf(snap.scope);
157 if (path === undefined) return;
158 const body = JSON.stringify(signSnapshot(this.priv, snap));
159 const tmp = `${path}.${id()}.tmp`;
160 writeFileSync(tmp, body);
161 renameSync(tmp, path);
162 const kv = this.options.kv;
163 if (kv === undefined) return;
164 const name = edgeName(snap.scope)!;
165 const url =
166 `https://api.cloudflare.com/client/v4/accounts/${kv.account}` +
167 `/storage/kv/namespaces/${kv.namespace}/values/${name}`;
168 const res = await (this.options.fetch ?? fetch)(url, {
169 method: "PUT",
170 headers: { authorization: `Bearer ${kv.token}`, "content-type": "application/json" },
171 body,
172 });
173 if (!res.ok) throw new Error(`edge kv put ${name}: ${res.status}`);
174 }
175
176 /** The published file for a scope, as text, or undefined when none. */
177 read(scope: string): string | undefined {
178 const path = this.pathOf(scope);
179 if (path === undefined || !existsSync(path)) return undefined;
180 return readFileSync(path, "utf8");
181 }
182 }
src/core/config.ts added +301
@@ -0,0 +1,301 @@
1 /**
2 * The config store — small values read everywhere and changed rarely: flags,
3 * settings, an app's configuration. The middle rung of the cache spectrum
4 * (`docs/CACHE.md`).
5 *
6 * - A scope (`forge`, or `app/<id>`) holds one map of key to JSON value.
7 * One write is one new snapshot: a fresh id, the next version, the whole
8 * map replaced in one row — a reader sees the snapshot before or after,
9 * never half.
10 * - Every process keeps the current snapshot of each scope in memory; a read
11 * is a map lookup. A write wakes this process's store at once through the
12 * bus; another process on the same database notices the changed snapshot
13 * id on its next poll (`start`, half a second), which is the "within a
14 * second" the store promises.
15 * - Writes say who and why, and each lands in `config_change`.
16 *
17 * Values are public by contract: the snapshot is published to the edge
18 * (`cloud/edge.ts`). Secrets belong in `core/secret_store.ts`.
19 */
20
21 import type { Database } from "bun:sqlite";
22 import { id } from "../kernel/id.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import type { EventBus } from "./events.ts";
25 import { noteRung } from "./rungs.ts";
26
27 export type ConfigValue =
28 | string
29 | number
30 | boolean
31 | null
32 | ConfigValue[]
33 | { [k: string]: ConfigValue };
34
35 export interface Snapshot {
36 readonly scope: string;
37 /** Changes with every write; sent as `X-Forge-Config` and as the ETag. */
38 readonly id: string;
39 readonly version: number;
40 readonly values: Readonly<Record<string, ConfigValue>>;
41 readonly updatedAt: string;
42 }
43
44 export type ConfigError =
45 | "invalid_scope"
46 | "invalid_key"
47 | "invalid_value"
48 | "too_large"
49 | "too_many_keys"
50 | "invalid_who"
51 | "invalid_why"
52 | "empty";
53
54 export const FORGE_SCOPE = "forge";
55 export const appScope = (appId: string): string => `app/${appId}`;
56
57 const KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/;
58 const SCOPE = /^(forge|app\/[0-9a-z]{1,40})$/;
59 const MAX_VALUE_BYTES = 4096;
60 const MAX_TOTAL_BYTES = 65536;
61 const MAX_KEYS = 256;
62 const MAX_WHY = 200;
63 const POLL_MS = 500;
64
65 interface Row {
66 scope: string;
67 snapshot: string;
68 version: number;
69 vals: string;
70 updated_at: string;
71 }
72
73 const EMPTY = (scope: string): Snapshot => ({
74 scope,
75 id: "0",
76 version: 0,
77 values: {},
78 updatedAt: "",
79 });
80
81 function toSnapshot(r: Row): Snapshot {
82 return {
83 scope: r.scope,
84 id: r.snapshot,
85 version: r.version,
86 values: JSON.parse(r.vals) as Record<string, ConfigValue>,
87 updatedAt: r.updated_at,
88 };
89 }
90
91 const bytes = (s: string): number => new TextEncoder().encode(s).length;
92
93 /** Whether `v` is plain JSON (no undefined, functions, NaN, cycles). */
94 function isJson(v: unknown, depth = 0): v is ConfigValue {
95 if (depth > 8) return false;
96 if (v === null || typeof v === "string" || typeof v === "boolean") return true;
97 if (typeof v === "number") return Number.isFinite(v);
98 if (Array.isArray(v)) return v.every((x) => isJson(x, depth + 1));
99 if (typeof v === "object")
100 return Object.entries(v).every(([k, x]) => k !== "__proto__" && isJson(x, depth + 1));
101 return false;
102 }
103
104 export class ConfigStore {
105 private readonly held = new Map<string, Snapshot>();
106 private readonly listeners = new Set<(s: Snapshot) => void>();
107 private timer: ReturnType<typeof setInterval> | undefined;
108 private unsubscribe: (() => void) | undefined;
109
110 constructor(
111 private readonly db: Database,
112 private readonly bus?: EventBus,
113 ) {
114 this.unsubscribe = bus?.subscribe((e) => {
115 if (e.kind === "config.set") this.refresh();
116 });
117 }
118
119 /** The current snapshot of a scope: held in memory, loaded on first ask. */
120 snapshot(scope: string): Snapshot {
121 const held = this.held.get(scope);
122 if (held !== undefined) {
123 noteRung("process");
124 return held;
125 }
126 noteRung("process", false);
127 const row = this.db
128 .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1")
129 .get(scope);
130 noteRung("sqlite", row !== null);
131 const snap = row ? toSnapshot(row) : EMPTY(scope);
132 this.held.set(scope, snap);
133 return snap;
134 }
135
136 /** One value: a map lookup. */
137 get(scope: string, key: string): ConfigValue | undefined {
138 return this.snapshot(scope).values[key];
139 }
140
141 /**
142 * Change keys in one write: a value sets, `null` removes. One new snapshot
143 * comes of it, and the change is recorded with `who` and `why`.
144 */
145 set(
146 scope: string,
147 patch: Record<string, unknown>,
148 who: string,
149 why: string,
150 ): Result<Snapshot, ConfigError> {
151 if (!SCOPE.test(scope)) return err("invalid_scope");
152 if (who.trim() === "" || who.length > 80) return err("invalid_who");
153 const reason = why.trim();
154 if (reason === "" || reason.length > MAX_WHY) return err("invalid_why");
155 const entries = Object.entries(patch);
156 if (entries.length === 0) return err("empty");
157 for (const [k, v] of entries) {
158 if (!KEY.test(k)) return err("invalid_key");
159 if (v !== null && !isJson(v)) return err("invalid_value");
160 if (v !== null && bytes(JSON.stringify(v)) > MAX_VALUE_BYTES)
161 return err("too_large");
162 }
163
164 const write = this.db.transaction((): Result<Snapshot, ConfigError> => {
165 const row = this.db
166 .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1")
167 .get(scope);
168 const values: Record<string, ConfigValue> = row
169 ? { ...(JSON.parse(row.vals) as Record<string, ConfigValue>) }
170 : {};
171 for (const [k, v] of entries) {
172 if (v === null) delete values[k];
173 else values[k] = v as ConfigValue;
174 }
175 if (Object.keys(values).length > MAX_KEYS) return err("too_many_keys");
176 const vals = JSON.stringify(values);
177 if (bytes(vals) > MAX_TOTAL_BYTES) return err("too_large");
178 const at = new Date().toISOString();
179 const snapshot = id();
180 const version = (row?.version ?? 0) + 1;
181 this.db
182 .query(
183 `INSERT INTO config (scope, snapshot, version, vals, updated_at)
184 VALUES (?1, ?2, ?3, ?4, ?5)
185 ON CONFLICT (scope) DO UPDATE SET snapshot = excluded.snapshot,
186 version = excluded.version, vals = excluded.vals,
187 updated_at = excluded.updated_at`,
188 )
189 .run(scope, snapshot, version, vals, at);
190 this.db
191 .query(
192 `INSERT INTO config_change (id, scope, snapshot, version, keys, by, why, at)
193 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
194 )
195 .run(id(), scope, snapshot, version, JSON.stringify(entries.map(([k]) => k)), who, reason, at);
196 return ok({ scope, id: snapshot, version, values, updatedAt: at });
197 });
198 // IMMEDIATE: take the write lock before reading, so two processes
199 // changing one scope serialize into consecutive versions.
200 const result = write.immediate();
201 if (!result.ok) return result;
202 this.adopt(result.value);
203 this.bus?.append({
204 kind: "config.set",
205 payload: {
206 scope,
207 snapshot: result.value.id,
208 version: result.value.version,
209 keys: entries.map(([k]) => k),
210 why: reason,
211 },
212 });
213 return result;
214 }
215
216 /** Every scope that has been written, for republishing at boot. */
217 scopes(): string[] {
218 return this.db
219 .query<{ scope: string }, []>("SELECT scope FROM config")
220 .all()
221 .map((r) => r.scope);
222 }
223
224 /** The recent changes to a scope, newest first. */
225 changes(scope: string, limit = 20) {
226 return this.db
227 .query<
228 { snapshot: string; version: number; keys: string; by: string; why: string; at: string },
229 [string, number]
230 >(
231 "SELECT snapshot, version, keys, by, why, at FROM config_change WHERE scope = ?1 ORDER BY version DESC LIMIT ?2",
232 )
233 .all(scope, limit)
234 .map((r) => ({ ...r, keys: JSON.parse(r.keys) as string[] }));
235 }
236
237 /**
238 * Reload every held scope whose stored snapshot id differs from the one
239 * in memory. One indexed read of a handful of short rows; returns how many
240 * scopes changed.
241 */
242 refresh(): number {
243 let changed = 0;
244 const stored = this.db
245 .query<{ scope: string; snapshot: string }, []>(
246 "SELECT scope, snapshot FROM config",
247 )
248 .all();
249 for (const { scope, snapshot } of stored) {
250 const held = this.held.get(scope);
251 if (held?.id === snapshot) continue;
252 const row = this.db
253 .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1")
254 .get(scope);
255 if (!row) continue;
256 noteRung("sqlite");
257 this.adopt(toSnapshot(row));
258 changed++;
259 }
260 return changed;
261 }
262
263 /** Called with each snapshot this process newly holds (edge publication). */
264 onChange(listener: (s: Snapshot) => void): () => void {
265 this.listeners.add(listener);
266 return () => this.listeners.delete(listener);
267 }
268
269 /** Poll for writes made by another process on this database. */
270 start(ms = POLL_MS): void {
271 if (this.timer !== undefined) return;
272 this.timer = setInterval(() => {
273 try {
274 this.refresh();
275 } catch {
276 // A closing database ends the poll; the next boot starts it again.
277 }
278 }, ms);
279 this.timer.unref?.();
280 }
281
282 stop(): void {
283 if (this.timer !== undefined) clearInterval(this.timer);
284 this.timer = undefined;
285 this.unsubscribe?.();
286 this.unsubscribe = undefined;
287 }
288
289 private adopt(snap: Snapshot): void {
290 const held = this.held.get(snap.scope);
291 if (held !== undefined && held.version >= snap.version) return;
292 this.held.set(snap.scope, snap);
293 for (const l of this.listeners) {
294 try {
295 l(snap);
296 } catch {
297 // A failed publication must not undo the write that caused it.
298 }
299 }
300 }
301 }
src/core/reserved.ts +1
@@ -63,6 +63,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6363 "audit.csv",
6464 "big",
6565 "board",
66 "edge",
6667 "events",
6768 "explore",
6869 "fleet",
src/core/rungs.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * The cache spectrum's counter (`docs/CACHE.md`): every answer that comes
3 * from a cache says which rung gave it, so the choice of rung for a kind of
4 * data can be checked against what actually happened. In memory and per
5 * process — a counter is not state worth a write on the hot path; it resets
6 * with the process and `GET /api/v1/cache` reads this process's.
7 */
8
9 export const RUNGS = ["process", "sqlite", "edge", "validator", "git"] as const;
10 export type Rung = (typeof RUNGS)[number];
11
12 export interface RungCount {
13 readonly hit: number;
14 readonly miss: number;
15 }
16
17 const counts = new Map<Rung, { hit: number; miss: number }>(
18 RUNGS.map((r) => [r, { hit: 0, miss: 0 }]),
19 );
20
21 /** One answer from `rung` (`hit`), or one that had to go a rung further (`miss`). */
22 export function noteRung(rung: Rung, hit = true): void {
23 const c = counts.get(rung)!;
24 if (hit) c.hit++;
25 else c.miss++;
26 }
27
28 export function rungCounts(): Record<Rung, RungCount> {
29 return Object.fromEntries(
30 RUNGS.map((r) => [r, { ...counts.get(r)! }]),
31 ) as Record<Rung, RungCount>;
32 }
33
34 export function resetRungs(): void {
35 for (const c of counts.values()) {
36 c.hit = 0;
37 c.miss = 0;
38 }
39 }
src/core/schema.ts +26
@@ -1578,6 +1578,32 @@ export const migrations: readonly string[] = [
15781578 expires_at TEXT NOT NULL
15791579 );
15801580 `,
1581 // 74 — the config store (#1138): small read-mostly values, one row per
1582 // scope holding the whole current snapshot, so a write is one new
1583 // snapshot id and a reader never sees half of it. `config_change` is
1584 // the ledger: who changed which keys, when, and why. A scope is `forge`
1585 // or `app/<id>`; neither row is derived from git, and each costs a
1586 // re-entry of the flags to lose, which `config_change` lists.
1587 `
1588 CREATE TABLE config (
1589 scope TEXT PRIMARY KEY,
1590 snapshot TEXT NOT NULL,
1591 version INTEGER NOT NULL,
1592 vals TEXT NOT NULL,
1593 updated_at TEXT NOT NULL
1594 );
1595 CREATE TABLE config_change (
1596 id TEXT PRIMARY KEY,
1597 scope TEXT NOT NULL,
1598 snapshot TEXT NOT NULL,
1599 version INTEGER NOT NULL,
1600 keys TEXT NOT NULL,
1601 by TEXT NOT NULL,
1602 why TEXT NOT NULL,
1603 at TEXT NOT NULL
1604 );
1605 CREATE INDEX config_change_scope ON config_change(scope, version);
1606 `,
15811607 ];
15821608
15831609 /**
src/http/config.ts added +145
@@ -0,0 +1,145 @@
1 /**
2 * The config store's routes (`core/config.ts`): the forge's own snapshot,
3 * an app's, the published edge files, and the cache counters. A read is the
4 * snapshot id and a map; a write is `{ set: { key: value | null }, why }`.
5 */
6
7 import { getAppById, getAppBySlug } from "../core/apps.ts";
8 import {
9 FORGE_SCOPE,
10 appScope,
11 type ConfigError,
12 type Snapshot,
13 } from "../core/config.ts";
14 import { canAdmin, canRead, getRepoById } from "../core/repos.ts";
15 import { noteRung, rungCounts } from "../core/rungs.ts";
16 import type { Ctx, Handler } from "./context.ts";
17 import type { Router } from "./router.ts";
18 import {
19 apiError,
20 body,
21 cached,
22 forbidden,
23 json,
24 notFound,
25 requireScope,
26 unauthorized,
27 } from "./respond.ts";
28
29 const STATUS: Record<ConfigError, number> = {
30 invalid_scope: 422,
31 invalid_key: 422,
32 invalid_value: 422,
33 too_large: 413,
34 too_many_keys: 422,
35 invalid_who: 422,
36 invalid_why: 422,
37 empty: 422,
38 };
39
40 const shape = (s: Snapshot) => ({
41 snapshot: s.id,
42 version: s.version,
43 values: s.values,
44 updated_at: s.updatedAt,
45 });
46
47 function read(ctx: Ctx, snap: Snapshot, kind: "edge" | "config"): Response {
48 return cached(ctx.request, kind, snap.id, JSON.stringify(shape(snap)), "application/json", {
49 "x-forge-config": snap.id,
50 });
51 }
52
53 async function write(ctx: Ctx, scope: string): Promise<Response> {
54 const input = await body(ctx.request);
55 const set = input.set;
56 if (typeof set !== "object" || set === null || Array.isArray(set))
57 return apiError("invalid_set", 422, "set is an object of key to value (null removes)");
58 const why = typeof input.why === "string" ? input.why : "";
59 const made = ctx.app.configs.set(
60 scope,
61 set as Record<string, unknown>,
62 ctx.auth.user!.username,
63 why,
64 );
65 if (!made.ok) return apiError(made.error, STATUS[made.error], `config refused: ${made.error}`);
66 return json(shape(made.value), 200, { "x-forge-config": made.value.id });
67 }
68
69 /** The app named by the URL, if the caller may read it; its repo with it. */
70 function appFor(ctx: Ctx) {
71 const record = getAppBySlug(ctx.app.db, ctx.params.slug!);
72 const repo = record && getRepoById(ctx.app.db, record.repoId);
73 if (!record || !repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return undefined;
74 return { record, repo };
75 }
76
77 export function configRoutes(router: Router<Handler>): void {
78 // The forge's own flags and settings are public by contract.
79 router.add("GET", "/api/v1/config", (ctx) =>
80 read(ctx, ctx.app.configs.snapshot(FORGE_SCOPE), "edge"),
81 );
82
83 router.add("PATCH", "/api/v1/config", async (ctx) => {
84 const denied = requireScope(ctx, "admin");
85 if (denied) return denied;
86 if (ctx.auth.user!.isAdmin !== true) return forbidden();
87 return write(ctx, FORGE_SCOPE);
88 });
89
90 router.add("GET", "/api/v1/apps/:slug/config", (ctx) => {
91 const found = appFor(ctx);
92 if (!found) return notFound();
93 return read(ctx, ctx.app.configs.snapshot(appScope(found.record.id)), "config");
94 });
95
96 router.add("PATCH", "/api/v1/apps/:slug/config", async (ctx) => {
97 const denied = requireScope(ctx, "admin");
98 if (denied) return denied;
99 const found = appFor(ctx);
100 if (!found) return notFound();
101 if (!canAdmin(ctx.app.db, found.repo, ctx.auth.user)) return forbidden();
102 return write(ctx, appScope(found.record.id));
103 });
104
105 router.add("GET", "/api/v1/cache", (ctx) => {
106 if (!ctx.auth.user) return unauthorized();
107 if (!ctx.auth.user.isAdmin) return notFound();
108 return json(
109 {
110 forge_snapshot: ctx.app.configs.snapshot(FORGE_SCOPE).id,
111 rungs: rungCounts(),
112 },
113 200,
114 { "cache-control": "no-store" },
115 );
116 });
117 }
118
119 /** `/edge/config/<name>.json` and `/edge/config/key.pem`: what the edge serves. */
120 export function edgeRoutes(router: Router<Handler>): void {
121 router.add("GET", "/edge/config/:file", (ctx) => {
122 const file = ctx.params.file!;
123 const edge = ctx.app.edge();
124 if (file === "key.pem")
125 return cached(ctx.request, "edge", "key", edge.publicPem, "application/x-pem-file");
126 const m = /^(forge|app-[0-9a-z]{1,40})\.json$/.exec(file);
127 if (!m) return notFound();
128 const name = m[1]!;
129 let scope = FORGE_SCOPE;
130 if (name !== "forge") {
131 const record = getAppById(ctx.app.db, name.slice(4));
132 const repo = record && getRepoById(ctx.app.db, record.repoId);
133 // Published for anyone only when the app is readable by anyone.
134 if (!record || !repo || !canRead(ctx.app.db, repo, undefined)) return notFound();
135 scope = appScope(record.id);
136 }
137 const text = edge.read(scope);
138 if (text === undefined) return notFound();
139 noteRung("edge");
140 const snapshot = (JSON.parse(JSON.parse(text).payload) as { snapshot: string }).snapshot;
141 return cached(ctx.request, "edge", snapshot, text, "application/json", {
142 "x-forge-config": snapshot,
143 });
144 });
145 }
src/http/respond.ts +83
@@ -7,6 +7,8 @@
77 import { bodyCapFor, readBounded } from "./limits.ts";
88 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
99 import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts";
10 import { noteRung } from "../core/rungs.ts";
11 import type { App } from "../app.ts";
1012 import type { User } from "../core/users.ts";
1113 import { crossOrigin, type Ctx } from "./context.ts";
1214
@@ -281,3 +283,84 @@ export function paged<T>(
281283 items.length >= limit && last !== undefined ? cursorOf(last) : null,
282284 };
283285 }
286
287 /**
288 * What a kind of response may be kept for, by whom (`docs/CACHE.md`). A
289 * route names its kind; it never writes `Cache-Control` itself.
290 *
291 * - `immutable`: content addressed, never changes under its URL.
292 * - `edge`: a published snapshot — any cache may hold it a few seconds,
293 * and serve it stale while it refetches; the ETag is the snapshot id.
294 * - `config`: the same data for a signed-in reader — only that reader's
295 * cache, and revalidated every time (a 304 costs one lookup).
296 * - `fragment`: a rendered piece of a page for one reader, brief.
297 * - `live`: never kept.
298 */
299 export type CacheKind = "immutable" | "edge" | "config" | "fragment" | "live";
300
301 export const CACHE_CONTROL: Readonly<Record<CacheKind, string>> = {
302 immutable: "public, max-age=31536000, immutable",
303 edge: "public, max-age=5, stale-while-revalidate=30",
304 config: "private, no-cache",
305 fragment: "private, max-age=30",
306 live: "no-store",
307 };
308
309 /** The headers a kind sets: `Cache-Control`, and `ETag` when it has a validator. */
310 export function cacheHeaders(
311 kind: CacheKind,
312 etag?: string,
313 ): Record<string, string> {
314 const headers: Record<string, string> = { "cache-control": CACHE_CONTROL[kind] };
315 if (etag !== undefined && kind !== "live") headers.etag = `"${etag}"`;
316 return headers;
317 }
318
319 /** Whether `If-None-Match` already names this validator (or `*`). */
320 export function notModified(request: Request, etag: string): boolean {
321 const sent = request.headers.get("if-none-match");
322 if (sent === null) return false;
323 return sent
324 .split(",")
325 .map((t) => t.trim().replace(/^W\//, ""))
326 .some((t) => t === `"${etag}"` || t === "*");
327 }
328
329 /**
330 * A body of a kind, answered `304` when the reader already holds `etag`.
331 * The one place a conditional response is made; the 304 is counted as a
332 * `validator` hit so the spectrum can be checked against reality.
333 */
334 export function cached(
335 request: Request,
336 kind: CacheKind,
337 etag: string,
338 body: string,
339 contentType = "application/json",
340 extra: Record<string, string> = {},
341 ): Response {
342 const headers = { ...cacheHeaders(kind, etag), ...extra };
343 if (notModified(request, etag)) {
344 noteRung("validator");
345 return new Response(null, { status: 304, headers });
346 }
347 noteRung("validator", false);
348 return new Response(body, {
349 status: 200,
350 headers: { "content-type": contentType, ...headers },
351 });
352 }
353
354 /**
355 * Say which config snapshot this forge holds, on every response: an edge
356 * or an app that cached an older id can see that it lags (`isStale`).
357 */
358 export function stampConfig(response: Response, app: App): Response {
359 try {
360 if (!response.headers.has("x-forge-config"))
361 response.headers.set("x-forge-config", app.configs.snapshot("forge").id);
362 } catch {
363 // A carried, immutable header set keeps what it came with.
364 }
365 return response;
366 }
src/http/server.ts +11 −1
@@ -358,6 +358,7 @@ import { notFoundPage } from "../web/chrome.ts";
358358 import { targetForShortCode } from "../origins/oauth.ts";
359359 import { apiRoutes } from "./api.ts";
360360 import { feedRoutes } from "./feed.ts";
361 import { configRoutes, edgeRoutes } from "./config.ts";
361362 import { mcpRoutes } from "./mcp.ts";
362363 import { oauthRoutes } from "./oauth.ts";
363364 import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts";
@@ -383,6 +384,7 @@ import {
383384 notFound,
384385 prefersHtml,
385386 securityFloor,
387 stampConfig,
386388 } from "./respond.ts";
387389 import { RateLimiter, type Verdict } from "../core/ratelimit.ts";
388390 import {
@@ -504,6 +506,8 @@ const gitChallenge = () =>
504506 export function buildRouter(): Router<Handler> {
505507 const router = new Router<Handler>();
506508
509 edgeRoutes(router);
510
507511 // Literal-prefix routes come before parameterized repo routes; the router
508512 // matches in insertion order. The stylesheet and the highlighter bundle are
509513 // both content-addressed: a stale hash is a 404 rather than a redirect, the
@@ -1122,6 +1126,7 @@ export function buildApiRouter(): Router<Handler> {
11221126 const router = new Router<Handler>();
11231127 apiRoutes(router);
11241128 feedRoutes(router);
1129 configRoutes(router);
11251130 return router;
11261131 }
11271132
@@ -1783,7 +1788,12 @@ async function answer(
17831788 limiter: RateLimiter,
17841789 request: Request,
17851790 ): Promise<Response> {
1786 const response = await answerGet(app, router, apiRouter, limiter, request);
1791 // Every answer the forge writes for itself names the config snapshot it
1792 // holds, so a stale edge or app is visible (`docs/CACHE.md`).
1793 const response = stampConfig(
1794 await answerGet(app, router, apiRouter, limiter, request),
1795 app,
1796 );
17871797 return request.method === "HEAD"
17881798 ? new Response(null, { status: response.status, headers: response.headers })
17891799 : response;
src/main.ts +7
@@ -167,6 +167,13 @@ await reconcile(app);
167167 // Issues linked under a pillar's umbrella before pillars had labels.
168168 const labelled = syncAllPillars(app);
169169 if (labelled > 0) app.log.info("pillars labelled", { issues: labelled });
170 // Config snapshots: poll for another process's writes, and publish what is
171 // held now so the edge file exists from the first request.
172 app.configs.start();
173 for (const scope of app.configs.scopes())
174 await app.edge().publish(app.configs.snapshot(scope)).catch((error) =>
175 app.log.warn("edge publish failed", { scope, error: String(error) }),
176 );
170177 const servers = await serve(app);
171178 const sshStarted =
172179 sshPort > 0 ? await startForgeSsh(app, { port: sshPort }) : undefined;
test/config-store.test.ts added +296
@@ -0,0 +1,296 @@
1 /**
2 * The config store and the edge rung (#1138): one write is one snapshot,
3 * another process sees it within a second, the signed edge file carries the
4 * new id, a stale id is detected, and each kind of response sets the headers
5 * `docs/CACHE.md` says.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { Database } from "bun:sqlite";
10 import { existsSync, readFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { newApp } from "../src/actions/apps.ts";
16 import { ConfigStore, FORGE_SCOPE, appScope } from "../src/core/config.ts";
17 import { noteRung, rungCounts, resetRungs } from "../src/core/rungs.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import {
21 EdgePublisher,
22 edgeName,
23 isStale,
24 kvFromEnv,
25 verifyEdgeFile,
26 } from "../src/cloud/edge.ts";
27 import {
28 CACHE_CONTROL,
29 cacheHeaders,
30 cached,
31 type CacheKind,
32 } from "../src/http/respond.ts";
33 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
34
35 async function admin(app: App, username: string): Promise<User> {
36 const made = await createUser(app.db, {
37 trusted: true,
38 username,
39 email: `${username}@forge.local`,
40 password: "a-good-passphrase",
41 adminIfFirst: true,
42 });
43 if (!made.ok) throw new Error(made.error);
44 return made.value;
45 }
46
47 describe("config store", () => {
48 let dir: string;
49 let app: App;
50 beforeAll(async () => {
51 dir = await mkdtemp(join(tmpdir(), "forge-config-"));
52 app = createApp({ dataDir: dir, port: 0 });
53 });
54 afterAll(async () => {
55 app.close();
56 await rm(dir, { recursive: true, force: true });
57 });
58
59 test("one write is one new snapshot; null removes; reads are the held map", () => {
60 const a = app.configs.set(FORGE_SCOPE, { "flag.new-ui": true, motd: "hi" }, "alice", "try it");
61 expect(a.ok).toBe(true);
62 if (!a.ok) return;
63 expect(a.value.version).toBe(1);
64 expect(app.configs.get(FORGE_SCOPE, "flag.new-ui")).toBe(true);
65 const b = app.configs.set(FORGE_SCOPE, { motd: null }, "alice", "drop motd");
66 if (!b.ok) throw new Error(b.error);
67 expect(b.value.id).not.toBe(a.value.id);
68 expect(b.value.version).toBe(2);
69 expect(app.configs.get(FORGE_SCOPE, "motd")).toBeUndefined();
70 expect(app.configs.snapshot(FORGE_SCOPE).id).toBe(b.value.id);
71 });
72
73 test("a write says who and why, and the ledger keeps both", () => {
74 const changes = app.configs.changes(FORGE_SCOPE);
75 expect(changes[0]).toMatchObject({ by: "alice", why: "drop motd", keys: ["motd"], version: 2 });
76 expect(app.configs.set(FORGE_SCOPE, { x: 1 }, "alice", " ").ok).toBe(false);
77 expect(app.configs.set(FORGE_SCOPE, { x: 1 }, "", "why").ok).toBe(false);
78 });
79
80 test("input is validated at the boundary", () => {
81 const err = (patch: Record<string, unknown>, scope = FORGE_SCOPE) => {
82 const r = app.configs.set(scope, patch, "a", "w");
83 return r.ok ? "ok" : r.error;
84 };
85 expect(err({ "Bad Key": 1 })).toBe("invalid_key");
86 expect(err({ "": 1 })).toBe("invalid_key");
87 expect(err({ k: undefined })).toBe("invalid_value");
88 expect(err({ k: Number.NaN })).toBe("invalid_value");
89 expect(err({ k: "x".repeat(5000) })).toBe("too_large");
90 expect(err({})).toBe("empty");
91 expect(err({ k: 1 }, "nope")).toBe("invalid_scope");
92 expect(err({ k: 1 }, "app/../x")).toBe("invalid_scope");
93 });
94
95 test("a write is visible to a second process within a second", async () => {
96 // A second process is a second connection and a second store on the same file.
97 const other = new ConfigStore(new Database(join(dir, "forge.db")));
98 other.start();
99 try {
100 expect(other.get(FORGE_SCOPE, "seen")).toBeUndefined();
101 const wrote = app.configs.set(FORGE_SCOPE, { seen: "yes" }, "alice", "cross-process");
102 if (!wrote.ok) throw new Error(wrote.error);
103 const t0 = Date.now();
104 while (other.snapshot(FORGE_SCOPE).id !== wrote.value.id && Date.now() - t0 < 1000)
105 await Bun.sleep(25);
106 expect(other.snapshot(FORGE_SCOPE).id).toBe(wrote.value.id);
107 expect(other.get(FORGE_SCOPE, "seen")).toBe("yes");
108 expect(Date.now() - t0).toBeLessThan(1000);
109 } finally {
110 other.stop();
111 }
112 });
113
114 test("the edge file carries the new id after a write, signed", async () => {
115 const wrote = app.configs.set(FORGE_SCOPE, { edge: 1 }, "alice", "publish");
116 if (!wrote.ok) throw new Error(wrote.error);
117 const text = app.edge().read(FORGE_SCOPE)!;
118 const file = JSON.parse(text);
119 const published = verifyEdgeFile(file, app.edge().publicPem)!;
120 expect(published.snapshot).toBe(wrote.value.id);
121 expect(published.values.edge).toBe(1);
122 // altered bytes do not verify
123 const forged = { ...file, payload: file.payload.replace('"edge":1', '"edge":2') };
124 expect(verifyEdgeFile(forged, app.edge().publicPem)).toBeUndefined();
125 // the private key stays in the data directory and is not world readable
126 expect(existsSync(join(dir, "edge", "signing.pem"))).toBe(true);
127 });
128
129 test("a stale id is detected", () => {
130 const current = app.configs.snapshot(FORGE_SCOPE).id;
131 expect(isStale(current, current)).toBe("fresh");
132 expect(isStale("older", current)).toBe("stale");
133 expect(isStale(null, current)).toBe("unknown");
134 expect(edgeName("forge")).toBe("forge");
135 expect(edgeName("app/abc")).toBe("app-abc");
136 expect(edgeName("../x")).toBeUndefined();
137 });
138
139 test("Cloudflare KV gets the same bytes as the file when configured", async () => {
140 const calls: { url: string; init: RequestInit }[] = [];
141 const fake = (async (url: string, init: RequestInit) => {
142 calls.push({ url, init });
143 return new Response("{}", { status: 200 });
144 }) as unknown as typeof fetch;
145 const kv = kvFromEnv({ FORGE_CF_ACCOUNT: "acct1", FORGE_CF_KV_NAMESPACE: "ns1", FORGE_CF_API_TOKEN: "t" });
146 expect(kvFromEnv({ FORGE_CF_ACCOUNT: "a/../b" })).toBeUndefined();
147 const edge = new EdgePublisher(dir, { kv, fetch: fake });
148 await edge.publish(app.configs.snapshot(FORGE_SCOPE));
149 expect(calls).toHaveLength(1);
150 expect(calls[0]!.url).toBe(
151 "https://api.cloudflare.com/client/v4/accounts/acct1/storage/kv/namespaces/ns1/values/forge",
152 );
153 expect(calls[0]!.init.body).toBe(edge.read(FORGE_SCOPE));
154 });
155 });
156
157 describe("cache headers, one helper per kind", () => {
158 test("each kind sets what the table in docs/CACHE.md says", () => {
159 const table: Record<CacheKind, string> = {
160 immutable: "public, max-age=31536000, immutable",
161 edge: "public, max-age=5, stale-while-revalidate=30",
162 config: "private, no-cache",
163 fragment: "private, max-age=30",
164 live: "no-store",
165 };
166 for (const [kind, value] of Object.entries(table)) {
167 expect(CACHE_CONTROL[kind as CacheKind]).toBe(value);
168 expect(cacheHeaders(kind as CacheKind)["cache-control"]).toBe(value);
169 }
170 expect(cacheHeaders("edge", "abc").etag).toBe('"abc"');
171 expect(cacheHeaders("live", "abc").etag).toBeUndefined();
172 const docs = readFileSync(join(import.meta.dir, "..", "docs", "CACHE.md"), "utf8");
173 for (const value of Object.values(table)) expect(docs).toContain(value);
174 });
175
176 test("a matching If-None-Match is a 304, counted as a validator hit", async () => {
177 resetRungs();
178 const url = "http://x/y";
179 const fresh = cached(new Request(url), "config", "s1", "{}");
180 expect(fresh.status).toBe(200);
181 const again = cached(new Request(url, { headers: { "if-none-match": '"s1"' } }), "config", "s1", "{}");
182 expect(again.status).toBe(304);
183 expect(await again.text()).toBe("");
184 expect(rungCounts().validator).toEqual({ hit: 1, miss: 1 });
185 noteRung("edge");
186 expect(rungCounts().edge.hit).toBe(1);
187 });
188 });
189
190 describe("config over HTTP", () => {
191 let dir: string;
192 let app: App;
193 let http: ForgeHttp;
194 let token: string;
195 let ro: string;
196 let slug: string;
197
198 beforeAll(async () => {
199 dir = await mkdtemp(join(tmpdir(), "forge-config-http-"));
200 app = createApp({ dataDir: dir, port: 0 });
201 http = forgeHttp(app);
202 const alice = await admin(app, "alice");
203 token = createToken(app.db, alice.id, "admin", "admin").token;
204 ro = createToken(app.db, alice.id, "ro", "ro").token;
205 const made = await newApp(app, alice, { name: "flags", description: "d", visibility: "public" });
206 if (!made.ok) throw new Error(String(made.error));
207 slug = made.value.app.slug;
208 });
209 afterAll(async () => {
210 app.close();
211 await rm(dir, { recursive: true, force: true });
212 });
213
214 const call = (path: string, init: RequestInit = {}, bearer?: string) =>
215 http.handle(new Request(`http://forge.test${path}`, {
216 ...init,
217 headers: {
218 ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
219 "content-type": "application/json",
220 ...(init.headers as Record<string, string> | undefined),
221 },
222 }));
223 const patch = (path: string, body: unknown, bearer?: string) =>
224 call(path, { method: "PATCH", body: JSON.stringify(body) }, bearer);
225
226 test("an app reads its config with the snapshot id, and revalidates with it", async () => {
227 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 }, why: "x" })).status).toBe(401);
228 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 }, why: "x" }, ro)).status).toBe(403);
229 const w = await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1, theme: "dark" }, why: "launch" }, token);
230 expect(w.status).toBe(200);
231 const wrote = (await w.json()) as { snapshot: string };
232 const r = await call(`/api/v1/apps/${slug}/config`, {}, ro);
233 expect(r.status).toBe(200);
234 const read = (await r.json()) as { snapshot: string; values: Record<string, unknown> };
235 expect(read.snapshot).toBe(wrote.snapshot);
236 expect(read.values).toEqual({ a: 1, theme: "dark" });
237 expect(r.headers.get("etag")).toBe(`"${wrote.snapshot}"`);
238 expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.config);
239 const again = await call(`/api/v1/apps/${slug}/config`, { headers: { "if-none-match": `"${wrote.snapshot}"` } }, ro);
240 expect(again.status).toBe(304);
241 });
242
243 test("a bad write is a 422 and an unknown app a 404", async () => {
244 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { "Bad": 1 }, why: "x" }, token)).status).toBe(422);
245 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 } }, token)).status).toBe(422);
246 expect((await call(`/api/v1/apps/nope/config`, {}, ro)).status).toBe(404);
247 });
248
249 test("the forge's flags are readable by anyone and written only by an admin token", async () => {
250 expect((await patch("/api/v1/config", { set: { f: true }, why: "w" }, ro)).status).toBe(403);
251 const w = await patch("/api/v1/config", { set: { f: true }, why: "w" }, token);
252 expect(w.status).toBe(200);
253 const r = await call("/api/v1/config");
254 expect(((await r.json()) as { values: Record<string, unknown> }).values.f).toBe(true);
255 expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.edge);
256 });
257
258 test("every response names the snapshot the forge holds", async () => {
259 const id = app.configs.snapshot(FORGE_SCOPE).id;
260 for (const path of ["/healthz", "/api/v1/config", "/nowhere-at-all"]) {
261 const r = await call(path, { headers: { accept: "application/json" } });
262 expect(r.headers.get("x-forge-config")).toBe(id);
263 }
264 });
265
266 test("the edge serves the signed file at a stable URL; a lagging copy is visible", async () => {
267 const r = await call("/edge/config/forge.json");
268 expect(r.status).toBe(200);
269 expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.edge);
270 const key = await (await call("/edge/config/key.pem")).text();
271 const published = verifyEdgeFile(await r.json(), key)!;
272 const id = app.configs.snapshot(FORGE_SCOPE).id;
273 expect(published.snapshot).toBe(id);
274 // a public app's file is served, under its id
275 const scope = appScope(
276 (await import("../src/core/apps.ts")).getAppBySlug(app.db, slug)!.id,
277 );
278 const name = edgeName(scope)!;
279 const mine = await call(`/edge/config/${name}.json`);
280 expect(mine.status).toBe(200);
281 expect(verifyEdgeFile(await mine.json(), key)!.scope).toBe(scope);
282 // the write moves the id; the copy held before it now reads stale
283 const w = await patch("/api/v1/config", { set: { g: 2 }, why: "move" }, token);
284 const next = ((await w.json()) as { snapshot: string }).snapshot;
285 expect(isStale(published.snapshot, next)).toBe("stale");
286 expect((await call("/edge/config/..%2fsigning.pem")).status).toBe(404);
287 expect((await call("/edge/config/app-nope.json")).status).toBe(404);
288 });
289
290 test("the cache counters are an admin's to read", async () => {
291 expect((await call("/api/v1/cache")).status).toBe(401);
292 const r = await call("/api/v1/cache", {}, token);
293 const body = (await r.json()) as { rungs: Record<string, { hit: number }> };
294 expect(body.rungs.process!.hit).toBeGreaterThan(0);
295 });
296 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs