diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 6b06e1a4a6..108810bd14 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -973,3 +973,192 @@ One small thing seen with it: the check's time moved from 03:42:46 to 03:42:49 between two reads of health. Two health reads arrived while the hourly check was due, and each ran it. At most a few reads of GitHub once an hour, and nothing shown wrongly; noted and left. + +## 2026-11-24T04:30Z Update: what is held, done here when the edge can (#13831) + +**What it was.** Something the owner did while the edge was turned +away and no machine could be reached was held for a machine, and only +a machine ever did it. Since the edge keeps to GitHub's own time for +asking again, that could be most of an hour of waiting for a laptop +that was not coming, for a comment or a rank the edge could have made +itself a few minutes later. + +**What it does now.** When it can act again (the time GitHub gave has +come, the hour it leaves a kind alone is up, or the owner says to try +again) the edge wakes itself and does what it holds of the kinds it +runs: the oldest first, each thing's actions in the order they were +done, and nothing about a thing behind one it could not do. The wake +is the object's own alarm, asked for whenever something is kept; there +is no other place the held list is worked through. + +**Never twice.** An action is one side's or the other's, never both. +(As first written here this was wrong in one case, found before it was +merged: see the correction below.) + +- _A machine's_ once a report's answer has handed it out: the machine + may be doing it. The edge never takes it, nor anything else about + the same thing while it waits. +- _The edge's_ once it is out of the held list, which happens, and is + written down (`taken`), before anything is begun. A machine that + reports meanwhile is not handed it, nor what waits behind it about + the same thing (that would be done out of turn). +- _Turned away again_ before anything was written, it goes back where + it was, a machine's by name as before. +- _Put away part-way_, it is settled by the next object from its + record: ended; never begun, and it waits again; or begun and not + known to have ended, which neither side does again, and the owner is + told to look. + +**Four faults in what was there, found doing this.** The edge already +did an older held action itself in one case, when a newer one about +the same thing arrived (#13398, a fleet lane's #13652). + +- It began the older one while it was still in the held list. A + machine reporting before it ended was handed it too, and would have + done it a second time. +- Turned away while trying it, the record that made the name a + machine's was cleared and not put back: sent again under that name + later, it could have been done here and by a machine. +- A held rank was dropped as "replaced" by any newer action about the + same issue, a comment included. Only a newer rank replaces a rank. +- An older held action that only a machine can do (marking a need + done) was tried here when a comment on the same need arrived, failed + for want of the means, and was lost. The newer one now waits behind + it. + +**Also.** The day's limit on what is held was only kept when a machine +reported; it is kept on the edge's own wake now. A pass that could do +nothing is not tried again for a minute, so that a fault cannot have +the object waking every second. + +**Checked.** Fifteen tests at the edge, each starting from the owner's +action being held: done here once with no machine; at GitHub's time +and not before; in order; a handed one left alone, with what waits +behind it; a machine reporting half-way through; a newer one arriving +half-way through; turned away again; put away part-way (each of the +three records); the last rank winning, and a comment not replacing +one; what only a machine can do left for it; a side that no longer +does the core doing none of it; the day's limit with no machine; a +wake asked for with nothing else to wake it; and the pause after a +pass that did nothing. 41 single faults planted in the new code: 40 +fail a test. The one that does not takes a failure of storage in the +middle of an action for being turned away; the store the tests have +cannot fail in the middle of one and work again for the next write, +so the two cannot be told apart there. In the real runtime: with the +host out of reach and GitHub's stand-in turning the Worker away, a +comment is held and nothing written; when it answers and the owner +says to try again, the Worker's own alarm fires and the comment is +made once. + +**Not done.** An action handed to a machine that then never reports +stays the machine's until the day is up: the edge cannot know whether +it was done. Every kind is kept to GitHub's time, though moving a task +asks only the queue store. + +## 2026-11-24T05:00Z Correction: an action sent to the host may have been done there (#13831) + +**The fault, mine, found reading the change before merging it.** The +rule above took "never handed out in a report's answer" to mean "never +reached a machine". It does not. Nearly everything held gets there by +being sent to the host and getting no answer, and no answer has two +meanings: the host never had the request, or the host did it and the +answer was lost on the way back. The second kind was done again by the +edge once it could. A test written first showed it: a comment the +laptop made, its answer lost, the laptop then away; an hour later the +edge made the same comment a second time. The code this was built on +(#13652) had the same hole in its one case, and waking by itself made +it reachable with nobody doing anything. + +**What can be known.** What comes back from asking the host is one of +three things: the host's own answer; nothing (the time ran out, the +connection broke); or an answer from what stands in front of it. Only +Cloudflare's 530 says the host never had the request. Cloudflare gives +it (with error 1033 in the body) when the tunnel has no connection to +send anything down, which is what a laptop asleep or off looks like. +Its documentation says so of both: the 530 page, and the 1033 page +("cannot find a healthy `cloudflared` instance to receive the +traffic"). A 502 from the tunnel's own daemon does not say as much (it +is also what a connection lost part-way looks like), and is treated as +no word. + +**The rule now.** A held action is the edge's to do only when it is +known to have reached no machine: it never set off toward one, or it +set off once and that one asking was answered 530. It then carries the +word `unsent`. Without the word it is a machine's by name, as +everything held was before this change: handed to the host when it +reports, which says what became of it. The word is the positive one on +purpose. What is held in service today was kept by a version that did +not write down how the asking ended, and has no word either way; read +as "may have", it is left to the laptop. + +**The same name, asked twice.** A device gives up on a send after a +minute and offers the name again, while the edge gives the host a +little longer. So two askings under one name can be out at once, and +word that the second never arrived says nothing of the first. Every +setting-off is counted under the name, and a 530 is believed only for +a name that set off once. Three more cases follow from the same +thought: + +- One waiting here that reached nobody is not sent toward the host + when its device offers it again. It would be on its way there while + the edge may be taking it for its own. +- A name the edge has taken to do itself, offered again in that + moment, is not sent to the host as well. The device is answered with + what came of doing it here, or told that it is not over. +- A name whose first asking is still out, offered again while + something else about the same thing waits here, is kept as the + host's. + +Also: a newer action about a thing waits behind an older one the host +may have, where before it waited only behind one handed out (a newer +rank would otherwise have replaced an older rank the host may be about +to set, and the older would have been the last word). And a host's +answer that cannot be read settles the name as any answer of the +host's does; it used to leave a hold under it. + +**What the owner sees.** Each held action is one of three, and is said +as that when it is kept, in "What you did", on the Machines screen and +in the note the device keeps: either side's, whichever can first; a +machine's only; or one a machine was given or may have got, which +nobody else does meanwhile. Dropped after a day, the last kind is said +to be worth checking, not "not sent". The health answer counts the +three (`held`), so that what the Worker made of a laptop being away +can be seen from outside. + +**Checked.** Thirteen more tests at the edge (28 now for this change), +the first of them written before the fix and seen to fail: the answer +lost; out of reach each way, side by side; offered again while +waiting; offered again with the first asking still out; the same with +something else waiting; a newer one behind one the host may have, a +rank among them; offered again at the moment the edge has taken it, +done and turned away; one kept by the version before; a name from +before the counting; an unreadable answer; and a take that could not +be written down leaving nothing marked as being done. In the real +runtime the Worker's own reading of what comes back is exercised both +ways: the host's stand-in answering 530, the comment is held as either +side's and the Worker makes it once; answering 502, it is held for the +host and the Worker does not make it, able as it is. + +71 single faults planted over the whole of the change: 68 fail a test. +The three that do not change nothing that can be seen. One takes a +failure of storage in the middle of an action for being turned away +(the tests' store cannot fail in the middle of one and work again for +the next write). One drops the check the taking itself makes that a +machine does not have the action: everything that takes asks the same +thing first, and between the asking and the taking there is nothing +but the object's own storage to wait for, during which Cloudflare lets +nothing else in. One drops the limit on how many times a newer action +looks again at what is ahead of it, which cannot be reached. The +Worker's reading of the host's answer is outside those tests, so it +was turned each way in the real runtime: taking everything for "never +reached", the Worker makes the comment it should have left to the +host; believing nothing, it leaves the one it should have made. Each +fails the checks it should. + +**Not done, and filed.** The 530 has not been seen in service: that +needs the owner's action to be turned away by GitHub while the laptop +is away. What it was taken for is then in the health answer. An older +action still out at the host does not hold back a newer one about the +same thing that the edge can do at once (a rank sent to the host, +then another the edge makes directly within the minute): the edge does +not keep track of askings that are out by what they are about. diff --git a/planning/roadmaps/pm-stack.md b/planning/roadmaps/pm-stack.md index 4d001fa85b..0de34da954 100644 --- a/planning/roadmaps/pm-stack.md +++ b/planning/roadmaps/pm-stack.md @@ -20,7 +20,7 @@ The roadmap of record is this file and its siblings in `planning/roadmaps/`. The | The edge's own GitHub allowance | in-progress | The core must not stop being readable when agents have used the account's hourly allowance. | #13489 | | Queue tasks filed, cancelled and unblocked from Cloudflare | shaped | A prompt sent with the laptop away is picked up, not only filed. | #13490 | | Questions, what needs you and sessions with no machine | shaped | The last sections that are only as fresh as a machine's last report. | #13491 | -| What waits for a machine, done from Cloudflare once it can be | shaped | With GitHub answering again and no machine there, what the owner did is done by the edge itself and not kept waiting; never twice. | #13831 | +| What waits for a machine, done from Cloudflare once it can be | shipped | With GitHub answering again and no machine there, what the owner did is done by the edge itself and not kept waiting; never twice. | #13831 | | The laptop's console follows main | proposed | The console on the laptop runs the build main is at, and it is seen from outside when it does not. | #13833 | ## Next diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 5df7a237fe..eea9c6149a 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -457,8 +457,56 @@ open nothing. same issue, task, reference or set of questions) that a machine has not taken yet, even when the machine can be reached again: sent straight on it would be done first, and the older one would undo it. - What is about something else goes straight on. Not covered (#13398): - an older action held for a machine and a newer one about the same - thing that the edge does itself. + What is about something else goes straight on. Where the newer one is + the edge's own to do, the older held one still comes first: if a + machine has been handed it, or only a machine can do it, the newer + waits behind it; otherwise the edge does the older itself first (or, + for a rank followed by a newer rank of the same issue, drops it as + replaced: the last one wins, and only over its own kind). +- **What is held and the edge can do, it does itself when it can.** + What the owner did while the edge was turned away and no machine + could be reached is held, but it does not have to wait for a machine. + When the time GitHub gave has come, or the hour the edge leaves a + kind alone is up, or the owner says to try again, the edge wakes + itself and does what it holds of the kinds it runs: the oldest first, + and each thing's actions in the order they were done. + Nothing is done twice, by one rule: an action is one side's or the + other's. It is a machine's once it may have reached one, and the edge + never takes it then, nor anything else about the same thing. It is + the edge's once it has taken it out of the held list, which it does, + and writes down (`taken`), before it begins. A machine reporting + meanwhile is not handed it, nor what waits behind it about the same + thing. Turned away again before anything was written, the action goes + back where it was. An object put away with an action taken is settled + by the next one from its record: ended; never begun, so it waits + again; or begun and not known to have ended, which neither side does + again and the owner is told to look at. What has waited a day is + dropped whether or not a machine ever reports. +- **Only what certainly reached no machine is the edge's to do.** An + action may have reached a machine in two ways: a report's answer + handed it out, or it was sent to the host and nothing came back to + say it never arrived. The second is the common one. Asking the host + ends in an answer of the host's, in no answer at all (the time ran + out, the connection broke), or in an answer from what stands in + front of the host. Only one of those says the host never had the + request: Cloudflare's own 530 (its error 1033 for a tunnel), given + when the tunnel has no connection to send anything down. That is + what a laptop that is asleep or off looks like. Anything else (a + gateway that got no answer out of the host, a wait that ran out) + leaves it open whether the host did the thing, so the action is kept + as the host's by name: the host, which writes a name down before it + starts, is handed it when it reports and says what became of it. + Each held action carries the word `unsent` only when it is known to + have reached nobody: it never set off toward a machine, or it set + off once and that one asking was answered 530. Every setting-off is + counted under the action's name, because a device that gave up + waiting offers the same name again while the first asking may still + be out: word that the second never arrived says nothing of the first. + A held action without the word (one kept by a version from before + it, too) is a machine's. One waiting here that reached nobody is not + sent toward the host when its device offers it again; it goes on + waiting for whichever side is first. The app says which of the three + each one is ("either", "machine", "asked"), the Machines screen shows + it, and the health answer counts them. - The storage is one Durable Object. A section larger than one stored value is kept in pieces. diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 6536d6ff7b..c3d8baa8ae 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -49,6 +49,7 @@ import { edgeConfig, HELD_FOR_MS, type Held, + type HeldFor, HOLDABLE, keyId, type MachineReport, @@ -146,6 +147,19 @@ interface ApkMeta { } const ACT_LIMIT = 256 * 1024; const HELD_MAX = 100; +/** After a pass over what is held that could do none of it, how long + * before another is tried. */ +const DRAIN_AGAIN_MS = 60_000; +/** Said of something begun by an object that was put away before it + * ended. */ +const RESTARTED = "Cloudflare restarted while doing this; check whether it happened before trying again."; +/** What the owner is told of something held, by who it waits for. */ +const HELD_SAID: Record = { + either: + "Held: it could not be done just now. Cloudflare does it as soon as it can again, or the laptop if it is back first.", + machine: "Held: the laptop cannot be reached. It will be sent when it is back.", + asked: "Held: the laptop did not answer. It may have got this, and says what became of it when it is back.", +}; const ACTS_KEPT = 30; const AUDIT_KEPT = 300; /** "Someone is looking" lasts this long after the last read of a document. */ @@ -206,6 +220,11 @@ interface Acted { state: "running" | "done" | "given"; status?: number; body?: Record; + /** For "given": how many times it has set off toward a machine. Word + * that one asking never arrived says the action reached no machine + * only when that asking was the only one. (A record from before this + * was counted has none, and is taken to have set off already.) */ + relays?: number; } const ICONS = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; @@ -328,6 +347,18 @@ export class Edge { private unread = new Map(); /** Names of actions this object is doing right now. */ private doing = new Set(); + /** Held actions this side has taken to do itself: out of the held + * list, so that no machine is handed them, and not yet settled. Kept + * in storage under "taken", so that an object that starts again + * knows what became of each (see recoverTaken). Null until read. */ + private taken: Held[] | null = null; + /** For each thing a taken action is about, the doing of it: a newer + * action about the same thing waits for it to end. */ + private busy = new Map>(); + /** A pass over what is held is under way in this object. */ + private draining = false; + /** No pass before this time: the last one could do nothing. */ + private drainNotBefore = 0; /** Both of those have been read back from storage. They are kept * there because this object is put away when idle: one that forgot * them would claim each section again on every start, and a machine, @@ -472,6 +503,9 @@ export class Edge { // still turned away, the first call says so again. await this.github.free(); await this.saveAway(); + // What is held and this side can do is done on its next wake, + // which the scheduling after this action sets for at once. + this.drainNotBefore = 0; return { tried }; }, touch: [], @@ -486,7 +520,10 @@ export class Edge { const held = await this.heldList(); const at = held.findIndex((h) => h.id === a.id); if (at < 0) { - throw new OpError(404, "That is no longer waiting: a machine took it, or it was taken back already."); + throw new OpError( + 404, + "That is no longer waiting: it was done or is being done, or was taken back already.", + ); } const [gone] = held.splice(at, 1); await this.saveHeld(); @@ -878,6 +915,355 @@ export class Edge { if (changed) await this.saveHanded(); } + // ---- what is held, done here ------------------------------------------ + // + // What the owner did while this side was turned away and no machine + // could be reached is held for a machine. When this side can act + // again it does what it holds itself, so that nothing waits for a + // machine that may not come. The rule that keeps anything from being + // done twice is that an action is one side's or the other's, never + // both. It is a machine's once it may have reached one: handed out in + // a report's answer, or sent toward one with nothing to say that it + // never arrived (see withMachine). It is this side's once it has been + // taken out of the held list, which is done before anything is begun, + // and only ever with one that certainly reached no machine. + + /** A machine has this, or may have. It was handed out in a report's + * answer; or it is not known to have reached no machine (it went + * toward one and nothing said that it never arrived, or it was kept + * before that was written down). It is that machine's by name, which + * sorts out whether it did it. This side never does it itself, and + * nothing newer about the same thing goes ahead of it. */ + private withMachine(h: Held, handed: Set): boolean { + return handed.has(h.id) || h.unsent !== true; + } + + /** What a held action is about, or itself when it stands alone. */ + private heldAbout(h: Held): string { + return subjectOf(h.kind, h.args) ?? `:${h.id}`; + } + + /** Who each held action waits for, as the owner is told it. The same + * rule heldMine goes by: this side does the oldest about a thing, and + * then the next, for as long as each is a kind it does and nothing + * about the thing is, or may be, with a machine. */ + private async heldWaits(cfg: EdgeConfig | null): Promise> { + const held = await this.heldList(); + const handed = await this.handedList(); + const can = this.primary(cfg) && this.mine(cfg) !== null; + const withMachine = new Set(held.filter((h) => this.withMachine(h, handed)).map((h) => this.heldAbout(h))); + // Things with something ahead that only a machine can do. + const behind = new Set(); + const waits = new Map(); + for (const h of held) { + const about = this.heldAbout(h); + if (this.withMachine(h, handed)) waits.set(h.id, "asked"); + else if ( + can && + (DIRECT_ACTIONS as readonly string[]).includes(h.kind) && + !withMachine.has(about) && + !behind.has(about) + ) { + waits.set(h.id, "either"); + } else { + waits.set(h.id, "machine"); + behind.add(about); + } + } + return waits; + } + + /** A held action put where its time says it goes: oldest first. */ + private insertHeld(held: Held[], item: Held): void { + const at = held.findIndex((h) => h.at > item.at); + if (at < 0) held.push(item); + else held.splice(at, 0, item); + } + + /** What this side has taken, read back when an object starts, and each + * settled by what its record says. One that is in the held list again + * (or never left it) is not taken. One whose record says it ended, + * ended. One begun and not ended was being done by an object that was + * put away: whether it happened is not known, and neither side does + * it again; the owner is told to look. One never begun waits again, + * where it was. */ + private async recoverTaken(): Promise { + const stored = (await this.kv.get("taken")) as unknown; + this.taken = []; + if (!Array.isArray(stored) || stored.length === 0) return; + const held = await this.heldList(); + let back = false; + for (const item of stored as Partial[]) { + if ( + !item || + typeof item.id !== "string" || + typeof item.kind !== "string" || + typeof item.at !== "string" || + typeof item.who !== "string" || + item.args === null || + typeof item.args !== "object" + ) { + continue; + } + const was = item as Held; + if (held.some((h) => h.id === was.id)) continue; + const key = `a:${was.id}`; + const record = ((await this.kv.get(key)) as Acted | undefined) ?? null; + if (record?.state === "done") continue; + if (record?.state === "running") { + await this.kv.put(key, { + at: this.now(), + kind: was.kind, + state: "done", + status: 502, + body: { error: RESTARTED }, + } satisfies Acted); + await this.logAct({ id: was.id, kind: was.kind, at: was.at, by: was.who, status: "failed", note: RESTARTED }); + continue; + } + this.insertHeld(held, was); + back = true; + await this.kv.put(key, { at: this.now(), kind: was.kind, state: "given" } satisfies Acted); + } + if (back) await this.saveHeld(); + await this.kv.delete("taken"); + } + + /** Take a held action to do here: out of the held list before anything + * is begun, so that a machine reporting meanwhile is not handed it. + * Null if it is not this side's to take: gone from the list, or a + * machine's (see withMachine), which may be doing it. */ + private async takeHeld(id: string): Promise<{ item: Held; ended: () => void } | null> { + await this.ready(); + const held = await this.heldList(); + const handed = await this.handedList(); + // From here until the lists are changed nothing is waited for: a + // report answered meanwhile sees the list with it or without it, + // and a newer action about the same thing finds this one being done. + const at = held.findIndex((h) => h.id === id); + if (at < 0 || this.withMachine(held[at], handed)) return null; + const [item] = held.splice(at, 1); + const taken = (this.taken ??= []); + taken.push(item); + const about = this.heldAbout(item); + let over: () => void = () => {}; + const doing = new Promise((resolve) => { + over = resolve; + }); + this.busy.set(about, doing); + const ended = () => { + if (this.busy.get(about) === doing) this.busy.delete(about); + over(); + }; + try { + // Written down as taken before it leaves the held list: an object + // put away between the two finds it in both, and it was not begun. + await this.kv.put("taken", taken); + await this.saveHeld(); + } catch (error) { + // It could not be written down: it was not taken, and waits as + // it did (nothing was handed out meanwhile that is about the + // same thing, since it was this side's for as long as this took). + this.taken = (this.taken ?? []).filter((t) => t.id !== item.id); + if (!held.some((h) => h.id === item.id)) this.insertHeld(held, item); + ended(); + throw error; + } + return { item, ended }; + } + + /** Do here a held action that never reached a machine. "done": it + * ended here, well or badly, and its record and "What you did" say + * how. "back": this side was turned away before anything was written, + * and it waits again where it was, a machine's by name as before. + * "gone": it was not this side's to take. */ + private async doHeld(item: Held): Promise<"done" | "back" | "gone"> { + const took = await this.takeHeld(item.id); + if (!took) return "gone"; + const { item: taken, ended } = took; + try { + let outcome: "done" | "back" = "done"; + try { + await this.once(taken.id, taken.kind, () => + this.directAct(taken.kind, taken.args, taken.who, "edge", taken.id), + ); + } catch (error) { + // Anything else is a failure of this side's own (its storage): + // it stays taken, and the next object settles it by its record. + if (!(error instanceof HandOver)) throw error; + outcome = "back"; + } + if (outcome === "back") { + await this.kv.put(`a:${taken.id}`, { at: this.now(), kind: taken.kind, state: "given" } satisfies Acted); + await this.actedIndex(taken.id); + this.insertHeld(await this.heldList(), taken); + await this.saveHeld(); + } + this.taken = (this.taken ?? []).filter((t) => t.id !== taken.id); + await this.kv.put("taken", this.taken); + return outcome; + } finally { + ended(); + } + } + + /** A held action that a newer one of its kind, about the same thing, + * makes pointless (a rank set twice ends at the last): dropped, and + * said to have been replaced. */ + private async replaceHeld(old: Held, by: string): Promise { + 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]); + await this.audit({ + at: new Date(this.now()).toISOString(), + who: old.who, + via: "edge", + action: old.kind, + phase: "done", + ok: false, + error: `replaced by a newer ${by}: 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 ${by}: 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); + } + + /** For each thing held actions are about (one that stands alone is + * its own), the oldest of them, where it is one this side could do + * itself: a kind it runs, that certainly reached no machine, and + * nothing else about the same thing with a machine either. Only the + * oldest about a thing can be done next, so these are all a pass can + * begin with. */ + private async heldMine(cfg: EdgeConfig | null): Promise { + if (!this.primary(cfg) || !this.mine(cfg)) return []; + const held = await this.heldList(); + const handed = await this.handedList(); + const withMachine = new Set(held.filter((h) => this.withMachine(h, handed)).map((h) => this.heldAbout(h))); + const seen = new Set(); + const first: Held[] = []; + for (const h of held) { + const about = this.heldAbout(h); + if (seen.has(about)) continue; + seen.add(about); + if ((DIRECT_ACTIONS as readonly string[]).includes(h.kind) && !withMachine.has(about)) first.push(h); + } + return first; + } + + /** When this side may next try one of its kind: not while it is + * turned away for the kind, nor before the time GitHub gave. (Every + * kind is kept to GitHub's time, though one or two ask only the queue + * store: tried sooner, the rest would only be turned away again.) */ + private async heldReadyAt(kind: string): Promise { + this.refusedKinds(); + return Math.max(this.refused.get(kind) ?? 0, (await this.github.quiet()).core?.until ?? 0); + } + + /** The time of the next thing to do about what is held: the first of + * it this side could do itself, and the day's end of the oldest of it + * whoever's it is. Null when nothing is held. */ + private async heldDue(cfg: EdgeConfig | null): Promise { + const held = await this.heldList(); + if (held.length === 0) return null; + const times = held.map((h) => Date.parse(h.at) + HELD_FOR_MS + 1000).filter((t) => Number.isFinite(t)); + for (const h of await this.heldMine(cfg)) { + times.push(Math.max(await this.heldReadyAt(h.kind), this.drainNotBefore)); + } + return times.length > 0 ? Math.min(...times) : null; + } + + /** What has waited more than a day is dropped, and said to have been. */ + private async expireHeld(now: number): Promise { + const held = await this.heldList(); + const handed = await this.handedList(); + let dropped = false; + for (const old of held.filter((h) => now - Date.parse(h.at) > HELD_FOR_MS)) { + // Said before it leaves the list: whether a machine may have had it. + const maybe = this.withMachine(old, handed); + held.splice(held.indexOf(old), 1); + dropped = true; + await this.logAct({ + id: old.id, + kind: old.kind, + at: old.at, + by: old.who, + status: "failed", + note: maybe + ? "The laptop may have got this, and did not say what became of it within a day: check whether it happened before trying again." + : "Not sent: the laptop was out of reach for more than a day.", + }); + } + return dropped; + } + + /** What is held and never reached a machine is done here, now that + * this side can: the oldest about each thing first, and nothing about + * a thing behind one that could not be done. One pass at a time. */ + private async drainHeld(cfg: EdgeConfig | null): Promise { + if (this.draining || this.now() < this.drainNotBefore) return; + this.draining = true; + let did = 0; + let tried = false; + try { + await this.ready(); + // Left for another pass: what this one could not do, and + // everything behind it about the same thing. + const left = new Set(); + for (let turn = 0; turn < 2 * HELD_MAX; turn++) { + const now = this.now(); + let pick: Held | null = null; + for (const h of await this.heldMine(cfg)) { + const about = this.heldAbout(h); + if (left.has(about)) continue; + if (this.doing.has(h.id) || (await this.heldReadyAt(h.kind)) > now) { + left.add(about); + continue; + } + pick = h; + break; + } + if (!pick) break; + tried = true; + const about = subjectOf(pick.kind, pick.args); + const one = pick; + if ( + LAST_WINS.has(one.kind) && + about !== null && + (await this.heldList()).some( + (h) => h.id !== one.id && h.kind === one.kind && subjectOf(h.kind, h.args) === about, + ) + ) { + await this.replaceHeld(one, one.kind); + did++; + continue; + } + const went = await this.doHeld(one); + if (went === "done") did++; + else left.add(about ?? `:${one.id}`); + } + } finally { + this.draining = false; + // A pass that tried and could do nothing is not tried again at + // once. (One that found nothing due yet sets no such pause.) + if (tried && did === 0) this.drainNotBefore = this.now() + DRAIN_AGAIN_MS; + } + } + /** 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. */ @@ -914,12 +1300,25 @@ export class Edge { sections: this.machine?.sections ?? [], }, ], - held: [...(await this.heldList())], + held: await this.heldSaid(cfg), }; } + /** How much is held, by who it waits for. */ + private async heldCounts(cfg: EdgeConfig | null): Promise> { + const counts: Record = { either: 0, machine: 0, asked: 0 }; + for (const waits of (await this.heldWaits(cfg)).values()) counts[waits]++; + return counts; + } + + /** What is held, each with who it waits for. */ + private async heldSaid(cfg: EdgeConfig | null): Promise<(Held & { waits: HeldFor })[]> { + const waits = await this.heldWaits(cfg); + return (await this.heldList()).map((h) => ({ ...h, waits: waits.get(h.id) ?? "machine" })); + } + /** What the app is told of this side, beside its state: how much is - * waiting for a machine, and whether this side does the core itself. */ + * waiting to be done, and whether this side does the core itself. */ private async showEdge(): Promise { this.docs.extra("edge", { held: (this.held ?? []).length, primary: this.primary(await this.config()) }); } @@ -960,6 +1359,7 @@ export class Edge { await this.heldList(); await this.showEdge(); } + if (this.taken === null) await this.recoverTaken(); if (this.ownActs === null) await this.showActs(); if (this.hostSeen === null) { const host = (await this.kv.get("host")) as @@ -1496,18 +1896,7 @@ export class Edge { } } // What has waited too long is dropped, and said to have been. - for (const old of held.filter((h) => now - Date.parse(h.at) > HELD_FOR_MS)) { - held.splice(held.indexOf(old), 1); - settled = true; - await this.logAct({ - id: old.id, - kind: old.kind, - at: old.at, - by: old.who, - status: "failed", - note: "Not sent: the laptop was out of reach for more than a day.", - }); - } + if (await this.expireHeld(now)) settled = true; if (settled) await this.saveHeld(); await this.pruneHanded(); // What a machine has just done late changed things this side reads @@ -1593,17 +1982,40 @@ export class Edge { const copy = await this.mirror(name); if (!copy || copy.own) want.push(name); } + const watching = now - this.lastDocAt < WATCHING_MS; + const notify = await this.someoneToTell(); + const phones = await this.phones.devices.links(); + const handed = await this.handedList(); + // What the machine is handed: everything held, less anything about + // a thing this side is doing something about right now (it would + // be done out of turn). Chosen and marked as handed with nothing + // waited for in between, so that this side cannot take one of them + // for itself meanwhile; and written down before the answer goes. + const mine = new Set( + (this.taken ?? []).map((t) => subjectOf(t.kind, t.args)).filter((about): about is string => about !== null), + ); + const commands = held.filter((h) => { + const about = subjectOf(h.kind, h.args); + return about === null || !mine.has(about); + }); + let marked = false; + for (const command of commands) { + if (!handed.has(command.id)) { + handed.add(command.id); + marked = true; + } + } + if (marked) await this.saveHanded(); const answer: SyncResponse = { ok: true, - watching: now - this.lastDocAt < WATCHING_MS, - notify: await this.someoneToTell(), + watching, + notify, want, - commands: held, - phones: await this.phones.devices.links(), + commands, + phones, // 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); } @@ -1632,6 +2044,11 @@ export class Edge { if (NOTIFIED.includes(name)) wakes.push(Math.max(now + 1000, (this.unread.get(name) ?? now) + 1000)); } } + // What is held and never reached a machine is this side's to do + // when it can, and what has waited a day is dropped: it wakes for + // the first of either. + const due = await this.heldDue(cfg); + if (due !== null) wakes.push(Math.max(now + 1000, due)); if (wakes.length > 0) await this.setAlarm(Math.min(...wakes)); } @@ -1674,6 +2091,12 @@ export class Edge { for (let look = 0; look < 2; look++) await this.docs.current(this.ownedTold(cfg), CLOCK_WAIT_MS); await this.tell(cfg).catch((error) => console.error(`pm-edge: notify: ${(error as Error).message}`)); } + // What is held: the day's limit is kept with no machine reporting, + // and what this side can now do itself, it does. + if (await this.expireHeld(now)) await this.saveHeld(); + await this.drainHeld(cfg).catch((error) => + console.error(`pm-edge: doing what was held: ${(error as Error).message}`), + ); await this.schedule(cfg); } @@ -1747,6 +2170,11 @@ export class Edge { // quiet. Notifications with no machine depend on this, and it // is how that is seen to be alive from outside. clock: { wanted: await this.clockWanted(cfg), next: await this.getAlarm().catch(() => null) }, + // How many things the owner did are waiting to be done, by who + // each waits for: either side, whichever can first; a machine + // only; or a machine that was given it or may have got it. + // Counts, and nothing of what they are. + held: await this.heldCounts(cfg), hostSeen: this.hostSeen || null, // The commit the host's console is running, as it last said. hostVersion: this.hostVersion, @@ -1953,68 +2381,50 @@ export class Edge { // 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 newer = { id: id ?? crypto.randomUUID(), kind, args, who: by }; + // Each turn waits out one thing being done here about the + // same thing, or settles the oldest of what is held about + // it; then it looks again, since either may have changed + // what is waiting. (There cannot be more turns than this.) + let clear = false; + for (let turn = 0; turn < 4 * HELD_MAX; turn++) { + const held = await this.heldList(); const handed = await this.handedList(); - if (older.some((h) => handed.has(h.id))) { - return this.keep({ id: id ?? crypto.randomUUID(), kind, args, who: by }); + // From here to the choice nothing is waited for. + // Something older about the same thing may be being done + // here right now (what was held, on this side's own wake): + // this one waits for it to end, so that the two are done + // in the order the owner did them. + const doing = this.busy.get(about); + if (doing) { + await doing; + continue; + } + const older = held.filter((h) => h.id !== id && subjectOf(h.kind, h.args) === about); + if (older.length === 0) { + clear = true; + break; } - 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]); - } + // One a machine has, or may have, may be being done + // there: the newer waits behind it. + if (older.some((h) => this.withMachine(h, handed))) return this.keep(newer); + // One that only a machine can do is a machine's whenever + // one comes: the newer waits behind it too. + if (older.some((h) => !(DIRECT_ACTIONS as readonly string[]).includes(h.kind))) return this.keep(newer); + const old = older[0]; + // One of the same kind where the last one wins is dropped + // as replaced by this. (Only by its own kind: a comment + // about an issue does not replace its rank.) + if (LAST_WINS.has(old.kind) && old.kind === kind) { + await this.replaceHeld(old, kind); + continue; } + // Refused here too: the newer waits behind the older. (If + // it was not this side's to take after all, the next look + // finds why: being done here, or a machine's.) + if ((await this.doHeld(old)) === "back") return this.keep(newer); } + if (!clear) return this.keep(newer); } try { return await this.once(id, kind, () => @@ -2027,7 +2437,7 @@ export class Edge { } // Written down as a machine's before it goes anywhere. if (id !== null && !given) { - await this.kv.put(`a:${id}`, { at: this.now(), kind, state: "given" } satisfies Acted); + await this.kv.put(`a:${id}`, { at: this.now(), kind, state: "given", relays: 0 } satisfies Acted); await this.actedIndex(id); } // What may be done late goes behind anything already waiting @@ -2039,13 +2449,40 @@ export class Edge { // 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 }); + const held = await this.heldList(); + if (about !== null && held.some((h) => h.id !== id && subjectOf(h.kind, h.args) === about)) { + // A name that was a machine's before this arrival set off + // toward one already: it may be there now, and is kept as + // that machine's. (One already waiting here is kept once, + // as it is.) + return this.keep({ id: id ?? crypto.randomUUID(), kind, args, who: by }, given ? "unknown" : "nowhere"); } } + if (id !== null) { + await this.ready(); + const handed = await this.handedList(); + const record = ((await this.kv.get(`a:${id}`)) as Acted | undefined) ?? null; + // From here to the choice nothing is waited for. + // This side took the name to do itself a moment ago: it is + // not sent to a machine as well. + if ((this.taken ?? []).some((t) => t.id === id)) return this.takenSaid(id); + // Offered again while it waits here, having reached no + // machine: it goes on waiting as it is, for this side or for + // a machine's next report, whichever is first. Sent toward + // the host now, it would be on its way there while this side + // may be taking it for its own. + const waiting = (this.held ?? []).find((h) => h.id === id); + if (waiting && !this.withMachine(waiting, handed)) { + const waits = (await this.heldWaits(cfg)).get(id) ?? "machine"; + return json({ ok: true, held: true, result: null, again: true, waits }); + } + // It sets off toward a machine, and that is counted under its + // name before it goes (a record from before the counting is + // taken to have set off once already). + const relays = (record?.state === "given" ? (record.relays ?? 1) : 0) + 1; + await this.kv.put(`a:${id}`, { at: this.now(), kind, state: "given", relays } satisfies Acted); + await this.actedIndex(id); + } // The host's to do. The stateless part relays it, and if the // host cannot be reached comes back to have it held. // It goes under the device's name for it, or one given here, @@ -2056,6 +2493,9 @@ export class Edge { return next("relay", { mode: "act", id: id ?? crypto.randomUUID(), + // Whether the name is the device's (it may be offered again) + // or one given here for this one asking. + named: id !== null, kind, args, who: by, @@ -2097,7 +2537,7 @@ export class Edge { // Started, and not by this object (it would hold the name): // one that was put away before it ended. Whether it happened // is not known, and doing it again could do it twice. - const body = { error: "Cloudflare restarted while doing this; check whether it happened before trying again." }; + const body = { error: RESTARTED }; await this.kv.put(key, { at: this.now(), kind, state: "done", status: 502, body } satisfies Acted); return json({ ...body, again: true }, 502); } @@ -2178,21 +2618,41 @@ export class Edge { } } - /** The host could not be reached: keep the action for it, if it is one - * that may be done late. */ + /** The host did not answer: keep the action, if it is one that may be + * done late. The stateless part, which saw what came back in the + * host's place, says whether that was word that the host was never + * reached. */ private async hold(req: Request): Promise { - return this.keep( - (await req.json().catch(() => null)) as { - id?: unknown; - kind?: unknown; - args?: unknown; - who?: unknown; - } | null, - ); - } - - /** Keep an action for a machine, at the back of what already waits. */ - private async keep(body: { id?: unknown; kind?: unknown; args?: unknown; who?: unknown } | null): Promise { + const body = (await req.json().catch(() => null)) as { + id?: unknown; + kind?: unknown; + args?: unknown; + who?: unknown; + unreached?: unknown; + named?: unknown; + } | null; + if (body?.unreached !== true) return this.keep(body, "unknown"); + // Word that this asking never arrived says the action reached no + // machine only if it set off this once: another asking under the + // same name (the device offered it again meanwhile) may be at the + // host now. A name given here, and not by the device, set off once. + const record = + body.named === false || typeof body.id !== "string" + ? null + : (((await this.kv.get(`a:${body.id}`)) as Acted | undefined) ?? null); + const once = body.named === false || (record?.state === "given" && record.relays === 1); + return this.keep(body, once ? "unreached" : "unknown"); + } + + /** Keep an action for later, at the back of what already waits. + * `went` is how far it got toward a machine. "nowhere": it was never + * sent to one. "unreached": it was sent, and what answered in the + * machine's place said it never arrived. "unknown": it was sent, and + * nothing says what became of it, so the machine may have done it. */ + private async keep( + body: { id?: unknown; kind?: unknown; args?: unknown; who?: unknown } | null, + went: "nowhere" | "unreached" | "unknown" = "nowhere", + ): Promise { const kind = typeof body?.kind === "string" ? body.kind : ""; const args = body?.args; if (!HOLDABLE.has(kind) || args === null || typeof args !== "object" || Array.isArray(args)) { @@ -2207,11 +2667,16 @@ export class Edge { ); } await this.ready(); + const cfg = await this.config(); const held = await this.heldList(); // Offered again under a name that is already waiting (the device - // never heard that it was kept): it is kept once. - if (typeof body?.id === "string" && held.some((h) => h.id === body.id)) { - return json({ ok: true, held: true, result: null, again: true }); + // never heard that it was kept): it is kept once, as it is. (One + // waiting here only sets off toward a machine again when it is a + // machine's already, so there is nothing about it to change.) + const waiting = typeof body?.id === "string" ? held.find((h) => h.id === body.id) : undefined; + if (waiting) { + const waits = (await this.heldWaits(cfg)).get(waiting.id) ?? "machine"; + return json({ ok: true, held: true, result: null, again: true, waits }); } if (held.length >= HELD_MAX) { return json({ error: "The laptop cannot be reached, and too much is already waiting for it." }, 503); @@ -2223,19 +2688,39 @@ export class Edge { args: args as Record, who: String(body?.who ?? "owner"), at: new Date(this.now()).toISOString(), + ...(went === "unknown" ? {} : { unsent: true as const }), }; held.push(item); await this.saveHeld(); - await this.audit({ at: item.at, who: item.who, via: "edge", action: kind, phase: "held", id: item.id }); - await this.logAct({ - id: item.id, - kind, + const waits = (await this.heldWaits(cfg)).get(item.id) ?? "machine"; + await this.audit({ at: item.at, - by: item.who, - status: "running", - note: "Held: the laptop cannot be reached. It will be sent when it is back.", + who: item.who, + via: "edge", + action: kind, + phase: "held", + id: item.id, + // Whether it is known to have reached no machine. + unsent: item.unsent === true, }); - return json({ ok: true, held: true, result: null }); + await this.logAct({ id: item.id, kind, at: item.at, by: item.who, status: "running", note: HELD_SAID[waits] }); + // If it is one this side could do itself when it can again, it + // asks to be woken for that; and for the day's end of it either way. + await this.schedule(cfg).catch(() => {}); + return json({ ok: true, held: true, result: null, waits }); + } + + /** A name this side has taken to do itself is not sent to a machine + * as well: its doing is waited for, and the answer is what came of + * it. If nothing did (this side was turned away again, or could not + * write down how it went), the device is told it is not over, and + * offers it again. (Called only for a name in the taken list.) */ + private async takenSaid(id: string): Promise { + const mine = (this.taken ?? []).find((t) => t.id === id); + if (mine) await this.busy.get(this.heldAbout(mine)); + const after = ((await this.kv.get(`a:${id}`)) as Acted | undefined) ?? null; + if (after?.state === "done") return json({ ...after.body, again: true }, after.status ?? 200); + return json({ error: "This is still being done.", running: true }, 409); } /** After the host did a relayed action: the sections it read again and diff --git a/pm-stack/console/edge/src/entry.ts b/pm-stack/console/edge/src/entry.ts index f1601195f4..a396cea016 100644 --- a/pm-stack/console/edge/src/entry.ts +++ b/pm-stack/console/edge/src/entry.ts @@ -17,6 +17,12 @@ export interface Io { /** The host behind the hostname's route. `ms` is how long it has to * start answering. Null when it could not be reached. */ host: (request: Request, ms: number) => Promise; + /** The host, asked to do something. As `host`, but what came back in + * the host's place is looked at: "unreached" when it says the host + * was never reached (the tunnel had no connection to send it down), + * so that nothing asked of it was done. Null is no answer at all, or + * one that does not say: the host may have got it, and done it. */ + act: (request: Request, ms: number) => Promise; /** The hostname this Worker is routed on. Only there is the host * behind it; anywhere else only the public paths answer. */ publicHost: string; @@ -158,15 +164,25 @@ export async function route(request: Request, io: Io): Promise { if (detail.mode === "act") { // The host is told the action's name with the action. No answer may // mean the host never got it, or did it and the answer was lost: it - // is held under that name, and the host sorts out which. + // is held under that name, and the host sorts out which. Only when + // what answered in its place says the host was never reached is the + // state told so: then, and only then, it may do the action itself. const named = withHeader(withHeader(forHost, "x-pm-edge", "1"), "x-pm-act", String(detail.id ?? "")); - const answer = await io.host(named, ACT_MS); - if (answer === null) return tell("/internal/hold", detail); + const answer = await io.act(named, ACT_MS); + if (answer === null || answer === "unreached") { + return tell("/internal/hold", { ...detail, unreached: answer === "unreached" }); + } // The host's answer says what it read again; keep that here, and // send the owner the rest. if (!(answer.headers.get("content-type") ?? "").startsWith("application/json")) return answer; const body = (await answer.json().catch(() => null)) as Record | null; - if (body === null) return offline("the host's answer could not be read"); + if (body === null) { + // The host answered, so it has the name written down, whatever + // it said: a hold left under the name is settled as by any other + // answer of the host's, and is nobody else's to do. + await tell("/internal/relayed", { id: detail.id }); + return offline("the host's answer could not be read"); + } const { sections, acts, ...rest } = body; // 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. diff --git a/pm-stack/console/edge/src/worker.ts b/pm-stack/console/edge/src/worker.ts index aecf3c4b3f..e4ff87bff2 100644 --- a/pm-stack/console/edge/src/worker.ts +++ b/pm-stack/console/edge/src/worker.ts @@ -10,6 +10,7 @@ import { DurableObject } from "cloudflare:workers"; import { Edge } from "./edge.ts"; import { route } from "./entry.ts"; +import { unread } from "../../src/timed.ts"; interface Env { PM: DurableObjectNamespace; @@ -108,9 +109,23 @@ function fromHost(res: Response): boolean { return res.headers.get("x-pm-console") === "1" || res.status < 500; } +/** What answered in the host's place says that the host was never + * reached. Cloudflare answers 530 (with one of its 1xxx errors in the + * body: 1033 for a tunnel) when it has no way to the origin at all: for + * a tunnel, no connection of the machine's to send the request down. + * Nothing was handed to the machine, so nothing asked of it was done. + * Any other answer in the host's place does not say as much: a gateway + * that lost the connection part-way answers for a host that may have + * had the request. */ +function neverReached(res: Response): boolean { + return res.status === 530 && res.headers.get("x-pm-console") !== "1"; +} + /** Ask the host. `ms` is how long it has to start answering; a stream it - * then keeps open (the dashboard's live pages) is left to run. */ -async function host(request: Request, ms: number, origin?: string): Promise { + * then keeps open (the dashboard's live pages) is left to run. Null when + * it did not answer, and "unreached" when what answered in its place + * says it was never reached (see neverReached). */ +async function ask(request: Request, ms: number, origin?: string): Promise { const abort = new AbortController(); const timer = setTimeout(() => abort.abort(), ms); try { @@ -118,7 +133,11 @@ async function host(request: Request, ms: number, origin?: string): Promise { + const answer = await ask(request, ms, origin); + return answer === "unreached" ? null : answer; +} + export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { ctx.passThroughOnException(); @@ -134,6 +158,7 @@ export default { state: (r) => stub.fetch(r), asset: (path) => env.ASSETS.fetch(new Request(`https://assets.internal${path}`)), host: (r, ms) => host(r, ms, env.HOST_ORIGIN), + act: (r, ms) => ask(r, ms, env.HOST_ORIGIN), publicHost: env.PUBLIC_HOST, version: env.VERSION ?? null, later: (work) => ctx.waitUntil(work), diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 8a9b279e14..352eeacbd9 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -271,7 +271,9 @@ function withoutAnswered(doc) { let hostSeen = null; /** How far behind the laptop may be before the app says so. */ const HOST_QUIET_MS = 3 * 60_000; -const HELD_NOTE = "Held: the laptop cannot be reached. It will be sent when it is back."; +/** Said of something the platform holds when it did not say more (the + * platform says who it waits for: outbox.js has the words). */ +const HELD_NOTE = "Held: it could not be done just now, and will be when it can."; const KEPT_NOTE = "Kept on this device. It is sent when you are connected."; @@ -391,7 +393,7 @@ async function sendAlone(entry) { const answer = await Outbox.httpSend(entry); const out = Outbox.classify(answer); if (out.state === "done") return { state: "done", result: out.result }; - if (out.state === "held") return { state: "held" }; + if (out.state === "held") return { state: "held", note: out.note }; if (out.state === "failed") return { state: "failed", note: out.note }; if (out.signin) signedOut = true; return { state: "refused", note: answer.network ? "This needs a connection." : out.signin ? NO_SIGNIN : out.note }; @@ -422,7 +424,7 @@ export function sentSaid(did, id) { const now = did.entry; if (!now) return { state: "refused", note: "It was taken back before it was sent." }; if (now.state === "done") return { state: "done", result: now.result ?? null, others: did.others }; - if (now.state === "held") return { state: "held", others: did.others }; + if (now.state === "held") return { state: "held", note: now.note || "", others: did.others }; if (now.state === "failed") return { state: "failed", note: now.note }; return { state: "kept", @@ -458,7 +460,7 @@ async function act(kind, args, done, button) { return out.result ?? { done: true }; } if (out.state === "held") { - toast(HELD_NOTE + also); + toast((out.note || HELD_NOTE) + also); await refresh(true); return { held: true }; } @@ -524,7 +526,7 @@ function notices(doc, only = null) { if (doc === docs.core && doc?.edge?.held > 0) { const n = doc.edge.held; out.push( - h("div", { class: "card flag" }, h("p", { class: "meta" }, `${n} ${n === 1 ? "thing" : "things"} you did ${n === 1 ? "is" : "are"} waiting for the laptop. See “What you did” below.`)), + h("div", { class: "card flag" }, h("p", { class: "meta" }, `${n} ${n === 1 ? "thing" : "things"} you did ${n === 1 ? "is" : "are"} waiting to be done. See “What you did” below.`)), ); } for (const said of unreadSaid(doc, only)) out.push(h("div", { class: "card flag" }, h("p", { class: "meta" }, said))); @@ -786,7 +788,7 @@ async function sendAnswer(kind, args, key, said) { // A choice was already acknowledged when it was made (with its // Undo); anything else says so now, or the question would simply // vanish. - if (out.state === "held") toast(HELD_NOTE); + if (out.state === "held") toast(out.note || HELD_NOTE); else if (out.state === "kept") toast(out.note); else if (said) toast(said); picks.delete(key); @@ -2155,13 +2157,25 @@ export function machinesMark(m, now = Date.now()) { (x.sections || []).length, x.quiet && x.seen ? Math.floor((now - x.seen) / 60_000) : 0, ]), - held: (m?.held || []).map((item) => item.id), + // Who each waits for is drawn too, and changes while it waits. + held: (m?.held || []).map((item) => [item.id, item.waits ?? ""]), }); } let machinesDrawn = ""; +/** Who something held waits for, in the owner's words; empty when the + * platform did not say (one older than the saying). */ +export function heldWaitsSaid(waits) { + const said = { + either: "Cloudflare does this as soon as it can again, or a machine that is back first.", + machine: "Waits for a machine: only one can do it, or it comes after something that waits for one.", + asked: "A machine was given this, or may have got it. It says what became of it when it is back; nobody else does it meanwhile.", + }; + return typeof waits === "string" && Object.hasOwn(said, waits) ? said[waits] : ""; +} + /** Machines: the platform's own part, each machine that reports and - * what only it can do, and what waits for one. */ + * what only it can do, and what waits to be done. */ async function viewMachines() { const m = await api("machines"); machinesDrawn = machinesMark(m); @@ -2218,13 +2232,14 @@ async function viewMachines() { ), ); } - out.push(h("h2", {}, `Waiting for a machine (${held.length})`)); + out.push(h("h2", {}, `Waiting to be done (${held.length})`)); if (held.length === 0) out.push(card(h("p", { class: "meta" }, "Nothing is waiting."))); for (const item of held) { out.push( card( h("h3", {}, Outbox.sayOf(item.kind, item.args)), h("p", { class: "meta" }, `${item.who} · ${ago(item.at)}`), + heldWaitsSaid(item.waits) ? h("p", { class: "meta" }, heldWaitsSaid(item.waits)) : null, h("div", { class: "row end" }, h("button", { class: "small ghost", onclick: (e) => takeBack(item, e) }, "Take back")), ), ); @@ -2345,7 +2360,7 @@ export function keptGroups(entries) { { state: "waiting", title: "Waiting to send", can: ["drop"], entries: of("waiting") }, { state: "stale", title: "Kept back for you to look at", can: ["send", "drop"], entries: of("stale") }, { state: "failed", title: "Could not be done", can: ["again", "drop"], entries: of("failed") }, - { state: "held", title: "With the platform, waiting for a machine", can: [], entries: of("held") }, + { state: "held", title: "With the platform, waiting to be done", can: [], entries: of("held") }, { state: "done", title: "Sent", can: [], entries: of("done") }, ].filter((g) => g.entries.length > 0); } diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 4e909a8dbc..6b97a529ec 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -159,6 +159,15 @@ return { id, kind, args: args ?? {}, said: said || sayOf(kind, args), at: now, state: "waiting", note: "", tries: 0 }; } + /** What is said of something the platform is holding, by who it + * waits for: either side, whichever can first; a machine only; or a + * machine that may already have it. */ + const HELD_NOTES = { + either: "Kept: Cloudflare does it as soon as it can again, or the laptop if it is back first.", + machine: "Kept for the laptop, which will do it when it is back.", + asked: "Kept: the laptop did not answer. It may have got this, and says what became of it when it is back.", + }; + /** What became of one try at sending. `answer` is what came back: * `{ network: true }` when nothing did, else the status, whether the * body was JSON, and the body. Returns the entry's new state and what @@ -173,7 +182,10 @@ } if (status === 200 && body.ok === true) { if (body.held === true) { - return { state: "held", note: "Kept for the laptop, which will do it when it is back.", result: null }; + // The platform says who it waits for; one that does not say is + // older than the saying, and holds things for the laptop only. + const waits = typeof body.waits === "string" && Object.hasOwn(HELD_NOTES, body.waits) ? body.waits : "machine"; + return { state: "held", note: HELD_NOTES[waits], result: null }; } // Taken, and answered "not recorded" without an error: an answer // to a question that was settled in the meantime. That is not diff --git a/pm-stack/console/scripts/edge-demo.ts b/pm-stack/console/scripts/edge-demo.ts index 92ad5e5dd3..ae9437bed5 100644 --- a/pm-stack/console/scripts/edge-demo.ts +++ b/pm-stack/console/scripts/edge-demo.ts @@ -84,6 +84,8 @@ const io: Io = { // The made-up host trusts every caller, as demo.ts does; here it is // only ever reached through the edge. host: async (r) => (net.hostUp ? marked(await handle(r, demoDeps)) : null), + // Away, the made-up host is away as a laptop asleep is: never reached. + act: async (r) => (net.hostUp ? marked(await handle(r, demoDeps)) : "unreached"), publicHost: HOSTNAME, version: "demo", later: (work) => void work.catch(() => {}), diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index 4d275d6a82..72a6cee52d 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -143,10 +143,18 @@ const outside: { tag?: string | null; status?: number; etag?: string; + /** How GitHub was asked: a read, or something written. */ + method?: string; }[] = []; /** GitHub turning every call away as one too many, until this second * (as it says it: nothing left of the allowance, and when it is back). */ const spent = { until: 0 }; +/** The host out of reach while GitHub and the queue store still + * answer, and what answers in its place. 530 is what Cloudflare says of + * a tunnel with no connection (its error 1033): the host was never + * reached. 502 is a gateway that could not get an answer out of it: + * that does not say the host never had the request. */ +const hostAway: { on: boolean; status: 530 | 502 } = { on: false, status: 530 }; /** The list of Workers answered at length, as GitHub answers a list of * open pull requests: well over a million characters, each of two * units (the Worker's store holds about two million bytes a value, so @@ -189,6 +197,7 @@ const server = Bun.serve({ path, auth: req.headers.get("authorization"), agent: req.headers.get("user-agent"), + method: req.method, }; outside.push(entry); if (spent.until > 0) { @@ -219,6 +228,11 @@ const server = Bun.serve({ }, ]); } + if (req.method === "POST" && /\/issues\/\d+\/comments$/.test(path)) { + // A comment is made, as GitHub answers one. + entry.status = 201; + return Response.json({ html_url: `https://github.com/${path.replace("repos/", "")}#made` }, { status: 201 }); + } if (path === "search/issues") return tagged(req, entry, { total_count: 0, items: [] }); if (path.endsWith("/issues")) return tagged(req, entry, []); return tagged(req, entry, { message: "Not Found" }, 404); @@ -235,6 +249,9 @@ const server = Bun.serve({ ), }); } + if (hostAway.on) { + return new Response(hostAway.status === 530 ? "error code: 1033" : "Bad Gateway", { status: hostAway.status }); + } seen.push(`${req.method} ${url.pathname}`); // Everything that arrives here came through the Worker, as it does // through the tunnel: never a caller on this machine. (Deployed, the @@ -540,6 +557,95 @@ try { (await githubSaid())?.quiet.core === null, `quiet until ${shortSaid}, GitHub said ${shortTo}; ${heldThen - askedThen} calls while quiet, ${hourly() - askedThen} after`, ); + // What is held that Cloudflare can do itself, it does, with no + // machine. The host is out of reach and GitHub turns the account + // away, so a comment the owner makes is held. Then GitHub answers + // again and the owner says to try again now: the Worker asks to be + // woken, the runtime wakes it, and it makes the comment itself, once. + { + const commentId = "55555555-5555-4555-8555-555555555555"; + const commentsOn = (issue: number, status: number) => + outside.filter( + (o) => + o.to === "github" && + o.method === "POST" && + o.path.endsWith(`/issues/${issue}/comments`) && + o.status === status, + ).length; + const comments = (status: number) => commentsOn(7, status); + type Waiting = { held?: { id: string; waits?: string }[] }; + hostAway.on = true; + hostAway.status = 530; + spent.until = Math.ceil(Date.now() / 1000) + 600; + const heldComment = (await ( + await actAsOwner( + "issue.comment", + { issue: 7, text: "held by the smoke run, then done by the Worker" }, + commentId, + ) + ).json()) as { ok?: boolean; held?: boolean; waits?: string }; + spent.until = 0; + check( + "turned away by GitHub with the tunnel down, a comment is held as either side's, and nothing was written", + heldComment.held === true && heldComment.waits === "either" && comments(403) === 1 && comments(201) === 0, + `${JSON.stringify(heldComment)}; ${comments(403)} turned away, ${comments(201)} made`, + ); + const tryAgain = await actAsOwner("edge.retry", {}); + await tryAgain.text(); + for (let waited = 0; waited < 20_000 && comments(201) === 0; waited += 500) { + await new Promise((resolve) => setTimeout(resolve, 500)); + } + // (Time for it to be done a second time, if it were going to be.) + await new Promise((resolve) => setTimeout(resolve, 4000)); + const waiting = (await (await asOwner("/console/api/machines")).json()) as Waiting; + check( + "and when GitHub answers and the owner says to try again, the Worker wakes itself and makes the comment: once, with no machine", + tryAgain.status === 200 && comments(201) === 1 && !(waiting.held ?? []).some((h) => h.id === commentId), + `try again ${tryAgain.status}; ${comments(201)} made; still waiting ${JSON.stringify(waiting.held)}`, + ); + // The other way of being out of reach. What answers in the host's + // place does not say the host never had the request (a gateway + // that got no answer out of it): the host may have made the + // comment, so the Worker holds it for the host and never makes it + // itself, however able it is. This is the Worker's own reading of + // what came back, which only this run exercises. + const maybeId = "66666666-6666-4666-8666-666666666666"; + hostAway.status = 502; + spent.until = Math.ceil(Date.now() / 1000) + 600; + const heldMaybe = (await ( + await actAsOwner("issue.comment", { issue: 9, text: "held by the smoke run for the host alone" }, maybeId) + ).json()) as { held?: boolean; waits?: string }; + spent.until = 0; + const againMaybe = await actAsOwner("edge.retry", {}); + await againMaybe.text(); + // (As long as the other took to be made, and more.) + await new Promise((resolve) => setTimeout(resolve, 8000)); + const waitingMaybe = (await (await asOwner("/console/api/machines")).json()) as Waiting; + const countsMaybe = ((await (await get("/console/health")).json()) as { held?: Record }).held; + check( + "out of reach with nothing to say the host never had it, a comment is held for the host alone: the Worker does not make it", + heldMaybe.held === true && + heldMaybe.waits === "asked" && + againMaybe.status === 200 && + commentsOn(9, 403) === 1 && + commentsOn(9, 201) === 0 && + (waitingMaybe.held ?? []).some((h) => h.id === maybeId && h.waits === "asked") && + countsMaybe?.asked === 1 && + countsMaybe?.either === 0, + `${JSON.stringify(heldMaybe)}; ${commentsOn(9, 403)} turned away, ${commentsOn(9, 201)} made; waiting ${JSON.stringify(waitingMaybe.held)}; health ${JSON.stringify(countsMaybe)}`, + ); + // Taken back, so that nothing of this is left waiting for the rest of the run. + const takenBack = await actAsOwner("held.drop", { id: maybeId }); + await takenBack.text(); + const left = (await (await asOwner("/console/api/machines")).json()) as Waiting; + check( + "and the owner can take it back", + takenBack.status === 200 && (left.held ?? []).length === 0, + `${takenBack.status}; waiting ${JSON.stringify(left.held)}`, + ); + hostAway.on = false; + hostAway.status = 530; + } // Someone to tell: a device takes notifications (its service is a // known one and its key a real point; nothing is sent to it in // this run unless the clock's news is worth sending). diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 497e17c284..97cb4957eb 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -148,10 +148,18 @@ export interface MachinesAnswer { actions: string[]; sections: string[]; }[]; - /** What the owner did that waits for a machine, oldest first. */ - held: Held[]; + /** What the owner did that waits to be done, oldest first, and who + * each waits for (absent from an answer older than the saying). */ + held: (Held & { waits?: HeldFor })[]; } +/** Who a held action waits for. "either": the platform does it itself + * as soon as it can again, or a machine that is back first. "machine": + * only a machine can do it, or it comes after something that waits for + * one. "asked": a machine was given it, or may have got it, and says + * what became of it when it is back; nobody else does it meanwhile. */ +export type HeldFor = "either" | "machine" | "asked"; + export interface PhoneLinks { devices: { id: string; name: string; hash: string; createdAt: string; seenAt: string | null }[]; removed: { hash: string; at: string }[]; @@ -165,6 +173,12 @@ export interface Held { /** Who took it, as the edge verified them. */ who: string; at: string; + /** It certainly reached no machine: it was never sent toward one, or + * the one time it was, what answered in the machine's place said it + * never arrived. Only then may the platform do it itself. Without + * this a machine may have got it (no answer came, or one that does + * not say) and may have done it: it stays that machine's by name. */ + unsent?: true; } export interface ApkReport { diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 00035a690a..8f20459a2f 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -24,6 +24,7 @@ import { intakeSaid, keptGroups, keptSaid, + heldWaitsSaid, levelHeadings, listed, machineSaid, @@ -646,7 +647,7 @@ test("what is kept is listed by what it needs: waiting, kept back, failed, with ["Waiting to send", ["drop"], ["w2", "w1"]], ["Kept back for you to look at", ["send", "drop"], ["s1"]], ["Could not be done", ["again", "drop"], ["f1"]], - ["With the platform, waiting for a machine", [], ["h1"]], + ["With the platform, waiting to be done", [], ["h1"]], ["Sent", [], ["d1"]], ]); // A group with nothing in it is not shown. @@ -717,7 +718,17 @@ test("what the owner is told of something just done, from what became of it when }); expect(sentSaid({ ...quiet, entry: { state: "done" } }, id)).toEqual({ state: "done", result: null, others: [] }); // Taken by the platform for a machine. - expect(sentSaid({ ...quiet, entry: { state: "held" }, others: older }, id)).toEqual({ state: "held", others: older }); + // Taken by the platform to be done later, with what it said of who will. + expect(sentSaid({ ...quiet, entry: { state: "held", note: "Kept: who will" }, others: older }, id)).toEqual({ + state: "held", + note: "Kept: who will", + others: older, + }); + expect(sentSaid({ ...quiet, entry: { state: "held" }, others: older }, id)).toEqual({ + state: "held", + note: "", + others: older, + }); // Refused: said, and nothing more. expect(sentSaid({ ...quiet, entry: { state: "failed", note: "no such issue" } }, id)).toEqual({ state: "failed", @@ -872,6 +883,7 @@ test("the Machines screen is drawn again when what it shows has changed, and not ["there is another", answer({ machines: [machine, { ...machine, name: "amd" }] })], ["there is none", answer({ machines: [] })], ["something else waits", answer({ held: [{ id: "h1" }, { id: "h2" }] })], + ["what waits now waits for someone else", answer({ held: [{ id: "h1", kind: "task.move", waits: "asked" }] })], ["nothing waits", answer({ held: [] })], [ "the platform stopped doing the core", @@ -893,6 +905,19 @@ test("the Machines screen is drawn again when what it shows has changed, and not expect(machinesMark(null, now)).toBe(machinesMark({}, now)); }); +test("who something held waits for is said in the owner's words, and not at all when the platform did not say", () => { + // Each of the three says something of its own. + const said = ["either", "machine", "asked"].map((waits) => heldWaitsSaid(waits)); + expect(said.every((line) => line.length > 20)).toBe(true); + expect(new Set(said).size).toBe(3); + expect(said[0]).toContain("Cloudflare does this as soon as it can again"); + expect(said[2]).toContain("may have got it"); + // An answer older than the saying, or one that says something else: nothing is made up. + for (const waits of [undefined, null, "", "someone", "constructor", "toString", 3, {}]) { + expect([waits, heldWaitsSaid(waits)]).toEqual([waits, ""]); + } +}); + test("a Worker's line on the Platform screen: how it gets into service, and how its last deploy went", () => { const now = Date.parse("2026-11-23T12:00:00Z"); const run = (state: string, more: Record = {}) => ({ diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 114094a305..ebbbb84453 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -730,6 +730,7 @@ async function setup(options: { direct?: boolean } = {}) { "issue.comment": { run: async (a) => { ran.push({ kind: "issue.comment", args: a }); + await gate.wait; if (a.issue === 13) throw new OpError(404, "no such issue"); return { commented: a.issue }; }, @@ -813,15 +814,21 @@ async function setup(options: { direct?: boolean } = {}) { }, }; const net: { + /** The host can be reached. When it cannot, what answers in its + * place says so (the tunnel is down), unless `silent`. */ hostUp: boolean; edgeUp: boolean; loseAnswer: boolean; giveUpEarly: boolean; + /** Out of reach with nothing to say so: asking it only runs out of time. */ + silent: boolean; + /** The host does the work and answers, and its answer cannot be read. */ + garble: boolean; /** A report of more than this many bytes does not get through: it * is cut off on the way ("lost", a slow connection running out of * time) or turned away by something in front of the edge ("refused"). */ large: { over: number; fate: "lost" | "refused" } | null; - } = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false, large: null }; + } = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false, silent: false, garble: false, large: null }; /** The size of each report the host sent, whether or not it arrived. */ const reportSizes: number[] = []; /** Each report the host sent, as it read. */ @@ -866,6 +873,27 @@ async function setup(options: { direct?: boolean } = {}) { ["/console/outbox.js", "// what is kept"], ["/icons/icon-192.png", "PNG"], ]); + const askHost = async (r: Request): Promise => { + if (!net.hostUp) return null; + hostSaw.push(`${r.method} ${new URL(r.url).pathname}`); + // Through the tunnel: the connection is local, the headers are the edge's. + const answer = handle(r, hostDeps, "127.0.0.1").then(marked); + // The edge stops waiting while the host is still at it. + if (net.giveUpEarly) { + stillRunning.push(answer); + return null; + } + // The host does the work and its answer is lost on the way back. + if (net.loseAnswer) { + await answer; + return null; + } + if (net.garble) { + const said = await answer; + return new Response("{", { status: said.status, headers: said.headers }); + } + return answer; + }; const io: Io = { state: (r) => edge.now.fetch(r), // The platform's file store tags each file by its content; the icon @@ -874,23 +902,10 @@ async function setup(options: { direct?: boolean } = {}) { files.has(path) ? new Response(files.get(path), path.startsWith("/icons/") ? {} : { headers: { ETag: `"tag-of-${path}"` } }) : new Response("", { status: 404 }), - host: async (r) => { - if (!net.hostUp) return null; - hostSaw.push(`${r.method} ${new URL(r.url).pathname}`); - // Through the tunnel: the connection is local, the headers are the edge's. - const answer = handle(r, hostDeps, "127.0.0.1").then(marked); - // The edge stops waiting while the host is still at it. - if (net.giveUpEarly) { - stillRunning.push(answer); - return null; - } - // The host does the work and its answer is lost on the way back. - if (net.loseAnswer) { - await answer; - return null; - } - return answer; - }, + host: askHost, + // Asked to do something: a host that cannot be reached is said to + // be, as Cloudflare says of a tunnel with no connection. + act: async (r) => (!net.hostUp && !net.silent ? "unreached" : askHost(r)), publicHost: HOST, version: "test", later: (work) => later.push(work), @@ -1099,6 +1114,7 @@ describe("before the host's first report", () => { version: "test", woke: w.now.t, clock: { wanted: false, next: null }, + held: { either: 0, machine: 0, asked: 0 }, host: HOST, }); // The owner's page is the host's own, reached through the edge. @@ -1480,7 +1496,7 @@ describe("actions", () => { w.net.edgeUp = false; const held = await w.act("ask.send", { text: "Do this when you are back" }); - expect(await held.json()).toEqual({ ok: true, held: true, result: null }); + expect(await held.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); // A merge acts on what the owner saw; it is never done late. const merge = await w.act("pr.merge", { pr: 7 }); expect(merge.status).toBe(503); @@ -1596,7 +1612,7 @@ describe("actions", () => { const res = await w.act("ask.send", { text: "only once" }); w.net.loseAnswer = false; // The edge cannot tell "never arrived" from "done, answer lost": it holds it. - expect(await res.json()).toEqual({ ok: true, held: true, result: null }); + expect(await res.json()).toEqual({ ok: true, held: true, result: null, waits: "asked" }); expect(w.ran).toHaveLength(1); // The host is offered it under the name it was relayed with, knows // it did it, and says so instead of doing it again. @@ -1723,7 +1739,7 @@ describe("actions", () => { // would be done first, and the older move would undo it. w.net.hostUp = true; const second = await w.act("task.move", { task: 21016, to: "last" }); - expect(await second.json()).toEqual({ ok: true, held: true, result: null }); + expect(await second.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); expect(w.ran.filter((r) => r.kind === "task.move")).toEqual([]); // Another task is nothing to do with it: it is done at once. const other = await w.act("task.move", { task: 21017, to: "first" }); @@ -1836,7 +1852,7 @@ describe("actions", () => { const again = await w.act("held.drop", { id: kept }); expect([again.status, await again.json()]).toEqual([ 404, - { error: "That is no longer waiting: a machine took it, or it was taken back already." }, + { error: "That is no longer waiting: it was done or is being done, or was taken back already." }, ]); // The machine is back: it is given what still waits, and not what was taken back. w.net.hostUp = true; @@ -1901,12 +1917,14 @@ describe("actions", () => { ok: true, held: true, result: null, + waits: "machine", }); expect(await (await w.act("ask.send", { text: "kept once" }, id)).json()).toEqual({ ok: true, held: true, result: null, again: true, + waits: "machine", }); expect((w.stored.get("held") as { id: string }[]).map((h) => h.id)).toEqual([id]); // The laptop comes back and does it once; sent yet again, the device @@ -1933,7 +1951,7 @@ describe("actions", () => { w.net.giveUpEarly = true; const res = await w.act("need.comment", { ref: "code#1", text: "slow" }); w.net.giveUpEarly = false; - expect(await res.json()).toEqual({ ok: true, held: true, result: null }); + expect(await res.json()).toEqual({ ok: true, held: true, result: null, waits: "asked" }); // Offered again while still running: not run a second time, and not answered for yet. w.now.t += 1_000; const during = await w.link.now.once(); @@ -4236,7 +4254,7 @@ describe("the edge does the core itself", () => { w.net.edgeUp = false; w.ghRefuses.push((method) => method !== "GET"); const comment = await w.act("issue.comment", { issue: 301, text: "later, then" }); - expect(await comment.json()).toEqual({ ok: true, held: true, result: null }); + expect(await comment.json()).toEqual({ ok: true, held: true, result: null, waits: "either" }); expect((w.stored.get("held") as { kind: string }[]).map((h) => h.kind)).toEqual(["issue.comment"]); const merge = await w.act("pr.merge", { pr: 55 }); expect(merge.status).toBe(503); @@ -5002,7 +5020,7 @@ describe("the edge does the core itself", () => { w.net.hostUp = false; w.net.edgeUp = false; const held = await w.act("issue.comment", { issue: 14, text: "late" }); - expect(await held.json()).toEqual({ ok: true, held: true, result: null }); + expect(await held.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); // And what the plan's screens read is the laptop's to answer. expect((await w.browse("/console/api/roadmap?area=fleet")).status).toBe(503); expect(w.githubCalls).toEqual([]); @@ -5096,6 +5114,7 @@ describe("the edge does the core itself", () => { ok: true, held: true, result: null, + waits: "machine", }); }); @@ -5111,6 +5130,7 @@ describe("the edge does the core itself", () => { ok: true, held: true, result: null, + waits: "either", }); 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. @@ -5148,6 +5168,7 @@ describe("the edge does the core itself", () => { ok: true, held: true, result: null, + waits: "either", }); 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. @@ -5179,6 +5200,7 @@ describe("the edge does the core itself", () => { ok: true, held: true, result: null, + waits: "either", }); // The token is put right and this side takes comments back. w.ghRefuses.length = 0; @@ -5195,7 +5217,7 @@ describe("the edge does the core itself", () => { // 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(await second.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); 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. @@ -5215,6 +5237,7 @@ describe("the edge does the core itself", () => { ok: true, held: true, result: null, + waits: "either", }); // The token is put right and this side takes comments back. w.ghRefuses.length = 0; @@ -5236,6 +5259,935 @@ describe("the edge does the core itself", () => { expect(posted.slice(-1)).toEqual(["unrelated"]); expect(w.stored.get(`a:${newerId}`)).toMatchObject({ kind: "issue.comment", state: "done" }); }); + + // ---- what is held, done here when this side can again (#13831) ----------- + + const COMMENT = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/comments$/.test(url); + type HeldWorld = Awaited>; + /** The words of every comment asked of GitHub, in order (refused ones too). */ + const commented = (w: HeldWorld) => + w.githubCalls + .filter((c) => COMMENT(c.method, c.url)) + .map((c) => (JSON.parse(c.body ?? "{}") as { body?: string }).body); + const heldIds = (w: HeldWorld) => ((w.stored.get("held") as { id: string }[] | undefined) ?? []).map((h) => h.id); + /** What is held, each with who it waits for, as the Machines screen is told it. */ + const heldWaits = async (w: HeldWorld) => + ((await (await w.browse("/console/api/machines")).json()) as MachinesAnswer).held.map((h) => [h.id, h.waits]); + /** This side wakes itself: at the time it asked for, and (as in service) as an object that has just started. */ + const wake = async (w: HeldWorld) => { + w.now.t = Math.max(w.now.t, w.alarm.at); + w.edge.now = w.makeEdge(); + await w.edge.now.alarm(); + await settle(w); + }; + /** Turned away for comments with every machine away: each comment asked for is held. */ + const heldComments = async (w: HeldWorld, comments: [id: string, issue: number, text: string][]) => { + w.ghRefuses.push(COMMENT); + w.net.hostUp = false; + w.net.edgeUp = false; + for (const [id, issue, text] of comments) { + expect(await (await w.act("issue.comment", { issue, text }, id)).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "either", + }); + w.now.t += 1_000; + } + }; + const ID = (n: number) => `0f000000-0000-4000-8000-${String(100_000 + n).padStart(12, "0")}`; + + test("what is held and never reached a machine is done here when this side can again: with no machine, once, and the owner sees it done", async () => { + const w = await primary(); + const t0 = w.now.t; + await heldComments(w, [[ID(1), 7, "held, then done here"]]); + expect(w.stored.get(`a:${ID(1)}`)).toMatchObject({ state: "given" }); + expect(commented(w)).toEqual(["held, then done here"]); + // The token is put right. Nothing tells this side so: it finds out when its hour for the + // kind is up, and it has asked to be woken then. A wake before that (to notice the laptop + // gone quiet) asks GitHub nothing about it. + w.ghRefuses.length = 0; + await wake(w); + expect(w.now.t).toBeLessThan(t0 + 60 * 60_000); + expect([commented(w).length, heldIds(w)]).toEqual([1, [ID(1)]]); + await wake(w); + expect(w.now.t).toBe(t0 + 60 * 60_000); + // Done here: asked of GitHub once more and no more, by no machine. + expect(commented(w)).toEqual(["held, then done here", "held, then done here"]); + expect([heldIds(w), w.stored.get("taken") ?? [], w.stored.get("handed") ?? [], w.ran]).toEqual([[], [], [], []]); + expect(w.stored.get(`a:${ID(1)}`)).toMatchObject({ kind: "issue.comment", state: "done", status: 200 }); + const { doc } = await w.core(); + expect(doc.edge).toEqual({ held: 0, primary: true }); + expect(doc.acts.find((a: { id: string }) => a.id === ID(1))).toMatchObject({ + kind: "issue.comment", + status: "done", + }); + // Sent again under its name, it is answered from the record, not done again; and a + // machine that comes back is handed nothing. + const again = (await (await w.act("issue.comment", { issue: 7, text: "held, then done here" }, ID(1))).json()) as { + again?: boolean; + }; + expect([again.again, commented(w).length]).toEqual([true, 2]); + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands).toEqual([]); + expect(w.ran).toEqual([]); + }); + + test("kept with the laptop long gone and nobody to tell, it still asks to be woken for it: nothing else would wake it", async () => { + const w = await primary(); + w.net.hostUp = false; + w.net.edgeUp = false; + // The laptop went quiet, and that has been said. Nothing is left to wake this side. + await wake(w); + expect(w.stored.get("silent")).toBe(true); + const idle = w.alarm.at; + w.now.t += 3 * 60 * 60_000; + const kept = w.now.t; + await heldComments(w, [[ID(91), 7, "kept late at night"]]); + expect(idle).toBeLessThan(kept); + expect(w.alarm.at).toBe(kept + 60 * 60_000); + w.ghRefuses.length = 0; + await wake(w); + expect([commented(w), heldIds(w)]).toEqual([["kept late at night", "kept late at night"], []]); + // With nothing held, and nothing else to wake for, it asks for no wake at all. + const after = w.alarm.at; + await wake(w); + expect(w.alarm.at).toBe(after); + }); + + test("turned away for calling too often, what is held is done at the time GitHub gave and not before", async () => { + const w = await primary(); + const t0 = w.now.t; + const back = Math.floor((t0 + 40 * 60_000) / 1000) * 1000; + w.ghLimits.push(COMMENT); + w.ghLimitSays.headers = { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(back / 1000) }; + w.net.hostUp = false; + w.net.edgeUp = false; + expect(await (await w.act("issue.comment", { issue: 7, text: "when GitHub answers" }, ID(2))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "either", + }); + w.ghLimits.length = 0; + const asked = w.githubCalls.length; + // Woken before the time (for the laptop gone quiet): nothing is asked of GitHub at all. + await wake(w); + expect([w.now.t < back, w.githubCalls.length, heldIds(w)]).toEqual([true, asked, [ID(2)]]); + // Woken again half a minute before the time: still nothing, and its next wake is the time + // itself (a pass that found nothing due does not put the next one off). + w.now.t = back - 30_000; + w.edge.now = w.makeEdge(); + await w.edge.now.alarm(); + expect([w.githubCalls.length, w.alarm.at]).toEqual([asked, back]); + // Its next wake is the time GitHub gave, and then it is done. + await wake(w); + expect(w.now.t).toBe(back); + expect(commented(w)).toEqual(["when GitHub answers", "when GitHub answers"]); + expect([heldIds(w), w.ran]).toEqual([[], []]); + expect(w.stored.get(`a:${ID(2)}`)).toMatchObject({ state: "done", status: 200 }); + }); + + test("done in the order they were done: two about one thing one after the other, and one about another thing not kept behind them", async () => { + const w = await primary(); + await heldComments(w, [ + [ID(11), 7, "first about seven"], + [ID(12), 8, "about eight"], + [ID(13), 7, "second about seven"], + ]); + w.ghRefuses.length = 0; + await wake(w); + await wake(w); + expect(commented(w).slice(1)).toEqual(["first about seven", "about eight", "second about seven"]); + expect([heldIds(w), w.ran]).toEqual([[], []]); + }); + + test("one a machine has been handed is the machine's: this side does not do it, nor anything else about the same thing", async () => { + const w = await primary(); + await heldComments(w, [ + [ID(21), 7, "handed"], + [ID(22), 9, "about nine"], + ]); + // The laptop comes back and is handed both. It goes again before saying what became of them. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(21), ID(22)]); + expect(w.stored.get("handed")).toEqual([ID(21), ID(22)]); + w.net.hostUp = false; + w.net.edgeUp = false; + // A later one about the same thing as a handed one waits behind it, held. + w.now.t += 2 * 60 * 60_000; + w.ghRefuses.length = 0; + expect(await (await w.act("issue.comment", { issue: 7, text: "behind it" }, ID(23))).json()).toMatchObject({ + held: true, + }); + const before = commented(w).length; + const kept = (w.stored.get("held") as { id: string; at: string }[]).map((h) => Date.parse(h.at)); + // Woken (to notice the laptop gone quiet), none of the three is done here: two are the + // laptop's, which may have done them, and the third waits behind one of those. + await wake(w); + expect([commented(w).length, heldIds(w)]).toEqual([before, [ID(21), ID(22), ID(23)]]); + expect(w.stored.get("taken") ?? []).toEqual([]); + // Nor does it wake itself over them again and again: nothing here is its own to do, and + // its next wake is the day's end of the oldest. + expect(w.alarm.at).toBe(kept[0] + 24 * 60 * 60_000 + 1_000); + // The laptop never comes back. At the day's end the first it was handed is dropped, and + // said to have been; what waited behind it is then this side's, and is done here, once. + await wake(w); + expect(heldIds(w)).toEqual([ID(22)]); + expect(commented(w).slice(before)).toEqual(["behind it"]); + const { doc } = await w.core(); + // (Not "not sent": the laptop was handed it, and may have done it.) + expect(doc.acts.find((a: { id: string }) => a.id === ID(21))).toMatchObject({ + status: "failed", + note: expect.stringMatching(/may have got this, and did not say what became of it within a day/), + }); + expect(doc.acts.find((a: { id: string }) => a.id === ID(23))).toMatchObject({ status: "done" }); + }); + + test("a machine reporting while this side is doing one: it is not handed that one, nor one behind it about the same thing, and each is done once", async () => { + const w = await primary(); + await heldComments(w, [ + [ID(31), 7, "A"], + [ID(32), 7, "B"], + [ID(33), 8, "C"], + ]); + w.ghRefuses.length = 0; + w.now.t += 60 * 60_000; + // This side wakes and begins A; GitHub is slow to answer. + let answerNow: () => void = () => {}; + w.ghHolds.push({ + match: COMMENT, + wait: new Promise((resolve) => { + answerNow = resolve; + }), + }); + const waking = w.edge.now.alarm(); + for (let turn = 0; turn < 200 && commented(w).length < 2; turn++) await new Promise((r) => setTimeout(r, 1)); + expect(commented(w)).toEqual(["A", "A"]); + expect([heldIds(w), (w.stored.get("taken") as { id: string }[]).map((t) => t.id)]).toEqual([ + [ID(32), ID(33)], + [ID(31)], + ]); + // The laptop is back, and reports while A is still being done. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + const answer = await w.link.now.once(); + expect(answer?.commands.map((c) => c.id)).toEqual([ID(33)]); + expect(w.stored.get("handed")).toEqual([ID(33)]); + expect(w.ran.filter((r) => r.kind === "issue.comment").map((r) => r.args.text)).toEqual(["C"]); + // GitHub answers. A is done here, then B behind it; C was the laptop's and is not done here. + w.ghHolds.length = 0; + answerNow(); + await waking; + await settle(w); + expect(commented(w)).toEqual(["A", "A", "B"]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + expect(heldIds(w)).toEqual([ID(33)]); + // The laptop says C is done, and nothing waits. + await w.hostReads(); + await w.link.now.once(); + expect([heldIds(w), w.stored.get("handed") ?? []]).toEqual([[], []]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + for (const n of [31, 32]) expect(w.stored.get(`a:${ID(n)}`)).toMatchObject({ state: "done", status: 200 }); + }); + + test("a newer one about a thing arriving while an older held one is being done here waits for it, and is done after", async () => { + const w = await primary(); + await heldComments(w, [[ID(41), 7, "older"]]); + w.ghRefuses.length = 0; + w.now.t += 60 * 60_000; + let answerNow: () => void = () => {}; + w.ghHolds.push({ + match: (method, url) => COMMENT(method, url), + wait: new Promise((resolve) => { + answerNow = resolve; + }), + }); + const waking = w.edge.now.alarm(); + for (let turn = 0; turn < 200 && commented(w).length < 2; turn++) await new Promise((r) => setTimeout(r, 1)); + // The owner comments again on the same issue. It is not asked of GitHub until the older has ended. + w.net.edgeUp = true; + const newer = w.act("issue.comment", { issue: 7, text: "newer" }, ID(42)); + for (let turn = 0; turn < 20; turn++) await new Promise((r) => setTimeout(r, 1)); + expect(commented(w)).toEqual(["older", "older"]); + w.ghHolds.length = 0; + answerNow(); + await waking; + expect(await (await newer).json()).toMatchObject({ ok: true }); + await settle(w); + expect(commented(w)).toEqual(["older", "older", "newer"]); + expect(heldIds(w)).toEqual([]); + }); + + test("turned away again when it tries: what it took goes back as it was, where it was, and a machine can still be handed it", async () => { + const w = await primary(); + await heldComments(w, [ + [ID(51), 7, "still refused"], + [ID(52), 8, "behind"], + ]); + // The hour passes and the token is as it was. + await wake(w); + await wake(w); + const tried = w.now.t; + expect(commented(w)).toEqual(["still refused", "still refused"]); + expect(heldIds(w)).toEqual([ID(51), ID(52)]); + expect([w.stored.get("taken") ?? [], w.stored.get("handed") ?? []]).toEqual([[], []]); + expect(w.stored.get(`a:${ID(51)}`)).toMatchObject({ state: "given" }); + // Not tried again before the kind's next hour is up. + expect(w.alarm.at).toBe(tried + 60 * 60_000); + // Sent again under its name meanwhile, it is not done here: it is a machine's by name, and waits once. + w.ghRefuses.length = 0; + expect(await (await w.act("issue.comment", { issue: 7, text: "still refused" }, ID(51))).json()).toMatchObject({ + held: true, + again: true, + }); + expect(commented(w)).toHaveLength(2); + // The laptop comes back, is handed both in order, and does each once. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(51), ID(52)]); + expect(w.ran.filter((r) => r.kind === "issue.comment").map((r) => r.args.text)).toEqual([ + "still refused", + "behind", + ]); + await w.hostReads(); + await w.link.now.once(); + expect(heldIds(w)).toEqual([]); + // Nothing more was asked of GitHub here. + expect(commented(w)).toHaveLength(2); + }); + + test("put away while it had one taken: an object that starts again settles each by its record, and nothing is done twice", async () => { + const w = await primary(); + await heldComments(w, [ + [ID(61), 7, "begun, and not known to have ended"], + [ID(62), 8, "never begun"], + [ID(63), 9, "back in the list already"], + [ID(64), 10, "ended"], + [ID(65), 11, "untouched"], + ]); + const held = w.stored.get("held") as { id: string; at: string }[]; + const by = (n: number) => held.find((h) => h.id === ID(n)) as { id: string; at: string }; + // As an object put away part-way would leave things: four taken, three of them out of the list. + w.stored.set("taken", [by(61), by(62), by(63), by(64), "not one", { id: 7 }]); + w.stored.set("held", [by(63), by(65)]); + w.stored.set(`a:${ID(61)}`, { at: w.now.t, kind: "issue.comment", state: "running" }); + w.stored.set(`a:${ID(64)}`, { at: w.now.t, kind: "issue.comment", state: "done", status: 200, body: { ok: true } }); + // (The one never begun was put away just after being turned away again: its name's record + // had been cleared for the try, and not yet written back.) + w.stored.delete(`a:${ID(62)}`); + const asked = commented(w).length; + w.edge.now = w.makeEdge(); + const { doc } = await w.core(); + // Never begun: it waits again, in its place (before the two that were kept after it). + expect(heldIds(w)).toEqual([ID(62), ID(63), ID(65)]); + expect(w.stored.get(`a:${ID(62)}`)).toMatchObject({ state: "given" }); + expect(w.stored.has("taken")).toBe(false); + // Begun and not known to have ended: neither side does it again, and the owner is told to look. + expect(w.stored.get(`a:${ID(61)}`)).toMatchObject({ state: "done", status: 502 }); + expect(doc.acts.find((a: { id: string }) => a.id === ID(61))).toMatchObject({ + status: "failed", + note: expect.stringMatching(/restarted while doing this/), + }); + // The one that had ended is as its record says. + expect(w.stored.get(`a:${ID(64)}`)).toMatchObject({ state: "done", status: 200 }); + expect(doc.edge).toEqual({ held: 3, primary: true }); + // The laptop comes back: it is handed the three that wait, and no other. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(62), ID(63), ID(65)]); + expect(commented(w)).toHaveLength(asked); + // Something in storage that is not a list of them is nothing taken. + for (const odd of [7, "x", { id: ID(61) }, null]) { + w.stored.set("taken", odd); + w.edge.now = w.makeEdge(); + expect([odd, (await w.core()).res.status]).toEqual([odd, 200]); + } + }); + + test("one that only a machine can do is a machine's: this side does not try it, and what comes after it about the same thing waits behind it", async () => { + const w = await primary(); + w.net.hostUp = false; + w.net.edgeUp = false; + const ref = "developing-today/code#1"; + // Marking a need done is the laptop's to do; a comment on it is something this side does. + expect(await (await w.act("hands.done", { ref }, ID(111))).json()).toMatchObject({ held: true }); + w.now.t += 1_000; + const asked = w.githubCalls.length; + expect(await (await w.act("need.comment", { ref, text: "after it" }, ID(112))).json()).toMatchObject({ + held: true, + }); + // Nothing was tried here for either, and neither was failed. + expect(heldIds(w)).toEqual([ID(111), ID(112)]); + // Each is said to wait for a machine: the one only it can do, and the one behind it. + expect(await heldWaits(w)).toEqual([ + [ID(111), "machine"], + [ID(112), "machine"], + ]); + expect(w.stored.get(`a:${ID(111)}`)).toMatchObject({ state: "given" }); + // Woken, this side still does neither: the comment is behind what is a machine's. + await wake(w); + expect([heldIds(w), w.githubCalls.length]).toEqual([[ID(111), ID(112)], asked]); + const { doc } = await w.core(); + expect(doc.acts.filter((a: { status: string }) => a.status === "failed")).toEqual([]); + // The laptop comes back and does both, in order. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(111), ID(112)]); + }); + + test("a pass that could do nothing is not tried again at once, until the owner says to", async () => { + const w = await primary(); + await heldComments(w, [[ID(121), 7, "when storage is well"]]); + w.ghRefuses.length = 0; + w.now.t += 60 * 60_000; + // What it takes cannot be written down: it is not taken, and still waits. + w.storeFails.add("taken"); + await w.edge.now.alarm(); + expect([commented(w).length, heldIds(w)]).toEqual([1, [ID(121)]]); + expect(((await w.core()).doc.edge as { held: number }).held).toBe(1); + // Its next wake for it is a minute on, not the next second. + expect(w.alarm.at).toBe(w.now.t + 60_000); + // Storage is well again, and the owner says to try again now: it wakes at once, and does it. + w.storeFails.clear(); + w.net.edgeUp = true; + expect((await w.act("edge.retry", {})).status).toBe(200); + expect(w.alarm.at).toBe(w.now.t + 1_000); + w.now.t = w.alarm.at; + await w.edge.now.alarm(); + expect([commented(w).length, heldIds(w)]).toEqual([2, []]); + }); + + test("a take that could not be written down does not leave the thing marked as being done: a newer one about it is not left waiting", async () => { + const w = await primary(); + await heldComments(w, [[ID(125), 7, "older"]]); + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + w.storeFails.add("taken"); + await w.edge.now.alarm(); + expect([commented(w).length, heldIds(w)]).toEqual([1, [ID(125)]]); + // Storage is well again, and the owner comments on the same issue: the older is made + // first, then the newer. (Were the issue still marked as being worked on, this would wait + // for an end that never comes.) + w.storeFails.clear(); + const newer = await w.act("issue.comment", { issue: 7, text: "newer" }, ID(126)); + expect(await newer.json()).toMatchObject({ ok: true, result: expect.anything() }); + expect([commented(w), heldIds(w)]).toEqual([["older", "older", "newer"], []]); + }); + + test("a side that no longer does the core does none of what is held: it stays a machine's, and is not failed", async () => { + const w = await primary(); + await heldComments(w, [[ID(131), 7, "for whoever does the core"]]); + w.ghRefuses.length = 0; + // The switch is turned off (which restarts the Worker), and the hour passes. + w.edge.now = w.makeEdge(false); + w.now.t += 61 * 60_000; + await w.edge.now.alarm(); + await settle(w); + expect([commented(w).length, heldIds(w)]).toEqual([1, [ID(131)]]); + expect(w.stored.get(`a:${ID(131)}`)).toMatchObject({ state: "given" }); + // The laptop comes back and does it. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(131)]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + }); + + test("an older held one this side is turned away for again keeps a newer one about the same thing behind it, though the newer is a kind it can do", async () => { + const w = await primary(); + const labels = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/labels$/.test(url); + w.ghRefuses.push(labels); + w.net.hostUp = false; + w.net.edgeUp = false; + expect(await (await w.act("issue.rank", { issue: 201, rank: "now" }, ID(141))).json()).toMatchObject({ + held: true, + }); + // The hour for ranking is up, GitHub still refuses it, and the owner comments on the same + // issue. The rank is tried first, refused again, and goes back; the comment, which this + // side could make, waits behind it and is not made out of turn. + w.now.t += 61 * 60_000; + const written = w.puts.length; + expect(await (await w.act("issue.comment", { issue: 201, text: "after the rank" }, ID(142))).json()).toMatchObject({ + held: true, + }); + expect([commented(w), heldIds(w)]).toEqual([[], [ID(141), ID(142)]]); + expect(w.stored.get(`a:${ID(141)}`)).toMatchObject({ state: "given" }); + // Tried once, not over and over: taken, and then no longer taken. + expect(w.puts.slice(written).filter((key) => key === "taken")).toHaveLength(2); + // The laptop comes back and does both, in order. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(141), ID(142)]); + }); + + test("of two ranks held for one issue the last wins, and a comment about an issue does not replace its rank", async () => { + const w = await primary(); + const labels = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/labels$/.test(url); + w.ghRefuses.push(labels); + w.net.hostUp = false; + w.net.edgeUp = false; + for (const [id, issue, rank] of [ + [ID(71), 201, "next"], + [ID(72), 201, "now"], + [ID(73), 202, "priority/high"], + ] as const) { + expect(await (await w.act("issue.rank", { issue, rank }, id)).json()).toMatchObject({ held: true }); + w.now.t += 1_000; + } + w.ghRefuses.length = 0; + // The hour for ranking is up, and before this side has woken the owner comments on #202: + // its rank, held and older, is done first. A comment is not a newer rank. + w.now.t += 60 * 60_000; + w.net.edgeUp = true; + expect(await (await w.act("issue.comment", { issue: 202, text: "and a word" }, ID(74))).json()).toMatchObject({ + ok: true, + }); + expect(w.ghLabels[202]).toContain("priority/high"); + expect(w.stored.get(`a:${ID(73)}`)).toMatchObject({ kind: "issue.rank", state: "done", status: 200 }); + expect(commented(w)).toEqual(["and a word"]); + // Then it wakes: of the two ranks for #201 the older is dropped as replaced, and the newer done. + await wake(w); + expect(w.stored.get(`a:${ID(71)}`)).toMatchObject({ kind: "issue.rank", state: "done", status: 409 }); + expect(w.stored.get(`a:${ID(72)}`)).toMatchObject({ kind: "issue.rank", state: "done", status: 200 }); + expect(w.ghLabels[201]).toContain("now"); + expect(w.ghLabels[201]).not.toContain("next"); + expect(heldIds(w)).toEqual([]); + const { doc } = await w.core(); + expect(doc.acts.find((a: { id: string }) => a.id === ID(71))).toMatchObject({ + status: "failed", + note: expect.stringMatching(/Replaced by a newer issue\.rank/), + }); + }); + + test("one the laptop may have done, its answer lost on the way back, is the laptop's by name: this side never does it, however long the laptop is away", async () => { + const w = await primary(); + w.ghRefuses.push(COMMENT); + // Turned away here, it goes to the laptop, which makes the comment. Its answer is lost on the way back. + w.net.loseAnswer = true; + expect( + await (await w.act("issue.comment", { issue: 7, text: "made by the laptop" }, ID(201))).json(), + ).toMatchObject({ held: true }); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + // The laptop goes away. The token is put right, the hour passes, and this side wakes. + w.net.loseAnswer = false; + w.net.hostUp = false; + w.net.edgeUp = false; + w.ghRefuses.length = 0; + const asked = commented(w).length; + w.now.t += 61 * 60_000; + await wakeNow(w); + // It does not make the comment a second time, and still holds it for the laptop. + expect([commented(w).length, heldIds(w)]).toEqual([asked, [ID(201)]]); + expect(await heldWaits(w)).toEqual([[ID(201), "asked"]]); + // Nor when the owner says to try again now. + expect((await w.act("edge.retry", {})).status).toBe(200); + w.now.t += 2_000; + await wakeNow(w); + expect([commented(w).length, heldIds(w)]).toEqual([asked, [ID(201)]]); + // The laptop comes back, is handed it by name, and says what became of it: made once. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(201)]); + await w.link.now.once(); + expect([heldIds(w), w.ran.filter((r) => r.kind === "issue.comment").length, commented(w).length]).toEqual([ + [], + 1, + asked, + ]); + }); + + /** Woken now, as an object that has just started. (Not at the time it asked for: with nothing + * of its own to do, that is the day's end of what it holds.) */ + const wakeNow = async (w: HeldWorld) => { + w.edge.now = w.makeEdge(); + await w.edge.now.alarm(); + await settle(w); + }; + + test("out of reach with nothing to say so, the laptop may have got it, and it is never done here; said to be out of reach, it is", async () => { + // Two comments, each turned away here with the laptop out of reach: one way, then the other. + const w = await primary(); + w.ghRefuses.push(COMMENT); + w.net.hostUp = false; + w.net.edgeUp = false; + w.net.silent = true; + expect(await (await w.act("issue.comment", { issue: 7, text: "may have arrived" }, ID(211))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "asked", + }); + w.net.silent = false; + expect(await (await w.act("issue.comment", { issue: 8, text: "never arrived" }, ID(212))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "either", + }); + expect(await heldWaits(w)).toEqual([ + [ID(211), "asked"], + [ID(212), "either"], + ]); + // The health answer, which anyone may read, counts them and says nothing else of them. + const health = (await (await w.browse("/console/health", { token: null })).json()) as { held: unknown }; + expect(health.held).toEqual({ either: 1, machine: 0, asked: 1 }); + const { doc } = await w.core(); + const noted = (id: string) => doc.acts.find((a: { id: string }) => a.id === id)?.note; + expect(noted(ID(211))).toMatch(/did not answer\. It may have got this/); + expect(noted(ID(212))).toMatch(/Cloudflare does it as soon as it can again/); + // So far GitHub was asked for the first, and refused it; with this side turned away by + // then, the second was not asked for at all. + expect(commented(w)).toEqual(["may have arrived"]); + // GitHub takes comments again, and the hour passes. + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + await wakeNow(w); + // Only the one that reached nobody is made here. The other is still the laptop's. + expect([commented(w), heldIds(w)]).toEqual([["may have arrived", "never arrived"], [ID(211)]]); + }); + + test("offered again while it waits here, having reached no machine, it is not sent toward the laptop: it waits as it was, and is done once", async () => { + const w = await primary(); + await heldComments(w, [[ID(221), 7, "offered twice"]]); + // The device never heard that it was kept, and offers it again. By now the laptop can be + // reached (it has not reported yet): sent on, the comment would be made there. + w.net.hostUp = true; + const again = await w.act("issue.comment", { issue: 7, text: "offered twice" }, ID(221)); + expect(await again.json()).toEqual({ ok: true, held: true, result: null, again: true, waits: "either" }); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toEqual([]); + expect(heldIds(w)).toEqual([ID(221)]); + // This side makes it when it can: once. + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + await wakeNow(w); + expect([commented(w), heldIds(w)]).toEqual([["offered twice", "offered twice"], []]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toEqual([]); + // Offered a third time, it is answered from what was written down. + expect(await (await w.act("issue.comment", { issue: 7, text: "offered twice" }, ID(221))).json()).toMatchObject({ + ok: true, + again: true, + }); + expect(commented(w)).toHaveLength(2); + }); + + test("offered again while its first asking of the laptop is still out: word that the second never arrived is not word that the first did not", async () => { + const w = await primary(); + w.ghRefuses.push(COMMENT); + // Turned away here, it goes to the laptop, which is slow about it. + let open = () => {}; + w.gate.wait = new Promise((resolve) => { + open = resolve; + }); + const acts = () => w.hostSaw.filter((seen) => seen === "POST /console/api/act").length; + const before = acts(); + const first = w.act("issue.comment", { issue: 7, text: "asked twice" }, ID(231)); + for (let turn = 0; turn < 200 && acts() === before; turn++) await new Promise((r) => setTimeout(r, 1)); + expect(acts()).toBe(before + 1); + // The device gives up on that try and offers it again. By now the tunnel is down. + w.net.hostUp = false; + const second = await w.act("issue.comment", { issue: 7, text: "asked twice" }, ID(231)); + expect(await second.json()).toEqual({ ok: true, held: true, result: null, waits: "asked" }); + // GitHub takes comments again and the hour passes: this side still does not make it. + w.ghRefuses.length = 0; + const asked = commented(w).length; + w.now.t += 61 * 60_000; + await wakeNow(w); + expect([commented(w).length, heldIds(w)]).toEqual([asked, [ID(231)]]); + // The laptop finishes the first asking. It made the comment, once, and its answer settles the name. + w.gate.wait = null; + open(); + expect(await (await first).json()).toMatchObject({ ok: true }); + expect([heldIds(w), w.ran.filter((r) => r.kind === "issue.comment").length, commented(w).length]).toEqual([ + [], + 1, + asked, + ]); + }); + + test("a newer one about the same thing does not go ahead of one the laptop may have: it waits behind it, and one about something else does not", async () => { + const w = await primary(); + w.ghRefuses.push(COMMENT); + w.net.loseAnswer = true; + expect(await (await w.act("issue.comment", { issue: 7, text: "the laptop's" }, ID(241))).json()).toMatchObject({ + held: true, + waits: "asked", + }); + w.net.loseAnswer = false; + w.net.hostUp = false; + w.net.edgeUp = false; + // This side takes comments again. + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + w.edge.now = w.makeEdge(); + const asked = commented(w).length; + const newer = await w.act("issue.comment", { issue: 7, text: "newer" }, ID(242)); + expect(await newer.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); + expect(commented(w)).toHaveLength(asked); + expect(await heldWaits(w)).toEqual([ + [ID(241), "asked"], + [ID(242), "machine"], + ]); + // A comment on another issue is nothing to do with either: it is made at once. + expect(await (await w.act("issue.comment", { issue: 8, text: "other" }, ID(243))).json()).toMatchObject({ + ok: true, + result: expect.anything(), + }); + expect(commented(w).slice(asked)).toEqual(["other"]); + // Woken, this side still does neither of the two. + await wakeNow(w); + expect([commented(w).length, heldIds(w)]).toEqual([asked + 1, [ID(241), ID(242)]]); + }); + + test("offered again at the moment this side has taken it to do itself, it is not sent to the laptop as well: the answer is what came of doing it here", async () => { + const w = await primary(); + await heldComments(w, [[ID(251), 7, "taken, then offered"]]); + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + // The laptop can be reached again (it has not reported): a name sent toward it is done there. + w.net.hostUp = true; + w.edge.now = w.makeEdge(); + // Its record is slow to read. The wake has taken it, and has not yet written down that it + // has begun, when the device offers it again: by its record it is still a machine's. + let read = () => {}; + w.storeSlow.set( + `a:${ID(251)}`, + new Promise((resolve) => { + read = resolve; + }), + ); + const waking = w.edge.now.alarm(); + const taken = () => ((w.stored.get("taken") as unknown[] | undefined) ?? []).length; + for (let turn = 0; turn < 200 && taken() === 0; turn++) await new Promise((r) => setTimeout(r, 1)); + expect(taken()).toBe(1); + const again = w.act("issue.comment", { issue: 7, text: "taken, then offered" }, ID(251)); + for (let turn = 0; turn < 20; turn++) await new Promise((r) => setTimeout(r, 1)); + w.storeSlow.clear(); + read(); + await waking; + expect(await (await again).json()).toMatchObject({ ok: true, again: true }); + await settle(w); + // Made here, once, and not by the laptop. + expect(commented(w)).toEqual(["taken, then offered", "taken, then offered"]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toEqual([]); + expect([heldIds(w), w.stored.get("taken")]).toEqual([[], []]); + }); + + test("one kept before it was written down whether it reached a machine is taken to have: this side leaves it to the laptop", async () => { + const w = await primary(); + await heldComments(w, [[ID(261), 7, "from before"]]); + // As the version before this one stored it: with no word either way. + const stored = w.stored.get("held") as Record[]; + expect(stored.map((h) => h.unsent)).toEqual([true]); + w.stored.set( + "held", + stored.map(({ unsent: _unsent, ...rest }) => rest), + ); + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + await wakeNow(w); + expect([commented(w).length, heldIds(w)]).toEqual([1, [ID(261)]]); + expect(await heldWaits(w)).toEqual([[ID(261), "asked"]]); + // The laptop, back, is handed it by name. + w.net.hostUp = true; + w.net.edgeUp = true; + await w.hostReads(); + expect((await w.link.now.once())?.commands.map((c) => c.id)).toEqual([ID(261)]); + }); + + test("the laptop answers for a name and its answer cannot be read: the name is the laptop's, and nothing is left waiting under it", async () => { + const w = await primary(); + w.ghRefuses.push(COMMENT); + w.net.loseAnswer = true; + expect(await (await w.act("issue.comment", { issue: 7, text: "answered, unread" }, ID(271))).json()).toMatchObject({ + held: true, + waits: "asked", + }); + w.net.loseAnswer = false; + // The device offers it again; the laptop says how it went, and what it says does not arrive whole. + w.net.garble = true; + const again = await w.act("issue.comment", { issue: 7, text: "answered, unread" }, ID(271)); + w.net.garble = false; + expect([again.status, await again.json()]).toEqual([503, { error: "the host's answer could not be read" }]); + expect(heldIds(w)).toEqual([]); + // Offered once more, the laptop's own answer comes through: made once. + expect(await (await w.act("issue.comment", { issue: 7, text: "answered, unread" }, ID(271))).json()).toMatchObject({ + ok: true, + }); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + }); + + test("turned away again at the moment it is offered again: the device is told it is not over, and it is not sent to the laptop", async () => { + const w = await primary(); + await heldComments(w, [[ID(255), 7, "taken, refused, offered"]]); + // The hour passes with GitHub still refusing comments, and the laptop can be reached again. + w.now.t += 61 * 60_000; + w.net.hostUp = true; + w.edge.now = w.makeEdge(); + let read = () => {}; + w.storeSlow.set( + `a:${ID(255)}`, + new Promise((resolve) => { + read = resolve; + }), + ); + const waking = w.edge.now.alarm(); + const taken = () => ((w.stored.get("taken") as unknown[] | undefined) ?? []).length; + for (let turn = 0; turn < 200 && taken() === 0; turn++) await new Promise((r) => setTimeout(r, 1)); + expect(taken()).toBe(1); + const again = w.act("issue.comment", { issue: 7, text: "taken, refused, offered" }, ID(255)); + for (let turn = 0; turn < 20; turn++) await new Promise((r) => setTimeout(r, 1)); + w.storeSlow.clear(); + read(); + await waking; + const answer = await again; + expect([answer.status, await answer.json()]).toEqual([409, { error: "This is still being done.", running: true }]); + await settle(w); + // Refused twice by GitHub, made by nobody, and waiting again as it was. + expect(commented(w)).toEqual(["taken, refused, offered", "taken, refused, offered"]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toEqual([]); + expect([heldIds(w), w.stored.get("taken")]).toEqual([[ID(255)], []]); + expect(await heldWaits(w)).toEqual([[ID(255), "either"]]); + }); + + test("a rank the laptop may have set is not replaced by a newer rank: the newer waits behind it, and neither is done here", async () => { + const w = await primary(); + const labels = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/labels$/.test(url); + const labelled = () => w.githubCalls.filter((c) => labels(c.method, c.url)).length; + w.ghRefuses.push(labels); + // Turned away here, the rank goes to the laptop. Its answer is lost on the way back. + w.net.loseAnswer = true; + expect(await (await w.act("issue.rank", { issue: 201, rank: "now" }, ID(281))).json()).toMatchObject({ + held: true, + waits: "asked", + }); + w.net.loseAnswer = false; + w.net.hostUp = false; + w.net.edgeUp = false; + // This side may label again, and the owner ranks the issue again. + w.ghRefuses.length = 0; + w.now.t += 61 * 60_000; + w.edge.now = w.makeEdge(); + const asked = labelled(); + expect(await (await w.act("issue.rank", { issue: 201, rank: "next" }, ID(282))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "machine", + }); + // Both wait, in the order they were done. GitHub was not asked, and the older was not + // dropped as replaced: done late by the laptop, it would otherwise be the last word. + expect([heldIds(w), labelled()]).toEqual([[ID(281), ID(282)], asked]); + const { doc } = await w.core(); + expect(doc.acts.find((a: { id: string }) => a.id === ID(281))).toMatchObject({ status: "running" }); + }); + + test("a name given to a machine before its askings were counted is taken to have set off already", async () => { + const w = await primary(); + w.ghRefuses.push(COMMENT); + w.net.hostUp = false; + w.net.edgeUp = false; + // As the version before this one wrote it down: a machine's, with no count of its askings. + w.stored.set(`a:${ID(291)}`, { at: w.now.t, kind: "issue.comment", state: "given" }); + // Word that this asking never arrived says nothing of the one before it. + expect(await (await w.act("issue.comment", { issue: 7, text: "from before the count" }, ID(291))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "asked", + }); + expect(w.stored.get(`a:${ID(291)}`)).toMatchObject({ state: "given", relays: 2 }); + // A name new to this side, out of reach the same way, set off once: it reached nobody. + expect(await (await w.act("issue.comment", { issue: 8, text: "new" }, ID(292))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "either", + }); + expect(w.stored.get(`a:${ID(292)}`)).toMatchObject({ state: "given", relays: 1 }); + }); + + test("offered again while its first asking is still out, with something else about the same thing waiting here: it is kept as the laptop's, and nothing about the thing is done here meanwhile", async () => { + const w = await primary(); + w.ghRefuses.push(COMMENT); + // Turned away here, the first comment goes to the laptop, which is slow about it. + let open = () => {}; + w.gate.wait = new Promise((resolve) => { + open = resolve; + }); + const acts = () => w.hostSaw.filter((seen) => seen === "POST /console/api/act").length; + const before = acts(); + const first = w.act("issue.comment", { issue: 7, text: "first, slow" }, ID(301)); + for (let turn = 0; turn < 200 && acts() === before; turn++) await new Promise((r) => setTimeout(r, 1)); + expect(acts()).toBe(before + 1); + // The tunnel drops. A second comment on the issue reaches nobody, and waits here. + w.net.hostUp = false; + expect(await (await w.act("issue.comment", { issue: 7, text: "second" }, ID(302))).json()).toMatchObject({ + held: true, + waits: "either", + }); + // The device gives up on the first and offers it again. It is kept, as the laptop's: + // its first asking may be being done. + expect(await (await w.act("issue.comment", { issue: 7, text: "first, slow" }, ID(301))).json()).toEqual({ + ok: true, + held: true, + result: null, + waits: "asked", + }); + expect(await heldWaits(w)).toEqual([ + [ID(302), "machine"], + [ID(301), "asked"], + ]); + // GitHub takes comments again and the hour passes: this side makes neither. + w.ghRefuses.length = 0; + const asked = commented(w).length; + w.now.t += 61 * 60_000; + await wakeNow(w); + expect([commented(w).length, heldIds(w)]).toEqual([asked, [ID(302), ID(301)]]); + // The laptop finishes the first asking: made there, once, and the name is settled. + w.gate.wait = null; + open(); + expect(await (await first).json()).toMatchObject({ ok: true }); + expect([heldIds(w), w.ran.filter((r) => r.kind === "issue.comment").length]).toEqual([[ID(302)], 1]); + // What is left reached nobody, and is this side's again: made here, once. + expect(await heldWaits(w)).toEqual([[ID(302), "either"]]); + w.now.t += 2_000; + await wakeNow(w); + expect([commented(w).slice(asked), heldIds(w)]).toEqual([["second"], []]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + }); + + test("with no machine ever reporting, what only a machine can do is still dropped after a day, and said to have been", async () => { + const w = await primary(); + w.net.hostUp = false; + w.net.edgeUp = false; + const t0 = w.now.t; + expect(await (await w.act("message.send", { to: ["lane-1"], text: "nobody came" }, ID(81))).json()).toMatchObject({ + held: true, + }); + // Woken meanwhile (for the laptop gone quiet), it is still held, and not this side's to try. + await wake(w); + expect([w.now.t < t0 + 60 * 60_000, heldIds(w)]).toEqual([true, [ID(81)]]); + // Its next wake is the day's end of it. + await wake(w); + expect(w.now.t).toBe(t0 + 24 * 60 * 60_000 + 1_000); + expect(heldIds(w)).toEqual([]); + const { doc } = await w.core(); + expect(doc.acts.find((a: { id: string }) => a.id === ID(81))).toMatchObject({ + status: "failed", + note: expect.stringMatching(/more than a day/), + }); + }); }); describe("telling the owner, with no machine", () => { diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts index 22147bd91e..91893475f6 100644 --- a/pm-stack/console/test/outbox.test.ts +++ b/pm-stack/console/test/outbox.test.ts @@ -185,6 +185,20 @@ test("what each kind of answer does to an entry", () => { note: "Kept for the laptop, which will do it when it is back.", result: null, }); + // The platform says who it waits for, and that is what is said of it. + const heldNote = (waits: unknown) => + O.classify({ status: 200, body: { ok: true, held: true, result: null, waits } }).note; + expect(heldNote("machine")).toBe("Kept for the laptop, which will do it when it is back."); + expect(heldNote("either")).toBe( + "Kept: Cloudflare does it as soon as it can again, or the laptop if it is back first.", + ); + expect(heldNote("asked")).toBe( + "Kept: the laptop did not answer. It may have got this, and says what became of it when it is back.", + ); + // Something it does not know to say is said as the plain case, never as whatever came. + for (const waits of ["someone", "constructor", "toString", "", 3, null, {}]) { + expect([waits, heldNote(waits)]).toEqual([waits, "Kept for the laptop, which will do it when it is back."]); + } // Refused or failed, in the platform's own words: not tried again by itself. expect(O.classify({ status: 404, body: { error: "no such issue" } })).toEqual({ state: "failed",