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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Software/so101/src/reports.ts stores chat reports in a JSON file the caller names: one per reporter per line, 20 per reporter, 200 overall - two new files, full suite green #337

Merged opened this

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

smith/arm:smith/330-software-so101-src-reports-ts-stores-cha → main 1 commit fork

  • Merged. smith/330-software-so101-src-reports-ts-stores-cha was merged into main as 97ff219.

Review

Sign in to review this change.
2 files changed +138 −0
Software/so101/src/reports.test.ts added +70
@@ -0,0 +1,70 @@
1 import { afterAll, expect, spyOn, test } from "bun:test";
2 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { Reports } from "./reports";
6
7 const dir = mkdtempSync(join(tmpdir(), "reports-"));
8 afterAll(() => rmSync(dir, { recursive: true, force: true }));
9 const rep = (id: string, reporter = "r", at = 1) => ({ id, text: `t${id}`, author: "a", reporter, at });
10
11 test("a repeat of the same reporter and line is refused; another reporter may report it", () => {
12 const r = new Reports(join(dir, "dup.json"));
13 expect(r.add(rep("1"))).toBe(true);
14 expect(r.add(rep("1"))).toBe(false);
15 expect(r.add(rep("1", "other"))).toBe(true);
16 expect(r.list()).toHaveLength(2);
17 });
18
19 test("list is newest first", () => {
20 const r = new Reports(join(dir, "order.json"));
21 r.add(rep("1")); r.add(rep("2"));
22 expect(r.list().map((x) => x.id)).toEqual(["2", "1"]);
23 });
24
25 test("20 per reporter, oldest dropped", () => {
26 const r = new Reports(join(dir, "per.json"));
27 for (let i = 0; i < 25; i++) r.add(rep(String(i)));
28 r.add(rep("x", "other"));
29 const ids = r.list().map((x) => x.id);
30 expect(ids).toHaveLength(21);
31 expect(ids).not.toContain("4");
32 expect(ids).toContain("5");
33 expect(ids).toContain("x");
34 });
35
36 test("200 overall, oldest dropped", () => {
37 const r = new Reports(join(dir, "all.json"));
38 for (let i = 0; i < 210; i++) r.add(rep("l", `u${i}`));
39 const l = r.list();
40 expect(l).toHaveLength(200);
41 expect(l[0]!.reporter).toBe("u209");
42 expect(l[199]!.reporter).toBe("u10");
43 });
44
45 test("a restart restores the list", () => {
46 const f = join(dir, "restart.json");
47 const a = new Reports(f);
48 a.add(rep("1")); a.add(rep("2"));
49 const b = new Reports(f);
50 expect(b.list()).toEqual(a.list());
51 expect(b.add(rep("2"))).toBe(false);
52 });
53
54 test("a missing file starts empty quietly", () => {
55 const spy = spyOn(console, "error").mockImplementation(() => {});
56 expect(new Reports(join(dir, "none.json")).list()).toEqual([]);
57 expect(spy).not.toHaveBeenCalled();
58 spy.mockRestore();
59 });
60
61 test("a corrupt file starts empty with one console.error", () => {
62 const f = join(dir, "bad.json");
63 writeFileSync(f, "{nope");
64 const spy = spyOn(console, "error").mockImplementation(() => {});
65 const r = new Reports(f);
66 expect(r.list()).toEqual([]);
67 expect(spy).toHaveBeenCalledTimes(1);
68 spy.mockRestore();
69 expect(r.add(rep("1"))).toBe(true);
70 });
Software/so101/src/reports.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * Chat reports kept in a JSON file the caller names. One report per reporter per chat line; 20 per reporter
3 * and 200 overall, oldest dropped first. Writes are synchronous (temp file, then rename), so nothing outlives a call.
4 */
5 import { readFileSync, renameSync, writeFileSync } from "node:fs";
6
7 export const PER_REPORTER = 20;
8 export const OVERALL = 200;
9
10 export interface Report {
11 id: string;
12 text: string;
13 author: string;
14 reporter: string;
15 at: number;
16 }
17
18 function valid(r: unknown): r is Report {
19 if (!r || typeof r !== "object") return false;
20 const o = r as Record<string, unknown>;
21 return typeof o.id === "string" && typeof o.text === "string" && typeof o.author === "string"
22 && typeof o.reporter === "string" && typeof o.at === "number" && Number.isFinite(o.at);
23 }
24
25 export class Reports {
26 /** Oldest first. */
27 private items: Report[] = [];
28
29 constructor(private readonly file: string) {
30 let raw: string;
31 try {
32 raw = readFileSync(file, "utf8");
33 } catch (e) {
34 if ((e as NodeJS.ErrnoException).code !== "ENOENT") console.error(`reports: ${file} is not readable; starting empty`);
35 return;
36 }
37 try {
38 const data: unknown = JSON.parse(raw);
39 if (!Array.isArray(data) || !data.every(valid)) throw new Error("not a list of reports");
40 this.items = data.map(({ id, text, author, reporter, at }) => ({ id, text, author, reporter, at }));
41 } catch {
42 console.error(`reports: ${file} is not valid reports JSON; starting empty`);
43 }
44 }
45
46 /** False when this reporter already reported this line. */
47 add(r: Report): boolean {
48 if (!valid(r)) throw new TypeError("invalid report");
49 if (this.items.some((x) => x.reporter === r.reporter && x.id === r.id)) return false;
50 this.items.push({ id: r.id, text: r.text, author: r.author, reporter: r.reporter, at: r.at });
51 const mine = this.items.filter((x) => x.reporter === r.reporter);
52 if (mine.length > PER_REPORTER) this.items.splice(this.items.indexOf(mine[0]!), 1);
53 if (this.items.length > OVERALL) this.items.shift();
54 this.save();
55 return true;
56 }
57
58 /** Newest first. */
59 list(): Report[] {
60 return this.items.map((r) => ({ ...r })).reverse();
61 }
62
63 private save(): void {
64 const tmp = `${this.file}.tmp`;
65 writeFileSync(tmp, JSON.stringify(this.items));
66 renameSync(tmp, this.file);
67 }
68 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs