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
16 changes: 10 additions & 6 deletions .github/workflows/pm-console-edge-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@ name: pm-console-edge deploy
# CLOUDFLARE_ACCOUNT_ID repository secrets, the ones message-bridge
# deploys with.
#
# The Worker has no secrets: the keys it uses it makes itself, or are
# published by the host. It has no route here either. The host's
# pm-stack/console/scripts/expose.py sends the hostname through it once
# it answers its health check, and `expose.py --edge off` takes the
# hostname off it again, which is the rollback that needs no deploy. A
# manual run with rollback_version puts an earlier version back.
# The Worker has no secrets from this deploy: the keys it uses it makes
# itself, or are published by the host. Three secrets are optional, put
# there by the host's scripts/expose.py --edge-direct (off by default):
# GITHUB_TOKEN and QUEUE_TOKEN, which let it act itself while the laptop
# is away, and EDGE_DIRECT, the opt-in that must read `on`. It has no
# route here either. The host's pm-stack/console/scripts/expose.py sends
# the hostname through it once it answers its health check, and
# `expose.py --edge off` takes the hostname off it again, which is the
# rollback that needs no deploy. A manual run with rollback_version puts
# an earlier version back.
#
# Until both secrets exist the job says so in its summary and skips the
# upload instead of failing.
Expand Down
41 changes: 33 additions & 8 deletions pm-stack/console/edge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ 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 | the board, pull requests, ranked issues and prompts refresh from GitHub and the queue store after one minute of silence; the rest stays 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 |
| Direct actions (reply to or close a prompt, comment, rank an issue, move a task) | edge, once the laptop has been quiet for a minute | run at the edge through the laptop's own classes, and never sent to the laptop, so they are not done twice; a new prompt is filed at the edge and only its queue task is held for the laptop |
| Actions not safe to do late (merge, units, unblock, …) | laptop, relayed at once | refused, saying why |
| The dashboard's own pages, logs, one pull request's page | laptop | a plain notice with a link to the app |

