diff --git a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md index 151f8c6ce1..25fc12eabd 100644 --- a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md +++ b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md @@ -171,3 +171,51 @@ One change nobody asked for: the contact handed to push services with every notification was the owner's address. It is now the project's page. Delivery does not depend on it, and an address has no reason to travel to Google or Mozilla with each message. + +## 2026-11-23T00:20Z Update: the owner's switch, the report's limits, the build's copy + +Direct mode (the edge reading and acting by itself while the laptop is +away) was built by the fleet in #12579 and deployed switched off. What +was added around it since: + +- **The switch is the owner's, in the app** (#12712). More, Laptop away + says what the mode covers and what turning it on hands over: the + repository automation token and the queue store token, as secrets of + the Worker. It runs `expose.py --edge-direct` on the laptop, where + the tokens are. The script now sends them through Cloudflare's API + rather than a tool that had to be installed; turning the mode off + takes them away again; an attempt that fails part-way leaves the + Worker holding nothing; a mode that is on gets back what the Worker + has lost; and runs take turns, so the timer cannot undo what the app + is doing. +- **Reports are refused unread** when they say they are too large or + are not shaped like a report, and an address with twenty refused + reports in a minute is refused unread until the minute is out + (#12715). A report the laptop signed that is merely wrong is not held + against its address. +- **The edge says which commit the laptop runs** (`hostVersion` in + `/console/health`, #12715). That a merge has reached the laptop can + be seen from anywhere. It was first used to confirm exactly that when + the session had no other way to look at the laptop. +- **A unit that keeps failing on its timer is reported**, once, with + what it is for, and so is its mending (#12719). This is what was + missing when `pm-git-sync` failed for two hours unseen. +- **The signed Android build is kept at the edge**, sent once per + build in the laptop's report and kept only if it matches its + fingerprint. The download is served from that copy when it is the + newest build or the laptop is away. + +Still open, and why: + +- Direct mode is off until the owner turns it on. Its check against + the real queue store and GitHub runs when it is turned on and shows + on the same screen; the five-minute laptop-away check in #12518 has + not been done. +- A rebuild commit that changes `flake.lock` still leaves the laptop's + `main` ahead and behind at once (#12520). It is now reported within + five minutes instead of never; carrying the commit to `main` without + a person is not built, because it has to be tried on the laptop. +- The deploy still uses `wrangler deploy`. The `cf` release flow is + staged in #12561 and needs two protected environments with their own + tokens before it can run. +- The Android project is still on androidbrowserhelper 2.5.0. diff --git a/planning/plans/2026-11-21_results-first.md b/planning/plans/2026-11-21_results-first.md index 0ab9ae3978..82c8f365cf 100644 --- a/planning/plans/2026-11-21_results-first.md +++ b/planning/plans/2026-11-21_results-first.md @@ -335,3 +335,4 @@ To undo: revert the plan's PR. The skills are additive and are loaded by descrip - 2026-11-22: The console is served from Cloudflare. #12501 gave the Android app its own parts (widget, share, dictation, tile, shortcuts) and a signed-in link for the widget. #12505 put a Worker, `pm-console-edge`, in front of the laptop: it serves the app, keeps the laptop's last report, holds twelve kinds of action for the laptop's return, sends notifications, and says when the laptop has gone quiet. #12511 finished the cutover (the setup script's health check was being refused as `Python-urllib`) and fixed what the first review found, including an action that could run twice. Live check: `curl https://pm-console-edge.developing-today.workers.dev/console/health` answers `configured: true` with a current `hostSeen`. Not checked: the owner's real sign-in at the edge; the counters `answered` and `deferred` in that answer show which happened at the first visit. - 2026-11-22: The laptop had stopped deploying merges for two hours: an empty rebuild marker commit on its `main` made the fast-forward-only sync stand still, 28 merges behind. Repaired by hand, then #12515 taught `pm-git-sync` to move empty markers aside (in service after the next system rebuild). A rebuild commit that changes `flake.lock` still diverges (#12520). - 2026-11-22: #12517 added More, Sign-in: the steps, the two addresses and a form that turn Google sign-in on from the app. The Google client itself still has to be made by a signed-in person (#12417). Not built: the edge acting on the queue and GitHub by itself while the laptop is away; designed in #12518. Also filed: #12519 (linked phones across an edge on/off change), #12521 (limit the report endpoint, Android build at the edge, `cf` deploy flow). +- 2026-11-23: The fleet built the edge acting by itself while the laptop is away (#12579); it is deployed and off. #12712 made turning it on the owner's switch in the app (More, Laptop away) and made the script behind it need nothing installed. #12715: reports refused unread from an address that keeps sending bad ones, and `hostVersion` in the edge's health, which showed the laptop taking merges with no access to the laptop. #12719: a unit that keeps failing on its timer is reported. The signed Android build is kept at the edge. Open: turning direct mode on and its laptop-away check (#12518), rebuild commits that change `flake.lock` (#12520), the `cf` deploy flow (#12561), the Android library upgrade. diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index f73f325ada..492394a90e 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -23,6 +23,8 @@ import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts"; import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; import { + type ApkReport, + apkReport, type EdgeConfig, edgeConfig, HELD_FOR_MS, @@ -47,6 +49,7 @@ import { json, manifest, type Phones, + SECURITY, sameSiteWrite, } from "../../src/http.ts"; import { Notifier } from "../../src/notify.ts"; @@ -85,6 +88,18 @@ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/; /** Reports from one address that may fail their checks in a minute * before that address is refused unread. The host's own never fail. */ const SYNC_REFUSALS = 20; +/** The Android build is kept in pieces of this many bytes. */ +const APK_CHUNK = 512 * 1024; +/** A build that could not be kept is asked for again no sooner than this. */ +const APK_RETRY_MS = 10 * 60_000; +/** With no report for this long, the laptop is not there to ask. */ +const HOST_QUIET_MS = 60_000; + +interface ApkMeta { + sha256: string; + size: number; + at: number; +} const ACT_LIMIT = 256 * 1024; const HELD_MAX = 100; const ACTS_KEPT = 30; @@ -171,6 +186,10 @@ export class Edge { private sure = 0; private unsure = 0; private hostVersion: string | null = null; + private latestApk: ApkMeta | null | undefined; + private keptApk: (ApkMeta & { chunks: number }) | null | undefined; + /** The build that could not be kept when it was last sent, and when. */ + private apkFailed: { sha256: string; at: number } | null = null; private syncRefused: KeyedLimiter; readonly docs: Docs; readonly push: Push; @@ -219,6 +238,67 @@ export class Edge { this.table = ownActions(this.push, devices); } + // ---- the Android build ------------------------------------------------- + + /** What the app is told of the copy kept here. */ + private async apkState(): Promise<{ at: number; current: boolean } | null> { + const kept = await this.apkKept(); + if (!kept) return null; + const latest = await this.apkLatest(); + return { at: kept.at, current: !latest || latest.sha256 === kept.sha256 }; + } + + /** The build the host last said it has. */ + private async apkLatest(): Promise { + if (this.latestApk === undefined) + this.latestApk = ((await this.kv.get("apk:latest")) as ApkMeta | undefined) ?? null; + return this.latestApk; + } + + /** The build a copy of which is kept here. */ + private async apkKept(): Promise<(ApkMeta & { chunks: number }) | null> { + if (this.keptApk === undefined) { + this.keptApk = ((await this.kv.get("apk")) as (ApkMeta & { chunks: number }) | undefined) ?? null; + } + return this.keptApk; + } + + /** Take in a build the host sent, if it is what the host says it is. */ + private async keepApk(build: ApkReport): Promise { + const bytes = Uint8Array.from(atob(build.data ?? ""), (c) => c.charCodeAt(0)); + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + const sha256 = [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""); + if (bytes.byteLength !== build.size || sha256 !== build.sha256) + throw new Error("the build sent is not the build described"); + const before = await this.apkKept(); + const chunks = Math.ceil(bytes.byteLength / APK_CHUNK); + for (let i = 0; i < chunks; i++) await this.kv.put(`apk:${i}`, bytes.slice(i * APK_CHUNK, (i + 1) * APK_CHUNK)); + for (let i = chunks; i < (before?.chunks ?? 0); i++) await this.kv.delete(`apk:${i}`); + this.keptApk = { sha256, size: build.size, at: build.at, chunks }; + await this.kv.put("apk", this.keptApk); + } + + /** The kept build, as a download. */ + private async serveApk(kept: ApkMeta & { chunks: number }): Promise { + const bytes = new Uint8Array(kept.size); + let at = 0; + for (let i = 0; i < kept.chunks; i++) { + const part = (await this.kv.get(`apk:${i}`)) as Uint8Array | undefined; + if (!part) return json({ error: "the copy of the Android build kept here is incomplete" }, 503); + bytes.set(part, at); + at += part.byteLength; + } + return new Response(bytes, { + headers: { + "Content-Type": "application/vnd.android.package-archive", + "Content-Disposition": 'attachment; filename="pm-console.apk"', + "Cache-Control": "no-store", + "X-Build-At": String(kept.at), + ...SECURITY, + }, + }); + } + // ---- what is kept ------------------------------------------------------ private async config(): Promise { @@ -670,8 +750,33 @@ export class Edge { await this.notifier.tick().catch((error) => console.error(`pm-edge: notify: ${(error as Error).message}`)); } + // The Android build: what the host has now, and the build itself + // when the host sent it because this side asked. + const build = apkReport(msg.apk); + if ( + JSON.stringify(build && { sha256: build.sha256, size: build.size, at: build.at }) !== + JSON.stringify(await this.apkLatest()) + ) { + this.latestApk = build && { sha256: build.sha256, size: build.size, at: build.at }; + if (this.latestApk) await this.kv.put("apk:latest", this.latestApk); + else await this.kv.delete("apk:latest"); + } + if (build?.data) { + await this.keepApk(build).catch((error) => { + // Not kept (it did not match its description, or could not be + // stored). It is not asked for again at once: a build that + // fails every time would otherwise be sent with every report. + this.apkFailed = { sha256: build.sha256, at: now }; + console.error(`pm-edge: apk: ${(error as Error).message}`); + }); + } + // What the host has and this side has lost (its storage was reset). const want: string[] = []; + const kept = await this.apkKept(); + const failedLately = + this.apkFailed?.sha256 === this.latestApk?.sha256 && now - (this.apkFailed?.at ?? 0) < APK_RETRY_MS; + if (this.latestApk && kept?.sha256 !== this.latestApk.sha256 && !failedLately) want.push("apk"); for (const name of Object.keys(SECTIONS)) { if (typeof msg.have?.[name]?.hash === "string" && !(await this.mirror(name))) want.push(name); } @@ -745,6 +850,9 @@ export class Edge { hostSeen: this.hostSeen || null, // The commit the host's console is running, as it last said. hostVersion: this.hostVersion, + // The copy of the Android build kept here: when it was built, + // and whether it is the host's newest. Null if there is none. + androidBuild: await this.apkState(), // Since this object last started: requests it answered as the // owner's, and requests it left to the host to judge. answered: this.sure, @@ -794,6 +902,17 @@ export class Edge { if (method === "GET" && Object.hasOwn(STATIC, rest)) { return next("asset", { path: `${BASE}/${rest}`, type: STATIC[rest] }); } + if (method === "GET" && rest === "pm-console.apk") { + // The newest build is the laptop's. The copy here is served when + // it is that build, or when the laptop is not there to ask. After + // a restart, when the laptop was last heard from has to be read + // back first, or it would look as if it never had been. + await this.ready(); + const kept = await this.apkKept(); + const latest = await this.apkLatest(); + const quiet = this.now() - (this.hostSeen ?? 0) >= HOST_QUIET_MS; + if (kept && (kept.sha256 === latest?.sha256 || quiet)) return this.serveApk(kept); + } if (!rest.startsWith("api/")) return next("relay", { mode: "live" }); const seg = rest.slice(4).split("/"); @@ -805,7 +924,11 @@ export class Edge { ...who, repo: cfg.repo, queue: cfg.queue, - androidApp: cfg.androidApp, + // There is a build to hand out if the laptop has one or a + // copy is kept here; `androidBuild` says of the copy when it + // was built and whether it is the laptop's newest. + androidApp: cfg.androidApp || (await this.apkKept()) !== null, + androidBuild: await this.apkState(), androidPackage: cfg.androidPackage, edge: true, }); diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 1bf7a2a36d..6735247cce 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -1236,6 +1236,15 @@ async function viewPhone(sub) { h("li", {}, h("b", {}, "Notifications. "), "Turn them on under Notifications; they arrive as the app's own."), ), me.androidApp ? h("div", { class: "row end" }, h("a", { class: "button", href: "/console/pm-console.apk" }, "Download the app")) : null, + // Served from Cloudflare's copy when the laptop is away: say so + // when that copy is not the laptop's newest build. + me.androidBuild && !me.androidBuild.current + ? h( + "p", + { class: "meta" }, + `With the laptop away you get the copy kept at Cloudflare, built ${ago(new Date(me.androidBuild.at).toISOString())}. The laptop has a newer build, which will be here once it has reported again.`, + ) + : null, ), ); return out; diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 71e3de1d80..5daf14e4ac 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -57,6 +57,11 @@ export interface SyncRequest { v: 1; /** Milliseconds, later than every sync before it. */ at: number; + /** The signed Android build the host has, if it has one: its + * fingerprint, size and date, and the build itself (base64) only in a + * report that follows the edge asking for it. The edge keeps a copy, + * so the app can be downloaded while the host is away. */ + apk?: ApkReport; /** The commit the host's console is running. The edge says it in its * health answer, so whether a merge has reached the host can be seen * from anywhere, without reaching the host. */ @@ -91,6 +96,37 @@ export interface Held { at: string; } +export interface ApkReport { + sha256: string; + size: number; + /** When the build was put in place on the host, in milliseconds. */ + at: number; + data?: string; +} + +/** The largest Android build that is carried in a report. */ +export const APK_LIMIT = 5 * 1024 * 1024; +/** What the host keeps a report under, with room to spare below what + * the edge refuses as too large (8 MiB). A report that would carry the + * build past this carries the build alone, and the sections follow in + * the next one. */ +export const REPORT_ROOM = 7.5 * 1024 * 1024; + +/** A build's description as a report may give it, or null. */ +export function apkReport(value: unknown): ApkReport | null { + const v = value as Record | null; + if (!v || typeof v !== "object") return null; + if (typeof v.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(v.sha256)) return null; + if (typeof v.size !== "number" || !Number.isSafeInteger(v.size) || v.size <= 0 || v.size > APK_LIMIT) return null; + if (typeof v.at !== "number" || !Number.isFinite(v.at)) return null; + return { + sha256: v.sha256, + size: v.size, + at: v.at, + ...(typeof v.data === "string" ? { data: v.data } : {}), + }; +} + export interface SyncResponse { ok: true; /** Someone has the app open: keep every section fresh. */ diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 20a6dcd776..3db3645503 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -543,6 +543,27 @@ export function marked(res: Response): Response { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }); } +/** The signed Android build at `path`, described for the edge. Its + * fingerprint is worked out again only when the file has changed. */ +export function androidBuild(path: string) { + let known: { mtime: number; size: number; sha256: string } | null = null; + return async () => { + const file = Bun.file(path); + if (!(await file.exists())) return null; + const { lastModified: mtime, size } = file; + if (!known || known.mtime !== mtime || known.size !== size) { + const sha256 = new Bun.CryptoHasher("sha256").update(await file.arrayBuffer()).digest("hex"); + known = { mtime, size, sha256 }; + } + return { + sha256: known.sha256, + size, + at: mtime, + read: async () => new Uint8Array(await Bun.file(path).arrayBuffer()), + }; + }; +} + /** The commit this console was started from, or nothing if it cannot * be told (not a checkout, no git). The service is restarted when a * merge is put into service, so this is the code that is running. */ @@ -588,6 +609,7 @@ if (import.meta.main) { ? new EdgeLink({ url: cfg.edgeUrl, version: await runningCommit(), + apk: androidBuild(cfg.androidApk), keys: fileStore(cfg.edgeKeyFile), done: fileStore(cfg.edgeDoneFile), docs, diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index df311c6963..7bbca73de9 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -11,6 +11,8 @@ // interrupted instead of being run a second time. import type { Docs } from "./docs.ts"; import { + APK_LIMIT, + type ApkReport, type EdgeConfig, type Held, HOLDABLE, @@ -19,6 +21,7 @@ import { type PublicKey, type PhoneLinks, publicKey, + REPORT_ROOM, type SyncRequest, type SyncResponse, sign, @@ -50,6 +53,9 @@ export interface LinkOptions { run: (held: Held) => Promise; /** The commit this console is running, if it could be found. */ version?: string; + /** The signed Android build on this host, if there is one, and a way + * to read it when the edge asks for it. */ + apk?: () => Promise<{ sha256: string; size: number; at: number; read: () => Promise } | null>; fetchImpl?: typeof fetch; now?: () => number; log?: (line: string) => void; @@ -182,13 +188,28 @@ export class EdgeLink { try { const pair = await this.keys(); const snapshot = this.o.docs.snapshot(); - const sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); + let sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); const acks = [...this.acks]; const at = Math.max(this.now(), this.lastAt + 1); + // The Android build: always what it is, and the build itself only + // when the edge has said it lacks this one. + const build = (await this.o.apk?.().catch(() => null)) ?? null; + const apk: ApkReport | null = + build && build.size <= APK_LIMIT ? { sha256: build.sha256, size: build.size, at: build.at } : null; + if (apk && build && this.want.has("apk")) { + apk.data = Buffer.from(await build.read()).toString("base64"); + // The build and large sections together could pass what the edge + // takes in one report, and a report refused as too large would be + // built the same way again and again. So the build goes alone + // then; the sections are not marked sent and follow next time. + const others = sections.reduce((sum, s) => sum + JSON.stringify(s.data).length, 0); + if (apk.data.length + others > REPORT_ROOM) sections = []; + } const message: SyncRequest & { acts: unknown } = { v: 1, at, ...(this.o.version ? { version: this.o.version } : {}), + ...(apk ? { apk } : {}), config: await this.o.config(), sections, have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])), @@ -251,7 +272,9 @@ export class EdgeLink { } const answer = await this.once(); // Something was done or is wanted: say so at once. - if (this.acks.length > 0 || this.want.size > 0) return 500; + // (The Android build is not such a thing: it waits for the next + // ordinary report, and half a megabyte is never sent in a hurry.) + if (this.acks.length > 0 || [...this.want].some((name) => name !== "apk")) return 500; return answer?.watching || this.o.docs.watched() ? FAST_MS : IDLE_MS; } diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index e7cddfbfff..b3ea25c41e 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -551,6 +551,13 @@ async function setup(options: { direct?: boolean } = {}) { }, }; const net = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false }; + /** The signed Android build on the host, if any, and how often it was read to be sent. */ + const build: { bytes: Uint8Array | null; at: number; reads: number; corrupt: boolean } = { + bytes: null, + at: 0, + reads: 0, + corrupt: false, + }; /** Requests to the host still running after the edge stopped waiting. */ const stillRunning: Promise[] = []; const hostSaw: string[] = []; @@ -606,6 +613,20 @@ async function setup(options: { direct?: boolean } = {}) { const makeLink = () => new EdgeLink({ version: "0123abcd4567", + apk: async () => { + if (!build.bytes) return null; + const bytes = build.bytes; + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + return { + sha256: [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), + size: bytes.byteLength, + at: build.at, + read: async () => { + build.reads++; + return build.corrupt ? bytes.map((b) => b ^ 1) : bytes; + }, + }; + }, url: `https://${HOST}`, keys, done, @@ -700,6 +721,7 @@ async function setup(options: { direct?: boolean } = {}) { act, core, hostReads, + build, failing, gate, stillRunning, @@ -738,6 +760,7 @@ describe("before the host's first report", () => { selfCheck: null, hostSeen: null, hostVersion: null, + androidBuild: null, answered: 0, deferred: 0, version: "test", @@ -1286,6 +1309,164 @@ describe("actions", () => { }); }); +describe("the Android build", () => { + const apk = (seed: number, size = 700_000) => Uint8Array.from({ length: size }, (_, i) => (i * 31 + seed) % 251); + const report = async (w: Awaited>) => { + w.now.t += 1_000; + return w.link.now.once(); + }; + const download = async (w: Awaited>) => { + const res = await w.browse("/console/pm-console.apk"); + return { res, bytes: new Uint8Array(await res.arrayBuffer()) }; + }; + + test("a copy is kept at the edge, sent once, and served when the laptop is away", async () => { + const w = await setup(); + await w.hostReads(); + // The host has no build: nothing is asked for, and the app is told there is none. + expect((await report(w))?.want).not.toContain("apk"); + w.build.bytes = apk(1); + w.build.at = w.now.t; + // It has one now. The first report only describes it; the edge asks; the next carries it. + // Being asked for the build does not hurry the host the way a missing section does. + w.now.t += 1_000; + expect(await w.link.now.turn()).toBeGreaterThan(500); + expect(w.link.now.last?.want).toContain("apk"); + expect(w.build.reads).toBe(0); + expect((await report(w))?.want).not.toContain("apk"); + expect(w.build.reads).toBe(1); + // After that it is not sent again, however many reports follow. + await report(w); + await report(w); + expect(w.build.reads).toBe(1); + // The copy is the laptop's build, so it is served from here without asking the laptop. + w.hostSaw.length = 0; + let got = await download(w); + expect(got.res.status).toBe(200); + expect(got.res.headers.get("content-type")).toBe("application/vnd.android.package-archive"); + expect(got.res.headers.get("content-disposition")).toBe('attachment; filename="pm-console.apk"'); + expect(got.bytes).toEqual(apk(1)); + expect(w.hostSaw).toEqual([]); + // The edge restarts and the laptop goes away: still served, byte for byte. + w.edge.now = w.makeEdge(); + w.net.hostUp = false; + w.now.t += 10 * 60_000; + got = await download(w); + expect(got.res.status).toBe(200); + expect(got.bytes).toEqual(apk(1)); + const me = (await (await w.browse("/console/api/me")).json()) as Record; + expect(me.androidApp).toBe(true); + expect(me.androidBuild).toEqual({ at: w.build.at, current: true }); + // Health says the same of the copy, to anyone: it is how its arrival is checked from outside. + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health.androidBuild).toEqual({ at: w.build.at, current: true }); + // Only the owner gets it. + expect((await w.browse("/console/pm-console.apk", { token: null })).status).not.toBe(200); + }); + + test("a newer build on the laptop is fetched, and until then the app says the copy is older", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(1); + w.build.at = w.now.t; + await report(w); + await report(w); + const first = w.build.at; + // A new build is signed on the laptop. The edge has heard of it but does not have it yet. + w.build.bytes = apk(2, 900_000); + w.build.at = w.now.t + 500; + expect((await report(w))?.want).toContain("apk"); + let me = (await (await w.browse("/console/api/me")).json()) as Record; + expect(me.androidBuild).toEqual({ at: first, current: false }); + // The laptop is there, so the download is the laptop's: the newest. + w.hostSaw.length = 0; + await w.browse("/console/pm-console.apk"); + expect(w.hostSaw).toEqual(["GET /console/pm-console.apk"]); + // The next report brings it, and then the copy is current again. + await report(w); + me = (await (await w.browse("/console/api/me")).json()) as Record; + expect(me.androidBuild).toEqual({ at: w.build.at, current: true }); + w.net.hostUp = false; + w.now.t += 10 * 60_000; + expect((await download(w)).bytes).toEqual(apk(2, 900_000)); + }); + + test("after the edge restarts, a laptop that is there is still asked for its newer build", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(1); + w.build.at = w.now.t; + await report(w); + await report(w); + // A newer build is announced, and the edge restarts before it has a copy. + w.build.bytes = apk(2); + w.build.at = w.now.t + 500; + await report(w); + w.edge.now = w.makeEdge(); + w.hostSaw.length = 0; + const got = await download(w); + // The laptop reported seconds ago: the download is its newest build, not the older copy. + expect(w.hostSaw).toEqual(["GET /console/pm-console.apk"]); + expect(got.bytes).not.toEqual(apk(1)); + }); + + test("a build and large sections that will not fit one report go in two, and both arrive", async () => { + const w = await setup(); + await w.hostReads(); + await report(w); + // Nearly the largest build that is carried, and three megabytes of questions changed at once. + w.build.bytes = apk(5, 4_900_000); + w.build.at = w.now.t; + await report(w); // described; the edge asks for it + w.data.questions = { sets: [{ id: "big", text: "q".repeat(3_000_000) }] }; + w.now.t += 11_000; + await w.hostReads(); + // Every report from here is accepted: none is refused as too large. + const answers = [await report(w), await report(w), await report(w)]; + expect(answers.every((answer) => answer?.ok === true)).toBe(true); + expect((w.stored.get("apk") as { size: number }).size).toBe(4_900_000); + // And the questions arrived whole, in the report after the build's. + const pieces = (w.stored.get("m:questions") as { chunks: number } | undefined)?.chunks ?? 0; + expect(pieces).toBeGreaterThan(1); + let text = ""; + for (let i = 0; i < pieces; i++) text += String(w.stored.get(`m:questions:${i}`)); + expect(JSON.parse(text).sets[0].text.length).toBe(3_000_000); + }); + + test("a build that is not the one described is not kept, and one too large is not sent", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(3); + w.build.at = w.now.t; + w.build.corrupt = true; + await report(w); + await report(w); + // What arrived did not match its fingerprint: nothing is kept. + expect(w.stored.has("apk")).toBe(false); + expect(w.build.reads).toBe(1); + // It is not asked for again with every report: a build that fails + // every time would be half a megabyte in each of them. + for (let i = 0; i < 20; i++) expect((await report(w))?.want).not.toContain("apk"); + expect(w.build.reads).toBe(1); + // Ten minutes on it is asked for once more, and this time it is right. + w.build.corrupt = false; + w.now.t += 10 * 60_000; + expect((await report(w))?.want).toContain("apk"); + await report(w); + expect(w.build.reads).toBe(2); + expect((w.stored.get("apk") as { size: number }).size).toBe(700_000); + // A build too large to carry in a report is never read to be sent. + const big = await setup(); + await big.hostReads(); + big.build.bytes = new Uint8Array(5 * 1024 * 1024 + 1); + big.build.at = big.now.t; + await report(big); + await report(big); + expect(big.build.reads).toBe(0); + expect(big.stored.has("apk")).toBe(false); + }); +}); + describe("the host's report is the host's", () => { const report = async ( w: Awaited>, diff --git a/pm-stack/console/test/signin.test.ts b/pm-stack/console/test/signin.test.ts index 9de318034c..5138da6931 100644 --- a/pm-stack/console/test/signin.test.ts +++ b/pm-stack/console/test/signin.test.ts @@ -168,3 +168,33 @@ describe("sign-in", () => { expect(failed.message).not.toContain(VALUE); }); }); + +test("the Android build on the laptop is described for the edge, and fingerprinted only when it changes", async () => { + const { androidBuild } = await import("../src/server.ts"); + const { mkdtempSync, writeFileSync, utimesSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const dir = mkdtempSync(join(tmpdir(), "pm-apk-")); + try { + const path = join(dir, "pm-console.apk"); + const build = androidBuild(path); + // No build installed: nothing to describe. + expect(await build()).toBeNull(); + writeFileSync(path, "first build"); + const one = await build(); + // SHA-256 of the text, worked out separately with sha256sum. + expect(one?.sha256).toBe("f3adf3a4014af2dc15376ed0b22ac63cae9073430512bad33659b8f352c9fb30"); + expect(one?.size).toBe(11); + expect(new TextDecoder().decode(await one?.read())).toBe("first build"); + // Unchanged: the same description. + expect((await build())?.sha256).toBe(one?.sha256); + // A new build put in its place, same length: a new fingerprint and date. + writeFileSync(path, "other build"); + utimesSync(path, new Date(Date.now() + 5_000), new Date(Date.now() + 5_000)); + const two = await build(); + expect(two?.sha256).not.toBe(one?.sha256); + expect(two?.at).toBeGreaterThan(one?.at ?? 0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});