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
244 changes: 244 additions & 0 deletions pm-stack/console/edge/src/config-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
// What this side goes by: the configuration a machine told, and the
// settings the owner changed over it. Split out of edge.ts (#16255,
// slice 22); the Edge keeps it fed with its store and clock, and is
// told through the audit log and the shown state it owns.
import type { EdgeConfig } from "../../src/edge-proto.ts";
import { edgeConfig } from "../../src/edge-proto.ts";
import { OpError } from "../../src/errors.ts";
import { json } from "../../src/http.ts";
import {
effectiveSettings,
OWNER_CHANGEABLE,
type OwnerChangeableName,
type OwnerSettings,
} from "../../src/settings.ts";
import type { KV } from "./edge-shared.ts";
import { flipRoute, healthRoutes, type RouteState, routeState } from "./route-state.ts";


/** Where the settings the owner changed are kept: beside "cfg", never in it. */
export const OWNER_SETTINGS_KEY = "ownerSettings";

/** The owner's record as kept, or null when what is kept is not one:
* only the names the owner may change, each in its setting's shape. */
export function ownerSettingsRecord(value: unknown): OwnerSettings | null {
const v = value as Record<string, unknown> | null;
if (!v || typeof v !== "object") return null;
if (!Number.isSafeInteger(v.rev) || (v.rev as number) < 1) return null;
if (typeof v.at !== "number" || !Number.isFinite(v.at)) return null;
if (typeof v.by !== "string" || v.by === "") return null;
const raw = v.values as Record<string, unknown> | null;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
const values: OwnerSettings["values"] = {};
for (const [name, setting] of Object.entries(raw)) {
if (name === "promptLabel") {
if (typeof setting !== "string" || setting === "") return null;
values.promptLabel = setting;
} else if (name === "needsRepos") {
if (
!Array.isArray(setting) ||
!setting.every((repo) => typeof repo === "string" && /^[^/\s]+\/[^/\s]+$/.test(repo))
)
return null;
values.needsRepos = [...new Set(setting as string[])];
} else {
return null;
}
}
return { rev: v.rev as number, at: v.at, by: v.by, values };
}

/** Whether the owner changed this setting: a machine is then compared
* with the owner's change by the revision it has taken, not with main. */
export function ownerChanged(owner: OwnerSettings | null, name: string): boolean {
return owner !== null && Object.prototype.hasOwnProperty.call(owner.values, name);
}

/** A revision of the owner's settings as a machine said it, or null. */
export function settingsRevSaid(value: unknown): number | null {
return Number.isSafeInteger(value) && (value as number) >= 0 ? (value as number) : null;
}

/** The app's files and what each is served as: public/files.json is the
* one list of them, and this Worker's build ships exactly those. */

/** What the configuration store needs of the Edge: its store and
* clock, its audit log, and word that the kept settings changed (the
* shown state is the Edge's). */
export interface ConfigHost {
kv: KV;
now: () => number;
audit(entry: Record<string, unknown>): Promise<void>;
onSettingsKept(): Promise<void>;
}

export class ConfigStore {
/** What this side goes by (see config()), worked out from `told`. */
private cfg: EdgeConfig | null | undefined;
/** What a machine told, as it is kept; undefined until read. */
private told: EdgeConfig | null | undefined;
/** The settings the owner changed, as kept under "ownerSettings";
* read once, and replaced only by a change made through this object. */
private owner: OwnerSettings | null | undefined;

constructor(private host: ConfigHost) {}

/** A machine's word on what this side goes by, taken in from a
* report: the kept copy is replaced, and what was worked out from
* the old one is worked out again on the next read. */
acceptTold(says: EdgeConfig | null): void {
this.told = says;
this.cfg = undefined;
}

async toldConfig(): Promise<EdgeConfig | null> {
if (this.told === undefined) this.told = edgeConfig(await this.host.kv.get("cfg"));
return this.told;
}

/** The per-surface route state (#14944, CF-4), kept under its own
* key in this object's storage: rebuildable front-door data, read
* as route state or as none. */
async routes(): Promise<RouteState> {
return routeState(await this.host.kv.get("routes"));
}

/** A flip of one surface's declared tier, on the trusted internal
* channel only (the stateless Worker's own calls, like
* /internal/key): the operator / deploy-pipeline operation of the
* design (§5.1). The flip is kept whole and said back as health
* will say it. Anything that is not a surface name and a tier is
* refused and changes nothing. */
async routeFlip(req: Request): Promise<Response> {
const body = (await req.json().catch(() => null)) as { surface?: unknown; tier?: unknown } | null;
try {
const next = flipRoute(await this.routes(), body?.surface as string, body?.tier as "hosted" | "tunnel");
await this.host.kv.put("routes", next);
return json({ ok: true, routes: healthRoutes(next) });
} catch (error) {
return json({ error: (error as Error).message }, 400);
}
}

/** What this side goes by; null until a machine has said who may
* sign in. Who may sign in is as the machine told it (the
* deployment's, until that is applied from Actions: #13495). The
* repository's settings are this side's own, as its deploy carries
* them, whatever a machine told for them; the list of repositories
* alone is still the machine's (src/settings.ts says why). */
async config(): Promise<EdgeConfig | null> {
if (this.cfg === undefined) {
const told = await this.toldConfig();
this.cfg = told === null ? null : effectiveSettings(told, await this.ownerSettings());
}
return this.cfg;
}

/** The settings the owner changed, kept under their own key beside
* "cfg" and never inside it: "cfg" is a machine's word and the next
* report that differs replaces it (#14163). A record that does not
* read as one is no record: the repository speaks. */
async ownerSettings(): Promise<OwnerSettings | null> {
if (this.owner === undefined) this.owner = ownerSettingsRecord(await this.host.kv.get(OWNER_SETTINGS_KEY));
return this.owner;
}

/** The owner sets one of the settings the owner may change: kept whole,
* at the next revision, and said in the audit log by name (never by
* value). What is gone by changes at once. The owner's actions call
* this once they have checked who asks and what is asked (#14956); a
* machine's report never reaches it. */
async setOwnerSetting<N extends OwnerChangeableName>(
by: string,
name: N,
value: OwnerSettings["values"][N] & {},
): Promise<OwnerSettings> {
const was = await this.ownerSettings();
const values = {
...was?.values,
[name]: Array.isArray(value) ? [...value] : value,
};
const record = ownerSettingsRecord({
rev: (was?.rev ?? 0) + 1,
at: this.host.now(),
by,
values,
});
if (record === null) throw new OpError(400, `${name}: not a value the owner can set`);
await this.keepOwnerSettings(record, [{ kind: "setting.set", name }]);
return record;
}

/** The owner clears one setting they changed, or every one with no
* name: the repository speaks for it again from now. Clearing what
* was not changed changes nothing and is not logged. */
async clearOwnerSetting(by: string, name?: OwnerChangeableName): Promise<OwnerSettings | null> {
const was = await this.ownerSettings();
if (was === null) return null;
const cleared = OWNER_CHANGEABLE.filter(
(n) => (name === undefined || n === name) && Object.prototype.hasOwnProperty.call(was.values, n),
);
if (cleared.length === 0) return was;
const values = { ...was.values };
for (const n of cleared) delete values[n];
const record: OwnerSettings = {
rev: was.rev + 1,
at: this.host.now(),
by,
values,
};
await this.keepOwnerSettings(
record,
cleared.map((n) => ({ kind: "setting.clear", name: n })),
);
return record;
}

/** Who changes a setting: the owner this side is sure of. */
changedBy(by: string | undefined): string {
if (typeof by !== "string" || by === "") throw new OpError(400, "Who is changing this is not known here.");
return by;
}

/** A change made from what the owner last saw: refused when the
* settings have changed since (another tab, another device), with
* what they are now, so the owner looks again and decides again.
* Without a revision the change is made over whatever is there. 0 is
* the revision before the owner has changed anything. */
async settingsBase(baseRev: unknown): Promise<void> {
if (baseRev === undefined) return;
if (!Number.isSafeInteger(baseRev) || (baseRev as number) < 0) {
throw new OpError(400, "baseRev: the revision the change was made from, a whole number");
}
const now = await this.ownerSettings();
if ((now?.rev ?? 0) !== baseRev) {
throw new OpError(
409,
"The settings were changed meanwhile, somewhere else: look at them again before changing them.",
{ settings: now },
);
}
}

private async keepOwnerSettings(
record: OwnerSettings,
changes: {
kind: "setting.set" | "setting.clear";
name: OwnerChangeableName;
}[],
): Promise<void> {
await this.host.kv.put(OWNER_SETTINGS_KEY, record);
this.owner = record;
this.cfg = undefined;
for (const change of changes) {
await this.host.audit({
...change,
rev: record.rev,
at: new Date(record.at).toISOString(),
by: record.by,
});
}
// The list of repositories may have changed.
await this.host.onSettingsKept();
}
}
Loading