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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

The queue order, the current driver with their turn end, and the hold state survive a restart, kept under FORGE_APP_DATA #250

Parked opened this
Closed without merging

smith/arm:smith/233-the-queue-order-the-current-driver-with → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +125 −2
Software/so101/bench/fake-serve.ts +1
@@ -52,6 +52,7 @@ const lobby = new Lobby({
5252 local,
5353 chatFile: join(dir, "chat.json"),
5454 adminFile: join(dir, "admin.json"),
55 turnsFile: join(dir, "turns.json"),
5556 wordsFile: join(dir, "words.json"),
5657 accounts: new Accounts({ file: join(dir, "accounts.sqlite") }),
5758 moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }),
Software/so101/src/lobby.ts +3 −1
@@ -52,6 +52,8 @@ export interface LobbyOptions {
5252 chatFile?: string;
5353 /** The word filter's file; none keeps it in memory. */
5454 wordsFile?: string;
55 /** The turn queue's file; none keeps it in memory. */
56 turnsFile?: string;
5557 /** The admin settings' file; none keeps them in memory. */
5658 adminFile?: string;
5759 /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */
@@ -102,7 +104,7 @@ export class Lobby {
102104 this.local = Boolean(options.local);
103105 this.admin = options.admin ?? new Admin({ file: options.adminFile });
104106 const a = this.admin.settings;
105 this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue });
107 this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue, file: options.turnsFile });
106108 this.turns.setPaused(a.paused);
107109 this.chat = options.chat ?? new Chat({ file: options.chatFile });
108110 this.accounts = options.accounts ?? new Accounts();
Software/so101/src/turns.test.ts +59
@@ -239,3 +239,62 @@ describe("ready check and extra time", () => {
239239 expect(turns.driver!.endsAt - turns.driver!.startedAt).toBe(360_000);
240240 });
241241 });
242
243 describe("turns kept in a file", () => {
244 const { mkdtempSync, writeFileSync } = require("node:fs") as typeof import("node:fs");
245 const file = () => `${mkdtempSync(`${require("node:os").tmpdir()}/so101-turns-`)}/turns.json`;
246 const open = (f: string) => new Turns({ turnMs: 180_000, idleMs: 30_000, now: () => clock, file: f });
247
248 test("a new Turns on the same file has the same queue and driver", () => {
249 const f = file();
250 clock = 1_000_000;
251 turns = open(f);
252 turns.join(alice);
253 turns.join(bob);
254 turns.join(carol);
255 clock += 60_000;
256 const again = open(f);
257 expect(again.driver?.id).toBe("a");
258 expect(again.driver?.endsAt).toBe(turns.driver!.endsAt);
259 expect(again.queue.map((p) => p.id)).toEqual(["b", "c"]);
260 again.dispose();
261 });
262
263 test("the hold and the line behind it come back", () => {
264 const f = file();
265 clock = 1_000_000;
266 turns = open(f);
267 turns.join(alice);
268 turns.join(bob);
269 turns.setPaused(true);
270 const again = open(f);
271 expect(again.paused).toBe(true);
272 expect(again.driver).toBeNull();
273 expect(again.queue.map((p) => p.id)).toEqual(["b"]);
274 again.dispose();
275 });
276
277 test("a turn that ended while the server was down is not restored; the line moves up", () => {
278 const f = file();
279 clock = 1_000_000;
280 turns = open(f);
281 turns.join(alice);
282 turns.join(bob);
283 clock += 200_000;
284 const again = open(f);
285 expect(again.driver?.id).toBe("b");
286 expect(again.queue).toEqual([]);
287 again.dispose();
288 });
289
290 test("a corrupt or missing file starts empty", () => {
291 const f = file();
292 writeFileSync(f, "{nope");
293 clock = 1_000_000;
294 turns = open(f);
295 expect(turns.driver).toBeNull();
296 expect(turns.queue).toEqual([]);
297 turns = open(`${f}.missing`);
298 expect(turns.driver).toBeNull();
299 });
300 });
Software/so101/src/turns.ts +62 −1
@@ -6,9 +6,12 @@
66 * The owner jumps the line: asking to drive ends whoever drives now. The owner can also end anyone's turn.
77 * Paused (maintenance), nobody new gets a turn but the owner, and the line keeps its order for when it resumes;
88 * the line holds at most `maxQueue`. Turn length and idle allowance change live, the current turn included.
9 * Plain state and deadlines; one timer, set to the nearest deadline, runs `check()`.
9 * With a `file`, the line, the driver with their turn end and the hold are kept there and come back on start; a turn
10 * that ended while the server was down does not. Plain state and deadlines; one timer, set to the nearest deadline, runs `check()`.
1011 */
1112
13 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14 import { dirname } from "node:path";
1215 import type { Person } from "./identity.ts";
1316
1417 export interface Turn extends Person {
@@ -43,6 +46,8 @@ export interface TurnsOptions {
4346 maxQueue?: number;
4447 paused?: boolean;
4548 now?: () => number;
49 /** Where the line, the driver and the hold are kept; none keeps them in memory. */
50 file?: string;
4651 }
4752
4853 export class Turns {
@@ -54,6 +59,7 @@ export class Turns {
5459 maxQueue: number;
5560 paused: boolean;
5661 private readonly now: () => number;
62 private readonly file: string | undefined;
5763 driver: Turn | null = null;
5864 readonly queue: Person[] = [];
5965 /** Open connections per person, and since when someone with none has been gone. */
@@ -70,6 +76,8 @@ export class Turns {
7076 this.maxQueue = options.maxQueue ?? Infinity;
7177 this.paused = options.paused ?? false;
7278 this.now = options.now ?? Date.now;
79 this.file = options.file;
80 if (this.file) this.load(this.file);
7381 }
7482
7583 on(listener: (event: TurnEvent) => void): () => void {
@@ -238,7 +246,60 @@ export class Turns {
238246 this.schedule();
239247 }
240248
249 private static person(value: unknown): Person | null {
250 const p = value as Partial<Person> | null;
251 if (!p || typeof p.id !== "string" || typeof p.name !== "string" || typeof p.owner !== "boolean") return null;
252 return { id: p.id, name: p.name, owner: p.owner };
253 }
254
255 private load(file: string): void {
256 let stored: { queue?: unknown; driver?: Record<string, unknown> | null; paused?: unknown };
257 try {
258 stored = JSON.parse(readFileSync(file, "utf8"));
259 if (!stored || typeof stored !== "object") throw new Error("not an object");
260 } catch (err) {
261 if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.error(`turns: starting empty, cannot read ${file}: ${(err as Error).message}`);
262 else console.error(`turns: starting empty, no ${file}`);
263 return;
264 }
265 const now = this.now();
266 if (typeof stored.paused === "boolean") this.paused = stored.paused;
267 const seen = new Set<string>();
268 const d = stored.driver;
269 const who = d ? Turns.person(d) : null;
270 if (d && who && Number.isFinite(d.startedAt) && Number.isFinite(d.endsAt) && (d.endsAt as number) > now) {
271 this.driver = { ...who, startedAt: d.startedAt as number, endsAt: d.endsAt as number, lastActive: now, readyBy: null, bonusMs: Number.isFinite(d.bonusMs) ? (d.bonusMs as number) : 0 };
272 seen.add(who.id);
273 }
274 if (Array.isArray(stored.queue)) {
275 for (const item of stored.queue) {
276 const p = Turns.person(item);
277 if (p && !seen.has(p.id)) {
278 seen.add(p.id);
279 this.queue.push(p);
280 }
281 }
282 }
283 if (!this.driver && !this.paused && this.queue.length) this.handOver(null);
284 this.schedule();
285 }
286
287 /** Write the line, the driver and the hold whole, atomically; a failed write is logged, never thrown into a turn. */
288 private save(): void {
289 if (!this.file) return;
290 const d = this.driver;
291 const driver = d ? { id: d.id, name: d.name, owner: d.owner, startedAt: d.startedAt, endsAt: d.endsAt, bonusMs: d.bonusMs } : null;
292 try {
293 mkdirSync(dirname(this.file), { recursive: true });
294 writeFileSync(`${this.file}.tmp`, JSON.stringify({ queue: this.queue, driver, paused: this.paused }));
295 renameSync(`${this.file}.tmp`, this.file);
296 } catch (err) {
297 console.error(`turns: cannot write ${this.file}: ${(err as Error).message}`);
298 }
299 }
300
241301 private emit(event: TurnEvent): void {
302 this.save();
242303 for (const listener of this.listeners) listener(event);
243304 }
244305

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs