Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pm-stack/console/edge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts
Android app this side knows of (`androidRelease`), beside the copy of
the laptop's build (`androidBuild`): that is how either arriving here
is checked from outside.
- **No class keeps the platform's `fetch` itself.** In the Worker
runtime `fetch` refuses to be called as a method of another object
("Illegal invocation"), and bun does not mind, so no test under bun
could see it: for the first day every notification the edge sent and
every read of the Android release failed that way. Each class keeps a
plain caller (`../src/plain.ts`); the tests hand the classes a fetch
that refuses as the runtime does (`asThePlatformFetch`); and the
deploy's run of the bundle in the runtime itself checks that the
state can make a request of its own. `/console/health` says why the
release could not be read when it could not
(`androidReleaseTrouble`).
- **The laptop reports** to `POST /console/edge/sync`: the sections of
state that changed, how current each unchanged one is, and what became
of anything held for it. The answer says whether anyone is looking, and
Expand Down
27 changes: 18 additions & 9 deletions pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
SECURITY,
sameSiteWrite,
} from "../../src/http.ts";
import { plain } from "../../src/plain.ts";
import { Notifier } from "../../src/notify.ts";
import { contact, Push } from "../../src/push.ts";
import type { Store } from "../../src/store.ts";
Expand Down Expand Up @@ -204,9 +205,9 @@ export class Edge {
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;
/** What GitHub last said of the released build, when, and whether it
* could be asked at all. */
private released: { at: number; asked: boolean; found: AndroidRelease | null } | null = null;
/** What GitHub last said of the released build, when, whether it
* could be asked at all, and if not, why. */
private released: { at: number; asked: boolean; found: AndroidRelease | null; trouble: string | null } | null = null;
private syncRefused: KeyedLimiter;
readonly docs: Docs;
readonly push: Push;
Expand All @@ -217,7 +218,7 @@ export class Edge {
constructor(options: EdgeOptions) {
this.kv = options.kv;
this.now = options.now ?? Date.now;
this.fetchImpl = options.fetchImpl ?? fetch;
this.fetchImpl = plain(options.fetchImpl ?? fetch);
this.direct = options.direct;
this.setAlarm = options.setAlarm ?? (async () => {});
this.syncRefused = new KeyedLimiter(SYNC_REFUSALS, 60_000, this.now);
Expand Down Expand Up @@ -274,11 +275,16 @@ export class Edge {
redirect: "follow",
signal: AbortSignal.timeout(RELEASE_ASK_MS),
});
if (res.status === 404) this.released = { at: now, asked: true, found: null };
else if (res.ok) this.released = { at: now, asked: true, found: androidRelease(await res.json()) };
else throw new Error(`http ${res.status}`);
} catch {
this.released = { at: now, asked: false, found: known?.found ?? null };
if (res.status === 404) this.released = { at: now, asked: true, found: null, trouble: null };
else if (res.ok) this.released = { at: now, asked: true, found: androidRelease(await res.json()), trouble: null };
else throw new Error(`GitHub answered ${res.status}`);
} catch (error) {
// Why it could not be asked is kept, and health says it: "none
// published" and "could not ask" are different things, and for a
// day the second looked like the first.
const e = error as Error;
const trouble = `${e.name && e.name !== "Error" ? `${e.name}: ` : ""}${e.message}`.slice(0, 160);
this.released = { at: now, asked: false, found: known?.found ?? null, trouble };
}
return this.released.found;
}
Expand Down Expand Up @@ -959,6 +965,9 @@ export class Edge {
// one. The release is public; this is how its arrival here is
// checked from outside. Null when none is published.
androidRelease: await this.releaseSaid(cfg),
// Why GitHub could not be asked, the last time it was tried;
// null when it answered (also when it answered "none").
androidReleaseTrouble: this.released?.trouble ?? null,
// Since this object last started: requests it answered as the
// owner's, and requests it left to the host to judge.
answered: this.sure,
Expand Down
12 changes: 12 additions & 0 deletions pm-stack/console/scripts/edge-smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,12 +224,24 @@ try {
// not answer a runner: either is said as null, and neither is a
// failure of this Worker. A release that is there must read as one.
const release = still.androidRelease as { name?: unknown; code?: unknown; built?: unknown } | null | undefined;
const trouble = still.androidReleaseTrouble as string | null | undefined;
check(
"health says which release of the Android app it knows of, or that it knows of none",
release === null ||
(typeof release?.name === "string" && Number.isInteger(release.code) && typeof release.built === "string"),
JSON.stringify(release),
);
// That read is a request the Worker's state makes of its own, with the
// fetch it keeps. This runtime refuses a fetch called as a method of
// another object ("Illegal invocation"), which no test under bun can
// see: it broke every notification and every read of the release for
// a day. GitHub not answering a runner is the network's business; the
// runtime refusing the call is ours.
check(
"the Worker's state can make a request of its own",
trouble === null || (typeof trouble === "string" && !/illegal invocation/i.test(trouble)),
`release ${JSON.stringify(release)}, trouble ${JSON.stringify(trouble)}`,
);
} catch (error) {
failed++;
console.log(`FAIL the run stopped: ${(error as Error).message}`);
Expand Down
12 changes: 10 additions & 2 deletions pm-stack/console/src/ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// resolved inside expose().
import type { Config } from "./config.ts";
import { OpError } from "./errors.ts";
import { plain } from "./plain.ts";

export interface RunResult {
code: number;
Expand Down Expand Up @@ -170,11 +171,18 @@ function id(value: unknown, name: string): number {
export class Ops {
private queueToken: string | null = null;

/** How the queue store and the dashboard are reached. Kept as a plain
* caller: these classes also run at the edge, where the platform's
* fetch may not be called as a method (see `plain`). */
readonly fetchImpl: Fetch;

constructor(
readonly cfg: Config,
readonly run: Run = realRun,
readonly fetchImpl: Fetch = fetch as unknown as Fetch,
) {}
fetchImpl: Fetch = fetch as unknown as Fetch,
) {
this.fetchImpl = plain(fetchImpl);
}

async must(argv: string[], opts?: { stdin?: string; timeoutMs?: number }): Promise<string> {
const r = await this.run(argv, opts);
Expand Down
15 changes: 15 additions & 0 deletions pm-stack/console/src/plain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// One function, with nothing else in its file so that anything may import it.

/** A function that calls `f` plainly, for keeping in place of `f`.
*
* The Worker runtime's fetch refuses to be called as a method of
* anything else: `this.fetchImpl(url)`, with the platform's fetch kept
* in `fetchImpl`, throws "Illegal invocation" there, and only there (bun
* and Node do not mind, so nothing run under them notices). A function
* kept on an object is called that way sooner or later; for a day every
* notification the edge sent, and every read of the Android release,
* failed on it. So nothing here keeps a fetch it was given: it keeps
* this. */
export function plain<A extends unknown[], R>(f: (...args: A) => R): (...args: A) => R {
return (...args: A) => f(...args);
}
3 changes: 2 additions & 1 deletion pm-stack/console/src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// starts; if the host dies part-way, the action is reported as
// interrupted instead of being run a second time.
import type { Docs } from "./docs.ts";
import { plain } from "./plain.ts";
import {
APK_LIMIT,
type ApkReport,
Expand Down Expand Up @@ -91,7 +92,7 @@ export class EdgeLink {

constructor(private o: LinkOptions) {
this.now = o.now ?? Date.now;
this.fetchImpl = o.fetchImpl ?? fetch;
this.fetchImpl = plain(o.fetchImpl ?? fetch);
this.log = o.log ?? ((line) => console.error(`pm-console: edge: ${line}`));
}

Expand Down
7 changes: 5 additions & 2 deletions pm-stack/console/test/direct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { readConfig } from "../src/config.ts";
import { directClasses, directConfig, directRead, edgeRun } from "../edge/src/direct.ts";
import type { Fetch } from "../src/ops.ts";
import type { EdgeConfig } from "../src/edge-proto.ts";
import { asThePlatformFetch } from "./support.ts";

const cfg = readConfig({ HOME: "/h", PM_CONSOLE_OWNER_EMAILS: "owner@example.com" });
const edgeConfig: EdgeConfig = {
Expand Down Expand Up @@ -37,8 +38,10 @@ function harness() {
calls.push({ url, init });
return { ok: answer.ok, status: answer.status, json: async () => answer.body };
}) as unknown as Fetch;
const run = edgeRun(directConfig(edgeConfig), { githubToken: "gh-test", queueToken: "queue-test" }, fetchImpl);
return { calls, answer, fetchImpl, run };
// As the Worker runtime's fetch is: not to be called as a method.
const strict = asThePlatformFetch(fetchImpl) as typeof fetchImpl;
const run = edgeRun(directConfig(edgeConfig), { githubToken: "gh-test", queueToken: "queue-test" }, strict);
return { calls, answer, fetchImpl: strict, run };
}

describe("the edge's run: GitHub through REST", () => {
Expand Down
21 changes: 18 additions & 3 deletions pm-stack/console/test/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { Ops } from "../src/ops.ts";
import { type Deps, handle, heldRunner, marked } from "../src/server.ts";
import { memoryStore } from "../src/store.ts";
import { EdgeLink } from "../src/sync.ts";
import { browser, signer } from "./support.ts";
import { asThePlatformFetch, browser, signer } from "./support.ts";

const HOST = "pm.example";
const OWNER = "owner@example.com";
Expand Down Expand Up @@ -451,9 +451,15 @@ async function setup(options: { direct?: boolean } = {}) {
new Edge({
kv,
now: clock,
fetchImpl: outward as never,
// As the Worker runtime's fetch is: not to be called as a method.
fetchImpl: asThePlatformFetch(outward) as never,
direct: options.direct
? { enabled: true, githubToken: "gh-test", queueToken: "queue-test", fetchImpl: directFetch }
? {
enabled: true,
githubToken: "gh-test",
queueToken: "queue-test",
fetchImpl: asThePlatformFetch(directFetch) as typeof directFetch,
}
: undefined,
setAlarm: async (at) => {
alarm.at = at;
Expand Down Expand Up @@ -810,6 +816,7 @@ describe("before the host's first report", () => {
hostVersion: null,
androidBuild: null,
androidRelease: null,
androidReleaseTrouble: null,
answered: 0,
deferred: 0,
version: "test",
Expand Down Expand Up @@ -1706,6 +1713,12 @@ describe("the Android build", () => {
w.now.t += 60_000;
expect((await ask())?.name).toBe("2026.11.23-a3a547e");
expect(w.github.asked.length).toBe(4);
// Health says why it could not be asked, to anyone: from outside,
// "none published" and "could not ask" must not look the same.
const trouble = async () =>
((await (await w.browse("/console/health", { token: null })).json()) as Record<string, unknown>)
.androidReleaseTrouble;
expect(await trouble()).toBe("github: connection reset");
// With GitHub out of reach the file cannot be fetched either: the download falls back to the laptop.
w.build.bytes = apk(1);
w.build.at = w.now.t;
Expand All @@ -1717,6 +1730,8 @@ describe("the Android build", () => {
w.github.version = null;
w.now.t += 60_000;
expect(await ask()).toBeNull();
// And once GitHub answers again (here with "none"), there is no trouble to report.
expect(await trouble()).toBeNull();
});

test("a copy whose replacement stops half-way is not handed out as either build", async () => {
Expand Down
15 changes: 15 additions & 0 deletions pm-stack/console/test/support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,18 @@ export async function signer(kid: string): Promise<Signer> {
},
};
}

/** A stand-in for the platform's fetch that behaves as the Worker
* runtime's does in one respect bun's does not: it refuses to be called
* as a method of some other object. There, `this.fetchImpl(url)` with
* the platform's fetch kept in `fetchImpl` throws "Illegal invocation",
* and under bun it works, so a test that hands a class a plain function
* cannot see the fault. Hand it this. */
export function asThePlatformFetch<A extends unknown[], R>(answer: (...args: A) => R): (...args: A) => R {
return function (this: unknown, ...args: A): R {
if (this !== undefined && this !== globalThis) {
throw new TypeError("Illegal invocation: function called with incorrect `this` reference.");
}
return answer(...args);
};
}
4 changes: 3 additions & 1 deletion pm-stack/console/test/work.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { Docs } from "../src/docs.ts";
import { type Fetch, OpError, Ops, type Run } from "../src/ops.ts";
import { type Deps, handle, loaders } from "../src/server.ts";
import { promptPacket, Work } from "../src/work.ts";
import { asThePlatformFetch } from "./support.ts";

const CFG = readConfig({ HOME: "/h" });
const REPO = "developing-today/code";
Expand Down Expand Up @@ -74,7 +75,8 @@ function world(opts: {
const a = opts.commands?.(argv, o?.stdin) ?? "{}";
return typeof a === "string" ? { code: 0, stdout: a, stderr: "" } : { code: a.code, stdout: "", stderr: a.stderr };
};
const ops = new Ops(CFG, run, fetchImpl);
// As the Worker runtime's fetch is (these classes run there too): not to be called as a method.
const ops = new Ops(CFG, run, asThePlatformFetch(fetchImpl) as Fetch);
return { ops, sqls, dashed, calls, gh: () => calls.filter((c) => c.argv[1] === "gh").map((c) => c.argv.slice(3)) };
}

Expand Down