Expand All @@ -31,7 +32,9 @@ Cloudflare Access ── sign-in (email code; Google once its client exists)
pm-console-edge (this Worker, on the hostname's route)
├─ src/worker.ts wiring: the object, the app's files, the laptop
├─ src/entry.ts what to do with a request
└─ src/edge.ts the state, in one Durable Object
├─ src/edge.ts the state, in one Durable Object
└─ src/direct.ts the laptop's own classes (Ops, Work) with stand-ins
for GitHub and the queue store, for while it is away
│ same hostname, through the tunnel
laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts
```
Expand Down Expand Up @@ -77,7 +80,21 @@ 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
Three secrets are optional, put there by the laptop's
`scripts/expose.py --edge-direct on` (off by default, remembered):
`GITHUB_TOKEN` (the repository automation token), `QUEUE_TOKEN` (the
queue store token), and `EDGE_DIRECT`, the explicit opt-in that must
read `on` for either to be used. With them, the edge reads the board,
pull requests, ranked issues and prompts itself, and runs the direct
actions, once the laptop has been quiet for a minute; without them, or
with the flag off, it serves only the laptop's last report and holds
what the owner does, as before. `/console/health` says whether the
flag is on, whether each token is present, whether the direct
capability is ready, and the result of the self-check: one direct read
of each kind, run when the secrets arrive and at most once an hour
after. A secret is sent only to its own service — the GitHub token
only to GitHub, the queue token only to the queue store — and is never
returned by health. The other keys the Worker uses it made itself
(notification signing) or were published to it (the laptop's, the
sign-in issuer's).

Expand Down Expand Up @@ -116,10 +133,18 @@ 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 the board,
pull requests, ranked issues and prompts, which the edge reads itself
after the laptop has been quiet for a minute. The rest ages, and the
app says how old it is.
- A new prompt filed at the edge still needs the laptop for its queue
task: the issue is filed at once and only the task is held, as
`prompt.enqueue`, for the laptop's return. The queue task is never
written from the edge itself: there is no fleet binary there, and
copying the queue's rows by hand would break its contract.
- An action the edge runs itself is never sent to the laptop, so the
laptop cannot repeat it; an action that was relayed and got no answer
is only ever resolved by the laptop, which wrote its name down before
starting. That is the rule against doing anything twice.
- The storage is one Durable Object. A section larger than one stored
value is kept in pieces.
197 changes: 197 additions & 0 deletions pm-stack/console/edge/src/direct.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
// What the edge can do itself while the laptop is away: the laptop
// console's own classes, with stand-ins only where they touch the
// outside world.
//
// Ops and Work take a `run` function and a `fetch`. At the edge, `run`
// turns `fleet gh api` argv into GitHub REST calls and
// `fleet secrets get <queue token name>` into the Worker secret, and
// refuses every other fleet verb as needing the laptop; `fetch` is the
// Worker's own, which already reaches the queue store. So board, pull
// requests, ranked issues and prompts are read, and the one-call writes
// are run, by the same code the laptop runs — nothing here re-implements
// their shapes.
//
// What stays the laptop's: `fleet queue enqueue` (the fleet binary is
// not here), `fleet bridge`, `systemctl`, and anything that reads the
// dashboard or the decisions file, which live on the laptop alone.
// A new prompt is filed at the edge and only its queue task is held for
// the laptop, as `prompt.enqueue`: the issue is never filed twice.
import { OpError } from "../../src/errors.ts";
import type { Config } from "../../src/config.ts";
import type { EdgeConfig } from "../../src/edge-proto.ts";
import { Ops, type Fetch, type Run, type RunResult } from "../../src/ops.ts";
import { Work } from "../../src/work.ts";

/** Sections the edge reads itself once the laptop has gone quiet. */
export const DIRECT_READ_SECTIONS = ["board", "prs", "priorities", "asks"] as const;
/** Actions the edge runs itself once the laptop has gone quiet. */
export const DIRECT_ACTIONS = [
"ask.send",
"ask.reply",
"ask.close",
"issue.comment",
"need.comment",
"issue.rank",
"task.move",
] as const;

export interface DirectSecrets {
githubToken?: string;
queueToken?: string;
}

/** One `fleet gh api` call as a GitHub REST call. `argv` is what follows
* `api`: an optional `-X METHOD`, the path, `-f key=value` pairs, and
* `--input -` for a JSON body on stdin. A failed call answers the way
* the fleet binary would: a non-zero code with the body's own words on
* stderr, so callers that look for them (the prompt label's
* `already_exists`) still find them. */
async function ghApi(
argv: string[],
stdin: string | undefined,
token: string | undefined,
fetchImpl: Fetch,
): Promise<RunResult> {
if (!token) throw new OpError(502, "the edge has no GitHub token");
let method = "GET";
let path = "";
const fields: [string, string][] = [];
let useStdin = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "-X") method = argv[++i] ?? "GET";
else if (arg === "-f") {
const pair = argv[++i] ?? "";
const at = pair.indexOf("=");
if (at < 0) throw new OpError(502, `fleet gh api: -f needs key=value, got ${pair}`);
fields.push([pair.slice(0, at), pair.slice(at + 1)]);
} else if (arg === "--input") {
if (argv[++i] !== "-") throw new OpError(502, "fleet gh api: --input takes -");
useStdin = true;
} else if (path === "") path = arg;
else throw new OpError(502, `fleet gh api: unexpected argument ${arg}`);
}
if (path === "") throw new OpError(502, "fleet gh api: no path");
let url = `https://api.github.com/${path}`;
let body: string | undefined;
if (method === "GET") {
if (fields.length > 0) {
const query = new URLSearchParams(fields);
url += (url.includes("?") ? "&" : "?") + query.toString();
}
} else if (useStdin) {
body = stdin;
} else if (fields.length > 0) {
body = JSON.stringify(Object.fromEntries(fields));
}
const res = await fetchImpl(url, {
method,
headers: {
accept: "application/vnd.github+json",
authorization: `Bearer ${token}`,
// The Workers runtime supplies no User-Agent of its own, and
// GitHub requires one: without it every direct call is refused.
"user-agent": "pm-console-edge",
"x-github-api-version": "2022-11-28",
...(body === undefined ? {} : { "content-type": "application/json" }),
},
Comment thread
dezren39 marked this conversation as resolved.
Resolved
...(body === undefined ? {} : { body }),
signal: AbortSignal.timeout(20_000),
});
// The body is read as JSON and written back out, so an empty answer
// (a 204) stays empty and an error body keeps its own words for the
// caller.
const text = await (async () => {
try {
return JSON.stringify(await res.json());
} catch {
return "";
}
})();
if (!res.ok) {
return { code: 1, stdout: "", stderr: text === "" ? `GitHub answered http ${res.status}` : text };
}
return { code: 0, stdout: text, stderr: "" };
}

/** The edge's `run`: GitHub through REST, the queue token from its
* Worker secret, and everything else refused as the laptop's. */
export function edgeRun(config: Config, secrets: DirectSecrets, fetchImpl: Fetch): Run {
return async (argv, opts) => {
const [bin, verb, ...rest] = argv;
if (bin === config.fleetBin && verb === "gh" && rest[0] === "api") {
return ghApi(rest.slice(1), opts?.stdin, secrets.githubToken, fetchImpl);
}
if (bin === config.fleetBin && verb === "secrets" && rest[0] === "get") {
const name = rest[1];
if (name === config.queueTokenName && secrets.queueToken) {
return { code: 0, stdout: `${secrets.queueToken}\n`, stderr: "" };
}
throw new OpError(502, `the edge has no secret named ${name ?? "?"}`);
}
throw new OpError(502, "needs the laptop");
};
}

/** The laptop console's config, as the edge knows it: what the host
* reported, and nothing the edge cannot use left blank. The dashboard
* is null, so anything that reads it refuses rather than reaching
* somewhere it cannot. */
export function directConfig(edge: EdgeConfig): Config {
return {
port: 0,
bind: "127.0.0.1",
owners: edge.owners,
certNames: edge.certNames,
issuers: edge.issuers,
repo: edge.repo,
queue: edge.queue,
queueDbUrl: edge.queueDbUrl,
queueTokenName: edge.queueTokenName,
fleetBin: "fleet",
unitPatterns: [],
protectedUnits: [],
auditFile: "",
dashboardUrl: null,
androidPackage: edge.androidPackage,
androidFingerprints: edge.androidFingerprints,
androidApk: "",
devicesFile: "",
edgeUrl: null,
edgeKeyFile: "",
edgeDoneFile: "",
decisionsFile: "",
promptLabel: edge.promptLabel,
needsRepos: edge.needsRepos,
};
}

export interface DirectOptions {
githubToken?: string;
queueToken?: string;
fetchImpl?: Fetch;
}

/** The laptop's own classes, wired for the edge. */
export function directClasses(edge: EdgeConfig, options: DirectOptions): { ops: Ops; work: Work } {
const config = directConfig(edge);
const fetchImpl = options.fetchImpl ?? (fetch as unknown as Fetch);
const ops = new Ops(config, edgeRun(config, options, fetchImpl), fetchImpl);
return { ops, work: new Work(ops) };
}

/** One section, read by the class that reads it on the laptop. */
export async function directRead(section: string, ops: Ops, work: Work): Promise<unknown> {
switch (section) {
case "board":
return work.board();
case "prs":
return ops.prs();
case "priorities":
return ops.priorities();
case "asks":
return work.asks();
default:
throw new Error(`not a section the edge reads itself: ${section}`);
}
}
Loading