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 #16824
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/1138-the-cache-spectrum-chosen-on-purpose-in → main 0 commits fork
40 files
changed +1625
−4
- docs/CACHE.md
- docs/REFERENCE.md
- docs/features/config.md
- forge.json
- src/actions/repos.ts
- src/app.ts
- src/cloud/edge.ts
- src/cloud/edge_open.ts
- src/contract/openapi/routes/getApiV1AppsSlugConfig.ts
- src/contract/openapi/routes/getApiV1Cache.ts
- src/contract/openapi/routes/getApiV1Config.ts
- src/contract/openapi/routes/getEdgeConfigFile.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/patchApiV1AppsSlugConfig.ts
- src/contract/openapi/routes/patchApiV1Config.ts
- src/contract/tags.ts
- src/core/account_purge.ts
- src/core/config.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261130140000-config-store.pin
- src/core/migrations/20261130140000-config-store.ts
- src/core/reserved.ts
- src/core/rungs.ts
- src/http/config.ts
- src/http/marks/api-v1-cache.json
- src/http/marks/api-v1-config.json
- src/http/marks/edge.json
- src/http/respond.ts
- src/http/server.ts
- src/main.ts
- src/view/doc_sections.ts
- test/config-store.test.ts
- test/data-browser.test.ts
- test/docs-not-found.test.ts
- test/job-slices.test.ts
- test/no-polling.test.ts
- test/openapi-drift.test.ts
- test/openapi.test.ts
- test/pages-budget.test.ts
- test/security-floor-routes.test.ts
docs/CACHE.md added +73
| @@ -0,0 +1,73 @@ | ||
| 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 | content-addressed assets; `web/asset.ts` keeps its own literal header of the same value | | |
| 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 | | `live` | `no-store` | never | anything that must not be kept | | |
| 39 | ||
| 40 | Routes that predate the helper still set their own headers | |
| 41 | (`web/pages/*`, `apps/proxy.ts`); they move to a kind as they are touched. | |
| 42 | ||
| 43 | ## The edge rung | |
| 44 | ||
| 45 | Every write produces one snapshot id. Each process that learns of it | |
| 46 | publishes `<data>/edge/config/<name>.json`, an Ed25519-signed | |
| 47 | `{ payload, sig }`, served at `/edge/config/<name>.json` (`forge`, or | |
| 48 | `app-<id>` for an app whose repository anyone can read). The public key is | |
| 49 | at `/edge/config/key.pem`. With `FORGE_CF_ACCOUNT`, `FORGE_CF_KV_NAMESPACE` | |
| 50 | and `FORGE_CF_API_TOKEN` set, the same bytes are also `PUT` to that KV | |
| 51 | namespace under the same name, so a Worker reads flags without the forge. | |
| 52 | ||
| 53 | **A stale edge is visible.** Every response carries `X-Forge-Config`, the id | |
| 54 | of the snapshot this forge holds; compare it with the `snapshot` in the file | |
| 55 | you have. | |
| 56 | ||
| 57 | ## Apps | |
| 58 | ||
| 59 | `GET /api/v1/apps/:slug/config` (any credential that can read the app, so | |
| 60 | the read-only token an app starts with) returns | |
| 61 | `{ snapshot, version, values, updated_at }` with the id as `ETag`; send it | |
| 62 | back as `If-None-Match` for a `304`. `PATCH` with `{ "set": { key: value | | |
| 63 | null }, "why": "…" }` needs an admin token and repository admin. The edge | |
| 64 | file of a public app is the same data without the forge. | |
| 65 | ||
| 66 | The MCP tools and the terminal door are not built yet (the change carries a `No door:` line); an app's client is in `docs/features/config.md`. | |
| 67 | ||
| 68 | ## Checking the choice | |
| 69 | ||
| 70 | `GET /api/v1/cache` (admin) returns this process's hit/miss counts per rung: | |
| 71 | `process` (snapshot already held), `sqlite` (loaded or refreshed), `edge` | |
| 72 | (published file served), `validator` (`304`s). The counters are in memory | |
| 73 | and reset with the process. |
docs/REFERENCE.md +1
| @@ -515,6 +515,7 @@ Once a minute the forge measures its landing rate, names the one cause binding i | ||
| 515 | 515 | - [](REFERENCE.md): this page. |
| 516 | 516 | - The guide, in order: [](guide-what-a-forge-is.md), [](guide-first-app.md), [](guide-tell-the-crew.md), [](guide-ship-and-undo.md), [](guide-your-apps.md), [](guide-hosting.md), [](guide-own-ai.md), [](guide-agents.md), [](guide-backups-moving.md), [](guide-settings.md), [](guide-when-wrong.md). |
| 517 | 517 | - [](DATASET.md): the forge's dataset, one JSONL file per table, every field named. |
| 518 | - [](CACHE.md): the cache spectrum, which rung each kind of data sits on, and the config store. | |
| 518 | 519 | - [](WRITING.md): how to write documentation for the forge. |
| 519 | 520 | - [](DEVELOP.md) — developing the forge: tests, checks, the gate, lint and types. |
| 520 | 521 | - [](DEPENDENCIES.md) — every package in `package.json` and why it is there; the gate refuses a new one without its line. |
docs/features/config.md added +96
| @@ -0,0 +1,96 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Flags and settings: a versioned config store read from memory, published to the edge, offered to apps | |
| 4 | --- | |
| 5 | # Flags and settings (the config store) | |
| 6 | ||
| 7 | Small values that are read everywhere and change rarely live in the config store, not in code or | |
| 8 | the database (the whole spectrum is in `docs/CACHE.md`). One write makes one new snapshot id; every | |
| 9 | forge process holds the current snapshot in memory, so a read is a map lookup. | |
| 10 | ||
| 11 | - **The forge's own:** `GET /api/v1/config` (anyone), `PATCH /api/v1/config` (an admin token). | |
| 12 | - **An app's:** `GET /api/v1/apps/:slug/config` with the app's read-only forge token; `PATCH` | |
| 13 | needs an admin token and repository admin. Send the snapshot id back as `If-None-Match` for a `304`. | |
| 14 | - **A write says why:** `{ "set": { "beta": true, "old": null }, "why": "ship to everyone" }`; `null` | |
| 15 | removes a key. Add `?changes=1` to a read for the ledger of who changed what and why. | |
| 16 | - **The edge:** every write publishes a signed file at `/edge/config/<name>` (and to Cloudflare KV | |
| 17 | when `FORGE_CF_*` is set). Every response carries `X-Forge-Config`, the snapshot id held, so a | |
| 18 | stale copy is visible: compare it with the `snapshot` in the file. | |
| 19 | - **Which rung served:** an admin reads `GET /api/v1/cache` for hits and misses per rung. | |
| 20 | ||
| 21 | Values are public: no secrets. In an app, a client like this keeps the snapshot in memory and | |
| 22 | revalidates it with the id (`src/flags.ts`): | |
| 23 | ||
| 24 | ts | |
| 25 | /** | |
| 26 | * Flags and settings from the forge's config store (`GET | |
| 27 | * /api/v1/apps/<slug>/config`). The current snapshot is held in memory, so | |
| 28 | * `flag()` is a map lookup that never waits on the network; `refresh()` | |
| 29 | * revalidates with the snapshot id as the ETag (a 304 costs the forge one | |
| 30 | * lookup), and `start()` does it every few seconds. Values are public by | |
| 31 | * contract: no secrets here. Change them with `PATCH` and a `why`. | |
| 32 | * Without a forge to ask, every flag is its fallback. | |
| 33 | */ | |
| 34 | ||
| 35 | import { forgeApiUrl, forgeToken, publicOrigin } from "./env.ts"; | |
| 36 | ||
| 37 | export type FlagValue = string | number | boolean | null | FlagValue[] | { [k: string]: FlagValue }; | |
| 38 | ||
| 39 | /** `<slug>.<domain>` or `<slug>--<n>.<domain>`: the app's slug. */ | |
| 40 | export function slugOf(origin: string): string { | |
| 41 | return new URL(origin).hostname.split(".")[0]!.split("--")[0]!; | |
| 42 | } | |
| 43 | ||
| 44 | export class Flags { | |
| 45 | /** The id of the snapshot held; changes with every write. `"0"` before the first answer. */ | |
| 46 | snapshot = "0"; | |
| 47 | private values: Record<string, FlagValue> = {}; | |
| 48 | private timer: ReturnType<typeof setInterval> | undefined; | |
| 49 | ||
| 50 | constructor( | |
| 51 | private readonly url: string | undefined, | |
| 52 | private readonly token: string | undefined, | |
| 53 | private readonly slug: string, | |
| 54 | private readonly fetcher: typeof fetch = fetch, | |
| 55 | ) {} | |
| 56 | ||
| 57 | flag<T extends FlagValue>(name: string, fallback: T): T { | |
| 58 | const value = this.values[name]; | |
| 59 | return value === undefined ? fallback : (value as T); | |
| 60 | } | |
| 61 | ||
| 62 | /** Ask the forge whether the snapshot moved; true when this call changed it. */ | |
| 63 | async refresh(): Promise<boolean> { | |
| 64 | if (this.url === undefined || this.token === undefined) return false; | |
| 65 | try { | |
| 66 | const res = await this.fetcher(`${this.url}/apps/${this.slug}/config`, { | |
| 67 | headers: { | |
| 68 | authorization: `Bearer ${this.token}`, | |
| 69 | ...(this.snapshot === "0" ? {} : { "if-none-match": `"${this.snapshot}"` }), | |
| 70 | }, | |
| 71 | }); | |
| 72 | if (res.status !== 200) return false; | |
| 73 | const body = (await res.json()) as { snapshot?: unknown; values?: unknown }; | |
| 74 | if (typeof body.snapshot !== "string" || typeof body.values !== "object" || body.values === null) | |
| 75 | return false; | |
| 76 | this.values = body.values as Record<string, FlagValue>; | |
| 77 | this.snapshot = body.snapshot; | |
| 78 | return true; | |
| 79 | } catch { | |
| 80 | // The forge being away keeps the last snapshot; flags are never a reason to fail a request. | |
| 81 | return false; | |
| 82 | } | |
| 83 | } | |
| 84 | ||
| 85 | start(ms = 5000): void { | |
| 86 | if (this.timer !== undefined) return; | |
| 87 | void this.refresh(); | |
| 88 | this.timer = setInterval(() => void this.refresh(), ms); | |
| 89 | this.timer.unref?.(); | |
| 90 | } | |
| 91 | } | |
| 92 | ||
| 93 | export const flags = new Flags(forgeApiUrl, forgeToken, slugOf(publicOrigin)); | |
| 94 | ||
| 95 | ||
| 96 | Door: API only so far; the terminal and MCP doors are not built yet. `?changes=1` (who changed what, and why) is for an admin of the scope; anyone else gets the plain read. A private app's config is never published to the edge file or KV, and is taken down when the app goes private. |
forge.json +1
src/actions/repos.ts +3
| @@ -19,6 +19,7 @@ import { requireAbility } from "./roles.ts"; | ||
| 19 | 19 | import type { App } from "../app.ts"; |
| 20 | 20 | import { appsRuntime } from "../apps/runtime.ts"; |
| 21 | 21 | import { getAppByRepo } from "../core/apps.ts"; |
| 22 | import { syncEdge } from "../cloud/edge_open.ts"; | |
| 22 | 23 | import { canSeeSealed } from "../core/sealed.ts"; |
| 23 | 24 | import { capacityValue } from "../core/capacity.ts"; |
| 24 | 25 | import { NEW_FOR_MS } from "./accounts.ts"; |
| @@ -496,6 +497,8 @@ export async function updateRepoSettings( | ||
| 496 | 497 | } |
| 497 | 498 | const { archived, ...rest } = settings; |
| 498 | 499 | writeSettings(app.db, repo, rest); |
| 500 | // An app's config is on the edge only while its repository is public. | |
| 501 | if (settings.visibility !== undefined && settings.visibility !== repo.visibility) syncEdge(app, repo.id); | |
| 499 | 502 | // A bundle sits in a publicly readable bucket: a repository that stops being public takes it back |
| 500 | 503 | // (#14409). |
| 501 | 504 | if (repo.visibility === "public" && settings.visibility === "private") await retractBundles(app, repo); |
src/app.ts +23 −1
| @@ -19,6 +19,9 @@ import { existsSync, mkdirSync } from "node:fs"; | ||
| 19 | 19 | import { join, resolve } from "node:path"; |
| 20 | 20 | import { migrationFiles } from "./core/schema.ts"; |
| 21 | 21 | import { dropLegacyNewAccountGuards } from "./core/schema.ts"; |
| 22 | import { ConfigStore } from "./core/config.ts"; | |
| 23 | import { EdgePublisher, kvFromEnv } from "./cloud/edge.ts"; | |
| 24 | import { edgeOpen } from "./cloud/edge_open.ts"; | |
| 22 | 25 | import { EventBus } from "./core/events.ts"; |
| 23 | 26 | import { follow } from "./core/following.ts"; |
| 24 | 27 | import { enqueueForEvent } from "./core/webhooks.ts"; |
| @@ -264,6 +267,10 @@ export interface App { | ||
| 264 | 267 | readonly config: ForgeConfig; |
| 265 | 268 | readonly db: Database; |
| 266 | 269 | readonly bus: EventBus; |
| 270 | /** Small read-mostly values, held in memory (`core/config.ts`). */ | |
| 271 | readonly configs: ConfigStore; | |
| 272 | /** Where config snapshots are published for the edge (`cloud/edge.ts`); made on first use. */ | |
| 273 | edge(): EdgePublisher; | |
| 267 | 274 | readonly log: Log; |
| 268 | 275 | readonly reposRoot: string; |
| 269 | 276 | readonly socketPath: string; |
| @@ -336,11 +343,25 @@ export function createApp(config: ForgeConfig): App { | ||
| 336 | 343 | |
| 337 | 344 | const owner = id(); |
| 338 | 345 | const errors = forgeErrorLedger(owner); |
| 346 | const log = createLog("forge", owner); | |
| 347 | const configs = new ConfigStore(db, bus); | |
| 348 | let publisher: EdgePublisher | undefined; | |
| 349 | const edge = (): EdgePublisher => | |
| 350 | (publisher ??= new EdgePublisher(dataDir, { kv: kvFromEnv(process.env) })); | |
| 351 | // A snapshot this process newly holds is published within the same tick | |
| 352 | // (the file) and the next round trip (KV). | |
| 353 | configs.onChange((snap) => { | |
| 354 | edge() | |
| 355 | .publish(snap, edgeOpen(db, snap.scope)) | |
| 356 | .catch((error) => log.error("edge publish failed", { error: String(error) })); | |
| 357 | }); | |
| 339 | 358 | const app: App = { |
| 340 | 359 | config: { ...config, dataDir }, |
| 341 | 360 | db, |
| 342 | 361 | bus, |
| 343 | log: createLog("forge", owner), | |
| 362 | configs, | |
| 363 | edge, | |
| 364 | log, | |
| 344 | 365 | signals: { errors, refused: new RefusedLedger() }, |
| 345 | 366 | reposRoot, |
| 346 | 367 | // This process's own: two forges share a data directory for the length |
| @@ -356,6 +377,7 @@ export function createApp(config: ForgeConfig): App { | ||
| 356 | 377 | // otherwise. One data dir is one forge, so closing the forge is where |
| 357 | 378 | // that is said. |
| 358 | 379 | releaseErrorLedger(errors); |
| 380 | configs.stop(); | |
| 359 | 381 | closeReadersUnder(reposRoot); |
| 360 | 382 | db.close(); |
| 361 | 383 | }, |
src/cloud/edge.ts added +231
| @@ -0,0 +1,231 @@ | ||
| 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 a reader that kept an older id | |
| 18 | * can see that it lags. | |
| 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 { basename, 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 | /** What a KV call may take before it is given up on. */ | |
| 120 | const KV_TIMEOUT_MS = 5000; | |
| 121 | ||
| 122 | export class EdgePublisher { | |
| 123 | readonly dir: string; | |
| 124 | readonly publicPem: string; | |
| 125 | private readonly priv: KeyObject; | |
| 126 | /** The file text and snapshot id per scope, so a request never touches the disk. */ | |
| 127 | private readonly held = new Map<string, { text: string; snapshot: string; version: number }>(); | |
| 128 | /** The newest version published per scope; an older snapshot is skipped. */ | |
| 129 | private readonly newest = new Map<string, number>(); | |
| 130 | /** KV calls per scope run one after another, so none lands out of order. */ | |
| 131 | private readonly lane = new Map<string, Promise<void>>(); | |
| 132 | ||
| 133 | constructor( | |
| 134 | dataDir: string, | |
| 135 | private readonly options: { kv?: KvTarget | undefined; fetch?: typeof fetch | undefined } = {}, | |
| 136 | ) { | |
| 137 | this.dir = join(dataDir, "edge"); | |
| 138 | const key = loadKey(this.dir); | |
| 139 | this.priv = key.priv; | |
| 140 | this.publicPem = key.publicPem; | |
| 141 | mkdirSync(join(this.dir, "config"), { recursive: true }); | |
| 142 | writeFileSync(join(this.dir, "config", "key.pem"), this.publicPem); | |
| 143 | } | |
| 144 | ||
| 145 | pathOf(scope: string): string | undefined { | |
| 146 | const name = edgeName(scope); | |
| 147 | return name === undefined ? undefined : join(this.dir, "config", `${name}.json`); | |
| 148 | } | |
| 149 | ||
| 150 | /** | |
| 151 | * Write the signed file (atomically), then KV when configured. A scope | |
| 152 | * that is not `open` (a private app's) is taken down instead: never a file, | |
| 153 | * never a KV key. | |
| 154 | */ | |
| 155 | async publish(snap: Snapshot, open = true): Promise<void> { | |
| 156 | if (!open) return this.remove(snap.scope); | |
| 157 | const path = this.pathOf(snap.scope); | |
| 158 | if (path === undefined) return; | |
| 159 | if (snap.version < (this.newest.get(snap.scope) ?? 0)) return; | |
| 160 | this.newest.set(snap.scope, snap.version); | |
| 161 | const body = JSON.stringify(signSnapshot(this.priv, snap)); | |
| 162 | const tmp = `${path}.${id()}.tmp`; | |
| 163 | writeFileSync(tmp, body); | |
| 164 | renameSync(tmp, path); | |
| 165 | this.held.set(snap.scope, { text: body, snapshot: snap.id, version: snap.version }); | |
| 166 | await this.kv(snap.scope, "PUT", body, snap.version); | |
| 167 | } | |
| 168 | ||
| 169 | /** Take a scope's file out of service and its KV key away, if it has them. */ | |
| 170 | async remove(scope: string): Promise<void> { | |
| 171 | const path = this.pathOf(scope); | |
| 172 | if (path === undefined) return; | |
| 173 | this.held.delete(scope); | |
| 174 | this.newest.delete(scope); | |
| 175 | // Moved out of the served directory, not deleted: nothing here removes | |
| 176 | // data (the forge never deletes on a webhook's path), and the next write | |
| 177 | // of the same scope replaces it. | |
| 178 | if (existsSync(path)) { | |
| 179 | mkdirSync(join(this.dir, "withdrawn"), { recursive: true }); | |
| 180 | renameSync(path, join(this.dir, "withdrawn", basename(path))); | |
| 181 | } | |
| 182 | await this.kv(scope, "DELETE"); | |
| 183 | } | |
| 184 | ||
| 185 | private kv(scope: string, method: "PUT" | "DELETE", body?: string, version?: number): Promise<void> { | |
| 186 | const kv = this.options.kv; | |
| 187 | if (kv === undefined) return Promise.resolve(); | |
| 188 | const name = edgeName(scope)!; | |
| 189 | const url = | |
| 190 | `https://api.cloudflare.com/client/v4/accounts/${kv.account}` + | |
| 191 | `/storage/kv/namespaces/${kv.namespace}/values/${name}`; | |
| 192 | const run = async (): Promise<void> => { | |
| 193 | // A newer snapshot queued behind this one makes it not worth sending. | |
| 194 | if (method === "PUT" && version !== undefined && version < (this.newest.get(scope) ?? 0)) return; | |
| 195 | const res = await (this.options.fetch ?? fetch)(url, { | |
| 196 | method, | |
| 197 | headers: { authorization: `Bearer ${kv.token}`, "content-type": "application/json" }, | |
| 198 | ...(body === undefined ? {} : { body }), | |
| 199 | signal: AbortSignal.timeout(KV_TIMEOUT_MS), | |
| 200 | }); | |
| 201 | if (!res.ok && !(method === "DELETE" && res.status === 404)) | |
| 202 | throw new Error(`edge kv ${method} ${name}: ${res.status}`); | |
| 203 | }; | |
| 204 | const next = (this.lane.get(scope) ?? Promise.resolve()).then(run, run); | |
| 205 | this.lane.set(scope, next.catch(() => undefined)); | |
| 206 | return next; | |
| 207 | } | |
| 208 | ||
| 209 | /** | |
| 210 | * The published file for a scope and its snapshot id, or undefined when | |
| 211 | * none. Read from disk once (and only if its signature holds), then held. | |
| 212 | */ | |
| 213 | read(scope: string): { text: string; snapshot: string } | undefined { | |
| 214 | const held = this.held.get(scope); | |
| 215 | if (held !== undefined) return held; | |
| 216 | const path = this.pathOf(scope); | |
| 217 | if (path === undefined || !existsSync(path)) return undefined; | |
| 218 | const text = readFileSync(path, "utf8"); | |
| 219 | let published: Published | undefined; | |
| 220 | try { | |
| 221 | published = verifyEdgeFile(JSON.parse(text), this.publicPem); | |
| 222 | } catch { | |
| 223 | published = undefined; | |
| 224 | } | |
| 225 | if (published === undefined) return undefined; | |
| 226 | const entry = { text, snapshot: published.snapshot, version: published.version }; | |
| 227 | this.held.set(scope, entry); | |
| 228 | this.newest.set(scope, Math.max(this.newest.get(scope) ?? 0, published.version)); | |
| 229 | return entry; | |
| 230 | } | |
| 231 | } |
src/cloud/edge_open.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | /** | |
| 2 | * Which scopes may be on the edge: the forge's own, and an app's only while | |
| 3 | * its repository is readable by anyone. The edge file and the KV key are | |
| 4 | * public, so a private app's config is never put there, and is taken down | |
| 5 | * when the repository stops being public. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { getAppByRepo, getAppById } from "../core/apps.ts"; | |
| 11 | import { appScope } from "../core/config.ts"; | |
| 12 | import { canRead, getRepoById } from "../core/repos.ts"; | |
| 13 | ||
| 14 | /** Whether the scope's published copy may exist at all. */ | |
| 15 | export function edgeOpen(db: Database, scope: string): boolean { | |
| 16 | if (scope === "forge") return true; | |
| 17 | const m = /^app\/([0-9a-z]{1,40})$/.exec(scope); | |
| 18 | if (!m) return false; | |
| 19 | const record = getAppById(db, m[1]!); | |
| 20 | const repo = record && getRepoById(db, record.repoId); | |
| 21 | return repo !== undefined && repo !== null && canRead(db, repo, undefined); | |
| 22 | } | |
| 23 | ||
| 24 | /** After a repository's visibility moves: publish or take down its app's config. */ | |
| 25 | export function syncEdge(app: App, repoId: string): void { | |
| 26 | const record = getAppByRepo(app.db, repoId); | |
| 27 | if (!record) return; | |
| 28 | const scope = appScope(record.id); | |
| 29 | // Called after the settings row is written, so edgeOpen sees the new state. | |
| 30 | app | |
| 31 | .edge() | |
| 32 | .publish(app.configs.snapshot(scope), edgeOpen(app.db, scope)) | |
| 33 | .catch(() => undefined); | |
| 34 | } |
src/contract/openapi/routes/getApiV1AppsSlugConfig.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/apps/{slug}/config", | |
| 6 | summary: "An app's flags and settings, with the snapshot id", | |
| 7 | detail: "The app's config store (docs/CACHE.md), readable with the read-only token an app starts with: answers { snapshot, version, values, updated_at } with the snapshot id as ETag (If-None-Match gives a 304); ?changes=1 adds the ledger.", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | query: { changes: "string" }, | |
| 11 | alsoStatus: [304], | |
| 12 | refuses: [404], | |
| 13 | }; |
src/contract/openapi/routes/getApiV1Cache.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/cache", | |
| 6 | summary: "Cache hits and misses per rung for this process", | |
| 7 | detail: "A site admin reads this process's counts per rung (process, sqlite, edge, validator), so the choice of rung can be checked against reality; they reset with the process.", | |
| 8 | auth: true, | |
| 9 | role: "admin", | |
| 10 | refuses: [401], | |
| 11 | }; |
src/contract/openapi/routes/getApiV1Config.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/config", | |
| 6 | summary: "The forge's own flags and settings, with the snapshot id", | |
| 7 | detail: "The forge's config store (docs/CACHE.md): answers { snapshot, version, values, updated_at } with the snapshot id as ETag (send it as If-None-Match for a 304); ?changes=1 adds the ledger of who changed what and why. Values are public.", | |
| 8 | auth: false, | |
| 9 | role: "anonymous", | |
| 10 | query: { changes: "string" }, | |
| 11 | alsoStatus: [304], | |
| 12 | }; |
src/contract/openapi/routes/getEdgeConfigFile.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/edge/config/{file}", | |
| 6 | summary: "The signed snapshot file the edge serves", | |
| 7 | detail: "The published config snapshot at a stable URL (docs/CACHE.md), signed and carrying the snapshot id; cacheable for seconds, stale-while-revalidate.", | |
| 8 | auth: false, | |
| 9 | role: "anonymous", | |
| 10 | refuses: [404], | |
| 11 | }; |
src/contract/openapi/routes/index.ts +6
| @@ -70,6 +70,7 @@ export { route as getApiV1Agents } from "./getApiV1Agents.ts"; | ||
| 70 | 70 | export { route as getApiV1AgentsUsername } from "./getApiV1AgentsUsername.ts"; |
| 71 | 71 | export { route as getApiV1AppTemplates } from "./getApiV1AppTemplates.ts"; |
| 72 | 72 | export { route as getApiV1Apps } from "./getApiV1Apps.ts"; |
| 73 | export { route as getApiV1AppsSlugConfig } from "./getApiV1AppsSlugConfig.ts"; | |
| 73 | 74 | export { route as getApiV1Asked } from "./getApiV1Asked.ts"; |
| 74 | 75 | export { route as getApiV1Asks } from "./getApiV1Asks.ts"; |
| 75 | 76 | export { route as getApiV1AsksAdmin } from "./getApiV1AsksAdmin.ts"; |
| @@ -78,9 +79,11 @@ export { route as getApiV1BoardsPins } from "./getApiV1BoardsPins.ts"; | ||
| 78 | 79 | export { route as getApiV1BoardsSlug } from "./getApiV1BoardsSlug.ts"; |
| 79 | 80 | export { route as getApiV1BoardsSlugPanelsId } from "./getApiV1BoardsSlugPanelsId.ts"; |
| 80 | 81 | export { route as getApiV1BoardsSources } from "./getApiV1BoardsSources.ts"; |
| 82 | export { route as getApiV1Cache } from "./getApiV1Cache.ts"; | |
| 81 | 83 | export { route as getApiV1Changelog } from "./getApiV1Changelog.ts"; |
| 82 | 84 | export { route as getApiV1CloudAccounts } from "./getApiV1CloudAccounts.ts"; |
| 83 | 85 | export { route as getApiV1Codes } from "./getApiV1Codes.ts"; |
| 86 | export { route as getApiV1Config } from "./getApiV1Config.ts"; | |
| 84 | 87 | export { route as getApiV1Contribute } from "./getApiV1Contribute.ts"; |
| 85 | 88 | export { route as getApiV1ConversationFilesId } from "./getApiV1ConversationFilesId.ts"; |
| 86 | 89 | export { route as getApiV1ConversationTurns } from "./getApiV1ConversationTurns.ts"; |
| @@ -276,6 +279,7 @@ export { route as getApiV1UsersUsernameRepos } from "./getApiV1UsersUsernameRepo | ||
| 276 | 279 | export { route as getApiV1UsersUsernameSignins } from "./getApiV1UsersUsernameSignins.ts"; |
| 277 | 280 | export { route as getApiV1Version } from "./getApiV1Version.ts"; |
| 278 | 281 | export { route as getContractOpenapiJson } from "./getContractOpenapiJson.ts"; |
| 282 | export { route as getEdgeConfigFile } from "./getEdgeConfigFile.ts"; | |
| 279 | 283 | export { route as getExploreJson } from "./getExploreJson.ts"; |
| 280 | 284 | export { route as getHealth } from "./getHealth.ts"; |
| 281 | 285 | export { route as getMetrics } from "./getMetrics.ts"; |
| @@ -284,6 +288,8 @@ export { route as getOwnerNamePullsNumberCheckTxt } from "./getOwnerNamePullsNum | ||
| 284 | 288 | export { route as getWellKnownMcpServerCardJson } from "./getWellKnownMcpServerCardJson.ts"; |
| 285 | 289 | export { route as patchApiV1AdminSettings } from "./patchApiV1AdminSettings.ts"; |
| 286 | 290 | export { route as patchApiV1AgentsUsername } from "./patchApiV1AgentsUsername.ts"; |
| 291 | export { route as patchApiV1AppsSlugConfig } from "./patchApiV1AppsSlugConfig.ts"; | |
| 292 | export { route as patchApiV1Config } from "./patchApiV1Config.ts"; | |
| 287 | 293 | export { route as patchApiV1ConversationsId } from "./patchApiV1ConversationsId.ts"; |
| 288 | 294 | export { route as patchApiV1FeaturesSlugSettings } from "./patchApiV1FeaturesSlugSettings.ts"; |
| 289 | 295 | export { route as patchApiV1ForgeFollowing } from "./patchApiV1ForgeFollowing.ts"; |
src/contract/openapi/routes/patchApiV1AppsSlugConfig.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "patch", | |
| 5 | path: "/api/v1/apps/{slug}/config", | |
| 6 | summary: "Change an app's flags: one write, one new snapshot, with why", | |
| 7 | detail: "An admin of the app sets or removes (null) keys of its config; every write names why. Answers the new { snapshot, version, values, updated_at }.", | |
| 8 | auth: true, | |
| 9 | role: "admin", | |
| 10 | body: { set: "object", why: "string" }, | |
| 11 | errorStatus: { 413: "the change is larger than the store allows" }, | |
| 12 | refuses: [401, 403, 404], | |
| 13 | }; |
src/contract/openapi/routes/patchApiV1Config.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "patch", | |
| 5 | path: "/api/v1/config", | |
| 6 | summary: "Change the forge's flags: one write, one new snapshot, with why", | |
| 7 | detail: "An admin token sets or removes (null) keys of the forge's config; every write names why and the ledger keeps who. Answers the new { snapshot, version, values, updated_at }.", | |
| 8 | auth: true, | |
| 9 | role: "admin", | |
| 10 | body: { set: "object", why: "string" }, | |
| 11 | errorStatus: { 413: "the change is larger than the store allows" }, | |
| 12 | refuses: [401, 403, 422], | |
| 13 | }; |
src/contract/tags.ts +3
src/core/account_purge.ts +1
| @@ -54,6 +54,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 54 | 54 | "allocation_entry.actor_id": FORMER, |
| 55 | 55 | "allocation_weekly.set_by": FORMER, |
| 56 | 56 | "cloud_watch_ack.by": FORMER, |
| 57 | "config_change.by": FORMER, | |
| 57 | 58 | "crew_device.added_by": FORMER, |
| 58 | 59 | "crew_device.granted_by": FORMER, |
| 59 | 60 | "repo_review.by": FORMER, |
src/core/config.ts added +309
| @@ -0,0 +1,309 @@ | ||
| 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 { during } from "../perf/jobs.ts"; | |
| 23 | import { id } from "../kernel/id.ts"; | |
| 24 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 25 | import type { EventBus } from "./events.ts"; | |
| 26 | import { noteRung } from "./rungs.ts"; | |
| 27 | ||
| 28 | export type ConfigValue = | |
| 29 | | string | |
| 30 | | number | |
| 31 | | boolean | |
| 32 | | null | |
| 33 | | ConfigValue[] | |
| 34 | | { [k: string]: ConfigValue }; | |
| 35 | ||
| 36 | export interface Snapshot { | |
| 37 | readonly scope: string; | |
| 38 | /** Changes with every write; sent as `X-Forge-Config` and as the ETag. */ | |
| 39 | readonly id: string; | |
| 40 | readonly version: number; | |
| 41 | readonly values: Readonly<Record<string, ConfigValue>>; | |
| 42 | readonly updatedAt: string; | |
| 43 | } | |
| 44 | ||
| 45 | export type ConfigError = | |
| 46 | | "invalid_scope" | |
| 47 | | "invalid_key" | |
| 48 | | "invalid_value" | |
| 49 | | "too_large" | |
| 50 | | "too_many_keys" | |
| 51 | | "invalid_who" | |
| 52 | | "invalid_why" | |
| 53 | | "empty"; | |
| 54 | ||
| 55 | export const FORGE_SCOPE = "forge"; | |
| 56 | export const appScope = (appId: string): string => `app/${appId}`; | |
| 57 | ||
| 58 | const KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/; | |
| 59 | const SCOPE = /^(forge|app\/[0-9a-z]{1,40})$/; | |
| 60 | const MAX_VALUE_BYTES = 4096; | |
| 61 | const MAX_TOTAL_BYTES = 65536; | |
| 62 | const MAX_KEYS = 256; | |
| 63 | const MAX_WHY = 200; | |
| 64 | const POLL_MS = 500; | |
| 65 | ||
| 66 | interface Row { | |
| 67 | scope: string; | |
| 68 | snapshot: string; | |
| 69 | version: number; | |
| 70 | vals: string; | |
| 71 | updated_at: string; | |
| 72 | } | |
| 73 | ||
| 74 | const EMPTY = (scope: string): Snapshot => ({ | |
| 75 | scope, | |
| 76 | id: "0", | |
| 77 | version: 0, | |
| 78 | values: {}, | |
| 79 | updatedAt: "", | |
| 80 | }); | |
| 81 | ||
| 82 | function toSnapshot(r: Row): Snapshot { | |
| 83 | return { | |
| 84 | scope: r.scope, | |
| 85 | id: r.snapshot, | |
| 86 | version: r.version, | |
| 87 | values: JSON.parse(r.vals) as Record<string, ConfigValue>, | |
| 88 | updatedAt: r.updated_at, | |
| 89 | }; | |
| 90 | } | |
| 91 | ||
| 92 | const bytes = (s: string): number => new TextEncoder().encode(s).length; | |
| 93 | ||
| 94 | /** Whether `v` is plain JSON (no undefined, functions, NaN, cycles). */ | |
| 95 | function isJson(v: unknown, depth = 0): v is ConfigValue { | |
| 96 | if (depth > 8) return false; | |
| 97 | if (v === null || typeof v === "string" || typeof v === "boolean") return true; | |
| 98 | if (typeof v === "number") return Number.isFinite(v); | |
| 99 | if (Array.isArray(v)) return v.every((x) => isJson(x, depth + 1)); | |
| 100 | if (typeof v === "object") | |
| 101 | return Object.entries(v).every(([k, x]) => k !== "__proto__" && isJson(x, depth + 1)); | |
| 102 | return false; | |
| 103 | } | |
| 104 | ||
| 105 | export class ConfigStore { | |
| 106 | private readonly held = new Map<string, Snapshot>(); | |
| 107 | private readonly listeners = new Set<(s: Snapshot) => void>(); | |
| 108 | private timer: ReturnType<typeof setInterval> | undefined; | |
| 109 | private unsubscribe: (() => void) | undefined; | |
| 110 | ||
| 111 | constructor( | |
| 112 | private readonly db: Database, | |
| 113 | private readonly bus?: EventBus, | |
| 114 | ) { | |
| 115 | this.unsubscribe = bus?.subscribe((e) => { | |
| 116 | if (e.kind === "config.set") this.refresh(); | |
| 117 | }); | |
| 118 | } | |
| 119 | ||
| 120 | /** The current snapshot of a scope: held in memory, loaded on first ask. */ | |
| 121 | snapshot(scope: string): Snapshot { | |
| 122 | const held = this.held.get(scope); | |
| 123 | if (held !== undefined) { | |
| 124 | noteRung("process"); | |
| 125 | return held; | |
| 126 | } | |
| 127 | noteRung("process", false); | |
| 128 | const row = this.db | |
| 129 | .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1") | |
| 130 | .get(scope); | |
| 131 | noteRung("sqlite", row !== null); | |
| 132 | const snap = row ? toSnapshot(row) : EMPTY(scope); | |
| 133 | this.held.set(scope, snap); | |
| 134 | return snap; | |
| 135 | } | |
| 136 | ||
| 137 | /** One value: a map lookup. */ | |
| 138 | get(scope: string, key: string): ConfigValue | undefined { | |
| 139 | return this.snapshot(scope).values[key]; | |
| 140 | } | |
| 141 | ||
| 142 | /** | |
| 143 | * Change keys in one write: a value sets, `null` removes. One new snapshot | |
| 144 | * comes of it, and the change is recorded with `who` and `why`. | |
| 145 | */ | |
| 146 | set( | |
| 147 | scope: string, | |
| 148 | patch: Record<string, unknown>, | |
| 149 | who: string, | |
| 150 | why: string, | |
| 151 | ): Result<Snapshot, ConfigError> { | |
| 152 | if (!SCOPE.test(scope)) return err("invalid_scope"); | |
| 153 | if (who.trim() === "" || who.length > 80) return err("invalid_who"); | |
| 154 | const reason = why.trim(); | |
| 155 | if (reason === "" || reason.length > MAX_WHY) return err("invalid_why"); | |
| 156 | const entries = Object.entries(patch); | |
| 157 | if (entries.length === 0) return err("empty"); | |
| 158 | for (const [k, v] of entries) { | |
| 159 | if (!KEY.test(k)) return err("invalid_key"); | |
| 160 | if (v !== null && !isJson(v)) return err("invalid_value"); | |
| 161 | if (v !== null && bytes(JSON.stringify(v)) > MAX_VALUE_BYTES) | |
| 162 | return err("too_large"); | |
| 163 | } | |
| 164 | ||
| 165 | const write = this.db.transaction((): Result<Snapshot, ConfigError> => { | |
| 166 | const row = this.db | |
| 167 | .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1") | |
| 168 | .get(scope); | |
| 169 | const values: Record<string, ConfigValue> = row | |
| 170 | ? { ...(JSON.parse(row.vals) as Record<string, ConfigValue>) } | |
| 171 | : {}; | |
| 172 | for (const [k, v] of entries) { | |
| 173 | if (v === null) delete values[k]; | |
| 174 | else values[k] = v as ConfigValue; | |
| 175 | } | |
| 176 | if (Object.keys(values).length > MAX_KEYS) return err("too_many_keys"); | |
| 177 | const vals = JSON.stringify(values); | |
| 178 | if (bytes(vals) > MAX_TOTAL_BYTES) return err("too_large"); | |
| 179 | const at = new Date().toISOString(); | |
| 180 | const snapshot = id(); | |
| 181 | const version = (row?.version ?? 0) + 1; | |
| 182 | this.db | |
| 183 | .query( | |
| 184 | `INSERT INTO config (scope, snapshot, version, vals, updated_at) | |
| 185 | VALUES (?1, ?2, ?3, ?4, ?5) | |
| 186 | ON CONFLICT (scope) DO UPDATE SET snapshot = excluded.snapshot, | |
| 187 | version = excluded.version, vals = excluded.vals, | |
| 188 | updated_at = excluded.updated_at`, | |
| 189 | ) | |
| 190 | .run(scope, snapshot, version, vals, at); | |
| 191 | this.db | |
| 192 | .query( | |
| 193 | `INSERT INTO config_change (id, scope, snapshot, version, keys, by, why, at) | |
| 194 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`, | |
| 195 | ) | |
| 196 | .run(id(), scope, snapshot, version, JSON.stringify(entries.map(([k]) => k)), who, reason, at); | |
| 197 | return ok({ scope, id: snapshot, version, values, updatedAt: at }); | |
| 198 | }); | |
| 199 | // IMMEDIATE: take the write lock before reading, so two processes | |
| 200 | // changing one scope serialize into consecutive versions. | |
| 201 | const result = write.immediate(); | |
| 202 | if (!result.ok) return result; | |
| 203 | this.adopt(result.value); | |
| 204 | this.bus?.append({ | |
| 205 | kind: "config.set", | |
| 206 | payload: { | |
| 207 | scope, | |
| 208 | snapshot: result.value.id, | |
| 209 | version: result.value.version, | |
| 210 | keys: entries.map(([k]) => k), | |
| 211 | why: reason, | |
| 212 | }, | |
| 213 | }); | |
| 214 | return result; | |
| 215 | } | |
| 216 | ||
| 217 | /** Every scope that has been written, for republishing at boot. */ | |
| 218 | scopes(): string[] { | |
| 219 | return this.db | |
| 220 | .query<{ scope: string }, []>("SELECT scope FROM config") | |
| 221 | .all() | |
| 222 | .map((r) => r.scope); | |
| 223 | } | |
| 224 | ||
| 225 | /** The recent changes to a scope, newest first. */ | |
| 226 | changes(scope: string, limit = 20) { | |
| 227 | return this.db | |
| 228 | .query< | |
| 229 | { snapshot: string; version: number; keys: string; by: string; why: string; at: string }, | |
| 230 | [string, number] | |
| 231 | >( | |
| 232 | "SELECT snapshot, version, keys, by, why, at FROM config_change WHERE scope = ?1 ORDER BY version DESC LIMIT ?2", | |
| 233 | ) | |
| 234 | .all(scope, limit) | |
| 235 | .map((r) => ({ ...r, keys: JSON.parse(r.keys) as string[] })); | |
| 236 | } | |
| 237 | ||
| 238 | /** | |
| 239 | * Reload every held scope whose stored snapshot id differs from the one | |
| 240 | * in memory. One indexed read of a handful of short rows; returns how many | |
| 241 | * scopes changed. | |
| 242 | */ | |
| 243 | refresh(): number { | |
| 244 | let changed = 0; | |
| 245 | const stored = this.db | |
| 246 | .query<{ scope: string; snapshot: string }, []>( | |
| 247 | "SELECT scope, snapshot FROM config", | |
| 248 | ) | |
| 249 | .all(); | |
| 250 | for (const { scope, snapshot } of stored) { | |
| 251 | const held = this.held.get(scope); | |
| 252 | if (held?.id === snapshot) continue; | |
| 253 | const row = this.db | |
| 254 | .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1") | |
| 255 | .get(scope); | |
| 256 | if (!row) continue; | |
| 257 | noteRung("sqlite"); | |
| 258 | this.adopt(toSnapshot(row)); | |
| 259 | changed++; | |
| 260 | } | |
| 261 | return changed; | |
| 262 | } | |
| 263 | ||
| 264 | /** Called with each snapshot this process newly holds (edge publication). */ | |
| 265 | onChange(listener: (s: Snapshot) => void): () => void { | |
| 266 | this.listeners.add(listener); | |
| 267 | return () => this.listeners.delete(listener); | |
| 268 | } | |
| 269 | ||
| 270 | /** | |
| 271 | * Poll for writes made by another process on this database. The bus is | |
| 272 | * in-process: a write by a sibling process (a second server, a job) emits | |
| 273 | * its event only there, so the stored snapshot id is the one thing every | |
| 274 | * process can see. One indexed read of a few rows, every `ms`. | |
| 275 | */ | |
| 276 | start(ms = POLL_MS): void { | |
| 277 | if (this.timer !== undefined) return; | |
| 278 | this.timer = setInterval(() => { | |
| 279 | during("config-poll", () => { | |
| 280 | try { | |
| 281 | this.refresh(); | |
| 282 | } catch { | |
| 283 | // A closing database ends the poll; the next boot starts it again. | |
| 284 | } | |
| 285 | }); | |
| 286 | }, ms); | |
| 287 | this.timer.unref?.(); | |
| 288 | } | |
| 289 | ||
| 290 | stop(): void { | |
| 291 | if (this.timer !== undefined) clearInterval(this.timer); | |
| 292 | this.timer = undefined; | |
| 293 | this.unsubscribe?.(); | |
| 294 | this.unsubscribe = undefined; | |
| 295 | } | |
| 296 | ||
| 297 | private adopt(snap: Snapshot): void { | |
| 298 | const held = this.held.get(snap.scope); | |
| 299 | if (held !== undefined && held.version >= snap.version) return; | |
| 300 | this.held.set(snap.scope, snap); | |
| 301 | for (const l of this.listeners) { | |
| 302 | try { | |
| 303 | l(snap); | |
| 304 | } catch { | |
| 305 | // A failed publication must not undo the write that caused it. | |
| 306 | } | |
| 307 | } | |
| 308 | } | |
| 309 | } |
src/core/event_audience.ts +2
| @@ -250,6 +250,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 250 | 250 | kind.startsWith("app.egress.") || |
| 251 | 251 | // Clearing the build cache is an admin's act on the app's disk (#10526). |
| 252 | 252 | kind === "app.cache.cleared" || |
| 253 | // A change to the config store names its keys and why (`core/config.ts`). | |
| 254 | kind === "config.set" || | |
| 253 | 255 | kind.startsWith("prompt.") || |
| 254 | 256 | kind.startsWith("secret.") || |
| 255 | 257 | // The forge's mail ceiling is its owner's to hear (`actions/mail.ts`). |
src/core/migration-pins/20261130140000-config-store.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | e08d674615b46ccdb45b5360ddf05730697a3d17822d34ebd678990f0d035dd1 |
src/core/migrations/20261130140000-config-store.ts added +24
| @@ -0,0 +1,24 @@ | ||
| 1 | // The config store (#1138): small read-mostly values, one row per scope | |
| 2 | // holding the whole current snapshot, so a write is one new snapshot id and a | |
| 3 | // reader never sees half of it. `config_change` is the ledger: who changed | |
| 4 | // which keys, when, and why. A scope is `forge` or `app/<id>`. Additive. | |
| 5 | export default ` | |
| 6 | CREATE TABLE config ( | |
| 7 | scope TEXT PRIMARY KEY, | |
| 8 | snapshot TEXT NOT NULL, | |
| 9 | version INTEGER NOT NULL, | |
| 10 | vals TEXT NOT NULL, | |
| 11 | updated_at TEXT NOT NULL | |
| 12 | ); | |
| 13 | CREATE TABLE config_change ( | |
| 14 | id TEXT PRIMARY KEY, | |
| 15 | scope TEXT NOT NULL, | |
| 16 | snapshot TEXT NOT NULL, | |
| 17 | version INTEGER NOT NULL, | |
| 18 | keys TEXT NOT NULL, | |
| 19 | by TEXT NOT NULL, | |
| 20 | why TEXT NOT NULL, | |
| 21 | at TEXT NOT NULL | |
| 22 | ); | |
| 23 | CREATE INDEX config_change_scope ON config_change(scope, version); | |
| 24 | `; |
src/core/reserved.ts +1
src/core/rungs.ts added +32
| @@ -0,0 +1,32 @@ | ||
| 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"] 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 | } |
src/http/config.ts added +170
| @@ -0,0 +1,170 @@ | ||
| 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 | boundedBody, | |
| 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 | /** Room for the store's own limits to answer first. */ | |
| 41 | const MAX_BODY = 160 * 1024; | |
| 42 | ||
| 43 | const shape = (s: Snapshot) => ({ | |
| 44 | snapshot: s.id, | |
| 45 | version: s.version, | |
| 46 | values: s.values, | |
| 47 | updated_at: s.updatedAt, | |
| 48 | }); | |
| 49 | ||
| 50 | /** | |
| 51 | * `?changes=1` adds the ledger (who changed which keys, and why) for an admin of the scope; for | |
| 52 | * anyone else it is ignored. | |
| 53 | */ | |
| 54 | function read(ctx: Ctx, snap: Snapshot, kind: "edge" | "config", mayAudit: boolean): Response { | |
| 55 | // The ledger names people and their reasons: only an admin of the scope | |
| 56 | // gets it, and never from a shared cache. | |
| 57 | const changes = mayAudit && ctx.url.searchParams.get("changes") === "1"; | |
| 58 | if (changes) kind = "config"; | |
| 59 | const out = changes | |
| 60 | ? { ...shape(snap), changes: ctx.app.configs.changes(snap.scope) } | |
| 61 | : shape(snap); | |
| 62 | return cached( | |
| 63 | ctx.request, | |
| 64 | kind, | |
| 65 | changes ? `${snap.id}.changes` : snap.id, | |
| 66 | JSON.stringify(out), | |
| 67 | "application/json", | |
| 68 | { "x-forge-config": snap.id }, | |
| 69 | ); | |
| 70 | } | |
| 71 | ||
| 72 | async function write(ctx: Ctx, scope: string): Promise<Response> { | |
| 73 | const input = await boundedBody(ctx.request, MAX_BODY); | |
| 74 | if (input === "too_large") return apiError("too_large", 413, "the change is too large"); | |
| 75 | const set = input.set; | |
| 76 | if (typeof set !== "object" || set === null || Array.isArray(set)) | |
| 77 | return apiError("invalid_set", 422, "set is an object of key to value (null removes)"); | |
| 78 | const why = typeof input.why === "string" ? input.why : ""; | |
| 79 | const made = ctx.app.configs.set( | |
| 80 | scope, | |
| 81 | set as Record<string, unknown>, | |
| 82 | ctx.auth.user!.username, | |
| 83 | why, | |
| 84 | ); | |
| 85 | if (!made.ok) return apiError(made.error, STATUS[made.error], `config refused: ${made.error}`); | |
| 86 | return json(shape(made.value), 200, { "x-forge-config": made.value.id }); | |
| 87 | } | |
| 88 | ||
| 89 | /** The app named by the URL, if the caller may read it; its repo with it. */ | |
| 90 | function appFor(ctx: Ctx) { | |
| 91 | const record = getAppBySlug(ctx.app.db, ctx.params.slug!); | |
| 92 | const repo = record && getRepoById(ctx.app.db, record.repoId); | |
| 93 | if (!record || !repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return undefined; | |
| 94 | return { record, repo }; | |
| 95 | } | |
| 96 | ||
| 97 | export function configRoutes(router: Router<Handler>): void { | |
| 98 | // The forge's own flags and settings are public by contract. | |
| 99 | router.add("GET", "/api/v1/config", (ctx) => | |
| 100 | read(ctx, ctx.app.configs.snapshot(FORGE_SCOPE), "edge", ctx.auth.user?.isAdmin === true), | |
| 101 | ); | |
| 102 | ||
| 103 | router.add("PATCH", "/api/v1/config", async (ctx) => { | |
| 104 | const denied = requireScope(ctx, "admin"); | |
| 105 | if (denied) return denied; | |
| 106 | if (ctx.auth.user!.isAdmin !== true) return forbidden(); | |
| 107 | return write(ctx, FORGE_SCOPE); | |
| 108 | }); | |
| 109 | ||
| 110 | router.add("GET", "/api/v1/apps/:slug/config", (ctx) => { | |
| 111 | const found = appFor(ctx); | |
| 112 | if (!found) return notFound(); | |
| 113 | return read( | |
| 114 | ctx, | |
| 115 | ctx.app.configs.snapshot(appScope(found.record.id)), | |
| 116 | "config", | |
| 117 | canAdmin(ctx.app.db, found.repo, ctx.auth.user), | |
| 118 | ); | |
| 119 | }); | |
| 120 | ||
| 121 | router.add("PATCH", "/api/v1/apps/:slug/config", async (ctx) => { | |
| 122 | const denied = requireScope(ctx, "admin"); | |
| 123 | if (denied) return denied; | |
| 124 | const found = appFor(ctx); | |
| 125 | if (!found) return notFound(); | |
| 126 | if (!canAdmin(ctx.app.db, found.repo, ctx.auth.user)) return forbidden(); | |
| 127 | return write(ctx, appScope(found.record.id)); | |
| 128 | }); | |
| 129 | ||
| 130 | router.add("GET", "/api/v1/cache", (ctx) => { | |
| 131 | if (!ctx.auth.user) return unauthorized(); | |
| 132 | if (!ctx.auth.user.isAdmin) return notFound(); | |
| 133 | return json( | |
| 134 | { | |
| 135 | forge_snapshot: ctx.app.configs.snapshot(FORGE_SCOPE).id, | |
| 136 | rungs: rungCounts(), | |
| 137 | }, | |
| 138 | 200, | |
| 139 | { "cache-control": "no-store" }, | |
| 140 | ); | |
| 141 | }); | |
| 142 | } | |
| 143 | ||
| 144 | /** `/edge/config/<name>.json` and `/edge/config/key.pem`: what the edge serves. */ | |
| 145 | export function edgeRoutes(router: Router<Handler>): void { | |
| 146 | router.add("GET", "/edge/config/:file", (ctx) => { | |
| 147 | const file = ctx.params.file!; | |
| 148 | const edge = ctx.app.edge(); | |
| 149 | if (file === "key.pem") | |
| 150 | return cached(ctx.request, "edge", "key", edge.publicPem, "application/x-pem-file"); | |
| 151 | const m = /^(forge|app-[0-9a-z]{1,40})\.json$/.exec(file); | |
| 152 | if (!m) return notFound(); | |
| 153 | const name = m[1]!; | |
| 154 | let scope = FORGE_SCOPE; | |
| 155 | if (name !== "forge") { | |
| 156 | const record = getAppById(ctx.app.db, name.slice(4)); | |
| 157 | const repo = record && getRepoById(ctx.app.db, record.repoId); | |
| 158 | // Published for anyone only when the app is readable by anyone. | |
| 159 | if (!record || !repo || !canRead(ctx.app.db, repo, undefined)) return notFound(); | |
| 160 | scope = appScope(record.id); | |
| 161 | } | |
| 162 | const held = edge.read(scope); | |
| 163 | if (held === undefined) return notFound(); | |
| 164 | noteRung("edge"); | |
| 165 | const { snapshot, text } = held; | |
| 166 | return cached(ctx.request, "edge", snapshot, text, "application/json", { | |
| 167 | "x-forge-config": snapshot, | |
| 168 | }); | |
| 169 | }); | |
| 170 | } |
src/http/marks/api-v1-cache.json added +4
src/http/marks/api-v1-config.json added +4
src/http/respond.ts +81
| @@ -15,6 +15,8 @@ import { NOT_A_MEMBER } from "../core/roles.ts"; | ||
| 15 | 15 | import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts"; |
| 16 | 16 | import { VERIFY_FIRST } from "../actions/verify_words.ts"; |
| 17 | 17 | import { KINDS, type Kind, type Refusal } from "./error_kinds.ts"; |
| 18 | import { noteRung } from "../core/rungs.ts"; | |
| 19 | import type { App } from "../app.ts"; | |
| 18 | 20 | import type { User } from "../core/users.ts"; |
| 19 | 21 | import { crossOrigin, type Ctx } from "./context.ts"; |
| 20 | 22 | |
| @@ -636,3 +638,82 @@ export function paged<T>( | ||
| 636 | 638 | export const WINDOW = { minute: 60, day: 86_400 } as const; |
| 637 | 639 | /** Seconds until the next UTC midnight: when a per-day count starts over. */ |
| 638 | 640 | export const untilNextDay = (now = Date.now()): number => (WINDOW.day * 1000 - (now % (WINDOW.day * 1000))) / 1000; |
| 641 | ||
| 642 | /** | |
| 643 | * What a kind of response may be kept for, by whom (`docs/CACHE.md`). A | |
| 644 | * route names its kind; it never writes `Cache-Control` itself. | |
| 645 | * | |
| 646 | * - `immutable`: content addressed, never changes under its URL. | |
| 647 | * - `edge`: a published snapshot — any cache may hold it a few seconds, | |
| 648 | * and serve it stale while it refetches; the ETag is the snapshot id. | |
| 649 | * - `config`: the same data for a signed-in reader — only that reader's | |
| 650 | * cache, and revalidated every time (a 304 costs one lookup). | |
| 651 | * - `live`: never kept. | |
| 652 | */ | |
| 653 | export type CacheKind = "immutable" | "edge" | "config" | "live"; | |
| 654 | ||
| 655 | export const CACHE_CONTROL: Readonly<Record<CacheKind, string>> = { | |
| 656 | immutable: "public, max-age=31536000, immutable", | |
| 657 | edge: "public, max-age=5, stale-while-revalidate=30", | |
| 658 | config: "private, no-cache", | |
| 659 | live: "no-store", | |
| 660 | }; | |
| 661 | ||
| 662 | /** The headers a kind sets: `Cache-Control`, and `ETag` when it has a validator. */ | |
| 663 | export function cacheHeaders( | |
| 664 | kind: CacheKind, | |
| 665 | etag?: string, | |
| 666 | ): Record<string, string> { | |
| 667 | const headers: Record<string, string> = { "cache-control": CACHE_CONTROL[kind] }; | |
| 668 | if (etag !== undefined && kind !== "live") headers.etag = `"${etag}"`; | |
| 669 | return headers; | |
| 670 | } | |
| 671 | ||
| 672 | /** Whether `If-None-Match` already names this validator (or `*`). */ | |
| 673 | export function notModified(request: Request, etag: string): boolean { | |
| 674 | const sent = request.headers.get("if-none-match"); | |
| 675 | if (sent === null) return false; | |
| 676 | return sent | |
| 677 | .split(",") | |
| 678 | .map((t) => t.trim().replace(/^W\//, "")) | |
| 679 | .some((t) => t === `"${etag}"` || t === "*"); | |
| 680 | } | |
| 681 | ||
| 682 | /** | |
| 683 | * A body of a kind, answered `304` when the reader already holds `etag`. | |
| 684 | * The one place a conditional response is made; the 304 is counted as a | |
| 685 | * `validator` hit so the spectrum can be checked against reality. | |
| 686 | */ | |
| 687 | export function cached( | |
| 688 | request: Request, | |
| 689 | kind: CacheKind, | |
| 690 | etag: string, | |
| 691 | body: string, | |
| 692 | contentType = "application/json", | |
| 693 | extra: Record<string, string> = {}, | |
| 694 | ): Response { | |
| 695 | const headers = { ...cacheHeaders(kind, etag), ...extra }; | |
| 696 | if (notModified(request, etag)) { | |
| 697 | noteRung("validator"); | |
| 698 | return new Response(null, { status: 304, headers }); | |
| 699 | } | |
| 700 | noteRung("validator", false); | |
| 701 | return new Response(body, { | |
| 702 | status: 200, | |
| 703 | headers: { "content-type": contentType, ...headers }, | |
| 704 | }); | |
| 705 | } | |
| 706 | ||
| 707 | /** | |
| 708 | * Say which config snapshot this forge holds, on every response: an edge | |
| 709 | * or an app that cached an older id can see that it lags. | |
| 710 | */ | |
| 711 | export function stampConfig(response: Response, app: App): Response { | |
| 712 | try { | |
| 713 | if (!response.headers.has("x-forge-config")) | |
| 714 | response.headers.set("x-forge-config", app.configs.snapshot("forge").id); | |
| 715 | } catch { | |
| 716 | // A carried, immutable header set keeps what it came with. | |
| 717 | } | |
| 718 | return response; | |
| 719 | } |
src/http/server.ts +17
| @@ -585,6 +585,7 @@ import { readGrantGate } from "./read_grant_gate.ts"; | ||
| 585 | 585 | import { viaGate } from "./via_gate.ts"; |
| 586 | 586 | import { checksRecheckRoutes } from "./checks_recheck.ts"; |
| 587 | 587 | import { feedRoutes } from "./feed.ts"; |
| 588 | import { configRoutes, edgeRoutes } from "./config.ts"; | |
| 588 | 589 | import type { Database } from "bun:sqlite"; |
| 589 | 590 | import { loadMcp, MCP_ROUTES } from "./mcp/load.ts"; |
| 590 | 591 | import { lazyRoutes } from "./lazy_routes.ts"; |
| @@ -666,6 +667,7 @@ import { | ||
| 666 | 667 | prefersJson, |
| 667 | 668 | asksForPage, |
| 668 | 669 | securityFloor, |
| 670 | stampConfig, | |
| 669 | 671 | BodyTooLarge, |
| 670 | 672 | bodyTooLarge, |
| 671 | 673 | invalidJson, |
| @@ -880,6 +882,8 @@ function movedTo(noun: "issues" | "pulls", rest?: "new" | ":number"): Handler { | ||
| 880 | 882 | export function buildRouter(): Router<Handler> { |
| 881 | 883 | const router = new Router<Handler>(); |
| 882 | 884 | |
| 885 | edgeRoutes(router); | |
| 886 | ||
| 883 | 887 | // Literal-prefix routes come before parameterized repo routes; the router |
| 884 | 888 | // matches in insertion order. The stylesheet and the highlighter bundle are |
| 885 | 889 | // both content-addressed: a stale hash is a 404 rather than a redirect, the |
| @@ -1976,6 +1980,7 @@ export function buildApiRouter(): Router<Handler> { | ||
| 1976 | 1980 | const router = new Router<Handler>(); |
| 1977 | 1981 | apiRoutes(router, isPublicPage); |
| 1978 | 1982 | feedRoutes(router); |
| 1983 | configRoutes(router); | |
| 1979 | 1984 | checksRecheckRoutes(router); |
| 1980 | 1985 | // What went live, as /changelog shows it; the page's own module answers. |
| 1981 | 1986 | router.add("GET", "/api/v1/changelog", changelogJson); |
| @@ -3190,6 +3195,18 @@ async function answer( | ||
| 3190 | 3195 | apiRouter: Router<Handler>, |
| 3191 | 3196 | limiter: RateLimiter, |
| 3192 | 3197 | request: Request, |
| 3198 | ): Promise<Response> { | |
| 3199 | // Every answer the forge writes for itself names the config snapshot it | |
| 3200 | // holds, so a stale edge or app is visible (`docs/CACHE.md`). | |
| 3201 | return stampConfig(await answerRoute(app, router, apiRouter, limiter, request), app); | |
| 3202 | } | |
| 3203 | ||
| 3204 | async function answerRoute( | |
| 3205 | app: App, | |
| 3206 | router: Router<Handler>, | |
| 3207 | apiRouter: Router<Handler>, | |
| 3208 | limiter: RateLimiter, | |
| 3209 | request: Request, | |
| 3193 | 3210 | ): Promise<Response> { |
| 3194 | 3211 | const url = publicUrl(request, app.config.url); |
| 3195 | 3212 | // A control character in the path or query is a plain 400 before any route (#15364). |
src/main.ts +7
| @@ -489,6 +489,13 @@ const flagTimer = setInterval( | ||
| 489 | 489 | 10_000, |
| 490 | 490 | ); |
| 491 | 491 | await reconcile(app); |
| 492 | // Config snapshots: poll for another process's writes, and publish what is | |
| 493 | // held now so the edge file exists from the first request. | |
| 494 | app.configs.start(); | |
| 495 | for (const scope of app.configs.scopes()) | |
| 496 | await app.edge().publish(app.configs.snapshot(scope)).catch((error) => | |
| 497 | app.log.warn("edge publish failed", { scope, error: String(error) }), | |
| 498 | ); | |
| 492 | 499 | // Issues linked under a pillar's umbrella before pillars had labels. |
| 493 | 500 | const labelled = syncAllPillars(app); |
| 494 | 501 | if (labelled > 0) app.log.info("pillars labelled", { issues: labelled }); |
src/view/doc_sections.ts +1
| @@ -78,6 +78,7 @@ export const DOC_LINES: Record<string, Line> = { | ||
| 78 | 78 | "WRITING.md": ["internals", "How to write these docs."], |
| 79 | 79 | "DEPENDENCIES.md": ["internals", "Every package and why it is there."], |
| 80 | 80 | "DOMAINS.md": ["internals", "The ways the forge stops, and what it says."], |
| 81 | "CACHE.md": ["internals", "Which data lives on which cache rung, and how it is checked."], | |
| 81 | 82 | "CACHING.md": ["internals", "What the home and map cache, and for how long."], |
| 82 | 83 | "FLOW.md": ["internals", "An issue's stage, from records."], |
| 83 | 84 | "SENTINEL.md": ["internals", "Faults the forge files about itself.", "Self-checks"], |
test/config-store.test.ts added +414
| @@ -0,0 +1,414 @@ | ||
| 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, writeFileSync } 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 } 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 | kvFromEnv, | |
| 24 | verifyEdgeFile, | |
| 25 | } from "../src/cloud/edge.ts"; | |
| 26 | import { | |
| 27 | CACHE_CONTROL, | |
| 28 | cacheHeaders, | |
| 29 | cached, | |
| 30 | type CacheKind, | |
| 31 | } from "../src/http/respond.ts"; | |
| 32 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 33 | import { waitFor } from "./helpers/poll.ts"; | |
| 34 | ||
| 35 | async function admin(app: App, username: string): Promise<User> { | |
| 36 | const made = await createUser(app.db, { | |
| 37 | origin: "seed", | |
| 38 | trusted: true, | |
| 39 | username, | |
| 40 | email: `${username}@forge.local`, | |
| 41 | password: "a-good-passphrase", | |
| 42 | adminIfFirst: true, | |
| 43 | }); | |
| 44 | if (!made.ok) throw new Error(made.error); | |
| 45 | return made.value; | |
| 46 | } | |
| 47 | ||
| 48 | describe("config store", () => { | |
| 49 | let dir: string; | |
| 50 | let app: App; | |
| 51 | beforeAll(async () => { | |
| 52 | dir = await mkdtemp(join(tmpdir(), "forge-config-")); | |
| 53 | app = createApp({ dataDir: dir, port: 0 }); | |
| 54 | }); | |
| 55 | afterAll(async () => { | |
| 56 | app.close(); | |
| 57 | await rm(dir, { recursive: true, force: true }); | |
| 58 | }); | |
| 59 | ||
| 60 | test("one write is one new snapshot; null removes; reads are the held map", () => { | |
| 61 | const a = app.configs.set(FORGE_SCOPE, { "flag.new-ui": true, motd: "hi" }, "alice", "try it"); | |
| 62 | expect(a.ok).toBe(true); | |
| 63 | if (!a.ok) return; | |
| 64 | expect(a.value.version).toBe(1); | |
| 65 | expect(app.configs.get(FORGE_SCOPE, "flag.new-ui")).toBe(true); | |
| 66 | const b = app.configs.set(FORGE_SCOPE, { motd: null }, "alice", "drop motd"); | |
| 67 | if (!b.ok) throw new Error(b.error); | |
| 68 | expect(b.value.id).not.toBe(a.value.id); | |
| 69 | expect(b.value.version).toBe(2); | |
| 70 | expect(app.configs.get(FORGE_SCOPE, "motd")).toBeUndefined(); | |
| 71 | expect(app.configs.snapshot(FORGE_SCOPE).id).toBe(b.value.id); | |
| 72 | }); | |
| 73 | ||
| 74 | test("a write says who and why, and the ledger keeps both", () => { | |
| 75 | const changes = app.configs.changes(FORGE_SCOPE); | |
| 76 | expect(changes[0]).toMatchObject({ by: "alice", why: "drop motd", keys: ["motd"], version: 2 }); | |
| 77 | expect(app.configs.set(FORGE_SCOPE, { x: 1 }, "alice", " ").ok).toBe(false); | |
| 78 | expect(app.configs.set(FORGE_SCOPE, { x: 1 }, "", "why").ok).toBe(false); | |
| 79 | }); | |
| 80 | ||
| 81 | test("input is validated at the boundary", () => { | |
| 82 | const err = (patch: Record<string, unknown>, scope = FORGE_SCOPE) => { | |
| 83 | const r = app.configs.set(scope, patch, "a", "w"); | |
| 84 | return r.ok ? "ok" : r.error; | |
| 85 | }; | |
| 86 | expect(err({ "Bad Key": 1 })).toBe("invalid_key"); | |
| 87 | expect(err({ "": 1 })).toBe("invalid_key"); | |
| 88 | expect(err({ k: undefined })).toBe("invalid_value"); | |
| 89 | expect(err({ k: Number.NaN })).toBe("invalid_value"); | |
| 90 | expect(err({ k: "x".repeat(5000) })).toBe("too_large"); | |
| 91 | expect(err({})).toBe("empty"); | |
| 92 | expect(err({ k: 1 }, "nope")).toBe("invalid_scope"); | |
| 93 | expect(err({ k: 1 }, "app/../x")).toBe("invalid_scope"); | |
| 94 | }); | |
| 95 | ||
| 96 | test("a write is visible to a second process within a second", async () => { | |
| 97 | // A second process is a second connection and a second store on the same file. | |
| 98 | const other = new ConfigStore(new Database(join(dir, "forge.db"))); | |
| 99 | other.start(); | |
| 100 | try { | |
| 101 | expect(other.get(FORGE_SCOPE, "seen")).toBeUndefined(); | |
| 102 | const wrote = app.configs.set(FORGE_SCOPE, { seen: "yes" }, "alice", "cross-process"); | |
| 103 | if (!wrote.ok) throw new Error(wrote.error); | |
| 104 | const t0 = Date.now(); | |
| 105 | await waitFor(() => other.snapshot(FORGE_SCOPE).id === wrote.value.id, { every: 25, within: 1000 }); | |
| 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)!.text; | |
| 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("the edge names its files", () => { | |
| 130 | expect(edgeName("forge")).toBe("forge"); | |
| 131 | expect(edgeName("app/abc")).toBe("app-abc"); | |
| 132 | expect(edgeName("../x")).toBeUndefined(); | |
| 133 | }); | |
| 134 | ||
| 135 | test("Cloudflare KV gets the same bytes as the file when configured", async () => { | |
| 136 | const calls: { url: string; init: RequestInit }[] = []; | |
| 137 | const fake = (async (url: string, init: RequestInit) => { | |
| 138 | calls.push({ url, init }); | |
| 139 | return new Response("{}", { status: 200 }); | |
| 140 | }) as unknown as typeof fetch; | |
| 141 | const kv = kvFromEnv({ FORGE_CF_ACCOUNT: "acct1", FORGE_CF_KV_NAMESPACE: "ns1", FORGE_CF_API_TOKEN: "t" }); | |
| 142 | expect(kvFromEnv({ FORGE_CF_ACCOUNT: "a/../b" })).toBeUndefined(); | |
| 143 | const edge = new EdgePublisher(dir, { kv, fetch: fake }); | |
| 144 | await edge.publish(app.configs.snapshot(FORGE_SCOPE)); | |
| 145 | expect(calls).toHaveLength(1); | |
| 146 | expect(calls[0]!.url).toBe( | |
| 147 | "https://api.cloudflare.com/client/v4/accounts/acct1/storage/kv/namespaces/ns1/values/forge", | |
| 148 | ); | |
| 149 | expect(calls[0]!.init.body).toBe(edge.read(FORGE_SCOPE)!.text); | |
| 150 | }); | |
| 151 | }); | |
| 152 | ||
| 153 | describe("the edge publisher", () => { | |
| 154 | test("a snapshot older than the last published is skipped, and a KV call has a timeout", async () => { | |
| 155 | const dir = await mkdtemp(join(tmpdir(), "forge-edge-")); | |
| 156 | try { | |
| 157 | const calls: RequestInit[] = []; | |
| 158 | const fake = (async (_u: string, init: RequestInit) => { | |
| 159 | calls.push(init); | |
| 160 | return new Response("{}", { status: 200 }); | |
| 161 | }) as unknown as typeof fetch; | |
| 162 | const kv = kvFromEnv({ FORGE_CF_ACCOUNT: "a", FORGE_CF_KV_NAMESPACE: "n", FORGE_CF_API_TOKEN: "t" }); | |
| 163 | const edge = new EdgePublisher(dir, { kv, fetch: fake }); | |
| 164 | const snap = (version: number) => ({ | |
| 165 | scope: "forge", id: `s${version}`, version, values: { v: version }, updatedAt: "now", | |
| 166 | }); | |
| 167 | await edge.publish(snap(2)); | |
| 168 | await edge.publish(snap(1)); | |
| 169 | expect(calls).toHaveLength(1); | |
| 170 | expect(calls[0]!.signal).toBeDefined(); | |
| 171 | expect(edge.read("forge")!.snapshot).toBe("s2"); | |
| 172 | } finally { | |
| 173 | await rm(dir, { recursive: true, force: true }); | |
| 174 | } | |
| 175 | }); | |
| 176 | ||
| 177 | test("a file altered on disk is not served", async () => { | |
| 178 | const dir = await mkdtemp(join(tmpdir(), "forge-edge-")); | |
| 179 | try { | |
| 180 | const edge = new EdgePublisher(dir); | |
| 181 | await edge.publish({ scope: "forge", id: "s1", version: 1, values: { v: 1 }, updatedAt: "now" }); | |
| 182 | const path = edge.pathOf("forge")!; | |
| 183 | writeFileSync(path, readFileSync(path, "utf8").replace('\\"v\\":1', '\\"v\\":9')); | |
| 184 | expect(new EdgePublisher(dir).read("forge")).toBeUndefined(); | |
| 185 | } finally { | |
| 186 | await rm(dir, { recursive: true, force: true }); | |
| 187 | } | |
| 188 | }); | |
| 189 | }); | |
| 190 | ||
| 191 | describe("cache headers, one helper per kind", () => { | |
| 192 | test("each kind sets what the table in docs/CACHE.md says", () => { | |
| 193 | const table: Record<CacheKind, string> = { | |
| 194 | immutable: "public, max-age=31536000, immutable", | |
| 195 | edge: "public, max-age=5, stale-while-revalidate=30", | |
| 196 | config: "private, no-cache", | |
| 197 | live: "no-store", | |
| 198 | }; | |
| 199 | for (const [kind, value] of Object.entries(table)) { | |
| 200 | expect(CACHE_CONTROL[kind as CacheKind]).toBe(value); | |
| 201 | expect(cacheHeaders(kind as CacheKind)["cache-control"]).toBe(value); | |
| 202 | } | |
| 203 | expect(cacheHeaders("edge", "abc").etag).toBe('"abc"'); | |
| 204 | expect(cacheHeaders("live", "abc").etag).toBeUndefined(); | |
| 205 | const docs = readFileSync(join(import.meta.dir, "..", "docs", "CACHE.md"), "utf8"); | |
| 206 | for (const value of Object.values(table)) expect(docs).toContain(value); | |
| 207 | }); | |
| 208 | ||
| 209 | test("a matching If-None-Match is a 304, counted as a validator hit", async () => { | |
| 210 | const before = rungCounts().validator; | |
| 211 | const url = "http://x/y"; | |
| 212 | const fresh = cached(new Request(url), "config", "s1", "{}"); | |
| 213 | expect(fresh.status).toBe(200); | |
| 214 | const again = cached(new Request(url, { headers: { "if-none-match": '"s1"' } }), "config", "s1", "{}"); | |
| 215 | expect(again.status).toBe(304); | |
| 216 | expect(await again.text()).toBe(""); | |
| 217 | const after = rungCounts().validator; | |
| 218 | expect(after.hit - before.hit).toBe(1); | |
| 219 | expect(after.miss - before.miss).toBe(1); | |
| 220 | const edge = rungCounts().edge.hit; | |
| 221 | noteRung("edge"); | |
| 222 | expect(rungCounts().edge.hit - edge).toBe(1); | |
| 223 | }); | |
| 224 | }); | |
| 225 | ||
| 226 | describe("config over HTTP", () => { | |
| 227 | let dir: string; | |
| 228 | let app: App; | |
| 229 | let http: ForgeHttp; | |
| 230 | let token: string; | |
| 231 | let ro: string; | |
| 232 | let slug: string; | |
| 233 | ||
| 234 | beforeAll(async () => { | |
| 235 | dir = await mkdtemp(join(tmpdir(), "forge-config-http-")); | |
| 236 | app = createApp({ dataDir: dir, port: 0 }); | |
| 237 | http = forgeHttp(app); | |
| 238 | const alice = await admin(app, "alice"); | |
| 239 | token = createToken(app.db, alice.id, "admin", "admin").token; | |
| 240 | ro = createToken(app.db, alice.id, "ro", "ro").token; | |
| 241 | const made = await newApp(app, alice, { name: "flags", description: "d", visibility: "public" }); | |
| 242 | if (!made.ok) throw new Error(String(made.error)); | |
| 243 | slug = made.value.app.slug; | |
| 244 | }); | |
| 245 | afterAll(async () => { | |
| 246 | app.close(); | |
| 247 | await rm(dir, { recursive: true, force: true }); | |
| 248 | }); | |
| 249 | ||
| 250 | const call = (path: string, init: RequestInit = {}, bearer?: string) => | |
| 251 | http.handle(new Request(`http://forge.test${path}`, { | |
| 252 | ...init, | |
| 253 | headers: { | |
| 254 | ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), | |
| 255 | "content-type": "application/json", | |
| 256 | ...(init.headers as Record<string, string> | undefined), | |
| 257 | }, | |
| 258 | })); | |
| 259 | const patch = (path: string, body: unknown, bearer?: string) => | |
| 260 | call(path, { method: "PATCH", body: JSON.stringify(body) }, bearer); | |
| 261 | ||
| 262 | test("an app reads its config with the snapshot id, and revalidates with it", async () => { | |
| 263 | expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 }, why: "x" })).status).toBe(401); | |
| 264 | expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 }, why: "x" }, ro)).status).toBe(403); | |
| 265 | const w = await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1, theme: "dark" }, why: "launch" }, token); | |
| 266 | expect(w.status).toBe(200); | |
| 267 | const wrote = (await w.json()) as { snapshot: string }; | |
| 268 | const r = await call(`/api/v1/apps/${slug}/config`, {}, ro); | |
| 269 | expect(r.status).toBe(200); | |
| 270 | const read = (await r.json()) as { snapshot: string; values: Record<string, unknown> }; | |
| 271 | expect(read.snapshot).toBe(wrote.snapshot); | |
| 272 | expect(read.values).toEqual({ a: 1, theme: "dark" }); | |
| 273 | expect(r.headers.get("etag")).toBe(`"${wrote.snapshot}"`); | |
| 274 | expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.config); | |
| 275 | const again = await call(`/api/v1/apps/${slug}/config`, { headers: { "if-none-match": `"${wrote.snapshot}"` } }, ro); | |
| 276 | expect(again.status).toBe(304); | |
| 277 | }); | |
| 278 | ||
| 279 | test("a bad write is a 422 and an unknown app a 404", async () => { | |
| 280 | expect((await patch(`/api/v1/apps/${slug}/config`, { set: { "Bad": 1 }, why: "x" }, token)).status).toBe(422); | |
| 281 | expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 } }, token)).status).toBe(422); | |
| 282 | expect((await call(`/api/v1/apps/nope/config`, {}, ro)).status).toBe(404); | |
| 283 | }); | |
| 284 | ||
| 285 | test("an oversized change is a 413, not a 422", async () => { | |
| 286 | const big = await patch(`/api/v1/apps/${slug}/config`, { set: { k: "x".repeat(300 * 1024) }, why: "x" }, token); | |
| 287 | expect(big.status).toBe(413); | |
| 288 | expect(((await big.json()) as { error: string }).error).toBe("too_large"); | |
| 289 | }); | |
| 290 | ||
| 291 | test("?changes=1 reads the ledger, under its own validator", async () => { | |
| 292 | await patch(`/api/v1/apps/${slug}/config`, { set: { led: 1 }, why: "ledger please" }, token); | |
| 293 | const r = await call(`/api/v1/apps/${slug}/config?changes=1`, {}, ro); | |
| 294 | const body = (await r.json()) as { snapshot: string; changes: { by: string; why: string; keys: string[] }[] }; | |
| 295 | expect(body.changes[0]).toMatchObject({ by: "alice", why: "ledger please", keys: ["led"] }); | |
| 296 | expect(r.headers.get("etag")).not.toBe(`"${body.snapshot}"`); | |
| 297 | expect(((await (await call(`/api/v1/apps/${slug}/config`, {}, ro)).json()) as object)).not.toHaveProperty("changes"); | |
| 298 | }); | |
| 299 | ||
| 300 | test("the ledger is an admin's: anonymous callers never get it, and it is never public", async () => { | |
| 301 | await patch("/api/v1/config", { set: { f: 1 }, why: "secret reason" }, token); | |
| 302 | const anon = await call("/api/v1/config?changes=1"); | |
| 303 | expect(await anon.text()).not.toContain("secret reason"); | |
| 304 | expect(anon.headers.get("cache-control")).toBe(CACHE_CONTROL.edge); | |
| 305 | const anonApp = await call(`/api/v1/apps/${slug}/config?changes=1`); | |
| 306 | expect(await anonApp.text()).not.toContain("changes"); | |
| 307 | const mine = await call("/api/v1/config?changes=1", {}, token); | |
| 308 | const body = (await mine.json()) as { changes: { by: string }[] }; | |
| 309 | expect(body.changes[0]!.by).toBe("alice"); | |
| 310 | expect(mine.headers.get("cache-control")).not.toContain("public"); | |
| 311 | }); | |
| 312 | ||
| 313 | test("a private app's config is never on the edge, and leaves it when the app goes private", async () => { | |
| 314 | const calls: { method: string; url: string }[] = []; | |
| 315 | const fake = (async (url: string, init: RequestInit) => { | |
| 316 | calls.push({ method: String(init.method), url }); | |
| 317 | return new Response("{}", { status: 200 }); | |
| 318 | }) as unknown as typeof fetch; | |
| 319 | const kv = kvFromEnv({ FORGE_CF_ACCOUNT: "a", FORGE_CF_KV_NAMESPACE: "n", FORGE_CF_API_TOKEN: "t" }); | |
| 320 | const kvDir = await mkdtemp(join(tmpdir(), "forge-config-kv-")); | |
| 321 | const kvApp = createApp({ dataDir: kvDir, port: 0 }); | |
| 322 | try { | |
| 323 | // route this process's publisher through the fake KV | |
| 324 | (kvApp as { edge: () => EdgePublisher }).edge = (() => { | |
| 325 | const e = new EdgePublisher(kvDir, { kv, fetch: fake }); | |
| 326 | return () => e; | |
| 327 | })(); | |
| 328 | const owner = await admin(kvApp, "bob"); | |
| 329 | const made = await newApp(kvApp, owner, { name: "secret", description: "d", visibility: "private" }); | |
| 330 | if (!made.ok) throw new Error(String(made.error)); | |
| 331 | const scope = appScope(made.value.app.id); | |
| 332 | const name = edgeName(scope)!; | |
| 333 | const edge = kvApp.edge(); | |
| 334 | const { edgeOpen } = await import("../src/cloud/edge_open.ts"); | |
| 335 | // the same wiring app.ts does on every change | |
| 336 | kvApp.configs.onChange((snap) => void edge.publish(snap, edgeOpen(kvApp.db, snap.scope))); | |
| 337 | kvApp.configs.set(scope, { k: "private" }, "bob", "w"); | |
| 338 | await waitFor(() => calls.some((c) => c.method === "DELETE"), { every: 5, within: 1000 }); | |
| 339 | expect(calls.filter((c) => c.method === "PUT" && c.url.endsWith(name))).toHaveLength(0); | |
| 340 | expect(existsSync(edge.pathOf(scope)!)).toBe(false); | |
| 341 | // made public: the file and KV key appear | |
| 342 | const { updateRepoSettings } = await import("../src/actions/repos.ts"); | |
| 343 | const { getRepoById } = await import("../src/core/repos.ts"); | |
| 344 | const repo = getRepoById(kvApp.db, made.value.app.repoId)!; | |
| 345 | const up = await updateRepoSettings(kvApp, owner, repo, { visibility: "public" }); | |
| 346 | expect(up.ok).toBe(true); | |
| 347 | await waitFor(() => calls.some((c) => c.method === "PUT"), { every: 5, within: 1000 }); | |
| 348 | expect(existsSync(edge.pathOf(scope)!)).toBe(true); | |
| 349 | expect(calls.some((c) => c.method === "PUT" && c.url.endsWith(name))).toBe(true); | |
| 350 | // private again: both go | |
| 351 | const again = await updateRepoSettings(kvApp, owner, getRepoById(kvApp.db, repo.id)!, { visibility: "private" }); | |
| 352 | expect(again.ok).toBe(true); | |
| 353 | await waitFor(() => calls.filter((c) => c.method === "DELETE").length > 1, { every: 5, within: 1000 }); | |
| 354 | expect(existsSync(edge.pathOf(scope)!)).toBe(false); | |
| 355 | expect(calls.some((c) => c.method === "DELETE" && c.url.endsWith(name))).toBe(true); | |
| 356 | } finally { | |
| 357 | kvApp.close(); | |
| 358 | await rm(kvDir, { recursive: true, force: true }); | |
| 359 | } | |
| 360 | }); | |
| 361 | ||
| 362 | test("the built assets take the immutable kind", async () => { | |
| 363 | const { stylesheetResponse } = await import("../src/web/asset.ts"); | |
| 364 | expect(stylesheetResponse(new Request("http://x/")).headers.get("cache-control")).toBe(CACHE_CONTROL.immutable); | |
| 365 | }); | |
| 366 | ||
| 367 | test("the forge's flags are readable by anyone and written only by an admin token", async () => { | |
| 368 | expect((await patch("/api/v1/config", { set: { f: true }, why: "w" }, ro)).status).toBe(403); | |
| 369 | const w = await patch("/api/v1/config", { set: { f: true }, why: "w" }, token); | |
| 370 | expect(w.status).toBe(200); | |
| 371 | const r = await call("/api/v1/config"); | |
| 372 | expect(((await r.json()) as { values: Record<string, unknown> }).values.f).toBe(true); | |
| 373 | expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.edge); | |
| 374 | }); | |
| 375 | ||
| 376 | test("every response names the snapshot the forge holds", async () => { | |
| 377 | const id = app.configs.snapshot(FORGE_SCOPE).id; | |
| 378 | for (const path of ["/healthz", "/api/v1/config", "/nowhere-at-all"]) { | |
| 379 | const r = await call(path, { headers: { accept: "application/json" } }); | |
| 380 | expect(r.headers.get("x-forge-config")).toBe(id); | |
| 381 | } | |
| 382 | }); | |
| 383 | ||
| 384 | test("the edge serves the signed file at a stable URL; a lagging copy is visible", async () => { | |
| 385 | const r = await call("/edge/config/forge.json"); | |
| 386 | expect(r.status).toBe(200); | |
| 387 | expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.edge); | |
| 388 | const key = await (await call("/edge/config/key.pem")).text(); | |
| 389 | const published = verifyEdgeFile(await r.json(), key)!; | |
| 390 | const id = app.configs.snapshot(FORGE_SCOPE).id; | |
| 391 | expect(published.snapshot).toBe(id); | |
| 392 | // a public app's file is served, under its id | |
| 393 | const scope = appScope( | |
| 394 | (await import("../src/core/apps.ts")).getAppBySlug(app.db, slug)!.id, | |
| 395 | ); | |
| 396 | const name = edgeName(scope)!; | |
| 397 | const mine = await call(`/edge/config/${name}.json`); | |
| 398 | expect(mine.status).toBe(200); | |
| 399 | expect(verifyEdgeFile(await mine.json(), key)!.scope).toBe(scope); | |
| 400 | // the write moves the id; the copy held before it now reads stale | |
| 401 | const w = await patch("/api/v1/config", { set: { g: 2 }, why: "move" }, token); | |
| 402 | const next = ((await w.json()) as { snapshot: string }).snapshot; | |
| 403 | expect(next).not.toBe(published.snapshot); | |
| 404 | expect((await call("/edge/config/..%2fsigning.pem")).status).toBe(404); | |
| 405 | expect((await call("/edge/config/app-nope.json")).status).toBe(404); | |
| 406 | }); | |
| 407 | ||
| 408 | test("the cache counters are an admin's to read", async () => { | |
| 409 | expect((await call("/api/v1/cache")).status).toBe(401); | |
| 410 | const r = await call("/api/v1/cache", {}, token); | |
| 411 | const body = (await r.json()) as { rungs: Record<string, { hit: number }> }; | |
| 412 | expect(body.rungs.process!.hit).toBeGreaterThan(0); | |
| 413 | }); | |
| 414 | }); |
test/data-browser.test.ts +2
| @@ -33,6 +33,8 @@ const AUDITED_CLEAR: string[] = [ | ||
| 33 | 33 | "child_reach_ask.body_id", |
| 34 | 34 | "child_reach_grant.body_id", |
| 35 | 35 | "comment.body", |
| 36 | // The names of the keys a config change touched, never their values (`core/config.ts`). | |
| 37 | "config_change.keys", | |
| 36 | 38 | // The call a kept Talk result came from, in plain words (`stepOf` in core/talk_steps.ts, from a |
| 37 | 39 | // card-drawing read: "Issues"); never an argument's value. |
| 38 | 40 | "conversation_card.said", |
test/docs-not-found.test.ts +1 −1
| @@ -46,7 +46,7 @@ for (const path of ["/docs/start", "/docs/features/nope"]) { | ||
| 46 | 46 | } |
| 47 | 47 | |
| 48 | 48 | /** Routes that are data feeds a page reads, not pages: they answer JSON or a stream by design. */ |
| 49 | const FEEDS = new Set(["/forges/:name/bill", "/forges/:name/ready", "/:owner/:name/stream", "/:owner/:name/paths/:ref", "/origins/:id/r/:owner/:name/paths/:ref"]); | |
| 49 | const FEEDS = new Set(["/edge/config/:file", "/forges/:name/bill", "/forges/:name/ready", "/:owner/:name/stream", "/:owner/:name/paths/:ref", "/origins/:id/r/:owner/:name/paths/:ref"]); | |
| 50 | 50 | |
| 51 | 51 | test("no GET page route answers a browser a JSON 404", async () => { |
| 52 | 52 | const patterns = [...new Set(buildRouter().routes().filter((r) => r.method === "GET").map((r) => r.pattern))].filter( |
test/job-slices.test.ts +1
| @@ -263,6 +263,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 263 | 263 | * on. |
| 264 | 264 | */ |
| 265 | 265 | const UNTIMED: Record<string, string> = { |
| 266 | "config-poll": "a short timer that re-reads one small row per scope and fires listeners only when another process changed it (core/config.ts start/refresh); config-store.test.ts drives a change from a second handle", | |
| 266 | 267 | "allocation": "one settle pass hourly over repositories with a wallet (core/allocation.ts settleAll): indexed reads and a write only when a week turned; allocation tests drive settleAll directly", |
| 267 | 268 | "copies-prune": "two DELETEs on indexed time columns (core/copies.ts pruneCopies), hourly on the outsider prune's own timer; copies-elsewhere.test.ts drives both fades", |
| 268 | 269 | "places-page-wait": "a one-shot timer in the new-forge page that only resolves the race when the Places catalog refresh outlives PAGE_WAIT_MS; no work of its own; new-forge-refresh.test.ts drives the refresh", |
test/no-polling.test.ts +1
| @@ -302,6 +302,7 @@ export function findPolling(source: string): string[] { | ||
| 302 | 302 | */ |
| 303 | 303 | const ORIGIN = "needs a connected origin account; the seed connects none"; |
| 304 | 304 | const NOT_WALKED: Record<string, string> = { |
| 305 | "/edge/config/:file": "a published config file for the edge, JSON or a key, not a page; the seed publishes none", | |
| 305 | 306 | "/:owner/-/teams/:team": "needs an organization and a team", |
| 306 | 307 | "/:owner/:name/app/:env/open": "needs a running app environment to open", |
| 307 | 308 | "/:owner/:name/archive/:file": "a tarball download, not a page; the file name is one the seed cannot guess", |
test/openapi-drift.test.ts +1
| @@ -9,6 +9,7 @@ import { norm, registered } from "./helpers/registered_routes.ts"; | ||
| 9 | 9 | const NOT_ROUTED: Readonly<Record<string, string>> = { |
| 10 | 10 | "GET /contract/openapi.json": "the document, an alias of /api/v1/openapi.json served outside /api/v1", |
| 11 | 11 | "GET /api/v1/repos/{}/{}/app/production/open": "the described form of the routed /app/:env/open, with env fixed to production", |
| 12 | "GET /edge/config/{}": "the published config snapshot, routed outside /api/v1 (src/http/config.ts); a signed file for the edge, not a REST call", | |
| 12 | 13 | "GET /metrics": "routed outside /api/v1 (src/http/api.ts); the scan reads /api/v1 routes only", |
| 13 | 14 | "GET /health": "routed outside /api/v1 (src/http/api.ts), the monitor's alias of /api/v1/health (#13191)", |
| 14 | 15 | "GET /{}/{}/pulls/{}/check.txt": "routed outside /api/v1 (src/http/server.ts, check_text.ts); test/openapi-check-txt.test.ts pins it to server.ts", |
test/openapi.test.ts +1 −1
| @@ -41,7 +41,7 @@ test("every http route the manifest names is described", () => { | ||
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | 43 | test("every described route is registered in the router", () => { |
| 44 | const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/contract/served.ts", | |
| 44 | const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/config.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/contract/served.ts", | |
| 45 | 45 | ...readdirSync("src/http/api").map((f) => `src/http/api/${f}`)] |
| 46 | 46 | .map((f) => readFileSync(f, "utf8")) |
| 47 | 47 | .join("\n") |
test/pages-budget.test.ts +1 −1
| @@ -70,7 +70,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = { | ||
| 70 | 70 | }; |
| 71 | 71 | |
| 72 | 72 | /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */ |
| 73 | const MAX_UNFIXTURED = 160; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839) | |
| 73 | const MAX_UNFIXTURED = 162; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839) | |
| 74 | 74 | |
| 75 | 75 | /** Streams and live fragments: no page. */ |
| 76 | 76 | const NOT_PAGES = new Set([ |
test/security-floor-routes.test.ts +1
| @@ -70,6 +70,7 @@ const REPORT = "needs a report an outsider filed; the seed has none"; | ||
| 70 | 70 | const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothing"; |
| 71 | 71 | const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers its headers)"; |
| 72 | 72 | const UNSEEDED: Record<string, string> = { |
| 73 | "/edge/config/:file": "a published file name, written by a config change the seed does not make (test/config-store.test.ts covers its headers)", | |
| 73 | 74 | "/:owner/-/teams/:team": ORG, |
| 74 | 75 | "/api/v1/repos/:owner/:name/changes/:room": "an app's change stream needs forge.json sync:true on its default branch, which the seed does not declare (test/app-changes.test.ts covers it)", |
| 75 | 76 | "/api/v1/repos/:owner/:name/drop/:file": "a file name in an app's private drop; the seed drops none", |
new above
offline