diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index e31493164e..5ee94f6703 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -79,6 +79,11 @@ import { Notifier, WATCHED as NOTIFIED } from "../../src/notify.ts"; import { contact, Push } from "../../src/push.ts"; import type { Store } from "../../src/store.ts"; +/** A rank set twice ends at the last one: an older held rank never + * runs when a newer rank for the same issue is done. Anything else + * held runs first, in the order it was done. */ +const LAST_WINS = new Set(["issue.rank"]); + /** The edge's own storage: small values by key. */ export interface KV { get(key: string): Promise; @@ -299,6 +304,12 @@ export class Edge { private cfg: EdgeConfig | null | undefined; private mirrors = new Map(); private held: Held[] | null = null; + /** Held actions already handed to a machine in a report answer and not + * yet acknowledged: the machine may be doing them, so the edge never + * does them itself. Anything held and not in here was never handed + * out, and the edge may do it itself first. Kept in storage under + * "handed", so an object that starts again knows. */ + private handed: Set | null = null; private ownActs: Act[] | null = null; private hostActs: Act[] = []; private lastDocAt = 0; @@ -411,6 +422,7 @@ export class Edge { } const [gone] = held.splice(at, 1); await this.saveHeld(); + await this.unhand([gone.id]); // Under its name it is over. A device that never heard it was // kept offers it again: it is told it was taken back, and it // is neither kept again nor handed to a machine. @@ -677,6 +689,57 @@ export class Edge { await this.showEdge(); } + /** Names of held actions already handed to a machine. */ + private async handedList(): Promise> { + if (this.handed === null) { + const stored = ((await this.kv.get("handed")) as string[] | undefined) ?? []; + this.handed = new Set(stored.filter((id) => typeof id === "string")); + } + return this.handed; + } + + private async saveHanded(): Promise { + await this.kv.put("handed", [...(this.handed ?? [])]); + } + + /** Forget handed names that are no longer held (acknowledged, dropped, + * expired, or done here). */ + private async pruneHanded(): Promise { + const held = await this.heldList(); + const handed = await this.handedList(); + let changed = false; + for (const id of [...handed]) { + if (!held.some((h) => h.id === id)) { + handed.delete(id); + changed = true; + } + } + if (changed) await this.saveHanded(); + } + + private async markHanded(ids: string[]): Promise { + if (ids.length === 0) return; + const handed = await this.handedList(); + let changed = false; + for (const id of ids) { + if (!handed.has(id)) { + handed.add(id); + changed = true; + } + } + if (changed) await this.saveHanded(); + } + + private async unhand(ids: string[]): Promise { + if (ids.length === 0) return; + const handed = await this.handedList(); + let changed = false; + for (const id of ids) { + if (handed.delete(id)) changed = true; + } + if (changed) await this.saveHanded(); + } + /** The platform's own part, each machine that reports, and what is * held for one: what the Machines screen is drawn from. Answered * here, so it is there with every machine away. */ @@ -1256,6 +1319,7 @@ export class Edge { }); } if (settled) await this.saveHeld(); + await this.pruneHanded(); // What a machine has just done late changed things this side reads // itself: they are read again, so the next document shows it. if (did.length > 0) { @@ -1349,6 +1413,7 @@ export class Edge { // What this side reads itself, and so need not be sent. owns: this.owned(settings), }; + await this.markHanded(held.map((h) => h.id)); return json(answer); } @@ -1657,6 +1722,79 @@ export class Edge { this.primary(cfg) && !this.refusedKinds().includes(kind); if (here) { + // An older action held for a machine about the same thing + // comes first. One already handed to a machine may be being + // done there: the newer waits behind it instead. One never + // handed out never reached a machine, so the edge does it + // itself first, under its name; a kind where the last one + // wins is dropped as replaced by the newer instead. + const about = subjectOf(kind, args as Record); + if (about !== null) { + const older = (await this.heldList()).filter( + (h) => h.id !== id && subjectOf(h.kind, h.args) === about, + ); + if (older.length > 0) { + const handed = await this.handedList(); + if (older.some((h) => handed.has(h.id))) { + return this.keep({ id: id ?? crypto.randomUUID(), kind, args, who: by }); + } + for (const old of older) { + if (LAST_WINS.has(old.kind)) { + const list = await this.heldList(); + const at = list.findIndex((h) => h.id === old.id); + if (at >= 0) list.splice(at, 1); + await this.saveHeld(); + await this.unhand([old.id]); + const atIso = new Date(this.now()).toISOString(); + await this.audit({ + at: atIso, + who: old.who, + via: "edge", + action: old.kind, + phase: "done", + ok: false, + error: `replaced by a newer ${kind}: the last one wins`, + }); + await this.logAct({ + id: old.id, + kind: old.kind, + at: old.at, + by: old.who, + status: "failed", + note: `Replaced by a newer ${kind}: the last one wins.`, + }); + await this.kv.put(`a:${old.id}`, { + at: this.now(), + kind: old.kind, + state: "done", + status: 409, + body: { error: "This was replaced by a newer action about the same thing." }, + } satisfies Acted); + await this.actedIndex(old.id); + } else { + try { + await this.once(old.id, old.kind, () => + this.directAct(old.kind, old.args, old.who, "edge", old.id), + ); + } catch (error) { + // Refused here too: the newer waits behind the older, + // as behind one handed to a machine. + if (error instanceof HandOver) { + return this.keep({ id: id ?? crypto.randomUUID(), kind, args, who: by }); + } + throw error; + } + const list = await this.heldList(); + const at = list.findIndex((h) => h.id === old.id); + if (at >= 0) { + list.splice(at, 1); + await this.saveHeld(); + } + await this.unhand([old.id]); + } + } + } + } try { return await this.once(id, kind, () => this.directAct(kind, args as Record, by, who.via, id), @@ -1677,7 +1815,10 @@ export class Edge { // the older one, which would undo it when its turn came. if (HOLDABLE.has(kind)) { const about = subjectOf(kind, args as Record); - if (about !== null && (await this.heldList()).some((h) => subjectOf(h.kind, h.args) === about)) { + // A retry under the same name is the same action, not a later + // one: it goes back to the host, which sorts out whether it + // already did it, instead of waiting behind itself. + if (about !== null && (await this.heldList()).some((h) => h.id !== id && subjectOf(h.kind, h.args) === about)) { return this.keep({ id: id ?? crypto.randomUUID(), kind, args, who: by }); } } @@ -1874,10 +2015,23 @@ export class Edge { } /** After the host did a relayed action: the sections it read again and - * its record of what was done, so the next document already shows it. */ + * its record of what was done, so the next document already shows it. + * The relayed id is settled: a hold left behind by a lost answer for + * the same name is dropped, since the host has now answered it. */ private async relayed(req: Request): Promise { - const body = (await req.json().catch(() => null)) as { sections?: unknown; acts?: unknown } | null; + const body = (await req.json().catch(() => null)) as + | { sections?: unknown; acts?: unknown; id?: unknown } + | null; await this.ready(); + if (typeof body?.id === "string") { + const held = await this.heldList(); + const at = held.findIndex((h) => h.id === body.id); + if (at >= 0) { + held.splice(at, 1); + await this.saveHeld(); + await this.unhand([body.id]); + } + } // What the machine read again after doing this, and this side reads // itself, is not taken from it. That it was sent says its source // has just changed, so it is read again here: first, so that one diff --git a/pm-stack/console/edge/src/entry.ts b/pm-stack/console/edge/src/entry.ts index d79e526c6a..f1601195f4 100644 --- a/pm-stack/console/edge/src/entry.ts +++ b/pm-stack/console/edge/src/entry.ts @@ -168,7 +168,9 @@ export async function route(request: Request, io: Io): Promise { const body = (await answer.json().catch(() => null)) as Record | null; if (body === null) return offline("the host's answer could not be read"); const { sections, acts, ...rest } = body; - if (sections !== undefined || acts !== undefined) await tell("/internal/relayed", { sections, acts }); + // The relayed name is settled even when the host read nothing new: + // a hold left behind by a lost answer for the same name is dropped. + await tell("/internal/relayed", { sections, acts, id: detail.id }); const headers = new Headers(answer.headers); headers.delete("content-length"); headers.delete("content-encoding"); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index b987b2f746..a818d57150 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -4596,6 +4596,146 @@ describe("the edge does the core itself", () => { result: null, }); }); + + test("an older held action the laptop never took is done here first, under its own name", async () => { + const w = await primary(); + const comment = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/comments$/.test(url); + // This side is turned away for comments, so the older one waits. + w.ghRefuses.push(comment); + w.net.hostUp = false; + w.net.edgeUp = false; + const olderId = "0f000000-0000-4000-8000-000000000001"; + expect(await (await w.act("issue.comment", { issue: 7, text: "older" }, olderId)).json()).toEqual({ + ok: true, + held: true, + result: null, + }); + expect((w.stored.get("held") as { id: string }[]).map((h) => h.id)).toEqual([olderId]); + // The token is put right and this side takes comments back. + w.ghRefuses.length = 0; + w.net.hostUp = true; + w.net.edgeUp = true; + expect((await w.act("edge.retry", {})).status).toBe(200); + // A newer comment about the same issue: the older one the laptop + // never took is done here first, under its own name, then the newer. + const newerId = "0f000000-0000-4000-8000-000000000002"; + const second = await w.act("issue.comment", { issue: 7, text: "newer" }, newerId); + const done = (await second.json()) as { ok?: boolean; held?: boolean }; + expect(done).toMatchObject({ ok: true }); + expect(done.held).toBeUndefined(); + const posted = w.githubCalls + .filter((c) => comment(c.method, c.url)) + .map((c) => (JSON.parse(c.body ?? "{}") as { body?: string }).body); + // The refused first try is recorded too: the two that count come last, in order. + expect(posted.slice(-2)).toEqual(["older", "newer"]); + expect(w.stored.get("held") ?? []).toEqual([]); + expect(w.stored.get(`a:${olderId}`)).toMatchObject({ kind: "issue.comment", state: "done" }); + expect(w.stored.get(`a:${newerId}`)).toMatchObject({ kind: "issue.comment", state: "done" }); + expect(w.stored.get("handed") ?? []).toEqual([]); + }); + + test("a held rank is replaced by a newer rank about the same issue: the last one wins", async () => { + const w = await primary(); + const labels = (method: string, url: string) => method === "POST" && /\/issues\/201\/labels$/.test(url); + // This side is turned away for labelling, so the older rank waits. + w.ghRefuses.push(labels); + w.net.hostUp = false; + w.net.edgeUp = false; + const olderId = "0f000000-0000-4000-8000-000000000011"; + expect(await (await w.act("issue.rank", { issue: 201, rank: "next" }, olderId)).json()).toEqual({ + ok: true, + held: true, + result: null, + }); + expect((w.stored.get("held") as { id: string }[]).map((h) => h.id)).toEqual([olderId]); + // The token is put right and this side takes ranking back. + w.ghRefuses.length = 0; + w.net.hostUp = true; + w.net.edgeUp = true; + expect((await w.act("edge.retry", {})).status).toBe(200); + // A newer rank about the same issue: the older one is dropped as + // replaced, and only the newer is done. + const newerId = "0f000000-0000-4000-8000-000000000012"; + const second = await w.act("issue.rank", { issue: 201, rank: "now" }, newerId); + expect(await second.json()).toMatchObject({ ok: true }); + expect(w.stored.get("held") ?? []).toEqual([]); + expect(w.stored.get(`a:${olderId}`)).toMatchObject({ kind: "issue.rank", state: "done", status: 409 }); + expect(w.stored.get(`a:${newerId}`)).toMatchObject({ kind: "issue.rank", state: "done" }); + expect(w.ghLabels[201]).toContain("now"); + expect(w.ghLabels[201]).not.toContain("next"); + }); + + test("an older held action handed to the laptop blocks a newer one about the same thing", async () => { + const w = await primary(); + const comment = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/comments$/.test(url); + // This side is turned away for comments, so the older one waits. + w.ghRefuses.push(comment); + w.net.hostUp = false; + w.net.edgeUp = false; + const olderId = "0f000000-0000-4000-8000-000000000021"; + expect(await (await w.act("issue.comment", { issue: 7, text: "older" }, olderId)).json()).toEqual({ + ok: true, + held: true, + result: null, + }); + // The token is put right and this side takes comments back. + w.ghRefuses.length = 0; + w.net.hostUp = true; + w.net.edgeUp = true; + expect((await w.act("edge.retry", {})).status).toBe(200); + // The laptop reports and is handed the older one, which it does. + await w.hostReads(); + const answer = await w.link.now.once(); + expect(answer?.commands.map((c) => c.id)).toEqual([olderId]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + expect(w.stored.get("handed")).toEqual([olderId]); + // A newer comment about the same issue waits behind the handed one: + // it is kept, not done here. + const newerId = "0f000000-0000-4000-8000-000000000022"; + const second = await w.act("issue.comment", { issue: 7, text: "newer" }, newerId); + expect(await second.json()).toEqual({ ok: true, held: true, result: null }); + expect((w.stored.get("held") as { id: string }[]).map((h) => h.id)).toEqual([olderId, newerId]); + // Nothing was done here: the laptop did the older, the newer waits. + // The only call this side made was the older one's refused try. + expect( + w.githubCalls.filter((c) => comment(c.method, c.url)).map((c) => c.body), + ).toEqual(['{"body":"older"}']); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + }); + + test("a newer action about something else is not held behind an older one", async () => { + const w = await primary(); + const comment = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/comments$/.test(url); + // This side is turned away for comments, so the older one waits. + w.ghRefuses.push(comment); + w.net.hostUp = false; + w.net.edgeUp = false; + const olderId = "0f000000-0000-4000-8000-000000000031"; + expect(await (await w.act("issue.comment", { issue: 7, text: "older" }, olderId)).json()).toEqual({ + ok: true, + held: true, + result: null, + }); + // The token is put right and this side takes comments back. + w.ghRefuses.length = 0; + w.net.hostUp = true; + w.net.edgeUp = true; + expect((await w.act("edge.retry", {})).status).toBe(200); + // A newer comment about another issue goes straight through. + const newerId = "0f000000-0000-4000-8000-000000000032"; + const second = await w.act("issue.comment", { issue: 8, text: "unrelated" }, newerId); + const done = (await second.json()) as { ok?: boolean; held?: boolean }; + expect(done).toMatchObject({ ok: true }); + expect(done.held).toBeUndefined(); + expect((w.stored.get("held") as { kind: string; args: Record }[]).map((h) => h.args.issue)).toEqual([ + 7, + ]); + const posted = w.githubCalls + .filter((c) => comment(c.method, c.url)) + .map((c) => (JSON.parse(c.body ?? "{}") as { body?: string }).body); + expect(posted.slice(-1)).toEqual(["unrelated"]); + expect(w.stored.get(`a:${newerId}`)).toMatchObject({ kind: "issue.comment", state: "done" }); + }); }); describe("telling the owner, with no machine", () => {