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

forge/boards edits in the file form as well as in the boards editor (schema + acceptance) #16676

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/7338-forge-boards-edits-in-the-file-form-as-w → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/7338-forge-boards-edits-in-the-file-form-as-w was merged into main as 964a8fe.

Review

Sign in to review this change.
6 files changed +263 −4
docs/features/config-form.md +9
@@ -160,3 +160,12 @@ Every preview's sample repository (`/preview-admin/sample`) holds
160160 They have comments, an anchor and a merge key (YAML), and a date and an
161161 array of tables (TOML). Open either on the blob page, press **Edit as
162162 form**, change one value and **Review**: the diff touches only that line.
163
164 ## Boards
165
166 The files in `forge/boards` are tuned the same way (#7338). When `findSchema` finds no schema
167 for a `*.json` at the top of `forge/boards`, it falls back to `boardSchema()` in
168 `src/boards/schema.ts`, built from the parser's own lists, so chart kinds, sources, aggregates,
169 buckets, `w`/`h`, the panel limit, title length and the range and refresh choices cannot drift
170 from `parseBoard`. Nothing is committed to forge/boards; a schema the repository carries itself
171 still wins. The form also says in words when a list is over `maxItems` or a string under `minLength`.
src/boards/query.ts +1 −1
@@ -11,7 +11,7 @@ import { SOURCES, type ColumnType } from "./sources.ts";
1111 const OPS = { eq: "=", ne: "<>", lt: "<", lte: "<=", gt: ">", gte: ">=", starts: null } as const;
1212 /** A bucket's width in seconds; a query's `step` replaces it. */
1313 export const BUCKETS = { minute: 60, hour: 3600, day: 86_400 } as const;
14 const AGGREGATES = ["count", "sum", "avg", "max"] as const;
14 export const AGGREGATES = ["count", "sum", "avg", "max"] as const;
1515 const MAX_ROWS = 1000;
1616 /**
1717 * A query grouped by time is never cut short: past this many rows it is
src/boards/schema.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * The JSON Schema of a board file, generated from the parser's own lists so
3 * the two cannot drift: `test/boards-schema.test.ts` holds it to `parseBoard`.
4 * The file form (#7336) falls back to it for a file in forge/boards, so
5 * nothing is committed there.
6 */
7 import type { FoundSchema } from "../web/render/json-schema.ts";
8 import { CHARTS } from "./chart.ts";
9 import { AGGREGATES, BUCKETS } from "./query.ts";
10 import { SOURCES } from "./sources.ts";
11 import { BOARDS_OWNER, BOARDS_REPO, MAX_H, MAX_PANELS, MAX_TITLE, MAX_W, RANGES, REFRESHES } from "./store.ts";
12
13 const sources = Object.keys(SOURCES).sort();
14
15 export function boardSchema(): Record<string, unknown> {
16 const panel = {
17 type: "object",
18 required: ["title", "chart", "query", "w", "h"],
19 properties: {
20 title: { type: "string", minLength: 1, maxLength: MAX_TITLE, description: `The panel's name, up to ${MAX_TITLE} characters.` },
21 chart: { type: "string", enum: [...CHARTS], description: "How the answer is drawn." },
22 query: {
23 type: "object",
24 required: ["source", "aggregate"],
25 properties: {
26 source: { type: "string", enum: sources, description: "The table the panel reads." },
27 aggregate: { type: "string", enum: [...AGGREGATES], description: "count needs no column." },
28 column: { type: "string", description: "The column to sum, average or take the max of." },
29 groupBy: {
30 type: ["string", "object"],
31 description: "A column of the source, or {\"bucket\": minute|hour|day} for time.",
32 properties: { bucket: { type: "string", enum: Object.keys(BUCKETS) } },
33 },
34 step: { type: "integer", minimum: 1, description: "Seconds per time bucket, in place of the bucket's width." },
35 series: { type: "string", description: "A second grouping column." },
36 },
37 },
38 w: { type: "integer", default: 1, minimum: 1, maximum: MAX_W, description: "Columns wide." },
39 h: { type: "integer", default: 1, minimum: 1, maximum: MAX_H, description: "Rows tall." },
40 },
41 };
42 return {
43 $schema: "http://json-schema.org/draft-07/schema#",
44 title: "Forge board",
45 type: "object",
46 required: ["title", "range", "refresh", "panels"],
47 properties: {
48 title: { type: "string", minLength: 1, maxLength: MAX_TITLE, description: `The board's name, up to ${MAX_TITLE} characters.` },
49 range: { type: "string", enum: [...RANGES], description: "How far back the panels look." },
50 refresh: { type: "string", enum: [...REFRESHES], description: "How often the page re-reads." },
51 panels: { type: "array", maxItems: MAX_PANELS, description: `At most ${MAX_PANELS} panels, in the order shown.`, items: panel },
52 },
53 };
54 }
55
56 /**
57 * The schema for a file at the top of forge/boards, served by the forge itself
58 * so no copy has to be committed there (and none can go stale); undefined for
59 * any other repository or file.
60 */
61 export function builtinSchema(fullName: string, path: string): FoundSchema | undefined {
62 if (fullName !== `${BOARDS_OWNER}/${BOARDS_REPO}` || path.includes("/") || !path.endsWith(".json")) return undefined;
63 return { root: boardSchema() as FoundSchema["root"], from: "board schema", builtin: true };
64 }
src/web/pages/config.ts +10 −2
@@ -36,6 +36,7 @@ import { isFormConfig, languageOf, parseConfig, writeConfig } from "../render/co
3636 import { applyOp, configFields, countFields, MAX_FIELDS, readValues } from "../render/config-form.ts";
3737 import { lineDiff, parseJson, sameDoc, stringify, type Json } from "../render/json-doc.ts";
3838 import { findSchema, validate, type FoundSchema } from "../render/json-schema.ts";
39 import { builtinSchema } from "../../boards/schema.ts";
3940 import { localScope, type RepoScope } from "../scope.ts";
4041 import { btn, field, icon } from "../ui.ts";
4142 import { editErrorText } from "./edit.ts";
@@ -86,7 +87,12 @@ async function readText(scope: RepoScope, ref: string, path: string, max: number
8687 }
8788
8889 const schemaFor = (scope: RepoScope, ref: string, path: string, doc: Json): Promise<FoundSchema | undefined> =>
89 findSchema(path, doc, (p) => (isSafeTreePath(p) ? readText(scope, ref, p, MAX_SCHEMA_BYTES) : Promise.resolve(undefined)));
90 findSchema(
91 path,
92 doc,
93 (p) => (isSafeTreePath(p) ? readText(scope, ref, p, MAX_SCHEMA_BYTES) : Promise.resolve(undefined)),
94 () => builtinSchema(scope.fullName, path),
95 );
9096
9197 interface FormState {
9298 readonly ref: string;
@@ -110,7 +116,9 @@ function head(scope: RepoScope, s: FormState, proposing: boolean, step: string):
110116 <span class="mono">${scope.fullName}</span>${
111117 s.found === undefined
112118 ? html` · fields from the values`
113 : html` · fields from <a href="${blobHref(scope, s.ref, s.found.from)}" class="mono">${s.found.from}</a>`
119 : s.found.builtin
120 ? html` · fields from the forge's board schema`
121 : html` · fields from <a href="${blobHref(scope, s.ref, s.found.from)}" class="mono">${s.found.from}</a>`
114122 }`,
115123 });
116124 }
src/web/render/json-schema.ts +20 −1
@@ -27,6 +27,10 @@ export interface Schema {
2727 readonly minimum?: number;
2828 readonly maximum?: number;
2929 readonly pattern?: string;
30 readonly minLength?: number;
31 readonly maxLength?: number;
32 readonly minItems?: number;
33 readonly maxItems?: number;
3034 readonly default?: unknown;
3135 readonly $ref?: string;
3236 }
@@ -36,6 +40,8 @@ export interface FoundSchema {
3640 readonly root: Schema;
3741 /** The repository path it was read from. */
3842 readonly from: string;
43 /** Served by the forge itself, not read from the repository: there is no file to link to. */
44 readonly builtin?: boolean;
3945 }
4046
4147 const isObject = (v: unknown): v is Record<string, unknown> =>
@@ -109,6 +115,12 @@ export function validate(doc: Json, found: FoundSchema | undefined): Map<string,
109115 if (typeof s.minimum === "number" && n < s.minimum) errors.set(p, `Must be at least ${s.minimum}.`);
110116 if (typeof s.maximum === "number" && n > s.maximum) errors.set(p, `Must be at most ${s.maximum}.`);
111117 }
118 if (v.t === "string") {
119 const n = [...v.v].length;
120 if (typeof s.minLength === "number" && n < s.minLength)
121 errors.set(p, s.minLength === 1 ? "Cannot be empty." : `Needs at least ${s.minLength} characters.`);
122 if (typeof s.maxLength === "number" && n > s.maxLength) errors.set(p, `Can be at most ${s.maxLength} characters.`);
123 }
112124 if (v.t === "object") {
113125 const missing = (Array.isArray(s.required) ? s.required : []).filter(
114126 (k) => typeof k === "string" && !v.entries.some(([key]) => key === k),
@@ -116,6 +128,11 @@ export function validate(doc: Json, found: FoundSchema | undefined): Map<string,
116128 if (missing.length > 0) errors.set(p, `Needs ${missing.join(", ")}.`);
117129 for (const [k, x] of v.entries) walk(x, schemaAt(found, pointer(p, k)), pointer(p, k));
118130 }
131 if (v.t === "array") {
132 if (typeof s.maxItems === "number" && v.items.length > s.maxItems)
133 errors.set(p, `Has ${v.items.length} entries; at most ${s.maxItems} are allowed. Remove ${v.items.length - s.maxItems}.`);
134 if (typeof s.minItems === "number" && v.items.length < s.minItems) errors.set(p, `Needs at least ${s.minItems} entries.`);
135 }
119136 if (v.t === "array") v.items.forEach((x, i) => walk(x, schemaAt(found, `${p}/${i}`), `${p}/${i}`));
120137 };
121138 walk(doc, schemaAt(found, ""), "");
@@ -188,6 +205,8 @@ export async function findSchema(
188205 path: string,
189206 doc: Json,
190207 read: (path: string) => Promise<string | undefined>,
208 /** Tried last: a schema the forge itself knows for this file. */
209 fallback?: () => FoundSchema | undefined,
191210 ): Promise<FoundSchema | undefined> {
192211 const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
193212 const tryRead = async (candidate: string | undefined): Promise<FoundSchema | undefined> => {
@@ -218,7 +237,7 @@ export async function findSchema(
218237 if (found !== undefined) return found;
219238 }
220239 }
221 return undefined;
240 return fallback?.();
222241 }
223242
224243 /**
test/boards-schema.test.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * The board schema (#7338): generated from the parser's lists, held to
3 * `parseBoard` by agreement, and good enough that the file form and the
4 * boards editor make the same change to a board.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { applyEdit } from "../src/boards/edit.ts";
8 import { boardSchema, builtinSchema } from "../src/boards/schema.ts";
9 import { STARTING_BOARDS } from "../src/boards/starting.ts";
10 import { parseBoard, type Board } from "../src/boards/store.ts";
11 import { applyOp, configFields, readValues } from "../src/web/render/config-form.ts";
12 import { parseJson, stringify, type Json } from "../src/web/render/json-doc.ts";
13 import { findSchema, validate, type FoundSchema } from "../src/web/render/json-schema.ts";
14
15 const found: FoundSchema = { root: boardSchema() as FoundSchema["root"], from: "board.schema.json" };
16 const doc = (v: unknown): Json => {
17 const p = parseJson(JSON.stringify(v));
18 if (!p.ok) throw new Error(p.error.message);
19 return p.value;
20 };
21 const panel = (o: Record<string, unknown> = {}) => ({
22 title: "P", chart: "bar", query: { source: "runs", aggregate: "count" }, w: 1, h: 1, ...o,
23 });
24 const board = (panels: unknown[] = [panel()], o: Record<string, unknown> = {}) => ({
25 title: "B", range: "7d", refresh: "off", panels, ...o,
26 });
27
28 describe("the schema and the parser agree", () => {
29 const cases: [string, unknown][] = [
30 ["a board", board()],
31 ["an empty board", board([])],
32 ["a bucketed query", board([panel({ query: { source: "runs", aggregate: "count", groupBy: { bucket: "hour" } } })])],
33 ["a column query", board([panel({ query: { source: "runs", aggregate: "sum", column: "cost_usd", groupBy: "kind" } })])],
34 ["a bad chart", board([panel({ chart: "pie" })])],
35 ["a bad source", board([panel({ query: { source: "nope", aggregate: "count" } })])],
36 ["w too wide", board([panel({ w: 4 })])],
37 ["h zero", board([panel({ h: 0 })])],
38 ["a fractional w", board([panel({ w: 1.5 })])],
39 ["a bad range", board([], { range: "1y" })],
40 ["a bad refresh", board([], { refresh: "5s" })],
41 ["no panels key", { title: "B", range: "7d", refresh: "off" }],
42 ["24 panels", board(Array.from({ length: 24 }, () => panel()))],
43 ];
44 for (const [name, value] of cases) {
45 test(name, () => {
46 expect(validate(doc(value), found).size === 0).toBe(parseBoard(value).ok);
47 });
48 }
49
50 // The parser leaves a query's aggregate and bucket to the run that reads it; the schema says so
51 // earlier.
52 test("the schema is stricter than the parser on aggregate and bucket, never looser", () => {
53 const q = (query: unknown) => board([panel({ query })]);
54 for (const bad of [{ source: "runs", aggregate: "median" }, { source: "runs", aggregate: "count", groupBy: { bucket: "week" } }]) {
55 expect(parseBoard(q(bad)).ok).toBe(true);
56 expect(validate(doc(q(bad)), found).size).toBeGreaterThan(0);
57 }
58 });
59
60 test("the panel limit is in the schema and in the parser", () => {
61 const props = boardSchema().properties as Record<string, { maxItems?: number }>;
62 expect(props.panels?.maxItems).toBe(24);
63 expect(parseBoard(board(Array.from({ length: 25 }, () => panel()))).ok).toBe(false);
64 });
65
66 test("every starting board passes both", () => {
67 for (const b of Object.values(STARTING_BOARDS)) expect(validate(doc(b), found).size).toBe(0);
68 });
69
70 test("the enums are the parser's own lists", () => {
71 const text = JSON.stringify(boardSchema());
72 for (const word of ["heat", "area", "30d", "10s", "adminActions", "minute", "avg"]) expect(text).toContain(`"${word}"`);
73 });
74
75 test("a file in forge/boards finds the schema with nothing committed, and no other file does", async () => {
76 const none = async () => undefined;
77 const via = (name: string, path: string) => findSchema(path, doc({}), none, () => builtinSchema(name, path));
78 expect((await via("forge/boards", "throughput.json"))?.builtin).toBe(true);
79 expect(await via("forge/boards", "notes/a.json")).toBeUndefined();
80 expect(await via("forge/boards", "a.yaml")).toBeUndefined();
81 expect(await via("someone/else", "throughput.json")).toBeUndefined();
82 });
83
84 test("a schema the repository carries wins over the built-in one", async () => {
85 const read = async (p: string) => (p === "a.schema.json" ? '{"type":"object"}' : undefined);
86 expect((await findSchema("a.json", doc({}), read, () => builtinSchema("forge/boards", "a.json")))?.from).toBe("a.schema.json");
87 });
88 });

Non-blocking: this three-way regex is loose. Assert the selected option's value once and drop the alternatives.

89
90 describe("what the form says and draws", () => {
91 const words = (v: unknown) => validate(doc(v), found);
92
93 test("a 25th panel and an empty title are named in words", () => {
94 const over = words(board(Array.from({ length: 25 }, () => panel())));
95 expect(over.get("/panels")).toBe("Has 25 entries; at most 24 are allowed. Remove 1.");
96 expect(words(board([panel({ title: "" })])).get("/panels/0/title")).toBe("Cannot be empty.");
97 expect(words(board([], { title: "x".repeat(81) })).get("/title")).toBe("Can be at most 80 characters.");
98 });
99
100 test("groupBy is a text field as a column and a bucket select as time", () => {
101 const html = (g: unknown) =>
102 String(configFields(doc(board([panel({ query: { source: "runs", aggregate: "count", groupBy: g } })])), { found }));
103 const column = html("kind");
104 expect(column).toContain('name="v/panels/0/query/groupBy"');
105 expect(column).toContain('value="kind"');
106 const bucket = html({ bucket: "hour" });
107 expect(bucket).toContain('name="j/panels/0/query/groupBy/bucket"');
108 expect(bucket).toMatch(/<option value="&quot;hour&quot;"[^>]*selected|<option value="&#34;hour&#34;"[^>]*selected|selected[^>]*>hour/);
109 });
110
111 test("groupBy can be added from the form", () => {
112 const d = applyOp(doc(board()), JSON.stringify(["key", "/panels/0/query", "groupBy"]), found);
113 expect(String(configFields(d, { found }))).toContain('name="v/panels/0/query/groupBy"');
114 });
115 });
116
117 describe("the file form and the editor make the same change", () => {
118 const throughput = STARTING_BOARDS.throughput;
119
120 test("add a panel, bar to heat, reorder two", () => {
121 const fresh = {
122 title: "New", chart: "line", query: { source: "runs", aggregate: "count" }, w: 1, h: 1,
123 };
124
125 // The editor.
126 let viaEdit = (parseBoard(throughput!) as { value: Board }).value;
127 const edited = (e: Parameters<typeof applyEdit>[1]) => {
128 const r = applyEdit(viaEdit, e);
129 if (!r.ok) throw new Error(r.error);
130 viaEdit = r.value;
131 };
132 edited({ kind: "edit", index: 1, panel: { ...viaEdit.panels[1], chart: "heat" } });
133 edited({ kind: "move", index: 0, by: 1 });
134 edited({ kind: "add", panel: fresh });
135
136 // The form: the same values, through its own operations.
137 let d = doc(throughput);
138 d = applyOp(d, JSON.stringify(["down", "/panels/0"]), found);
139 d = applyOp(d, JSON.stringify(["add", "/panels"]), found);
140 // The blank card the schema offers is not yet a board: it needs a title.
141 const blank = d.t === "object" ? d.entries.find(([k]) => k === "panels")![1] : undefined;
142 expect(blank?.t === "array" && blank.items.length).toBe(4);
143 const read = readValues(d, (n) =>
144 ({ "v/panels/0/chart": "heat", "v/panels/3/title": "New", "v/panels/3/query/source": "runs", "v/panels/3/chart": "line" } as Record<string, string>)[n],
145 );
146 expect(read.errors.size).toBe(0);
147 const text = stringify(read.doc, { indent: " ", eol: "\n", finalNewline: true });
148 const viaForm = parseBoard(JSON.parse(text));
149 expect(viaForm.ok).toBe(true);
150 expect(viaForm.ok && viaForm.value).toEqual(viaEdit);
151 expect(validate(read.doc, found).size).toBe(0);
152 expect(viaEdit.panels.map((p: { chart: string }) => p.chart)).toEqual(["heat", "bar", "heat", "line"]);
153 });
154
155 test("a blank panel from the form is refused by the parser until it has a title", () => {
156 const d = applyOp(doc(board([])), JSON.stringify(["add", "/panels"]), found);
157 expect(parseBoard(JSON.parse(stringify(d))).ok).toBe(false);
158 });
159 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs