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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

TOP: a restart never costs you control - reconnect in a second, keep your turn and queue place, and the arm holds still meanwhile #230

Parked opened this in answer to
Closed without merging

smith/arm:smith/202-top-a-restart-never-costs-you-control-re → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +112 −5
Software/so101/bench/fake-serve.ts +1
@@ -50,6 +50,7 @@ const local = !identityKey && !process.env.FORGE_APP_ENV;
5050 const lobby = new Lobby({
5151 identityKey,
5252 local,
53 turnsFile: join(dir, "turns.json"),
5354 chatFile: join(dir, "chat.json"),
5455 adminFile: join(dir, "admin.json"),
5556 wordsFile: join(dir, "words.json"),
Software/so101/src/admin-relay.test.ts +9
@@ -123,3 +123,12 @@ test("/status names who is driving: null, then alice, then the owner after a tak
123123 sim.stop(true);
124124 }
125125 });
126
127 test("/deploy-ok says 200 when nobody drives and 409 while someone does", async () => {
128 const base = await boot();
129 expect((await fetch(`${base}/deploy-ok`)).status).toBe(200);
130 lobby!.turns.join({ id: "id-a", name: "a", owner: false });
131 const busy = await fetch(`${base}/deploy-ok`);
132 expect(busy.status).toBe(409);
133 expect(await busy.json()).toEqual({ ok: false, driving: true });
134 });
Software/so101/src/lobby.ts +3 −1
@@ -56,6 +56,8 @@ export interface LobbyOptions {
5656 adminFile?: string;
5757 /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */
5858 turns?: Turns;
59 /** Where the driver and the line survive a restart; none keeps them in memory. */
60 turnsFile?: string;
5961 chat?: Chat;
6062 admin?: Admin;
6163 /** Checks each posted line in the background; none leaves the chat unchecked. */
@@ -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({ file: options.turnsFile, turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue });
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/relay.ts +4
@@ -543,6 +543,10 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
543543 const path = url.pathname + url.search;
544544 const reading = req.method === "GET" || req.method === "HEAD";
545545 if (!reading && !sameOrigin(req)) return json(res, 403, { error: "only this page may change the arm" });
546 if (req.method === "GET" && url.pathname === "/deploy-ok") {
547 const driving = Boolean(lobby?.turns.driver);
548 return json(res, driving ? 409 : 200, { ok: !driving, driving });
549 }
546550 if (req.method === "GET" && url.pathname === "/cameras") return json(res, 200, cameras.list().map(({ id, name, online }) => ({ id, name, online })));
547551 if (req.method === "GET" && url.pathname === "/admin/camera-list") {
548552 res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
Software/so101/src/turns.test.ts +43
@@ -239,3 +239,46 @@ describe("ready check and extra time", () => {
239239 expect(turns.driver!.endsAt - turns.driver!.startedAt).toBe(360_000);
240240 });
241241 });
242
243 describe("turns across a restart", () => {
244 const file = `${process.env.TMPDIR ?? "/tmp"}/turns-restart-${process.pid}.json`;
245 const boot = () => new Turns({ turnMs: 180_000, idleMs: 30_000, graceMs: 10_000, now: () => clock, file });
246
247 test("the driver keeps the turn and the line keeps its order when they reconnect in time", () => {
248 clock = 1_000_000;
249 const before = boot();
250 before.join(alice);
251 before.join(bob);
252 before.join(carol);
253 const endsAt = before.driver!.endsAt;
254 before.dispose(); // the server goes down
255 clock += 3_000;
256 turns = boot();
257 expect(turns.driver).toMatchObject({ id: "a", endsAt });
258 expect(turns.queue.map((p) => p.id)).toEqual(["b", "c"]);
259 for (const id of ["a", "b", "c"]) turns.connect(id);
260 clock += 20_000;
261 turns.check();
262 expect(turns.driver?.id).toBe("a");
263 expect(turns.queue.map((p) => p.id)).toEqual(["b", "c"]);
264 });
265
266 test("anyone who does not come back within the grace loses their place as usual", () => {
267 clock = 1_000_000;
268 const before = boot();
269 before.join(alice);
270 before.join(bob);
271 before.dispose();
272 turns = boot();
273 turns.connect("b");
274 clock += 11_000;
275 turns.check();
276 expect(turns.driver?.id).toBe("b"); // alice never came back, bob moved up
277 });
278
279 test("an unreadable file starts empty", async () => {
280 await Bun.write(file, "{nope");
281 turns = boot();
282 expect(turns.driver).toBeNull();
283 });
284 });
Software/so101/src/turns.ts +48
@@ -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 /** Where the driver and the line are kept so a restart gives them back; none keeps them in memory. */
49 file?: string;
4650 }
4751
4852 export class Turns {
@@ -61,6 +65,7 @@ export class Turns {
6165 private readonly gone = new Map<string, number>();
6266 private readonly listeners = new Set<(event: TurnEvent) => void>();
6367 private timer: ReturnType<typeof setTimeout> | undefined;
68 private readonly file: string | undefined;
6469
6570 constructor(options: TurnsOptions = {}) {
6671 this.turnMs = options.turnMs ?? 180_000;
@@ -70,6 +75,9 @@ 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);
80 this.on(() => this.save());
7381 }
7482
7583 on(listener: (event: TurnEvent) => void): () => void {
@@ -217,6 +225,46 @@ export class Turns {
217225 this.listeners.clear();
218226 }
219227
228 /** Read back the driver and the line. Each starts as if just disconnected, so the usual grace lets them reconnect and keep their place. */
229 private load(file: string): void {
230 try {
231 const saved = JSON.parse(readFileSync(file, "utf8"));
232 const person = (p: any): Person | null => (p && typeof p.id === "string" && typeof p.name === "string" ? { id: p.id, name: p.name, owner: p.owner === true } : null);
233 const num = (n: unknown, fallback: number) => (typeof n === "number" && Number.isFinite(n) ? n : fallback);
234 const now = this.now();
235 const d = person(saved.driver);
236 if (d) {
237 this.driver = { ...d, startedAt: num(saved.driver.startedAt, now), endsAt: num(saved.driver.endsAt, now), lastActive: now, readyBy: null, bonusMs: num(saved.driver.bonusMs, 0) };
238 this.gone.set(d.id, now);
239 }
240 if (Array.isArray(saved.queue)) {
241 for (const q of saved.queue.slice(0, 1000)) {
242 const p = person(q);
243 if (p && !this.queue.some((x) => x.id === p.id) && p.id !== d?.id) {
244 this.queue.push(p);
245 this.gone.set(p.id, now);
246 }
247 }
248 }
249 this.schedule();
250 } catch {
251 /* no file yet, or unreadable: start empty */
252 }
253 }
254
255 private save(): void {
256 if (!this.file) return;
257 const d = this.driver;
258 const state = { driver: d && { id: d.id, name: d.name, owner: d.owner, startedAt: d.startedAt, endsAt: d.endsAt, bonusMs: d.bonusMs }, queue: this.queue.map((p) => ({ id: p.id, name: p.name, owner: p.owner })) };
259 try {
260 mkdirSync(dirname(this.file), { recursive: true });
261 writeFileSync(`${this.file}.tmp`, JSON.stringify(state));
262 renameSync(`${this.file}.tmp`, this.file);
263 } catch {
264 /* a full disk must not stop the arm; the next change tries again */
265 }
266 }
267
220268 private remove(id: string): boolean {
221269 const i = this.queue.findIndex((p) => p.id === id);
222270 if (i < 0) return false;
Software/so101/src/ui/lobby-panel.js +4 −4
@@ -30,7 +30,7 @@ export function createRoom(page) {
3030 // the type check has no DOM (as ./machine-panel.js)
3131 const win = /** @type {any} */ (globalThis), doc = win.document, nav = win.navigator, location = win.location;
3232 /** @type {{ ws: WebSocket | null, hello: any, state: any, mutedList: any[], bannedList: any[], crew?: any, [k: string]: any }} */
33 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null, statusSeen: false };
33 const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 250, mutedList: [], bannedList: [], admin: null, statusSeen: false };
3434 function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); }
3535 function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); }
3636 const say = (/** @type {Record<string, unknown>} */ m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); };
@@ -240,7 +240,7 @@ export function createRoom(page) {
240240 function lobbyConnect() {
241241 const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`);
242242 lobby.ws = ws;
243 ws.onopen = () => { lobby.retry = 500; };
243 ws.onopen = () => { lobby.retry = 250; };
244244 ws.onmessage = (e) => {
245245 const m = JSON.parse(e.data);
246246 if (m.type === "ping") return say({ type: "pong" });
@@ -263,9 +263,9 @@ export function createRoom(page) {
263263 if (lobby.ws !== ws) return;
264264 lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back
265265 page.applyLock();
266 $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…";
266 $("driverLine").className = "none"; $("driverLine").textContent = "reconnecting…";
267267 setTimeout(lobbyConnect, lobby.retry);
268 lobby.retry = Math.min(lobby.retry * 2, 8000);
268 lobby.retry = Math.min(lobby.retry * 2, 2000);
269269 };
270270 }
271271 $("say").onsubmit = (/** @type {any} */ e) => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs