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

Boards: starting boards shipped with the forge — Throughput, Usage, Crew, Releases, Apps, Security #1944

Parked opened this
Closed without merging

scout/forge:scout/1577-boards-starting-boards-shipped-with-the → main 11 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +480 −3
README.md +5
@@ -874,6 +874,11 @@ work here.
874874 A board with a refresh redraws its grid on that beat through the live-region swap
875875 (`/boards/:slug/live`, etag'd). The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug`
876876 (an agent is 403, anyone but an admin 404; a panel whose query cannot run is refused with 422). No dependency was added.
877 Six starting boards (Throughput, Usage, Crew, Releases, Apps, Security; `boards/starting.ts`) are
878 committed to `forge/boards` once each, as soon as an admin who is a person exists; the slugs done are kept in
879 `forge_setting` `boards.seeded`, so a deleted one is never made again. What no table kept is counted per hour in
880 `tally` (`boards/tally.ts`; source `tally`): sign-ins, failed sign-ins (no name, no password), tokens used by
881 scope (once a minute each), requests, errors, wakes and sleeps per app, refused pushes.
877882 - **Issues** — labels, threaded comments, close/reopen, markdown.
878883 - **Pull requests** — open from a branch, a **beautiful diff viewer** (syntax
879884 highlighting composed with intra-line word highlighting, mobile-first,
scripts/gate.ts +1
@@ -43,6 +43,7 @@ export const GATE: readonly string[] = [
4343 "test/boards-page.test.ts",
4444 "test/boards-store.test.ts",
4545 "test/boards-sampler.test.ts",
46 "test/boards-starting.test.ts",
4647 "test/turnstile.test.ts",
4748 "test/variants-deck.test.ts",
4849 "test/variants-surfaces.test.ts",
src/actions/boards.ts +44 −1
@@ -10,6 +10,7 @@
1010 import type { App } from "../app.ts";
1111 import { applyEdit, type Edit } from "../boards/edit.ts";
1212 import { runQuery } from "../boards/query.ts";
13 import { STARTING } from "../boards/starting.ts";
1314 import {
1415 BOARDS_OWNER, BOARDS_REPO, emptyBoard, isSlug, listBoards, parseBoard, readBoard, removeBoard, saveBoard, slugOf,
1516 type Board, type Stored, type StoreError,
@@ -17,7 +18,7 @@ import {
1718 import { commitIdentity } from "../core/commit_identity.ts";
1819 import { createOrg } from "../core/orgs.ts";
1920 import { createRepo, getRepo } from "../core/repos.ts";
20 import { getUserByName, type User } from "../core/users.ts";
21 import { getUserById, getUserByName, type User } from "../core/users.ts";
2122 import { err, ok, type Result } from "../kernel/result.ts";
2223
2324 export type BoardError = StoreError | "not_found" | "no_slug" | "repo" | { refused: string };
@@ -140,3 +141,45 @@ export async function deleteBoard(app: App, actor: User | undefined, slug: strin
140141 if (done.ok) app.bus.append({ kind: "board.deleted", actorId: who.value.id, payload: { slug } });
141142 return done;
142143 }
144
145 const SEEDED = "boards.seeded";
146
147 /**
148 * Put each starting board (`boards/starting.ts`) in the repo once. The slugs
149 * done are kept in `forge_setting`, so a board an admin deleted is not made
150 * again and one they edited is not touched. Needs an admin who is a person
151 * to author the commits; with none yet, nothing happens and the next call
152 * tries again. Returns the slugs it made.
153 */
154 export async function seedBoards(app: App): Promise<string[]> {
155 const row = app.db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(SEEDED);
156 let done: string[] = [];
157 try {
158 const parsed: unknown = JSON.parse(row?.value ?? "[]");
159 if (Array.isArray(parsed)) done = parsed.filter((s): s is string => typeof s === "string");
160 } catch {
161 // An unreadable marker is an empty one.
162 }
163 const todo = Object.keys(STARTING).filter((slug) => !done.includes(slug));
164 if (todo.length === 0) return [];
165 const who = app.db
166 .query<{ id: string }, []>("SELECT id FROM user WHERE is_admin = 1 AND kind = 'user' AND is_agent = 0 ORDER BY created_at LIMIT 1")
167 .get();
168 const user = who ? getUserById(app.db, who.id) : undefined;
169 if (!user || !(await ensureRepo(app, user))) return [];
170 const made: string[] = [];
171 for (const slug of todo) {
172 const there = (await readBoard(app.reposRoot, slug)) !== undefined;
173 const saved = there ? ok(true) : await save(app, user, slug, STARTING[slug], `Seed board ${slug}`, "create");
174 if (!saved.ok) continue;
175 done.push(slug);
176 if (!there) made.push(slug);
177 }
178 app.db
179 .query(
180 `INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES (?1, ?2, ?3, ?4)
181 ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
182 )
183 .run(SEEDED, JSON.stringify(done), user.id, new Date().toISOString());
184 return made;
185 }
src/apps/proxy.ts +23
@@ -14,6 +14,7 @@
1414 * directory — so guessing a hostname yields the forge's own "not found".
1515 */
1616
17 import { tally } from "../boards/tally.ts";
1718 import type { Database } from "bun:sqlite";
1819 import { getIssue, type Issue } from "../core/issues.ts";
1920 import { mayView } from "../core/sealed.ts";
@@ -473,6 +474,28 @@ export async function proxyApp(
473474 request: Request,
474475 target: AppTarget,
475476 server: Bun.Server<AppSocket>,
477 ): Promise<Response | undefined> {
478 const slug = target.app.slug;
479 let response: Response | undefined;
480 try {
481 response = await serveApp(runtime, request, target, server);
482 } catch (error) {
483 tally(runtime.app.db, "request", slug);
484 tally(runtime.app.db, "request_error", slug);
485 throw error;
486 }
487 if (response !== undefined) {
488 tally(runtime.app.db, "request", slug);
489 if (response.status >= 500) tally(runtime.app.db, "request_error", slug);
490 }
491 return response;
492 }
493
494 async function serveApp(
495 runtime: AppsRuntime,
496 request: Request,
497 target: AppTarget,
498 server: Bun.Server<AppSocket>,
476499 ): Promise<Response | undefined> {
477500 const url = new URL(request.url);
478501 // A grant with this forge's own token is answered here. On a nested
src/apps/runtime.ts +3
@@ -13,6 +13,7 @@
1313 * commit, once.
1414 */
1515
16 import { tally } from "../boards/tally.ts";
1617 import { recordCarried } from "../core/carried.ts";
1718 import { pullDir, runDir } from "../core/pulls.ts";
1819 import { accountActive } from "../core/accounts.ts";
@@ -1821,6 +1822,7 @@ export class AppsRuntime {
18211822
18221823 /** The environment began serving: its awake interval opens, if not open. */
18231824 private awake(state: Environment, at: string): void {
1825 tally(this.app.db, "wake", state.app.slug);
18241826 this.metered(() =>
18251827 openAwake(this.app.db, {
18261828 repoId: state.app.repoId,
@@ -1833,6 +1835,7 @@ export class AppsRuntime {
18331835
18341836 /** The environment stopped serving: its awake interval closes. */
18351837 private resting(state: Environment, at: number = Date.now()): void {
1838 tally(this.app.db, "sleep", state.app.slug);
18361839 this.metered(() =>
18371840 closeAwake(this.app.db, {
18381841 repoId: state.app.repoId,
src/boards/sources.ts +39
@@ -98,6 +98,45 @@ export const SOURCES: Readonly<Record<string, Source>> = {
9898 outcome: "text", at: "time",
9999 },
100100 },
101 // Issues and pulls as items moving through the pipeline (`flow/`).
102 items: {
103 table: "issue",
104 owner: "repo_id",
105 time: "created_at",
106 columns: {
107 id: "text", repo_id: "text", kind: "text", state: "text",
108 created_at: "time", closed_at: "time",
109 },
110 },
111 // Each release of the forge itself (`release/record.ts`).
112 releases: {
113 table: "release",
114 owner: "admin",
115 time: "created_at",
116 columns: { id: "number", pull_number: "number", ok: "number", created_at: "time" },
117 docs: { ok: "1 when the preflight passed, 0 when it did not" },
118 },
119 // What admins did: the outbox's events whose actor is an admin. The kind is
120 // a fixed word (`pull.merged`); the payload is not listed.
121 admin_actions: {
122 table: "event",
123 owner: "admin",
124 where: "actor_id IN (SELECT id FROM user WHERE is_admin = 1)",
125 time: "created_at",
126 columns: { id: "text", kind: "text", actor_id: "text", created_at: "time" },
127 },
128 // What happened, counted per hour (`boards/tally.ts`): sum `n`.
129 tally: {
130 table: "tally",
131 owner: "admin",
132 time: "at",
133 columns: { kind: "text", subject: "text", n: "number", at: "time" },
134 docs: {
135 kind: "signin, signin_failed, token_used, request, request_error, wake, sleep or refusal",
136 subject: "a token's scope (token_used) or an app's slug (request, request_error, wake, sleep)",
137 n: "how many happened in the hour that begins at `at`",
138 },
139 },
101140 // What the machine used (`boards/sampler.ts`, kept by `boards/ring.ts`):
102141 // 15-s points for the last day, 5-min points before that, never both
103142 // for one moment.
src/boards/starting.ts added +94
@@ -0,0 +1,94 @@
1 /**
2 * The boards the forge ships with: plain data, seeded once each into
3 * `forge/boards` (`actions/boards.ts`, `seedBoards`) and from then on
4 * ordinary boards — edited, duplicated or deleted like any other.
5 */
6 import type { Board, Panel } from "./store.ts";
7
8 const hour = { bucket: "hour" };
9 const panel = (title: string, chart: Panel["chart"], query: Record<string, unknown>, w = 1, h = 1): Panel =>
10 ({ title, chart, query, w, h });
11 const board = (title: string, range: Board["range"], panels: Panel[]): Board =>
12 ({ title, range, refresh: "1m", panels });
13 const per = (title: string, source: string, extra: Record<string, unknown> = {}, chart: Panel["chart"] = "bar") =>
14 panel(title, chart, { source, aggregate: "count", groupBy: hour, ...extra });
15 const machine = (title: string, target: string, column: string, chart: Panel["chart"] = "line") =>
16 panel(title, chart, {
17 source: "machine", aggregate: "avg", column, groupBy: hour,
18 filter: [{ column: "target", op: "eq", value: target }],
19 });
20 const tallied = (title: string, kind: string, chart: Panel["chart"] = "bar", extra: Record<string, unknown> = {}) =>
21 panel(title, chart, {
22 source: "tally", aggregate: "sum", column: "n", groupBy: hour,
23 filter: [{ column: "kind", op: "eq", value: kind }], ...extra,
24 });
25
26 export const STARTING: Readonly<Record<string, Board>> = {
27 throughput: board("Throughput", "24h", [
28 per("Issues and pulls opened per hour", "items", { series: "kind" }, "area"),
29 per("Runs started per hour (building)", "runs", { series: "kind" }, "area"),
30 per("Checks started per hour", "deploys"),
31 per("Reviews returned per hour", "reviews", { series: "state" }),
32 per("Pulls landed per hour", "pulls"),
33 per("Deploys serving per hour (live)", "deploys", { filter: [{ column: "state", op: "eq", value: "ok" }] }),
34 per("Releases per hour", "releases"),
35 ]),
36 usage: board("Usage", "24h", [
37 machine("Forge pod CPU (cores)", "forge", "cpu_cores"),
38 machine("Forge pod memory (bytes)", "forge", "memory_bytes"),
39 machine("Node load", "node", "load"),
40 machine("Node CPU (cores)", "node", "cpu_cores"),
41 machine("Node memory (bytes)", "node", "memory_bytes"),
42 panel("CPU by cell (cores)", "area", {
43 source: "machine", aggregate: "avg", column: "cpu_cores", groupBy: hour, series: "target",
44 filter: [{ column: "target", op: "ne", value: "node" }],
45 }, 2),
46 panel("Memory by cell (bytes)", "area", {
47 source: "machine", aggregate: "avg", column: "memory_bytes", groupBy: hour, series: "target",
48 filter: [{ column: "target", op: "ne", value: "node" }],
49 }, 2),
50 ]),
51 crew: board("Crew", "7d", [
52 per("Runs per hour by outcome", "spend", { series: "outcome" }, "area"),
53 panel("Runs by agent", "bar", { source: "spend", aggregate: "count", groupBy: "agent_id" }),
54 panel("Runs by kind", "bar", { source: "runs", aggregate: "count", groupBy: "kind" }),
55 panel("Runs by state", "bar", { source: "runs", aggregate: "count", groupBy: "state" }),
56 panel("Cost per hour (USD)", "line", { source: "spend", aggregate: "sum", column: "cost_usd", groupBy: hour }),
57 panel("Cost, all runs (USD)", "number", { source: "spend", aggregate: "sum", column: "cost_usd" }),
58 panel("Review verdicts", "bar", { source: "reviews", aggregate: "count", groupBy: "state" }),
59 ]),
60 releases: board("Releases", "30d", [
61 panel("Releases per day", "bar", { source: "releases", aggregate: "count", groupBy: { bucket: "day" } }),
62 panel("Preflight failures per day", "bar", {
63 source: "releases", aggregate: "count", groupBy: { bucket: "day" },
64 filter: [{ column: "ok", op: "eq", value: 0 }],
65 }),
66 panel("Releases", "number", { source: "releases", aggregate: "count" }),
67 panel("Landings by pull", "table", { source: "releases", aggregate: "count", groupBy: "pull_number" }, 2),
68 panel("Pulls landed per day", "bar", { source: "pulls", aggregate: "count", groupBy: { bucket: "day" } }),
69 ]),
70 apps: board("Apps", "24h", [
71 tallied("Requests per hour", "request", "area", { series: "subject" }),
72 tallied("Errors per hour", "request_error", "bar", { series: "subject" }),
73 tallied("Wakes per hour", "wake"),
74 tallied("Sleeps per hour", "sleep"),
75 panel("Requests by app", "table", {
76 source: "tally", aggregate: "sum", column: "n", groupBy: "subject",
77 filter: [{ column: "kind", op: "eq", value: "request" }],
78 }),
79 panel("Errors by app", "table", {
80 source: "tally", aggregate: "sum", column: "n", groupBy: "subject",
81 filter: [{ column: "kind", op: "eq", value: "request_error" }],
82 }),
83 ]),
84 security: board("Security", "7d", [
85 tallied("Sign-ins per hour", "signin"),
86 tallied("Failed sign-ins per hour", "signin_failed"),
87 tallied("Tokens used per hour, by scope", "token_used", "area", { series: "subject" }),
88 tallied("Pushes refused per hour", "refusal"),
89 panel("Admin actions per hour", "bar", {
90 source: "admin_actions", aggregate: "count", groupBy: hour,
91 }),
92 panel("Admin actions by kind", "table", { source: "admin_actions", aggregate: "count", groupBy: "kind" }, 2),
93 ]),
94 };
src/boards/tally.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * What happened, counted per hour (`tally`): the record behind the boards
3 * that no table already keeps. A row is an hour, a kind, a subject and a
4 * count. The kind is from `KINDS`; the subject is one of a short fixed list
5 * (a token's scope) or an app's slug — never a name, a password, a token or
6 * anything a stranger typed, so there is nothing in it to leak. `pruneTally` drops rows older than
7 * `KEEP_DAYS`.
8 */
9 import type { Database } from "bun:sqlite";
10
11 export const KINDS = [
12 "signin", // a session opened
13 "signin_failed", // a password that did not match (the name is not kept)
14 "token_used", // a token seen, at most once a minute each; subject: its scope
15 "request", // a request answered for an app; subject: its slug
16 "request_error", // ... with a 5xx, or none at all
17 "wake", // an environment began serving; subject: its slug
18 "sleep", // an environment stopped serving; subject: its slug
19 "refusal", // a push the forge refused
20 ] as const;
21 export type Kind = (typeof KINDS)[number];
22
23 const KEEP_DAYS = 35;
24 const MAX_SUBJECT = 64;
25 const hourOf = (ms: number) => new Date(ms - (ms % 3_600_000)).toISOString();
26
27 /** Count one `kind` for `subject` in the current hour. Never throws: a count is not worth a request. */
28 export function tally(db: Database, kind: Kind, subject = "", now = Date.now()): void {
29 try {
30 db.query(
31 `INSERT INTO tally (at, kind, subject, n) VALUES (?1, ?2, ?3, 1)
32 ON CONFLICT (at, kind, subject) DO UPDATE SET n = n + 1`,
33 ).run(hourOf(now), kind, subject.slice(0, MAX_SUBJECT));
34 } catch {
35 // Telemetry only.
36 }
37 }
38
39 /** Drop what has left its window; run now and then, not per count. */
40 export function pruneTally(db: Database, now = Date.now()): void {
41 db.query("DELETE FROM tally WHERE at < ?1").run(hourOf(now - KEEP_DAYS * 86_400_000));
42 }
src/core/migrations/20261015100000-the-tally.ts added +13
@@ -0,0 +1,13 @@
1 // The tally (#1577, boards/tally.ts): what happened, counted per hour
2 // — sign-ins and failures, tokens used, requests and errors per app, wakes
3 // and sleeps, refused pushes. A count and two words from fixed lists, never
4 // a credential or a person's text. Telemetry: a lost row is a gap in a chart.
5 export default `
6 CREATE TABLE tally (
7 at TEXT NOT NULL,
8 kind TEXT NOT NULL,
9 subject TEXT NOT NULL,
10 n INTEGER NOT NULL,
11 PRIMARY KEY (at, kind, subject)
12 ) WITHOUT ROWID;
13 `;
src/core/releases.json +4
@@ -20,10 +20,14 @@
2020 {
2121 "version": "0.7.123",
2222 "migrations": 93,
23 <<<<<<< HEAD
24 "ids": ["20261015090000-feed-chips", "20261015230000-a-domain-drill"]
25 =======
2326 "ids": [
2427 "20261015090000-feed-chips",
2528 "20261015230000-a-domain-drill"
2629 ]
30 >>>>>>> origin/main
2731 },
2832 {
2933 "version": "0.7.122",
src/core/sessions.ts +2
@@ -3,6 +3,7 @@
33 * only its hash — a leaked database never yields a usable session.
44 */
55
6 import { tally } from "../boards/tally.ts";
67 import type { Database } from "bun:sqlite";
78 import { sha256 } from "../kernel/hash.ts";
89 import { id as newId, secret } from "../kernel/id.ts";
@@ -32,6 +33,7 @@ export function createSession(
3233 db.query(
3334 "INSERT INTO session (token_hash, user_id, expires_at, id) VALUES (?1, ?2, ?3, ?4)",
3435 ).run(sha256(token), userId, expiresAt.toISOString(), newId());
36 tally(db, "signin");
3537 return { token, expiresAt };
3638 }
3739
src/core/tokens.ts +2
@@ -4,6 +4,7 @@
44 * Scopes are deliberately coarse in v1: ro < rw < admin.
55 */
66
7 import { tally } from "../boards/tally.ts";
78 import type { Database } from "bun:sqlite";
89 import { sha256 } from "../kernel/hash.ts";
910 import { id, secret } from "../kernel/id.ts";
@@ -95,6 +96,7 @@ export function verifyToken(
9596 new Date(now).toISOString(),
9697 row.id,
9798 );
99 tally(db, "token_used", row.scope);
98100 }
99101 return ok({ user, scope: row.scope });
100102 }
src/core/users.ts +7 −2
@@ -3,6 +3,7 @@
33 * narrower; there is no second identity system.
44 */
55
6 import { tally } from "../boards/tally.ts";
67 import { markUnproven, markVerified } from "./verify.ts";
78 import type { Database } from "bun:sqlite";
89 import { isSafeName } from "../git/guard.ts";
@@ -359,10 +360,14 @@ export async function verifyPassword(
359360 const valid = await Bun.password.verify(password, hash).catch(() => false);
360361 // Org rows own repos but never authenticate, whatever their stored hash;
361362 // neither does an agent, whose hash is empty besides.
362 if (!valid || !row || row.kind === "org" || row.is_agent === 1)
363 if (!valid || !row || row.kind === "org" || row.is_agent === 1) {
364 tally(db, "signin_failed");
363365 return err("bad_credentials");
366 }
364367 const user = toUser(row);
365 return isActive(user) ? ok(user) : err("bad_credentials");
368 if (isActive(user)) return ok(user);
369 tally(db, "signin_failed");
370 return err("bad_credentials");
366371 }
367372
368373 /**
src/http/server.ts +7
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { tally } from "../boards/tally.ts";
89 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
910 import { unsealReleased } from "../actions/sealed.ts";
1011 import { accessPage } from "../web/pages/access.ts";
@@ -1486,6 +1487,12 @@ function hookCallerAllowed(app: App, request: Request): boolean {
14861487 }
14871488
14881489 async function handleHook(app: App, request: Request): Promise<Response> {
1490 const answer = await decideHook(app, request);
1491 if (answer.status === 403) tally(app.db, "refusal");
1492 return answer;
1493 }
1494
1495 async function decideHook(app: App, request: Request): Promise<Response> {
14891496 const parsed = (await request.json()) as HookRequest;
14901497 const input: HookRequest = { ...parsed, gitEnv: forwardedGitEnv(parsed.gitEnv) };
14911498 const repo = getRepoById(app.db, input.repoId);
src/main.ts +9
@@ -4,7 +4,9 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { seedBoards } from "./actions/boards.ts";
78 import { startSampler } from "./boards/sampler.ts";
9 import { pruneTally } from "./boards/tally.ts";
810 import { sweepStanding } from "./crew/standing.ts";
911 import { handover } from "./release/swap.ts";
1012 import { parentUrlProblem } from "./core/parent_releases.ts";
@@ -331,6 +333,13 @@ const snapshots = startSnapshots(
331333 // What the machine uses (boards/sampler.ts): the pod, each cell and the
332334 // node, every 15 s into a ring the `machine` board source reads.
333335 const sampler = startSampler(app);
336 // The starting boards (actions/boards.ts), once each; waits for an admin to exist.
337 const seeding = setInterval(() => {
338 pruneTally(app.db);
339 void seedBoards(app).catch(() => undefined);
340 }, 60_000);
341 seeding.unref();
342 void seedBoards(app).catch(() => undefined);
334343 const crewHeldOff = crewOffInPreview();
335344 if (appsOn && crewHeldOff)
336345 app.log.info(CREW_OFF_IN_PREVIEW, {
test/apps-sleep.test.ts +10
@@ -111,6 +111,16 @@ describe("apps that sleep", () => {
111111 .find((e) => e.env === "production")!.runId!;
112112 expect(log(runId)).toContain("asleep: nothing asked for it");
113113 expect(log(runId)).toContain("awake");
114 // The tally behind the Apps board saw it sleep and wake, by slug.
115 const counted = (kind: string): number =>
116 app.db
117 .query<{ n: number }, [string, string]>(
118 "SELECT COALESCE(SUM(n), 0) AS n FROM tally WHERE kind = ?1 AND subject = ?2",
119 )
120 .get(kind, record.slug)!.n;
121 expect(counted("sleep")).toBeGreaterThanOrEqual(1);
122 expect(counted("wake")).toBeGreaterThanOrEqual(2);
123 expect(counted("request")).toBeGreaterThanOrEqual(2);
114124 // Wanted again, it stays up past the limit.
115125 await Bun.sleep(400);
116126 expect((await viaHost(`hello.${DOMAIN}`)).status).toBe(200);
test/boards-starting.test.ts added +175
@@ -0,0 +1,175 @@
1 /**
2 * The starting boards: every one parses, every panel runs against a fresh
3 * forge, they are seeded once each (a deleted one stays deleted), and the
4 * tally behind Apps and Security counts without keeping a credential.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { deleteBoard, listAllBoards, seedBoards } from "../src/actions/boards.ts";
11 import { createApp } from "../src/app.ts";
12 import { runQuery } from "../src/boards/query.ts";
13 import { STARTING } from "../src/boards/starting.ts";
14 import { parseBoard } from "../src/boards/store.ts";
15 import { pruneTally, tally } from "../src/boards/tally.ts";
16 import { proxyApp, type AppTarget } from "../src/apps/proxy.ts";
17 import type { AppsRuntime } from "../src/apps/runtime.ts";
18 import { createRepo } from "../src/actions/repos.ts";
19 import type { AppRecord } from "../src/core/apps.ts";
20 import { createToken, verifyToken } from "../src/core/tokens.ts";
21 import { fetchInternal } from "../src/git/hook-address.ts";
22 import { serve } from "../src/http/server.ts";
23 import { createSession } from "../src/core/sessions.ts";
24 import { createUser, verifyPassword, type User } from "../src/core/users.ts";
25
26 let dir: string;
27 let app: ReturnType<typeof createApp>;
28 let alice: User;
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-boards-starting-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 });
34 afterAll(async () => {
35 await rm(dir, { recursive: true, force: true });
36 });
37
38 describe("starting boards", () => {
39 test("the six are there, parse, and every panel runs against a fresh forge", () => {
40 expect(Object.keys(STARTING).sort()).toEqual(["apps", "crew", "releases", "security", "throughput", "usage"]);
41 for (const [slug, board] of Object.entries(STARTING)) {
42 const parsed = parseBoard(board);
43 expect(parsed.ok, slug).toBe(true);
44 for (const p of board.panels) {
45 const ran = runQuery(app.db, p.query, { repoIds: "all" });
46 expect(ran.ok, `${slug}: ${p.title}`).toBe(true);
47 }
48 }
49 });
50
51 test("nothing is seeded until an admin exists, then each once; a deleted one stays deleted", async () => {
52 expect(await seedBoards(app)).toEqual([]);
53 const made = await createUser(app.db, {
54 trusted: true, username: "alice", email: "[email protected]",
55 password: "a-good-passphrase", adminIfFirst: true,
56 });
57 if (!made.ok) throw new Error(made.error);
58 alice = made.value;
59 expect((await seedBoards(app)).sort()).toEqual(Object.keys(STARTING).sort());
60 const listed = await listAllBoards(app, alice);
61 expect(listed.ok && listed.value.map((b) => b.slug).sort()).toEqual(Object.keys(STARTING).sort());
62 expect(await seedBoards(app)).toEqual([]);
63 expect((await deleteBoard(app, alice, "crew")).ok).toBe(true);
64 expect(await seedBoards(app)).toEqual([]);
65 const after = await listAllBoards(app, alice);
66 expect(after.ok && after.value.some((b) => b.slug === "crew")).toBe(false);
67 });
68 });
69
70 describe("the tally", () => {
71 const sum = (kind: string, subject?: string) => {
72 const r = runQuery(
73 app.db,
74 {
75 source: "tally", aggregate: "sum", column: "n",
76 filter: [{ column: "kind", op: "eq", value: kind }, ...(subject ? [{ column: "subject", op: "eq", value: subject }] : [])],
77 },
78 { repoIds: "all" },
79 );
80 return r.ok ? (r.rows[0]?.value ?? 0) : -1;
81 };
82
83 test("counts per hour by kind and subject", () => {
84 tally(app.db, "request", "shop");
85 tally(app.db, "request", "shop");
86 tally(app.db, "request_error", "shop");
87 expect(sum("request", "shop")).toBe(2);
88 expect(sum("request_error", "shop")).toBe(1);
89 });
90
91 test("sign-ins and failed sign-ins are counted and no password is kept", async () => {
92 const before = sum("signin_failed");
93 const bad = await verifyPassword(app.db, "alice", "not-the-passphrase");
94 expect(bad.ok).toBe(false);
95 expect(sum("signin_failed")).toBe(before + 1);
96 const opened = sum("signin");
97 createSession(app.db, alice.id);
98 expect(sum("signin")).toBe(opened + 1);
99 const dump = JSON.stringify(app.db.query("SELECT * FROM tally").all());
100 expect(dump).not.toContain("not-the-passphrase");
101 expect(dump).not.toContain("alice");
102 });
103
104 test("pruneTally drops rows older than 35 days and keeps this hour's", () => {
105 tally(app.db, "request", "pruned");
106 expect(sum("request", "pruned")).toBe(1);
107 pruneTally(app.db, Date.now() + 34 * 86_400_000);
108 expect(sum("request", "pruned")).toBe(1);
109 pruneTally(app.db, Date.now() + 36 * 86_400_000);
110 expect(sum("request", "pruned")).toBe(0);
111 });
112
113 test("a token seen twice within a minute is one token_used, under its scope", () => {
114 const { token } = createToken(app.db, alice.id, "ci", "ro");
115 const before = sum("token_used", "ro");
116 expect(verifyToken(app.db, token).ok).toBe(true);
117 expect(verifyToken(app.db, token).ok).toBe(true);
118 expect(sum("token_used", "ro")).toBe(before + 1);
119 });
120
121 test("a refused hook counts a refusal; an accepted one does not", async () => {
122 const made = await createRepo(app, alice, { name: "hooked" });
123 if (!made.ok) throw new Error(String(made.error));
124 const servers = await serve(app);
125 try {
126 const push = (ref: string) =>
127 fetchInternal(app.hookAddress.current, "/internal/hook", {
128 method: "POST",
129 headers: { "x-forge-hook-secret": app.hookSecret },
130 body: JSON.stringify({
131 hook: "pre-receive",
132 repoId: made.value.id,
133 actorId: alice.id,
134 updates: [{ ref, oldOid: "0".repeat(40), newOid: "1".repeat(40) }],
135 gitEnv: {},
136 }),
137 });
138 const before = sum("refusal");
139 expect((await push("refs/heads/feature")).status).toBe(200);
140 expect(sum("refusal")).toBe(before);
141 expect((await push("refs/pull/1/head")).status).toBe(403);
142 expect(sum("refusal")).toBe(before + 1);
143 } finally {
144 servers.stop();
145 }
146 });
147
148 test("a proxied request counts a request, and a 5xx or a throw also a request_error", async () => {
149 const record = { id: "a1", slug: "tallied", repoId: "none", access: "public" } as AppRecord;
150 const target: AppTarget = { app: record, env: "production" };
151 const base = { app, options: { forgeUrl: "http://forge.test" } };
152 const ask = (runtime: object, path: string) =>
153 proxyApp(
154 runtime as AppsRuntime,
155 new Request(`http://tallied.apps.test${path}`, { headers: { host: "tallied.apps.test" } }),
156 target,
157 {} as never,
158 );
159 // Answered 303 by the forge itself: a request, not an error.
160 const ok = await ask(base, "/__forge/signin");
161 expect(ok?.status).toBe(303);
162 expect(sum("request", "tallied")).toBe(1);
163 expect(sum("request_error", "tallied")).toBe(0);
164 // Nothing running: the forge's 5xx page.
165 const down = await ask({ ...base, envStatus: () => undefined, rouse() {}, touch() {} }, "/");
166 expect(down?.status).toBeGreaterThanOrEqual(500);
167 expect(sum("request", "tallied")).toBe(2);
168 expect(sum("request_error", "tallied")).toBe(1);
169 // The handler throws: both counted, and the error still propagates.
170 const boom = { ...base, envStatus: () => { throw new Error("boom"); } };
171 await expect(ask(boom, "/")).rejects.toThrow("boom");
172 expect(sum("request", "tallied")).toBe(3);
173 expect(sum("request_error", "tallied")).toBe(2);
174 });
175 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs