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

Forgify a business: origins mirror its repos in, extract pulls them apart, the crew writes the sync and pull adapters, and the result ships as its own forge #467

Closed opened this in answer to
Closed without merging

scout/forge:scout/390-forgify-a-business-origins-mirror-its-re → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +934 −0
docs/ADAPTERS.md added +15
@@ -0,0 +1,15 @@
1 # Adapters
2
3 An app whose `forge.json` carries an `adapter` block is a sync adapter: it
4 pulls an external system into its own state on a schedule. The forge parses
5 the block at the boundary (`src/apps/adapter.ts`), runs pulls (`src/apps/pull.ts`),
6 records each one (`src/core/adapter_pulls.ts`) and shows the last pull on the
7 app page.
8
9 The block declares the source (name and allowed hosts), the interval, and typed
10 config with env names and defaults. Pulls must be idempotent; hosts outside the
11 declared list are refused (`hostAllowed`). `examples/adapter-template/` is a
12 working starting point for the crew.
13
14 Not done here: the first real adapters (owner to choose) and Atlas turning a
15 description into apps and adapters.
examples/adapter-template/README.md added +8
@@ -0,0 +1,8 @@
1 # Adapter template
2
3 Copy this directory into a new repository to sync an external system into the
4 forge. Rewrite `src/pull.ts` (the source's URL and page shape) and the
5 `adapter` block of `forge.json` (source, hosts, schedule, config); keep
6 `src/guard.ts`, `src/store.ts` and the `POST /pull` handler as they are. The
7 contract is in `docs/ADAPTERS.md` of the forge. Run its tests with `bun test`.
8 Zero dependencies.
examples/adapter-template/forge.json added +16
@@ -0,0 +1,16 @@
1 {
2 "app": {
3 "run": "bun run src/server.ts",
4 "install": "",
5 "test": "bun test",
6 "health": "/healthz"
7 },
8 "adapter": {
9 "source": { "name": "Example API", "hosts": ["api.example.com"] },
10 "schedule": { "every": "15m" },
11 "config": {
12 "api_token": { "type": "secret", "env": "EXAMPLE_API_TOKEN", "required": true },
13 "page_size": { "type": "number", "env": "EXAMPLE_PAGE_SIZE", "default": 100 }
14 }
15 }
16 }
examples/adapter-template/src/guard.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * The adapter's only way out: a fetch that refuses any host the manifest
3 * did not declare (the forge hands the list over as FORGE_ADAPTER_HOSTS).
4 * Every outbound call in this app goes through it — keep it that way.
5 */
6
7 export function hostAllowed(url: string, hosts: readonly string[]): boolean {
8 let u: URL;
9 try {
10 u = new URL(url);
11 } catch {
12 return false;
13 }
14 return u.protocol === "https:" && u.username === "" && hosts.includes(u.hostname);
15 }
16
17 export const declaredHosts = (
18 value = process.env["FORGE_ADAPTER_HOSTS"] ?? "",
19 ): string[] => value.split(",").filter((h) => h !== "");
20
21 export function guardedFetch(
22 hosts: readonly string[],
23 inner: typeof fetch = fetch,
24 ): typeof fetch {
25 return ((input: string | URL | Request, init?: RequestInit) => {
26 const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
27 if (!hostAllowed(url, hosts))
28 return Promise.reject(new Error(`refused: ${new URL(url, "http://x").hostname} is not a declared source host`));
29 return inner(input, { ...init, redirect: "error" });
30 }) as typeof fetch;
31 }
examples/adapter-template/src/pull.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * The pull: the one function to rewrite for a real source. Read the cursor,
3 * ask the source for what is after it, keep it, move the cursor. It returns
4 * the contract's shape — `{pulled, skipped, cursor, errors}` — and never
5 * throws: a source that fails is `errors`, with the cursor where it was.
6 *
7 * The source here is imaginary: GET https://api.example.com/items?after=<cursor>
8 * answering `{"items":[{"id":"…","body":"…"}],"next":"<cursor>"}`.
9 */
10
11 import type { Store } from "./store.ts";
12
13 export interface PullResult {
14 pulled: number;
15 skipped: number;
16 cursor: string;
17 errors: string[];
18 }
19
20 const ITEMS_MAX = 1_000;
21
22 export async function pull(
23 store: Store,
24 fetcher: typeof fetch,
25 token: string,
26 ): Promise<PullResult> {
27 const cursor = store.cursor();
28 const result: PullResult = { pulled: 0, skipped: 0, cursor, errors: [] };
29 try {
30 const res = await fetcher(
31 `https://api.example.com/items?after=${encodeURIComponent(cursor)}`,
32 { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30_000) },
33 );
34 if (!res.ok) throw new Error(`the source answered ${res.status}`);
35 const page = (await res.json()) as { items?: unknown; next?: unknown };
36 // Everything from the source is input: check it before it is kept.
37 if (!Array.isArray(page.items) || page.items.length > ITEMS_MAX) throw new Error("the source's page did not read");
38 const items = [];
39 for (const raw of page.items as { id?: unknown; body?: unknown }[]) {
40 if (typeof raw?.id !== "string" || raw.id === "" || raw.id.length > 200 || typeof raw.body !== "string") {
41 result.skipped += 1;
42 continue;
43 }
44 items.push({ id: raw.id, body: raw.body.slice(0, 10_000) });
45 }
46 const next = typeof page.next === "string" && page.next.length <= 500 ? page.next : cursor;
47 const fresh = store.keep(items, next);
48 result.pulled = fresh;
49 result.skipped += items.length - fresh;
50 result.cursor = next;
51 } catch (error) {
52 result.errors.push(error instanceof Error ? error.message : "the pull failed");
53 }
54 return result;
55 }
examples/adapter-template/src/server.ts added +60
@@ -0,0 +1,60 @@
1 import { timingSafeEqual } from "node:crypto";
2 import { declaredHosts, guardedFetch } from "./guard.ts";
3 import { pull } from "./pull.ts";
4 import { Store } from "./store.ts";
5
6 const esc = (s: string): string =>
7 s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
8
9 const SECURITY = {
10 "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'",
11 "x-content-type-options": "nosniff",
12 "referrer-policy": "no-referrer",
13 };
14
15 export function handler(store: Store, key: string, token: () => string, fetcher: typeof fetch) {
16 let pulling = false;
17 const send = (body: string, type: string, status = 200): Response =>
18 new Response(body, { status, headers: { "content-type": type, ...SECURITY } });
19
20 return async (req: Request): Promise<Response> => {
21 const { pathname } = new URL(req.url);
22 if (pathname === "/healthz") return send("ok", "text/plain");
23 if (pathname === "/" && req.method === "GET")
24 return send(
25 `<!doctype html><meta charset=utf-8><title>Adapter</title><h1>Adapter</h1><p>${store.count()} records · cursor ${esc(store.cursor() || "(start)")}</p>`,
26 "text/html; charset=utf-8",
27 );
28 if (pathname === "/pull" && req.method === "POST") {
29 // Only the forge may start a pull: it holds the key, a browser does not.
30 const given = (req.headers.get("authorization") ?? "").replace(/^Bearer /, "");
31 const a = Buffer.from(given);
32 const b = Buffer.from(key);
33 if (key === "" || a.length !== b.length || !timingSafeEqual(a, b) || req.headers.has("origin"))
34 return send("forbidden", "text/plain", 403);
35 if (pulling) return send(JSON.stringify({ pulled: 0, skipped: 0, cursor: store.cursor(), errors: ["a pull is already running"] }), "application/json");
36 pulling = true;
37 try {
38 return send(JSON.stringify(await pull(store, fetcher, token())), "application/json");
39 } finally {
40 pulling = false;
41 }
42 }
43 return send("not found", "text/plain", 404);
44 };
45 }
46
47 if (import.meta.main) {
48 const store = new Store(process.env["FORGE_APP_DATA"] ?? "./data");
49 const serve = handler(
50 store,
51 process.env["FORGE_APP_IDENTITY_KEY"] ?? "",
52 () => process.env["EXAMPLE_API_TOKEN"] ?? "",
53 guardedFetch(declaredHosts()),
54 );
55 Bun.serve({
56 hostname: process.env["HOST"] ?? "127.0.0.1",
57 port: Number(process.env["PORT"] ?? 3000),
58 fetch: serve,
59 });
60 }
examples/adapter-template/src/store.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * The adapter's state, all of it under FORGE_APP_DATA: the records it has
3 * pulled and the cursor it resumes from. One file, bun:sqlite.
4 */
5
6 import { Database } from "bun:sqlite";
7 import { mkdirSync } from "node:fs";
8 import { join } from "node:path";
9
10 export interface Item {
11 readonly id: string;
12 readonly body: string;
13 }
14
15 export class Store {
16 readonly db: Database;
17
18 constructor(dir: string) {
19 mkdirSync(dir, { recursive: true });
20 this.db = new Database(join(dir, "adapter.sqlite"));
21 this.db.run("PRAGMA journal_mode = WAL");
22 this.db.run("CREATE TABLE IF NOT EXISTS item (id TEXT PRIMARY KEY, body TEXT NOT NULL)");
23 this.db.run("CREATE TABLE IF NOT EXISTS cursor (id INTEGER PRIMARY KEY CHECK (id = 1), value TEXT NOT NULL)");
24 }
25
26 cursor(): string {
27 return this.db.query<{ value: string }, []>("SELECT value FROM cursor").get()?.value ?? "";
28 }
29
30 count(): number {
31 return this.db.query<{ n: number }, []>("SELECT count(*) AS n FROM item").get()?.n ?? 0;
32 }
33
34 /**
35 * Keep a page and move the cursor in one transaction: a pull that dies
36 * halfway moves nothing, and a replay of the same page writes nothing new.
37 * Returns how many items were new.
38 */
39 keep(items: readonly Item[], cursor: string): number {
40 let fresh = 0;
41 this.db.transaction(() => {
42 for (const item of items)
43 fresh += this.db.query("INSERT OR IGNORE INTO item (id, body) VALUES (?1, ?2)").run(item.id, item.body).changes;
44 this.db.query("INSERT INTO cursor (id, value) VALUES (1, ?1) ON CONFLICT(id) DO UPDATE SET value = excluded.value").run(cursor);
45 })();
46 return fresh;
47 }
48 }
examples/adapter-template/test/adapter.test.ts added +87
@@ -0,0 +1,87 @@
1 import { describe, expect, test } from "bun:test";
2 import { mkdtempSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { guardedFetch } from "../src/guard.ts";
6 import { pull } from "../src/pull.ts";
7 import { handler } from "../src/server.ts";
8 import { Store } from "../src/store.ts";
9
10 const fresh = () => new Store(mkdtempSync(join(tmpdir(), "adapter-")));
11 const source = (pages: Record<string, unknown>): typeof fetch =>
12 (async (url: string) => {
13 const after = new URL(url).searchParams.get("after") ?? "";
14 const page = pages[after];
15 return page === undefined ? new Response("no", { status: 500 }) : Response.json(page);
16 }) as unknown as typeof fetch;
17
18 const pages = {
19 "": { items: [{ id: "a", body: "one" }, { id: "b", body: "two" }, { nope: 1 }], next: "c1" },
20 c1: { items: [{ id: "b", body: "two" }, { id: "c", body: "three" }], next: "c2" },
21 };
22
23 describe("the pull", () => {
24 test("keeps new records, skips bad and seen ones, moves the cursor", async () => {
25 const store = fresh();
26 const f = source(pages);
27 expect(await pull(store, f, "t")).toEqual({ pulled: 2, skipped: 1, cursor: "c1", errors: [] });
28 expect(await pull(store, f, "t")).toEqual({ pulled: 1, skipped: 1, cursor: "c2", errors: [] });
29 expect(store.count()).toBe(3);
30 });
31
32 test("a replay of the same page writes nothing new", async () => {
33 const store = fresh();
34 const f = source(pages);
35 await pull(store, f, "t");
36 store.db.run("DELETE FROM cursor"); // the same cursor again
37 const again = await pull(store, f, "t");
38 expect(again.pulled).toBe(0);
39 expect(store.count()).toBe(2);
40 });
41
42 test("a failing source is an error with the cursor where it was", async () => {
43 const store = fresh();
44 await pull(store, source(pages), "t");
45 const r = await pull(store, source({}), "t");
46 expect(r.errors).toEqual(["the source answered 500"]);
47 expect(r.cursor).toBe("c1");
48 expect(store.cursor()).toBe("c1");
49 });
50 });
51
52 describe("outbound hosts", () => {
53 test("a host the manifest did not declare is refused", async () => {
54 const inner = (async () => new Response("leaked")) as unknown as typeof fetch;
55 const f = guardedFetch(["api.example.com"], inner);
56 expect((await f("https://api.example.com/x")).status).toBe(200);
57 for (const url of [
58 "https://evil.example.net/x",
59 "http://api.example.com/x",
60 "https://api.example.com.evil.net/x",
61 "https://[email protected]/x",
62 "not a url",
63 ])
64 await expect(f(url)).rejects.toThrow(/refused/);
65 });
66 });
67
68 describe("POST /pull", () => {
69 const serve = () => handler(fresh(), "k3y", () => "t", source(pages));
70 const post = (headers: Record<string, string>) =>
71 new Request("http://app/pull", { method: "POST", headers });
72
73 test("only the forge's key starts a pull", async () => {
74 const h = serve();
75 expect((await h(post({}))).status).toBe(403);
76 expect((await h(post({ authorization: "Bearer nope" }))).status).toBe(403);
77 expect((await h(post({ authorization: "Bearer k3y", origin: "http://evil" }))).status).toBe(403);
78 const ok = await h(post({ authorization: "Bearer k3y" }));
79 expect(await ok.json()).toEqual({ pulled: 2, skipped: 1, cursor: "c1", errors: [] });
80 });
81
82 test("security headers are on every response", async () => {
83 const res = await serve()(new Request("http://app/"));
84 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
85 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
86 });
87 });
src/apps/adapter.ts added +141
@@ -0,0 +1,141 @@
1 /**
2 * What an adapter declares about itself: the optional `adapter` block of
3 * `forge.json`, validated here and nowhere else. An adapter is an app that
4 * syncs one external system in; declaring it is what lets the forge
5 * schedule its pulls, show them, and say which host it may talk to
6 * (`docs/ADAPTERS.md`).
7 *
8 * Config carries names, never values: a secret field points at an
9 * operator variable (`core/app_env.ts`), so the repository can be read by
10 * anyone who can read the code without reading a credential.
11 */
12
13 import { isReservedAppEnvName } from "../core/app_env.ts";
14 import { err, ok, type Result } from "../kernel/result.ts";
15
16 export type AdapterFieldType = "string" | "number" | "boolean" | "secret";
17
18 export interface AdapterField {
19 readonly name: string;
20 readonly type: AdapterFieldType;
21 /** The environment variable the adapter reads it from. */
22 readonly env: string;
23 readonly required: boolean;
24 /** Never set on a secret. */
25 readonly default: string | number | boolean | null;
26 }
27
28 export interface AdapterManifest {
29 readonly source: { readonly name: string; readonly hosts: readonly string[] };
30 /** Milliseconds between pulls. */
31 readonly everyMs: number;
32 readonly config: readonly AdapterField[];
33 }
34
35 export const PULL_EVERY_MIN_MS = 60_000;
36 export const PULL_EVERY_MAX_MS = 24 * 3_600_000;
37 const HOSTS_MAX = 8;
38 const FIELDS_MAX = 32;
39 const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } as const;
40 const HOST = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
41 const FIELD_NAME = /^[a-z][a-z0-9_]{0,39}$/;
42 const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
43 const TYPES: readonly string[] = ["string", "number", "boolean", "secret"];
44
45 type Json = Record<string, unknown>;
46 const isObject = (v: unknown): v is Json =>
47 typeof v === "object" && v !== null && !Array.isArray(v);
48 const bad = (message: string): Result<never, string> =>
49 err(`forge.json: adapter.${message}`);
50
51 /** `"15m"` → 900000. Whole numbers of s/m/h/d, one minute to one day. */
52 export function parseEvery(value: unknown): Result<number, string> {
53 const m = typeof value === "string" ? /^([1-9]\d{0,5})([smhd])$/.exec(value) : null;
54 if (m === null)
55 return bad('schedule.every must look like "15m" (a whole number, then s, m, h or d)');
56 const ms = Number(m[1]) * UNIT_MS[m[2] as keyof typeof UNIT_MS];
57 if (ms < PULL_EVERY_MIN_MS || ms > PULL_EVERY_MAX_MS)
58 return bad("schedule.every must be between 1m and 1d");
59 return ok(ms);
60 }
61
62 /** A bare lowercase hostname: no scheme, port, path, wildcard or address. */
63 export const isSourceHost = (value: string): boolean =>
64 HOST.test(value) && !/^[0-9.]+$/.test(value);
65
66 /** `adapter` is the raw block; `undefined` means the app is not an adapter. */
67 export function parseAdapter(
68 raw: unknown,
69 ): Result<AdapterManifest | null, string> {
70 if (raw === undefined) return ok(null);
71 if (!isObject(raw)) return bad("must be an object");
72 const source = raw["source"];
73 if (!isObject(source)) return bad("source is required");
74 const name = source["name"];
75 if (typeof name !== "string" || !/^[\w .-]{1,60}$/.test(name))
76 return bad("source.name must be 1–60 letters, digits, spaces, dots or dashes");
77 const hosts = source["hosts"];
78 if (!Array.isArray(hosts) || hosts.length === 0 || hosts.length > HOSTS_MAX)
79 return bad(`source.hosts must list 1–${HOSTS_MAX} hostnames`);
80 for (const host of hosts)
81 if (typeof host !== "string" || !isSourceHost(host))
82 return bad("source.hosts entries must be bare lowercase hostnames (no scheme, port or path)");
83 const schedule = raw["schedule"];
84 if (!isObject(schedule)) return bad("schedule is required");
85 const every = parseEvery(schedule["every"]);
86 if (!every.ok) return every;
87
88 const config = raw["config"] ?? {};
89 if (!isObject(config)) return bad("config must be an object");
90 const names = Object.keys(config);
91 if (names.length > FIELDS_MAX) return bad(`config may name at most ${FIELDS_MAX} fields`);
92 const fields: AdapterField[] = [];
93 for (const fieldName of names) {
94 const f = config[fieldName];
95 if (!FIELD_NAME.test(fieldName))
96 return bad(`config.${fieldName}: names are lowercase letters, digits and _`);
97 if (!isObject(f)) return bad(`config.${fieldName} must be an object`);
98 const type = f["type"];
99 if (typeof type !== "string" || !TYPES.includes(type))
100 return bad(`config.${fieldName}.type must be one of ${TYPES.join(", ")}`);
101 const env = f["env"];
102 if (typeof env !== "string" || !ENV_NAME.test(env) || isReservedAppEnvName(env))
103 return bad(`config.${fieldName}.env must name an operator variable (A–Z, 0–9, _) the forge does not own`);
104 const def = f["default"];
105 if (type === "secret") {
106 if (def !== undefined || f["value"] !== undefined)
107 return bad(`config.${fieldName} is a secret: it names a variable, it never holds a value`);
108 } else if (
109 def !== undefined &&
110 typeof def !== type
111 )
112 return bad(`config.${fieldName}.default must be a ${type}`);
113 if (typeof def === "string" && def.length > 200)
114 return bad(`config.${fieldName}.default is too long`);
115 if (f["required"] !== undefined && typeof f["required"] !== "boolean")
116 return bad(`config.${fieldName}.required must be true or false`);
117 fields.push({
118 name: fieldName,
119 type: type as AdapterFieldType,
120 env,
121 required: f["required"] === true,
122 default: (def as string | number | boolean | undefined) ?? null,
123 });
124 }
125 return ok({
126 source: { name, hosts: hosts as string[] },
127 everyMs: every.value,
128 config: fields,
129 });
130 }
131
132 /** Whether `url` may be fetched by an adapter that declared `hosts`: https, exact host. */
133 export function hostAllowed(url: string, hosts: readonly string[]): boolean {
134 let u: URL;
135 try {
136 u = new URL(url);
137 } catch {
138 return false;
139 }
140 return u.protocol === "https:" && u.username === "" && hosts.includes(u.hostname);
141 }
src/apps/manifest.ts +10
@@ -11,6 +11,7 @@
1111 */
1212
1313 import { err, ok, type Result } from "../kernel/result.ts";
14 import { parseAdapter, type AdapterManifest } from "./adapter.ts";
1415
1516 export interface AppManifest {
1617 /** The command that serves on `$PORT`. Run through `sh -c`, `exec`-ed. */
@@ -35,6 +36,11 @@ export interface AppManifest {
3536 * before this field existed.
3637 */
3738 readonly looks: readonly string[];
39 /**
40 * Set when the app syncs an external system in: the forge schedules its
41 * pulls (`apps/pull.ts`). `null` for every app that is not one.
42 */
43 readonly adapter: AdapterManifest | null;
3844 }
3945
4046 export type ManifestError =
@@ -75,6 +81,7 @@ export function parseManifest(
7581 ready: READY_DEFAULT,
7682 tty: null,
7783 looks: ["/"],
84 adapter: null,
7885 });
7986 }
8087
@@ -117,6 +124,8 @@ export function parseManifest(
117124 );
118125 const looks = looksField(app);
119126 if (!looks.ok) return looks;
127 const adapter = parseAdapter(parsed.value["adapter"]);
128 if (!adapter.ok) return invalid(adapter.error);
120129
121130 return ok({
122131 run: runCommand,
@@ -133,6 +142,7 @@ export function parseManifest(
133142 ready: ready ?? READY_DEFAULT,
134143 tty: tty.value || null,
135144 looks: looks.value,
145 adapter: adapter.value,
136146 });
137147 }
138148
src/apps/process.ts +6
@@ -111,6 +111,8 @@ export function appEnv(input: {
111111 vars?: Record<string, string> | undefined;
112112 /** A read-only forge token for this process (`apps/token.ts`). */
113113 forgeToken?: string | undefined;
114 /** An adapter's declared source hosts: the only ones it may reach. */
115 adapterHosts?: readonly string[] | undefined;
114116 }): Record<string, string> {
115117 const pull = envPull(input.env);
116118 // The operator's variables go underneath everything the forge names, so
@@ -135,6 +137,9 @@ export function appEnv(input: {
135137 ...(input.forgeToken === undefined
136138 ? {}
137139 : { FORGE_TOKEN: input.forgeToken }),
140 ...(input.adapterHosts === undefined
141 ? {}
142 : { FORGE_ADAPTER_HOSTS: input.adapterHosts.join(",") }),
138143 ...(pull === undefined ? {} : { FORGE_APP_PULL: String(pull) }),
139144 // Printed verbatim by an app that tells people how to reach its
140145 // terminal; a guessed form (`[email protected]`) reaches the forge instead.
@@ -327,6 +332,7 @@ export async function startProcess(
327332 ssh: input.ssh,
328333 vars: input.vars,
329334 forgeToken: input.forgeToken,
335 adapterHosts: manifest.adapter?.source.hosts,
330336 }),
331337 stdin: "ignore",
332338 stdout: "pipe",
src/apps/pull.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * One pull: the forge calls an adapter's `POST /pull`, checks what comes
3 * back against the contract (`docs/ADAPTERS.md`), and records it — whatever
4 * came of it. The adapter owns its cursor and its records; the forge only
5 * schedules, bounds and remembers. A reply that does not read is a failed
6 * pull with the reason, never a guess at what was meant.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import type { AppRecord } from "../core/apps.ts";
11 import { recordPull, type AdapterPull } from "../core/adapter_pulls.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13
14 export interface PullReply {
15 readonly pulled: number;
16 readonly skipped: number;
17 readonly cursor: string;
18 readonly errors: readonly string[];
19 }
20
21 const COUNT_MAX = 1_000_000_000;
22 const CURSOR_MAX = 500;
23 const ERRORS_MAX = 50;
24 export const PULL_TIMEOUT_MS = 5 * 60_000;
25 const BODY_MAX = 64 * 1024;
26
27 const isCount = (v: unknown): v is number =>
28 typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= COUNT_MAX;
29
30 /** The reply an adapter owes: `{pulled, skipped, cursor, errors}`. */
31 export function parseReply(value: unknown): Result<PullReply, string> {
32 if (typeof value !== "object" || value === null || Array.isArray(value))
33 return err("the reply was not a JSON object");
34 const v = value as Record<string, unknown>;
35 if (!isCount(v["pulled"])) return err("reply.pulled must be a whole number");
36 if (!isCount(v["skipped"])) return err("reply.skipped must be a whole number");
37 const cursor = v["cursor"];
38 if (typeof cursor !== "string" || cursor.length > CURSOR_MAX || /[\x00-\x1f\x7f]/.test(cursor))
39 return err(`reply.cursor must be one line of at most ${CURSOR_MAX} characters`);
40 const errors = v["errors"];
41 if (
42 !Array.isArray(errors) ||
43 errors.length > ERRORS_MAX ||
44 errors.some((e) => typeof e !== "string")
45 )
46 return err(`reply.errors must be a list of at most ${ERRORS_MAX} strings`);
47 return ok({
48 pulled: v["pulled"],
49 skipped: v["skipped"],
50 cursor,
51 errors: (errors as string[]).map((e) => e.slice(0, 200)),
52 });
53 }
54
55 export interface PullInput {
56 readonly db: Database;
57 readonly app: AppRecord;
58 readonly port: number;
59 /**
60 * The app's identity key (`FORGE_APP_IDENTITY_KEY`), sent as a bearer
61 * token: `/pull` is reachable through the public proxy like any path, and
62 * only the forge holds this.
63 */
64 readonly key: string;
65 readonly fetch?: typeof fetch | undefined;
66 readonly timeoutMs?: number | undefined;
67 readonly now?: (() => number) | undefined;
68 }
69
70 export async function runPull(input: PullInput): Promise<AdapterPull> {
71 const now = input.now ?? Date.now;
72 const started = now();
73 const done = (
74 state: "ok" | "failed",
75 summary: string,
76 reply?: PullReply,
77 ): AdapterPull =>
78 recordPull(input.db, {
79 appId: input.app.id,
80 state,
81 pulled: reply?.pulled ?? 0,
82 skipped: reply?.skipped ?? 0,
83 errors: reply?.errors.length ?? 0,
84 cursor: reply?.cursor ?? "",
85 summary,
86 startedAt: new Date(started).toISOString(),
87 durationMs: Math.max(0, now() - started),
88 });
89 try {
90 const res = await (input.fetch ?? fetch)(
91 `http://127.0.0.1:${input.port}/pull`,
92 {
93 method: "POST",
94 headers: {
95 "content-type": "application/json",
96 authorization: `Bearer ${input.key}`,
97 },
98 body: "{}",
99 redirect: "error",
100 signal: AbortSignal.timeout(input.timeoutMs ?? PULL_TIMEOUT_MS),
101 },
102 );
103 const text = (await res.text()).slice(0, BODY_MAX);
104 if (!res.ok) return done("failed", `the adapter answered ${res.status}`);
105 let json: unknown;
106 try {
107 json = JSON.parse(text);
108 } catch {
109 return done("failed", "the reply was not JSON");
110 }
111 const reply = parseReply(json);
112 if (!reply.ok) return done("failed", reply.error);
113 const r = reply.value;
114 const words = `pulled ${r.pulled}, skipped ${r.skipped}`;
115 return r.errors.length === 0
116 ? done("ok", words, r)
117 : done(
118 "failed",
119 `${words}, ${r.errors.length} error${r.errors.length === 1 ? "" : "s"}: ${r.errors[0]}`,
120 r,
121 );
122 } catch (error) {
123 const timedOut = error instanceof DOMException && error.name === "TimeoutError";
124 return done("failed", timedOut ? "the pull timed out" : "the adapter was not reachable");
125 }
126 }
127
128 /** Whether a pull is owed: none yet, or the interval has passed since the last began. */
129 export function pullDue(
130 lastStartedAt: string | undefined,
131 everyMs: number,
132 now: number,
133 ): boolean {
134 return lastStartedAt === undefined || now - Date.parse(lastStartedAt) >= everyMs;
135 }
src/apps/runtime.ts +62
@@ -20,6 +20,9 @@ import { join } from "node:path";
2020 import type { App } from "../app.ts";
2121 import { getAppByRepo, listApps, type AppRecord } from "../core/apps.ts";
2222 import { resolveAppEnv } from "../core/app_env.ts";
23 import type { AdapterManifest } from "./adapter.ts";
24 import { lastPullOf } from "../core/adapter_pulls.ts";
25 import { pullDue, runPull } from "./pull.ts";
2326 import { mintAppToken, renewAppToken, revokeAppToken } from "./token.ts";
2427 import type { ForgeEvent } from "../core/events.ts";
2528 import { announceRun } from "../actions/runs.ts";
@@ -110,6 +113,8 @@ export interface RuntimeOptions {
110113 * its own, so proving `app.example.com` needs no network in a test.
111114 */
112115 readonly dns?: DomainResolver | undefined;
116 /** How often the forge looks for an adapter whose pull is owed. */
117 readonly pullTickMs?: number | undefined;
113118 }
114119
115120 export type EnvState =
@@ -121,6 +126,7 @@ export type EnvState =
121126
122127 const SLEEP_AFTER_MS = { production: 24 * 3_600_000, preview: 30 * 60_000 };
123128 const SWEEP_EVERY_MS = 60_000;
129 const PULL_TICK_MS = 15_000;
124130 const BUSY_GRACE_MS = 45 * 60_000;
125131
126132 export interface EnvStatus {
@@ -318,6 +324,9 @@ export class AppsRuntime {
318324 private readonly gate: Gate;
319325 private unsubscribe: (() => void) | undefined;
320326 private sweeper: ReturnType<typeof setInterval> | undefined;
327 private puller: ReturnType<typeof setInterval> | undefined;
328 /** Adapters mid-pull: one pull at a time per app, however slow. */
329 private readonly pulling = new Set<string>();
321330 private stopped = false;
322331
323332 constructor(
@@ -543,12 +552,18 @@ export class AppsRuntime {
543552 () => void this.sweep(),
544553 this.options.sweepEveryMs ?? SWEEP_EVERY_MS,
545554 );
555 this.puller = setInterval(
556 () => void this.pullOwed(),
557 this.options.pullTickMs ?? PULL_TICK_MS,
558 );
546559 }
547560
548561 /** Stop every process. The rows stay; a restart brings them back. */
549562 async stop(): Promise<void> {
550563 this.stopped = true;
551564 if (this.sweeper !== undefined) clearInterval(this.sweeper);
565 if (this.puller !== undefined) clearInterval(this.puller);
566 await Promise.all(this.pulling.size === 0 ? [] : [this.pullsDone()]);
552567 this.unsubscribe?.();
553568 const stops: Promise<void>[] = [];
554569 for (const state of this.envs.values()) {
@@ -1131,6 +1146,11 @@ export class AppsRuntime {
11311146 };
11321147 }
11331148
1149 /** What production's running commit declares about syncing, if it does. */
1150 adapterOf(record: AppRecord): AdapterManifest | undefined {
1151 return this.envs.get(key(record.id, "production"))?.live?.manifest.adapter ?? undefined;
1152 }
1153
11341154 /** The running environment a terminal session would attach to, if any. */
11351155 liveFor(record: AppRecord, env: EnvName): LiveEnv | undefined {
11361156 const state = this.envs.get(key(record.id, env));
@@ -1445,6 +1465,45 @@ export class AppsRuntime {
14451465 }
14461466
14471467 /** Stop what nobody has asked for lately, and keep it ready to wake. */
1468 /**
1469 * Pull every adapter that is owed one: production only (a preview holds a
1470 * copy of the data, and two environments syncing one source is a double
1471 * write), running, with its interval passed since the last pull began.
1472 * Returns once each pull is recorded.
1473 */
1474 async pullOwed(now = Date.now()): Promise<void> {
1475 if (this.stopped) return;
1476 const owed: Promise<unknown>[] = [];
1477 for (const state of this.envs.values()) {
1478 const live = state.live;
1479 const adapter = live?.manifest.adapter;
1480 if (state.env !== "production" || live === undefined || adapter == null)
1481 continue;
1482 if (state.deploying !== undefined || this.pulling.has(state.app.id))
1483 continue;
1484 const last = lastPullOf(this.app.db, state.app.id);
1485 if (!pullDue(last?.startedAt, adapter.everyMs, now)) continue;
1486 this.pulling.add(state.app.id);
1487 const work = runPull({
1488 db: this.app.db,
1489 app: state.app,
1490 port: live.handle.port,
1491 key: identityKey(this.app.config.dataDir, state.app.id),
1492 })
1493 .catch((error) =>
1494 log.error("pull failed to record", { error: String(error) }),
1495 )
1496 .finally(() => this.pulling.delete(state.app.id));
1497 this.inFlight.add(work);
1498 void work.finally(() => this.inFlight.delete(work));
1499 owed.push(work);
1500 }
1501 await Promise.all(owed);
1502 }
1503
1504 private readonly inFlight = new Set<Promise<unknown>>();
1505 private pullsDone = (): Promise<unknown> => Promise.all([...this.inFlight]);
1506
14481507 private async sweep(): Promise<void> {
14491508 if (this.stopped) return;
14501509 await this.hibernate();
@@ -1465,6 +1524,9 @@ export class AppsRuntime {
14651524 state.waking !== undefined
14661525 )
14671526 continue;
1527 // An adapter's work is on a clock, not on requests: asleep, it
1528 // would miss every pull.
1529 if (live.manifest.adapter !== null) continue;
14681530 const limit =
14691531 state.env === "production" ? after.production : after.preview;
14701532 const last = state.lastRequestAt ?? Date.parse(live.since);
src/core/adapter_pulls.ts added +85
@@ -0,0 +1,85 @@
1 /**
2 * An adapter's pulls — one row per call the forge made to its `POST /pull`
3 * (`apps/pull.ts`), success or not. Pure data: no authz, no events.
4 */
5
6 import type { Database } from "bun:sqlite";
7 import { id } from "../kernel/id.ts";
8
9 export interface AdapterPull {
10 readonly id: string;
11 readonly appId: string;
12 readonly state: "ok" | "failed";
13 readonly pulled: number;
14 readonly skipped: number;
15 readonly errors: number;
16 readonly cursor: string;
17 readonly summary: string;
18 readonly startedAt: string;
19 readonly durationMs: number;
20 }
21
22 interface Row {
23 id: string;
24 app_id: string;
25 state: "ok" | "failed";
26 pulled: number;
27 skipped: number;
28 errors: number;
29 cursor: string;
30 summary: string;
31 started_at: string;
32 duration_ms: number;
33 }
34
35 const toPull = (r: Row): AdapterPull => ({
36 id: r.id,
37 appId: r.app_id,
38 state: r.state,
39 pulled: r.pulled,
40 skipped: r.skipped,
41 errors: r.errors,
42 cursor: r.cursor,
43 summary: r.summary,
44 startedAt: r.started_at,
45 durationMs: r.duration_ms,
46 });
47
48 export type NewAdapterPull = Omit<AdapterPull, "id">;
49
50 export function recordPull(db: Database, input: NewAdapterPull): AdapterPull {
51 const row = { ...input, id: id() };
52 db.query(
53 `INSERT INTO adapter_pull (id, app_id, state, pulled, skipped, errors, cursor, summary, started_at, duration_ms)
54 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)`,
55 ).run(
56 row.id,
57 row.appId,
58 row.state,
59 row.pulled,
60 row.skipped,
61 row.errors,
62 row.cursor,
63 row.summary.slice(0, 500),
64 row.startedAt,
65 row.durationMs,
66 );
67 return row;
68 }
69
70 /** Newest first. */
71 export function listPullsOf(
72 db: Database,
73 appId: string,
74 limit = 10,
75 ): AdapterPull[] {
76 return db
77 .query<Row, [string, number]>(
78 "SELECT * FROM adapter_pull WHERE app_id = ?1 ORDER BY started_at DESC, id DESC LIMIT ?2",
79 )
80 .all(appId, limit)
81 .map(toPull);
82 }
83
84 export const lastPullOf = (db: Database, appId: string): AdapterPull | undefined =>
85 listPullsOf(db, appId, 1)[0];
src/core/schema.ts +19
@@ -1081,4 +1081,23 @@ export const migrations: readonly string[] = [
10811081 PRIMARY KEY (operation_id, position)
10821082 );
10831083 `,
1084
1085 // 41 — an adapter's pulls (`apps/pull.ts`): one row per call the forge
1086 // made to an adapter's POST /pull, whatever came of it. Not a run: a run
1087 // is work on a commit, and a pull is work on an external system.
1088 `
1089 CREATE TABLE adapter_pull (
1090 id TEXT PRIMARY KEY,
1091 app_id TEXT NOT NULL REFERENCES app(id) ON DELETE CASCADE,
1092 state TEXT NOT NULL CHECK (state IN ('ok','failed')),
1093 pulled INTEGER NOT NULL DEFAULT 0,
1094 skipped INTEGER NOT NULL DEFAULT 0,
1095 errors INTEGER NOT NULL DEFAULT 0,
1096 cursor TEXT NOT NULL DEFAULT '',
1097 summary TEXT NOT NULL DEFAULT '',
1098 started_at TEXT NOT NULL,
1099 duration_ms INTEGER NOT NULL DEFAULT 0
1100 );
1101 CREATE INDEX adapter_pull_app ON adapter_pull(app_id, started_at DESC);
1102 `,
10841103 ];
src/web/studio/app.ts +29
@@ -12,6 +12,7 @@
1212 import { audit } from "../../contract/audit.ts";
1313 import { latestProbes } from "../../contract/probes.ts";
1414 import { appsRuntime } from "../../apps/runtime.ts";
15 import { lastPullOf } from "../../core/adapter_pulls.ts";
1516 import { listCrewRoles } from "../../core/agents.ts";
1617 import type { AppRecord } from "../../core/apps.ts";
1718 import { decisionStats, type DecisionStat } from "../../core/decisions.ts";
@@ -183,6 +184,33 @@ async function policyLine(
183184 </p>`;
184185 }
185186
187 /**
188 * An adapter's pulls in one line: the last, the next, the cursor. Nothing
189 * for an app that is not one. The source and its host list are the repo's
190 * own words, so every part is escaped by the template.
191 */
192 function adapterLine(ctx: Ctx, record: AppRecord): Html {
193 const adapter = appsRuntime(ctx.app)?.adapterOf(record);
194 if (adapter === undefined) return html``;
195 const last = lastPullOf(ctx.app.db, record.id);
196 const next =
197 last === undefined
198 ? "due now"
199 : new Date(Date.parse(last.startedAt) + adapter.everyMs).toISOString();
200 return html`<p class="policy-line" data-tone="${last?.state ?? "none"}">
201 ${icon("clock")}
202 <span
203 ><b>Syncs ${adapter.source.name}</b> from ${adapter.source.hosts.join(", ")}:
204 ${last === undefined
205 ? "not pulled yet"
206 : html`last pull ${time(last.startedAt)}, ${last.state === "ok" ? "ok" : "failed"} —
207 ${last.summary} (${last.durationMs} ms)`}; next
208 ${next === "due now" ? next : time(next)}; cursor
209 <code>${last?.cursor === undefined || last.cursor === "" ? "(none)" : last.cursor}</code>.</span
210 >
211 </p>`;
212 }
213
186214 export async function studioApp(
187215 ctx: Ctx,
188216 repo: Repo,
@@ -426,6 +454,7 @@ export async function studioApp(
426454 })}
427455 <div id="app-head">${head}</div>
428456 ${await policyLine(ctx, repo, record)}
457 ${adapterLine(ctx, record)}
429458 <div class="dash">
430459 <div class="dash-main stack">
431460 ${tell}
test/adapter.test.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * The adapter contract (docs/ADAPTERS.md): what `forge.json` may declare,
3 * what a pull reply must look like, and that every pull is recorded.
4 */
5
6 import { Database } from "bun:sqlite";
7 import { describe, expect, test } from "bun:test";
8 import { hostAllowed, parseAdapter, parseEvery } from "../src/apps/adapter.ts";
9 import { parseManifest } from "../src/apps/manifest.ts";
10 import { parseReply, pullDue, runPull } from "../src/apps/pull.ts";
11 import { lastPullOf, listPullsOf } from "../src/core/adapter_pulls.ts";
12 import type { AppRecord } from "../src/core/apps.ts";
13 import { migrations } from "../src/core/schema.ts";
14
15 const good = {
16 source: { name: "Shop API", hosts: ["api.shop.example"] },
17 schedule: { every: "15m" },
18 config: {
19 token: { type: "secret", env: "SHOP_TOKEN", required: true },
20 page: { type: "number", env: "SHOP_PAGE", default: 50 },
21 },
22 };
23
24 describe("the adapter block", () => {
25 test("absent means not an adapter; a good block parses", () => {
26 expect(parseAdapter(undefined)).toEqual({ ok: true, value: null });
27 const r = parseAdapter(good);
28 expect(r.ok && r.value?.everyMs).toBe(900_000);
29 expect(r.ok && r.value?.config[0]?.required).toBe(true);
30 });
31
32 test("intervals are whole s/m/h/d between one minute and a day", () => {
33 expect(parseEvery("1m").ok).toBe(true);
34 expect(parseEvery("1d").ok).toBe(true);
35 for (const v of ["30s", "2d", "0m", "15", "1.5h", 15, "-1m"])
36 expect(parseEvery(v).ok).toBe(false);
37 });
38
39 test("hosts are bare hostnames, never URLs, ports or addresses", () => {
40 for (const h of ["https://a.example", "a.example:8080", "a.example/x", "127.0.0.1", "*.example.com", "localhost", "A.Example"])
41 expect(parseAdapter({ ...good, source: { name: "x", hosts: [h] } }).ok).toBe(false);
42 expect(parseAdapter({ ...good, source: { name: "x", hosts: [] } }).ok).toBe(false);
43 });
44
45 test("a secret names a variable and never holds a value", () => {
46 const cfg = { token: { type: "secret", env: "T", default: "hunter2" } };
47 expect(parseAdapter({ ...good, config: cfg }).ok).toBe(false);
48 });
49
50 test("a config field may not point at a variable the forge owns", () => {
51 const cfg = { k: { type: "string", env: "FORGE_TOKEN" } };
52 expect(parseAdapter({ ...good, config: cfg }).ok).toBe(false);
53 });
54
55 test("a default must match its type", () => {
56 const cfg = { n: { type: "number", env: "N", default: "ten" } };
57 expect(parseAdapter({ ...good, config: cfg }).ok).toBe(false);
58 });
59
60 test("the manifest carries it, and an invalid block fails the manifest", () => {
61 const m = parseManifest(JSON.stringify({ app: { run: "bun x.ts" }, adapter: good }), undefined);
62 expect(m.ok && m.value.adapter?.source.name).toBe("Shop API");
63 const plain = parseManifest(JSON.stringify({ app: { run: "bun x.ts" } }), undefined);
64 expect(plain.ok && plain.value.adapter).toBe(null);
65 expect(parseManifest(JSON.stringify({ app: { run: "bun x.ts" }, adapter: { source: 1 } }), undefined).ok).toBe(false);
66 });
67
68 test("hostAllowed is https and an exact declared host", () => {
69 const hosts = ["api.shop.example"];
70 expect(hostAllowed("https://api.shop.example/v1", hosts)).toBe(true);
71 expect(hostAllowed("http://api.shop.example/v1", hosts)).toBe(false);
72 expect(hostAllowed("https://evil.example/", hosts)).toBe(false);
73 expect(hostAllowed("https://api.shop.example.evil.example/", hosts)).toBe(false);
74 expect(hostAllowed("https://[email protected]/", hosts)).toBe(false);
75 expect(hostAllowed("nonsense", hosts)).toBe(false);
76 });
77 });
78
79 describe("a pull", () => {
80 const db = new Database(":memory:");
81 for (const m of migrations) db.exec(m);
82 const app = { id: "app1" } as AppRecord;
83 const reply = (body: unknown, status = 200): typeof fetch =>
84 (async () => new Response(JSON.stringify(body), { status })) as unknown as typeof fetch;
85 const pull = (f: typeof fetch) => runPull({ db, app, port: 1, key: "k", fetch: f });
86
87 test("the reply is validated field by field", () => {
88 expect(parseReply({ pulled: 1, skipped: 0, cursor: "c", errors: [] }).ok).toBe(true);
89 for (const bad of [null, [], { pulled: -1, skipped: 0, cursor: "", errors: [] },
90 { pulled: 1.5, skipped: 0, cursor: "", errors: [] },
91 { pulled: 1, skipped: 0, cursor: "a\nb", errors: [] },
92 { pulled: 1, skipped: 0, cursor: "", errors: [1] },
93 { pulled: 1, skipped: 0, cursor: "" }])
94 expect(parseReply(bad).ok).toBe(false);
95 });
96
97 test("success is recorded with its cursor, and sends the key as a bearer", async () => {
98 let auth = "";
99 const f = (async (_u: string, init: RequestInit) => {
100 auth = String((init.headers as Record<string, string>)["authorization"]);
101 return new Response(JSON.stringify({ pulled: 3, skipped: 2, cursor: "p7", errors: [] }));
102 }) as unknown as typeof fetch;
103 const p = await pull(f);
104 expect(auth).toBe("Bearer k");
105 expect(p).toMatchObject({ state: "ok", pulled: 3, skipped: 2, cursor: "p7" });
106 expect(lastPullOf(db, "app1")?.id).toBe(p.id);
107 });
108
109 test("reported errors, bad status, bad JSON, bad shape and a dead adapter all fail, recorded", async () => {
110 expect((await pull(reply({ pulled: 1, skipped: 0, cursor: "", errors: ["boom"] }))).summary).toContain("boom");
111 expect((await pull(reply({}, 500))).summary).toContain("500");
112 expect((await pull((async () => new Response("<html>")) as unknown as typeof fetch)).summary).toContain("not JSON");
113 expect((await pull(reply({ pulled: "x" }))).state).toBe("failed");
114 const dead = (async () => { throw new Error("refused"); }) as unknown as typeof fetch;
115 expect((await pull(dead)).summary).toContain("not reachable");
116 expect(listPullsOf(db, "app1", 50).every((p, i, a) => i === 0 || a[i - 1]!.startedAt >= p.startedAt)).toBe(true);
117 expect(listPullsOf(db, "app1", 50).length).toBeGreaterThanOrEqual(6);
118 });
119
120 test("a pull is due when none has run or the interval has passed", () => {
121 const t = Date.parse("2026-01-01T00:15:00Z");
122 expect(pullDue(undefined, 900_000, t)).toBe(true);
123 expect(pullDue("2026-01-01T00:00:00Z", 900_000, t)).toBe(true);
124 expect(pullDue("2026-01-01T00:00:01Z", 900_000, t)).toBe(false);
125 });
126 });
test/apps.test.ts +1
@@ -2017,6 +2017,7 @@ describe("a start that fails reports the message, not its last line (issue #270)
20172017 ready: 2,
20182018 tty: null,
20192019 looks: ["/"],
2020 adapter: null,
20202021 };
20212022
20222023 // A realistic crash: the message, a blank line, three frames, then the

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs