Skip to content
Open
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
22 changes: 13 additions & 9 deletions pm-stack/console/edge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ runs the fleet's tools can be reached.
| -------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------- |
| The app's page, script and icons | edge | unchanged |
| Checking who is calling | edge, and again on the laptop | the edge still answers the owner; anyone it is unsure of gets nothing |
| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | served as of the last report, with that time shown |
| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | pull requests can be refreshed from GitHub after one minute of silence; other data remains as of the last report |
| Notifications: keys, subscriptions, sending | edge | unchanged; and one says the laptop has gone quiet |
| Linked phones and the widget's summary | edge | unchanged |
| Actions safe to do late (prompts, answers, comments, …) | laptop, relayed at once | held at the edge, run once when it is back, dropped after a day and said so |
Expand Down Expand Up @@ -77,9 +77,12 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts
only actions on the late list, and records each in its audit log as
`via: edge-held` with who took it and when.

The Worker has no secrets configured. The keys it uses it made itself
(notification signing) or were published to it (the laptop's, the
sign-in issuer's).
The optional direct pull-request read uses the `GITHUB_TOKEN` Worker
secret only when `GITHUB_READ_ENABLED=on`. It is disabled by default;
`/console/health` reports whether it is enabled, whether the secret exists,
and whether the capability is ready. The token is sent only to GitHub's
read endpoint and is never returned by health. Other edge reads and writes
are not implemented by this first slice.

## Deploy, and going back

Expand Down Expand Up @@ -116,10 +119,11 @@ simply what is behind the hostname.

## Limits worth knowing

- State at the edge is the laptop's last report. With the laptop gone it
ages, and the app says how old it is; it does not go on changing.
- Reading the queue and filing a prompt straight from the edge, with the
laptop off, is not built: it needs the queue store's and GitHub's
credentials at the edge.
- State at the edge is the laptop's last report except for open pull
requests, which can refresh from GitHub after the laptop has been quiet
for one minute and the direct-read switch and secret are present.
- Fresh board, ranked-issue and prompt reads, and direct actions remain
unimplemented. Prompt queue-task creation still requires the documented
fleet queue contract or explicit laptop enqueue on return.
- The storage is one Durable Object. A section larger than one stored
value is kept in pieces.
63 changes: 63 additions & 0 deletions pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ const AUDIT_KEPT = 300;
const WATCHING_MS = 90_000;
/** The host is reported silent after this long without a sync. */
export const SILENT_MS = 10 * 60_000;
/** The laptop is quiet long enough to bypass it for safe reads. */
const DIRECT_READ_AFTER_MS = 60_000;
const KEY_FETCH_EVERY_MS = 30_000;
const STATIC: Record<string, string> = {
"app.js": "text/javascript; charset=utf-8",
Expand Down Expand Up @@ -123,15 +125,30 @@ export interface EdgeOptions {
now?: () => number;
/** Reaches the sign-in issuer's keys and the push services. */
fetchImpl?: typeof fetch;
/** Reads a section from its source when the host has gone quiet. */
freshRead?: (section: string, config: EdgeConfig) => Promise<unknown>;
githubReadEnabled?: boolean;
githubTokenConfigured?: boolean;
/** Ask to be woken at a time: the check for a silent host. */
setAlarm?: (at: number) => Promise<void>;
/** Work that may finish after the response has gone: the object's
* own waitUntil, so a background read is not cut off with the
* response. Defaults to letting it run unattended. */
later?: (work: Promise<unknown>) => void;
}

export class Edge {
private kv: KV;
private now: () => number;
private fetchImpl: typeof fetch;
private setAlarm: (at: number) => Promise<void>;
private later: (work: Promise<unknown>) => void;
private freshRead?: EdgeOptions["freshRead"];
private githubReadEnabled: boolean;
private githubTokenConfigured: boolean;
/** A pull-request read already running: shared by every request
* while it runs, so a slow GitHub is asked once, not once a poll. */
private prsRefresh: Promise<void> | null = null;
private cfg: EdgeConfig | null | undefined;
private mirrors = new Map<string, Mirror | null>();
private held: Held[] | null = null;
Expand All @@ -156,7 +173,11 @@ export class Edge {
this.kv = options.kv;
this.now = options.now ?? Date.now;
this.fetchImpl = options.fetchImpl ?? fetch;
this.freshRead = options.freshRead;
this.githubReadEnabled = options.githubReadEnabled ?? false;
this.githubTokenConfigured = options.githubTokenConfigured ?? false;
this.setAlarm = options.setAlarm ?? (async () => {});
this.later = options.later ?? ((work) => void work);
this.docs = new Docs(
Object.fromEntries(
Object.entries(SECTIONS).map(([name, ttlMs]) => [
Expand Down Expand Up @@ -477,6 +498,31 @@ export class Edge {
}
}

/** Read pull requests from GitHub again without making a document
* wait for it: the read runs after the response, through the
* object's waitUntil, and a request that arrives while it runs
* shares it instead of starting another. */
private refreshPrs(cfg: EdgeConfig): void {
if (this.prsRefresh) return;
const read = this.freshRead;
if (!read) return;
this.prsRefresh = (async () => {
try {
this.docs.record("prs", await read("prs", cfg), this.now());
} catch (error) {
// The stored copy is still the last good list: read it back
// before saying the fresh read failed, so the failure does not
// hide it. A failed read stamps the section's time, which is
// what decides whether the stored copy is ever loaded.
await this.docs.refresh("prs");
this.docs.recordFailure("prs", error);
} finally {
this.prsRefresh = null;
}
})();
this.later(this.prsRefresh);
}

// ---- requests ----------------------------------------------------------

async fetch(req: Request): Promise<Response> {
Expand All @@ -502,6 +548,9 @@ export class Edge {
ok: true,
edge: true,
configured: cfg !== null,
githubReadEnabled: this.githubReadEnabled,
githubTokenConfigured: this.githubTokenConfigured,
githubReadReady: this.freshRead !== undefined,
hostSeen: this.hostSeen || null,
// Since this object last started: requests it answered as the
// owner's, and requests it left to the host to judge.
Expand Down Expand Up @@ -570,6 +619,20 @@ export class Edge {
}
if (seg.length === 2 && seg[0] === "doc" && DOC_NAMES.includes(seg[1] as DocName)) {
this.lastDocAt = this.now();
// Pull requests are a read-only GitHub view. When the laptop is
// quiet, refresh them directly if this Worker has that capability.
// The read runs in the background: the document answers at once
// from what is cached, and the fresh list arrives on the next
// poll. Only a stale section is refreshed, so GitHub is asked
// at most once per interval while the laptop is quiet.
if (
seg[1] === "ops" &&
this.freshRead &&
this.now() - (this.hostSeen ?? 0) >= DIRECT_READ_AFTER_MS &&
this.docs.isStale("prs")
) {
this.refreshPrs(cfg);
}
const res = docResponse(req, await this.docs.doc(seg[1] as DocName));
// When the host last reported, beside the document rather than
// in it: it changes with every report and the content does not.
Expand Down
46 changes: 46 additions & 0 deletions pm-stack/console/edge/src/github.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export interface PullRequestSummary {
number: number;
title: string;
draft: boolean;
url: string;
created: string;
author: string;
branch: string;
}

/** Read the same bounded open-PR view the laptop console presents. */
export async function readOpenPullRequests(
repo: string,
token: string,
fetchImpl: typeof fetch = fetch,
): Promise<PullRequestSummary[]> {
const response = await fetchImpl(`https://api.github.com/repos/${repo}/pulls?state=open&per_page=60`, {
headers: {
accept: "application/vnd.github+json",
authorization: `Bearer ${token}`,
"user-agent": "pm-console-edge",
"x-github-api-version": "2022-11-28",
},
Comment thread
dezren39 marked this conversation as resolved.
Resolved
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) throw new Error(`GitHub answered http ${response.status}`);
const pulls = (await response.json()) as {
number: number;
title: string;
draft: boolean;
html_url: string;
created_at: string;
user: { login: string };
head: { ref: string };
}[];
if (!Array.isArray(pulls)) throw new Error("GitHub returned an invalid pull request list");
return pulls.map((pull) => ({
number: pull.number,
title: pull.title,
draft: pull.draft,
url: pull.html_url,
created: pull.created_at.slice(0, 16),
author: pull.user.login,
branch: pull.head.ref,
}));
}
16 changes: 16 additions & 0 deletions pm-stack/console/edge/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@
import { DurableObject } from "cloudflare:workers";
import { Edge } from "./edge.ts";
import { route } from "./entry.ts";
import { readOpenPullRequests } from "./github.ts";

interface Env {
PM: DurableObjectNamespace;
ASSETS: { fetch(request: Request): Promise<Response> };
PUBLIC_HOST: string;
/** Optional read-only GitHub token; provisioned as a Worker secret. */
GITHUB_TOKEN?: string;
/** Explicit opt-in; reads stay disabled unless set to `on`. */
GITHUB_READ_ENABLED?: string;
VERSION?: string;
/** Local development only: where the host is, when it is not simply
* behind this hostname's route. Never set where this is deployed. */
Expand All @@ -36,6 +41,17 @@ export class PmEdge extends DurableObject<Env> {
},
},
setAlarm: (at) => ctx.storage.setAlarm(at),
// The object's own waitUntil: a background read outlives the
// response that started it.
later: (work) => ctx.waitUntil(work),
githubReadEnabled: env.GITHUB_READ_ENABLED === "on",
githubTokenConfigured: Boolean(env.GITHUB_TOKEN),
freshRead: env.GITHUB_READ_ENABLED === "on" && env.GITHUB_TOKEN
? (section, config) =>
section === "prs"
? readOpenPullRequests(config.repo, env.GITHUB_TOKEN as string)
: Promise.reject(new Error("unsupported edge read"))
: undefined,
});
}

Expand Down
40 changes: 36 additions & 4 deletions pm-stack/console/src/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,15 @@ export class Docs {
const loaded = await s.load();
const now = this.now();
// A copy read elsewhere is as old as that read, never newer than now.
s.data = loaded instanceof Stamped ? loaded.data : loaded;
s.goodAt = loaded instanceof Stamped ? Math.min(now, loaded.at) : now;
s.error = loaded instanceof Stamped ? loaded.error : null;
s.ok = s.error === null;
const loadedAt = loaded instanceof Stamped ? Math.min(now, loaded.at) : now;
// A read that finishes after a newer one must not put its older
// copy back: the section keeps the freshest data it has.
if (loadedAt >= s.goodAt) {
s.data = loaded instanceof Stamped ? loaded.data : loaded;
s.goodAt = loadedAt;
s.error = loaded instanceof Stamped ? loaded.error : null;
s.ok = s.error === null;
}
} catch (error) {
s.ok = false;
s.error = (error as Error).message.slice(0, 300);
Expand All @@ -116,10 +121,37 @@ export class Docs {
await Promise.all(names.map((n) => this.refresh(n)));
}

/** Record a section read by another trusted source, such as the edge
* reading GitHub while the laptop is away. */
record(name: string, data: unknown, at = this.now()): void {
const s = this.sections.get(name);
if (!s) return;
s.data = data;
s.at = at;
s.goodAt = at;
s.ok = true;
s.error = null;
}

/** Keep the last good value, but say that a fresh read failed. */
recordFailure(name: string, error: unknown): void {
const s = this.sections.get(name);
if (!s) return;
s.at = this.now();
s.ok = false;
s.error = (error as Error).message.slice(0, 300);
}

private stale(s: Section): boolean {
return this.now() - s.at > s.ttlMs;
}

/** Whether a section is due a fresh read: never read, or older than its interval. */
isStale(name: string): boolean {
const s = this.sections.get(name);
return s !== undefined && this.stale(s);
}

/** One pass of the background loop: refresh what is stale, if anyone is looking. */
tick(): void {
if (this.now() - this.asked > WATCH_MS) return;
Expand Down
Loading