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
smith/arm:smith/202-top-a-restart-never-costs-you-control-re → main 1 commit fork
7 files
changed +112
−5
Software/so101/bench/fake-serve.ts +1
| @@ -50,6 +50,7 @@ const local = !identityKey && !process.env.FORGE_APP_ENV; | ||
| 50 | 50 | const lobby = new Lobby({ |
| 51 | 51 | identityKey, |
| 52 | 52 | local, |
| 53 | turnsFile: join(dir, "turns.json"), | |
| 53 | 54 | chatFile: join(dir, "chat.json"), |
| 54 | 55 | adminFile: join(dir, "admin.json"), |
| 55 | 56 | 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 | ||
| 123 | 123 | sim.stop(true); |
| 124 | 124 | } |
| 125 | 125 | }); |
| 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 { | ||
| 56 | 56 | adminFile?: string; |
| 57 | 57 | /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */ |
| 58 | 58 | turns?: Turns; |
| 59 | /** Where the driver and the line survive a restart; none keeps them in memory. */ | |
| 60 | turnsFile?: string; | |
| 59 | 61 | chat?: Chat; |
| 60 | 62 | admin?: Admin; |
| 61 | 63 | /** Checks each posted line in the background; none leaves the chat unchecked. */ |
| @@ -102,7 +104,7 @@ export class Lobby { | ||
| 102 | 104 | this.local = Boolean(options.local); |
| 103 | 105 | this.admin = options.admin ?? new Admin({ file: options.adminFile }); |
| 104 | 106 | 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 }); | |
| 106 | 108 | this.turns.setPaused(a.paused); |
| 107 | 109 | this.chat = options.chat ?? new Chat({ file: options.chatFile }); |
| 108 | 110 | this.accounts = options.accounts ?? new Accounts(); |
Software/so101/src/relay.ts +4
| @@ -543,6 +543,10 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 543 | 543 | const path = url.pathname + url.search; |
| 544 | 544 | const reading = req.method === "GET" || req.method === "HEAD"; |
| 545 | 545 | 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 | } | |
| 546 | 550 | if (req.method === "GET" && url.pathname === "/cameras") return json(res, 200, cameras.list().map(({ id, name, online }) => ({ id, name, online }))); |
| 547 | 551 | if (req.method === "GET" && url.pathname === "/admin/camera-list") { |
| 548 | 552 | 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", () => { | ||
| 239 | 239 | expect(turns.driver!.endsAt - turns.driver!.startedAt).toBe(360_000); |
| 240 | 240 | }); |
| 241 | 241 | }); |
| 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 @@ | ||
| 9 | 9 | * Plain state and deadlines; one timer, set to the nearest deadline, runs `check()`. |
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 13 | import { dirname } from "node:path"; | |
| 12 | 14 | import type { Person } from "./identity.ts"; |
| 13 | 15 | |
| 14 | 16 | export interface Turn extends Person { |
| @@ -43,6 +45,8 @@ export interface TurnsOptions { | ||
| 43 | 45 | maxQueue?: number; |
| 44 | 46 | paused?: boolean; |
| 45 | 47 | 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; | |
| 46 | 50 | } |
| 47 | 51 | |
| 48 | 52 | export class Turns { |
| @@ -61,6 +65,7 @@ export class Turns { | ||
| 61 | 65 | private readonly gone = new Map<string, number>(); |
| 62 | 66 | private readonly listeners = new Set<(event: TurnEvent) => void>(); |
| 63 | 67 | private timer: ReturnType<typeof setTimeout> | undefined; |
| 68 | private readonly file: string | undefined; | |
| 64 | 69 | |
| 65 | 70 | constructor(options: TurnsOptions = {}) { |
| 66 | 71 | this.turnMs = options.turnMs ?? 180_000; |
| @@ -70,6 +75,9 @@ export class Turns { | ||
| 70 | 75 | this.maxQueue = options.maxQueue ?? Infinity; |
| 71 | 76 | this.paused = options.paused ?? false; |
| 72 | 77 | this.now = options.now ?? Date.now; |
| 78 | this.file = options.file; | |
| 79 | if (this.file) this.load(this.file); | |
| 80 | this.on(() => this.save()); | |
| 73 | 81 | } |
| 74 | 82 | |
| 75 | 83 | on(listener: (event: TurnEvent) => void): () => void { |
| @@ -217,6 +225,46 @@ export class Turns { | ||
| 217 | 225 | this.listeners.clear(); |
| 218 | 226 | } |
| 219 | 227 | |
| 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 | ||
| 220 | 268 | private remove(id: string): boolean { |
| 221 | 269 | const i = this.queue.findIndex((p) => p.id === id); |
| 222 | 270 | if (i < 0) return false; |
Software/so101/src/ui/lobby-panel.js +4 −4
| @@ -30,7 +30,7 @@ export function createRoom(page) { | ||
| 30 | 30 | // the type check has no DOM (as ./machine-panel.js) |
| 31 | 31 | const win = /** @type {any} */ (globalThis), doc = win.document, nav = win.navigator, location = win.location; |
| 32 | 32 | /** @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 }; | |
| 34 | 34 | function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); } |
| 35 | 35 | function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); } |
| 36 | 36 | 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) { | ||
| 240 | 240 | function lobbyConnect() { |
| 241 | 241 | const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/live`); |
| 242 | 242 | lobby.ws = ws; |
| 243 | ws.onopen = () => { lobby.retry = 500; }; | |
| 243 | ws.onopen = () => { lobby.retry = 250; }; | |
| 244 | 244 | ws.onmessage = (e) => { |
| 245 | 245 | const m = JSON.parse(e.data); |
| 246 | 246 | if (m.type === "ping") return say({ type: "pong" }); |
| @@ -263,9 +263,9 @@ export function createRoom(page) { | ||
| 263 | 263 | if (lobby.ws !== ws) return; |
| 264 | 264 | lobby.ws = null; lobby.hello = null; lobby.statusSeen = false; // polling takes over until it is back |
| 265 | 265 | page.applyLock(); |
| 266 | $("driverLine").className = "none"; $("driverLine").textContent = "Reconnecting…"; | |
| 266 | $("driverLine").className = "none"; $("driverLine").textContent = "reconnecting…"; | |
| 267 | 267 | setTimeout(lobbyConnect, lobby.retry); |
| 268 | lobby.retry = Math.min(lobby.retry * 2, 8000); | |
| 268 | lobby.retry = Math.min(lobby.retry * 2, 2000); | |
| 269 | 269 | }; |
| 270 | 270 | } |
| 271 | 271 | $("say").onsubmit = (/** @type {any} */ e) => { |
new above
offline