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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

src/turns.ts can keep the queue order and the current driver's turn end in a file and restore them - module and test only #266

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/251-src-turns-ts-can-keep-the-queue-order-an → main 2 commits fork 2 threads · 2 unresolved

  • Merged. smith/251-src-turns-ts-can-keep-the-queue-order-an was merged into main as ef57c50.

Review

Sign in to review this change.
2 files changed +100 −0
Software/so101/src/turns.test.ts +47
@@ -1,4 +1,7 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2 import { mkdtempSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
25 import { Turns, type TurnEvent } from "./turns.ts";
36
47 const alice = { id: "a", name: "alice", owner: false };
@@ -239,3 +242,47 @@ describe("ready check and extra time", () => {
239242 expect(turns.driver!.endsAt - turns.driver!.startedAt).toBe(360_000);
240243 });
241244 });
245
246 describe("turns kept in a file", () => {
247 const file = () => join(mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "turns-")), "sub", "turns.json");
248 const open = (f: string) => new Turns({ turnMs: 180_000, idleMs: 30_000, now: () => clock, file: f });
249
250 test("a new Turns on the same file has the same queue and driver", () => {
251 const f = file();
252 clock = 1_000_000;
253 const first = open(f);
254 first.join(alice);
255 first.join(bob);
256 first.join(carol);
257 first.dispose();
258 clock += 10_000;
259 turns = open(f);
260 expect(turns.driver?.id).toBe("a");
261 expect(turns.driver?.endsAt).toBe(1_180_000);
262 expect(turns.queue.map((p) => p.id)).toEqual(["b", "c"]);
263 });
264
265 test("a turn that has ended is not restored; the head of the line is called", () => {
266 const f = file();
267 clock = 1_000_000;
268 const first = open(f);
269 first.join(alice);
270 first.join(bob);
271 first.dispose();
272 clock += 180_000;
273 turns = open(f);
274 expect(turns.driver?.id).toBe("b");
outdated

This asserts the stuck state. After the fix, expect driver?.id to be "b" and queue to be empty.

275 expect(turns.driver?.readyBy).toBe(clock + 15_000);
276 expect(turns.queue).toEqual([]);
277 });
278
279 test("a corrupt file starts empty", () => {
280 const f = file();
281 clock = 1_000_000;
282 open(f).join(alice);
283 writeFileSync(f, "{nope");
284 turns = open(f);
285 expect(turns.driver).toBeNull();
286 expect(turns.queue).toEqual([]);
287 });
288 });
Software/so101/src/turns.ts +53
@@ -9,6 +9,8 @@
99 * Plain state and deadlines; one timer, set to the nearest deadline, runs `check()`.
1010 */
1111
12 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
13 import { dirname } from "node:path";
1214 import type { Person } from "./identity.ts";
1315
1416 export interface Turn extends Person {
@@ -43,6 +45,8 @@ export interface TurnsOptions {
4345 maxQueue?: number;
4446 paused?: boolean;
4547 now?: () => number;
48 /** Keep the line and the current turn here, and restore them on construction. */
49 file?: string;
4650 }
4751
4852 export class Turns {
@@ -54,6 +58,7 @@ export class Turns {
5458 maxQueue: number;
5559 paused: boolean;
5660 private readonly now: () => number;
61 private readonly file: string | undefined;
5762 driver: Turn | null = null;
5863 readonly queue: Person[] = [];
5964 /** Open connections per person, and since when someone with none has been gone. */
@@ -70,6 +75,8 @@ export class Turns {
7075 this.maxQueue = options.maxQueue ?? Infinity;
7176 this.paused = options.paused ?? false;
7277 this.now = options.now ?? Date.now;
78 this.file = options.file;
79 if (this.file) this.load(this.file);
7380 }
7481
7582 on(listener: (event: TurnEvent) => void): () => void {
@@ -238,7 +245,53 @@ export class Turns {
238245 this.schedule();
239246 }
240247
248 /** The line and the driver's id with the turn's times; whoever was connected is not, after a restart. */
249 private save(): void {
250 if (!this.file) return;
251 const d = this.driver;
252 const state = { queue: this.queue, driver: d ? { id: d.id, name: d.name, owner: d.owner, startedAt: d.startedAt, endsAt: d.endsAt, bonusMs: d.bonusMs } : null };
253 try {
254 mkdirSync(dirname(this.file), { recursive: true });
255 writeFileSync(`${this.file}.tmp`, JSON.stringify(state));
256 renameSync(`${this.file}.tmp`, this.file);
257 } catch (error) {
258 console.error(`turns: cannot save ${this.file}: ${error instanceof Error ? error.message : error}`);
259 }
260 }
261
262 private load(file: string): void {
263 let stored: { queue?: unknown; driver?: unknown };
264 try {
265 stored = JSON.parse(readFileSync(file, "utf8"));
266 } catch (error) {
267 if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") console.error(`turns: cannot read ${file}, starting empty`);
268 return;
269 }
270 const isPerson = (p: unknown): p is Person => {
271 const o = p as Partial<Person> | null;
272 return typeof o?.id === "string" && typeof o.name === "string" && typeof o.owner === "boolean";
273 };
274 const isTurn = (d: unknown): d is Person & Pick<Turn, "startedAt" | "endsAt" | "bonusMs"> => {
275 const o = d as Partial<Turn> | null;
276 return isPerson(d) && Number.isFinite(o?.startedAt) && Number.isFinite(o?.endsAt) && Number.isFinite(o?.bonusMs);
277 };
278 const now = this.now();
279 const d = stored?.driver;
280 if (isTurn(d) && d.endsAt > now) {
281 this.driver = { id: d.id, name: d.name, owner: d.owner, startedAt: d.startedAt, endsAt: d.endsAt, lastActive: now, readyBy: null, bonusMs: d.bonusMs };
282 }
283 if (Array.isArray(stored?.queue)) {
284 for (const p of stored.queue) {
285 if (isPerson(p) && p.id !== this.driver?.id && !this.queue.some((q) => q.id === p.id)) this.queue.push({ id: p.id, name: p.name, owner: p.owner });
286 }
287 }
288 // An ended turn must not strand the line: call the head, as check() does.
289 if (!this.driver && this.queue.length && !this.paused) this.handOver(null);
290 this.schedule();
291 }
outdated

Add here: if (!this.driver && this.queue.length && !this.paused) this.handOver(null); before schedule(), so an expired turn does not strand the line.

292
241293 private emit(event: TurnEvent): void {
294 this.save();
242295 for (const listener of this.listeners) listener(event);
243296 }
244297

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs