@orthograph/prove 0.0.0-stage → 0.1.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +2 -2
- package/dist/index.d.ts +32 -0
- package/dist/index.js +32 -0
- package/dist/modules/build/internal/manifest.d.ts +15 -0
- package/dist/modules/build/internal/manifest.js +38 -0
- package/dist/modules/build/service.d.ts +2 -0
- package/dist/modules/build/service.js +74 -0
- package/dist/modules/build/types.d.ts +39 -0
- package/dist/modules/build/types.js +4 -0
- package/dist/modules/environments/internal/collector.d.ts +2 -0
- package/dist/modules/environments/internal/collector.js +5 -0
- package/dist/modules/environments/internal/config.d.ts +32 -0
- package/dist/modules/environments/internal/config.js +42 -0
- package/dist/modules/environments/internal/identity.d.ts +3 -0
- package/dist/modules/environments/internal/identity.js +17 -0
- package/dist/modules/environments/internal/logbook.d.ts +10 -0
- package/dist/modules/environments/internal/logbook.js +23 -0
- package/dist/modules/environments/internal/process.d.ts +41 -0
- package/dist/modules/environments/internal/process.js +103 -0
- package/dist/modules/environments/internal/secrets.d.ts +9 -0
- package/dist/modules/environments/internal/secrets.js +23 -0
- package/dist/modules/environments/internal/status.d.ts +7 -0
- package/dist/modules/environments/internal/status.js +31 -0
- package/dist/modules/environments/service.d.ts +2 -0
- package/dist/modules/environments/service.js +97 -0
- package/dist/modules/environments/types.d.ts +80 -0
- package/dist/modules/environments/types.js +4 -0
- package/dist/modules/evals/internal/calls.d.ts +19 -0
- package/dist/modules/evals/internal/calls.js +168 -0
- package/dist/modules/evals/internal/evidence.d.ts +13 -0
- package/dist/modules/evals/internal/evidence.js +29 -0
- package/dist/modules/evals/internal/run.d.ts +12 -0
- package/dist/modules/evals/internal/run.js +85 -0
- package/dist/modules/evals/internal/secrets.d.ts +5 -0
- package/dist/modules/evals/internal/secrets.js +72 -0
- package/dist/modules/evals/service.d.ts +2 -0
- package/dist/modules/evals/service.js +29 -0
- package/dist/modules/evals/testing.d.ts +12 -0
- package/dist/modules/evals/testing.js +15 -0
- package/dist/modules/evals/types.d.ts +43 -0
- package/dist/modules/evals/types.js +1 -0
- package/dist/modules/impact/internal/changed.d.ts +6 -0
- package/dist/modules/impact/internal/changed.js +34 -0
- package/dist/modules/impact/internal/closure.d.ts +12 -0
- package/dist/modules/impact/internal/closure.js +69 -0
- package/dist/modules/impact/internal/digest.d.ts +1 -0
- package/dist/modules/impact/internal/digest.js +2 -0
- package/dist/modules/impact/internal/files.d.ts +11 -0
- package/dist/modules/impact/internal/files.js +48 -0
- package/dist/modules/impact/internal/ledger.d.ts +5 -0
- package/dist/modules/impact/internal/ledger.js +25 -0
- package/dist/modules/impact/internal/linked.d.ts +4 -0
- package/dist/modules/impact/internal/linked.js +56 -0
- package/dist/modules/impact/internal/scan.d.ts +12 -0
- package/dist/modules/impact/internal/scan.js +66 -0
- package/dist/modules/impact/service.d.ts +2 -0
- package/dist/modules/impact/service.js +88 -0
- package/dist/modules/impact/types.d.ts +109 -0
- package/dist/modules/impact/types.js +1 -0
- package/dist/modules/journeys/internal/checks.d.ts +25 -0
- package/dist/modules/journeys/internal/checks.js +155 -0
- package/dist/modules/journeys/internal/d1-facts.d.ts +10 -0
- package/dist/modules/journeys/internal/d1-facts.js +53 -0
- package/dist/modules/journeys/internal/database-facts.d.ts +2 -0
- package/dist/modules/journeys/internal/database-facts.js +41 -0
- package/dist/modules/journeys/internal/device.d.ts +16 -0
- package/dist/modules/journeys/internal/device.js +68 -0
- package/dist/modules/journeys/internal/keepers.d.ts +6 -0
- package/dist/modules/journeys/internal/keepers.js +6 -0
- package/dist/modules/journeys/internal/load.d.ts +4 -0
- package/dist/modules/journeys/internal/load.js +94 -0
- package/dist/modules/journeys/internal/stand-call.d.ts +10 -0
- package/dist/modules/journeys/internal/stand-call.js +22 -0
- package/dist/modules/journeys/internal/subject.d.ts +8 -0
- package/dist/modules/journeys/internal/subject.js +15 -0
- package/dist/modules/journeys/internal/world.d.ts +70 -0
- package/dist/modules/journeys/internal/world.js +133 -0
- package/dist/modules/journeys/service.d.ts +2 -0
- package/dist/modules/journeys/service.js +231 -0
- package/dist/modules/journeys/types.d.ts +132 -0
- package/dist/modules/journeys/types.js +5 -0
- package/dist/modules/portal-feed/internal/listen.d.ts +10 -0
- package/dist/modules/portal-feed/internal/listen.js +32 -0
- package/dist/modules/portal-feed/service.d.ts +2 -0
- package/dist/modules/portal-feed/service.js +6 -0
- package/dist/modules/portal-feed/types.d.ts +30 -0
- package/dist/modules/portal-feed/types.js +5 -0
- package/dist/modules/promote/internal/environment.d.ts +6 -0
- package/dist/modules/promote/internal/environment.js +10 -0
- package/dist/modules/promote/internal/gate.d.ts +9 -0
- package/dist/modules/promote/internal/gate.js +37 -0
- package/dist/modules/promote/internal/publishing.d.ts +23 -0
- package/dist/modules/promote/internal/publishing.js +21 -0
- package/dist/modules/promote/service.d.ts +2 -0
- package/dist/modules/promote/service.js +112 -0
- package/dist/modules/promote/types.d.ts +54 -0
- package/dist/modules/promote/types.js +8 -0
- package/dist/modules/prove/internal/changed-run.d.ts +9 -0
- package/dist/modules/prove/internal/changed-run.js +14 -0
- package/dist/modules/prove/internal/device-host.d.ts +16 -0
- package/dist/modules/prove/internal/device-host.js +60 -0
- package/dist/modules/prove/internal/empty-world.d.ts +5 -0
- package/dist/modules/prove/internal/empty-world.js +26 -0
- package/dist/modules/prove/internal/exercise.d.ts +35 -0
- package/dist/modules/prove/internal/exercise.js +47 -0
- package/dist/modules/prove/internal/proof-verdicts.d.ts +5 -0
- package/dist/modules/prove/internal/proof-verdicts.js +37 -0
- package/dist/modules/prove/internal/report.d.ts +35 -0
- package/dist/modules/prove/internal/report.js +169 -0
- package/dist/modules/prove/internal/staged.d.ts +9 -0
- package/dist/modules/prove/internal/staged.js +30 -0
- package/dist/modules/prove/internal/stand.d.ts +40 -0
- package/dist/modules/prove/internal/stand.js +155 -0
- package/dist/modules/prove/internal/structured.d.ts +78 -0
- package/dist/modules/prove/internal/structured.js +55 -0
- package/dist/modules/prove/internal/test-run.d.ts +7 -0
- package/dist/modules/prove/internal/test-run.js +63 -0
- package/dist/modules/prove/service.d.ts +2 -0
- package/dist/modules/prove/service.js +98 -0
- package/dist/modules/prove/types.d.ts +120 -0
- package/dist/modules/prove/types.js +5 -0
- package/dist/modules/publish/internal/bundle.d.ts +24 -0
- package/dist/modules/publish/internal/bundle.js +46 -0
- package/dist/modules/publish/internal/env.d.ts +3 -0
- package/dist/modules/publish/internal/env.js +2 -0
- package/dist/modules/publish/internal/plan.d.ts +28 -0
- package/dist/modules/publish/internal/plan.js +28 -0
- package/dist/modules/publish/internal/registry.d.ts +24 -0
- package/dist/modules/publish/internal/registry.js +55 -0
- package/dist/modules/publish/internal/sea.d.ts +20 -0
- package/dist/modules/publish/internal/sea.js +77 -0
- package/dist/modules/publish/internal/source.d.ts +4 -0
- package/dist/modules/publish/internal/source.js +41 -0
- package/dist/modules/publish/internal/stage.d.ts +14 -0
- package/dist/modules/publish/internal/stage.js +95 -0
- package/dist/modules/publish/internal/tap.d.ts +22 -0
- package/dist/modules/publish/internal/tap.js +61 -0
- package/dist/modules/publish/service.d.ts +2 -0
- package/dist/modules/publish/service.js +99 -0
- package/dist/modules/publish/types.d.ts +80 -0
- package/dist/modules/publish/types.js +4 -0
- package/dist/modules/releases/internal/http.d.ts +12 -0
- package/dist/modules/releases/internal/http.js +14 -0
- package/dist/modules/releases/internal/stale.d.ts +13 -0
- package/dist/modules/releases/internal/stale.js +43 -0
- package/dist/modules/releases/service.d.ts +2 -0
- package/dist/modules/releases/service.js +59 -0
- package/dist/modules/releases/types.d.ts +81 -0
- package/dist/modules/releases/types.js +6 -0
- package/dist/modules/secrets/internal/file.d.ts +5 -0
- package/dist/modules/secrets/internal/file.js +25 -0
- package/dist/modules/secrets/service.d.ts +2 -0
- package/dist/modules/secrets/service.js +38 -0
- package/dist/modules/secrets/types.d.ts +44 -0
- package/dist/modules/secrets/types.js +7 -0
- package/dist/modules/server-config/internal/jsonc.d.ts +2 -0
- package/dist/modules/server-config/internal/jsonc.js +29 -0
- package/dist/modules/server-config/service.d.ts +2 -0
- package/dist/modules/server-config/service.js +21 -0
- package/dist/modules/server-config/types.d.ts +22 -0
- package/dist/modules/server-config/types.js +3 -0
- package/dist/modules/sinks/internal/axiom.d.ts +29 -0
- package/dist/modules/sinks/internal/axiom.js +25 -0
- package/dist/modules/sinks/internal/keychain.d.ts +2 -0
- package/dist/modules/sinks/internal/keychain.js +13 -0
- package/dist/modules/sinks/service.d.ts +2 -0
- package/dist/modules/sinks/service.js +26 -0
- package/dist/modules/sinks/types.d.ts +37 -0
- package/dist/modules/sinks/types.js +5 -0
- package/dist/modules/telemetry/internal/axiom-source.d.ts +2 -0
- package/dist/modules/telemetry/internal/axiom-source.js +108 -0
- package/dist/modules/telemetry/internal/binary.d.ts +11 -0
- package/dist/modules/telemetry/internal/binary.js +66 -0
- package/dist/modules/telemetry/internal/config.d.ts +13 -0
- package/dist/modules/telemetry/internal/config.js +22 -0
- package/dist/modules/telemetry/internal/file-metrics.d.ts +2 -0
- package/dist/modules/telemetry/internal/file-metrics.js +60 -0
- package/dist/modules/telemetry/internal/file-source.d.ts +2 -0
- package/dist/modules/telemetry/internal/file-source.js +38 -0
- package/dist/modules/telemetry/internal/journey-root.d.ts +44 -0
- package/dist/modules/telemetry/internal/journey-root.js +36 -0
- package/dist/modules/telemetry/internal/local.d.ts +11 -0
- package/dist/modules/telemetry/internal/local.js +57 -0
- package/dist/modules/telemetry/internal/otlp.d.ts +15 -0
- package/dist/modules/telemetry/internal/otlp.js +53 -0
- package/dist/modules/telemetry/internal/private-keys.d.ts +7 -0
- package/dist/modules/telemetry/internal/private-keys.js +28 -0
- package/dist/modules/telemetry/internal/process.d.ts +27 -0
- package/dist/modules/telemetry/internal/process.js +96 -0
- package/dist/modules/telemetry/internal/runs.d.ts +17 -0
- package/dist/modules/telemetry/internal/runs.js +48 -0
- package/dist/modules/telemetry/service.d.ts +9 -0
- package/dist/modules/telemetry/service.js +48 -0
- package/dist/modules/telemetry/types.d.ts +138 -0
- package/dist/modules/telemetry/types.js +13 -0
- package/dist/modules/test-worlds/internal/lifetime.d.ts +3 -0
- package/dist/modules/test-worlds/internal/lifetime.js +19 -0
- package/dist/modules/test-worlds/service.d.ts +2 -0
- package/dist/modules/test-worlds/service.js +35 -0
- package/dist/modules/test-worlds/types.d.ts +41 -0
- package/dist/modules/test-worlds/types.js +4 -0
- package/dist/modules/trace-trees/service.d.ts +2 -0
- package/dist/modules/trace-trees/service.js +40 -0
- package/dist/modules/trace-trees/types.d.ts +9 -0
- package/dist/modules/trace-trees/types.js +1 -0
- package/dist/modules/verdicts/internal/proof.d.ts +24 -0
- package/dist/modules/verdicts/internal/proof.js +59 -0
- package/dist/modules/verdicts/service.d.ts +16 -0
- package/dist/modules/verdicts/service.js +71 -0
- package/dist/modules/verdicts/types.d.ts +80 -0
- package/dist/modules/verdicts/types.js +4 -0
- package/dist/modules/warm/internal/source.d.ts +7 -0
- package/dist/modules/warm/internal/source.js +27 -0
- package/dist/modules/warm/service.d.ts +2 -0
- package/dist/modules/warm/service.js +76 -0
- package/dist/modules/warm/types.d.ts +43 -0
- package/dist/modules/warm/types.js +4 -0
- package/dist/modules/watch/internal/choose.d.ts +20 -0
- package/dist/modules/watch/internal/choose.js +24 -0
- package/dist/modules/watch/internal/evidence.d.ts +9 -0
- package/dist/modules/watch/internal/evidence.js +26 -0
- package/dist/modules/watch/internal/report.d.ts +18 -0
- package/dist/modules/watch/internal/report.js +59 -0
- package/dist/modules/watch/internal/tasks.d.ts +5 -0
- package/dist/modules/watch/internal/tasks.js +35 -0
- package/dist/modules/watch/service.d.ts +2 -0
- package/dist/modules/watch/service.js +38 -0
- package/dist/modules/watch/types.d.ts +44 -0
- package/dist/modules/watch/types.js +4 -0
- package/dist/modules/world/internal/ports.d.ts +8 -0
- package/dist/modules/world/internal/ports.js +30 -0
- package/dist/modules/world/internal/wrangler.d.ts +46 -0
- package/dist/modules/world/internal/wrangler.js +112 -0
- package/dist/modules/world/service.d.ts +2 -0
- package/dist/modules/world/service.js +46 -0
- package/dist/modules/world/types.d.ts +97 -0
- package/dist/modules/world/types.js +4 -0
- package/dist/modules/world-clock/internal/door.d.ts +8 -0
- package/dist/modules/world-clock/internal/door.js +9 -0
- package/dist/modules/world-clock/service.d.ts +2 -0
- package/dist/modules/world-clock/service.js +9 -0
- package/dist/modules/world-clock/types.d.ts +34 -0
- package/dist/modules/world-clock/types.js +1 -0
- package/package.json +38 -3
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type ChildProcess } from "node:child_process";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import type { Launched, WorldFailed } from "#modules/world/types.js";
|
|
4
|
+
export declare const files: (dir: string) => {
|
|
5
|
+
config: string;
|
|
6
|
+
secrets: string;
|
|
7
|
+
state: string;
|
|
8
|
+
pid: string;
|
|
9
|
+
port: string;
|
|
10
|
+
bundle: string;
|
|
11
|
+
log: string;
|
|
12
|
+
};
|
|
13
|
+
export declare const readPid: (dir: string) => number | undefined;
|
|
14
|
+
export declare const readPort: (dir: string) => number | undefined;
|
|
15
|
+
export declare const writePort: (dir: string, port: number) => void;
|
|
16
|
+
/** Something of this process group still runs. The group, not just wrangler: workerd is wrangler's child. */
|
|
17
|
+
export declare const groupAlive: (pid: number) => Effect.Effect<boolean, never, never>;
|
|
18
|
+
/** A PID belongs to this environment only when its full launch command names the derived config and state. */
|
|
19
|
+
export declare const isWrangler: (pid: number, dir: string) => boolean;
|
|
20
|
+
/** Stop the group: ask, wait up to ten seconds, then insist. */
|
|
21
|
+
export declare const stopGroup: (pid: number, dir: string) => Effect.Effect<void, never, never>;
|
|
22
|
+
/** What marks an environment as running goes: the state, the secrets and the port stay for the next start. */
|
|
23
|
+
export declare const forget: (dir: string) => void;
|
|
24
|
+
/** Whether a port can be listened on at 127.0.0.1 now. */
|
|
25
|
+
export declare const isFree: (port: number) => Effect.Effect<boolean, never, never>;
|
|
26
|
+
/** Stop only a verified environment process, remove its derived collector, and forget stale or foreign markers. */
|
|
27
|
+
export declare const reap: (dir: string) => Effect.Effect<void, never, never>;
|
|
28
|
+
/** The port asked for if it is free (an explicit one that isn't is refused), else the one it last had, else any. */
|
|
29
|
+
export declare const choosePort: (dir: string, wanted: number | undefined) => Effect.Effect<number, string, never>;
|
|
30
|
+
/** Run a command detached in its own process group, its output appended to `log`, its pid written at once. */
|
|
31
|
+
export declare const spawnDetached: (run: {
|
|
32
|
+
readonly command: string;
|
|
33
|
+
readonly args: ReadonlyArray<string>;
|
|
34
|
+
readonly env: Readonly<Record<string, string>>;
|
|
35
|
+
}, log: string, pidFile: string) => Effect.Effect<ChildProcess, never, never>;
|
|
36
|
+
/**
|
|
37
|
+
* Launch on `first`. A port that was free when it was chosen can be taken before wrangler binds it (the collector and the
|
|
38
|
+
* migrations come between), and wrangler then exits for a taken address: unless the caller named the port, launch again
|
|
39
|
+
* on a fresh one, remembered in the port file, up to `times` more.
|
|
40
|
+
*/
|
|
41
|
+
export declare const launchOnFreePort: (launch: (port: number) => Effect.Effect<Launched, WorldFailed>, dir: string, first: number, named: boolean, times?: number) => Effect.Effect<Launched, WorldFailed>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// What an environment leaves on disk to be found again: a pid, a port, and the bundle it runs. And stopping it.
|
|
2
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createServer } from "node:net";
|
|
5
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { Effect, Schedule } from "effect";
|
|
8
|
+
import { Collectors } from "#modules/telemetry/service.js";
|
|
9
|
+
import { Worlds } from "#modules/world/service.js";
|
|
10
|
+
import { telemetryDir } from "./collector.js";
|
|
11
|
+
export const files = (dir) => ({
|
|
12
|
+
config: join(dir, "wrangler.jsonc"),
|
|
13
|
+
secrets: join(dir, "secrets.env"),
|
|
14
|
+
state: join(dir, "state"),
|
|
15
|
+
pid: join(dir, "pid"),
|
|
16
|
+
port: join(dir, "port"),
|
|
17
|
+
bundle: join(dir, "bundle.json"),
|
|
18
|
+
log: join(dir, "wrangler.log"),
|
|
19
|
+
});
|
|
20
|
+
const readNumber = (file) => {
|
|
21
|
+
const n = existsSync(file) ? Number(readFileSync(file, "utf8").trim()) : NaN;
|
|
22
|
+
return Number.isInteger(n) && n > 1 ? n : undefined;
|
|
23
|
+
};
|
|
24
|
+
export const readPid = (dir) => readNumber(files(dir).pid);
|
|
25
|
+
export const readPort = (dir) => readNumber(files(dir).port);
|
|
26
|
+
export const writePort = (dir, port) => writeFileSync(files(dir).port, `${port}\n`);
|
|
27
|
+
/** Something of this process group still runs. The group, not just wrangler: workerd is wrangler's child. */
|
|
28
|
+
export const groupAlive = (pid) => Effect.try({ try: () => process.kill(-pid, 0), catch: () => "gone" }).pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
|
|
29
|
+
const wrangler = join(dirname(fileURLToPath(import.meta.resolve("wrangler/package.json"))), "bin/wrangler.js");
|
|
30
|
+
// The public logbook entry is src/index.ts in this workspace and dist/index.js after publishing; both are one level
|
|
31
|
+
// below its package-owned wrangler.jsonc. Every logbook shares that config, so its state argument must match too.
|
|
32
|
+
const logbookConfig = resolve(dirname(fileURLToPath(import.meta.resolve("@orthograph/logbook"))), "../wrangler.jsonc");
|
|
33
|
+
/** A PID belongs to this environment only when its full launch command names the derived config and state. */
|
|
34
|
+
export const isWrangler = (pid, dir) => {
|
|
35
|
+
const ps = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
|
36
|
+
if (ps.status !== 0)
|
|
37
|
+
return false;
|
|
38
|
+
const command = ps.stdout.trim();
|
|
39
|
+
const launch = command.indexOf(` ${wrangler} dev `);
|
|
40
|
+
if (launch < 1 || !/(?:^|\/)node(?:\.exe)?$/.test(command.slice(0, launch)))
|
|
41
|
+
return false;
|
|
42
|
+
const expected = files(resolve(dir));
|
|
43
|
+
const config = basename(resolve(dir)) === "logbook" ? logbookConfig : expected.config;
|
|
44
|
+
return command.includes(` --config ${config} `) && command.includes(` --persist-to ${expected.state} `);
|
|
45
|
+
};
|
|
46
|
+
const signal = (pid, name, dir) => Effect.try({ try: () => { if (isWrangler(pid, dir))
|
|
47
|
+
process.kill(-pid, name); }, catch: () => "gone" }).pipe(Effect.ignore);
|
|
48
|
+
/** Stop the group: ask, wait up to ten seconds, then insist. */
|
|
49
|
+
export const stopGroup = (pid, dir) => Effect.gen(function* () {
|
|
50
|
+
const gone = groupAlive(pid).pipe(Effect.flatMap((alive) => (alive ? Effect.fail("alive") : Effect.void)));
|
|
51
|
+
yield* signal(pid, "SIGTERM", dir);
|
|
52
|
+
const stopped = yield* gone.pipe(Effect.retry({ schedule: Schedule.spaced("100 millis"), times: 100 }), Effect.option);
|
|
53
|
+
if (stopped._tag === "None") {
|
|
54
|
+
yield* signal(pid, "SIGKILL", dir);
|
|
55
|
+
yield* gone.pipe(Effect.retry({ schedule: Schedule.spaced("100 millis"), times: 50 }), Effect.ignore);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
/** What marks an environment as running goes: the state, the secrets and the port stay for the next start. */
|
|
59
|
+
export const forget = (dir) => {
|
|
60
|
+
const f = files(dir);
|
|
61
|
+
for (const file of [f.pid, f.bundle])
|
|
62
|
+
rmSync(file, { force: true });
|
|
63
|
+
};
|
|
64
|
+
/** Whether a port can be listened on at 127.0.0.1 now. */
|
|
65
|
+
export const isFree = (port) => Effect.callback((resume) => {
|
|
66
|
+
const server = createServer();
|
|
67
|
+
server.once("error", () => resume(Effect.succeed(false)));
|
|
68
|
+
server.listen(port, "127.0.0.1", () => server.close(() => resume(Effect.succeed(true))));
|
|
69
|
+
});
|
|
70
|
+
/** Stop only a verified environment process, remove its derived collector, and forget stale or foreign markers. */
|
|
71
|
+
export const reap = (dir) => Effect.gen(function* () {
|
|
72
|
+
const pid = readPid(dir);
|
|
73
|
+
if (pid !== undefined && (yield* groupAlive(pid)) && isWrangler(pid, dir))
|
|
74
|
+
yield* stopGroup(pid, dir);
|
|
75
|
+
yield* Collectors.stop(telemetryDir(dir));
|
|
76
|
+
forget(dir);
|
|
77
|
+
});
|
|
78
|
+
/** The port asked for if it is free (an explicit one that isn't is refused), else the one it last had, else any. */
|
|
79
|
+
export const choosePort = (dir, wanted) => Effect.gen(function* () {
|
|
80
|
+
if (wanted !== undefined) {
|
|
81
|
+
if (!(yield* isFree(wanted)))
|
|
82
|
+
return yield* Effect.fail(`port ${wanted} is already in use`);
|
|
83
|
+
return wanted;
|
|
84
|
+
}
|
|
85
|
+
const last = readPort(dir);
|
|
86
|
+
return last !== undefined && (yield* isFree(last)) ? last : yield* Worlds.anyPort.pipe(Effect.mapError((e) => e.message));
|
|
87
|
+
});
|
|
88
|
+
/** Run a command detached in its own process group, its output appended to `log`, its pid written at once. */
|
|
89
|
+
export const spawnDetached = (run, log, pidFile) => Effect.sync(() => {
|
|
90
|
+
const out = openSync(log, "a");
|
|
91
|
+
const child = spawn(run.command, [...run.args], { stdio: ["ignore", out, out], detached: true, env: { ...process.env, ...run.env } });
|
|
92
|
+
child.unref();
|
|
93
|
+
writeFileSync(pidFile, `${child.pid}\n`);
|
|
94
|
+
return child;
|
|
95
|
+
});
|
|
96
|
+
/**
|
|
97
|
+
* Launch on `first`. A port that was free when it was chosen can be taken before wrangler binds it (the collector and the
|
|
98
|
+
* migrations come between), and wrangler then exits for a taken address: unless the caller named the port, launch again
|
|
99
|
+
* on a fresh one, remembered in the port file, up to `times` more.
|
|
100
|
+
*/
|
|
101
|
+
export const launchOnFreePort = (launch, dir, first, named, times = 3) => launch(first).pipe(Effect.catchTag("WorldFailed", (e) => e.taken !== true || named || times === 0
|
|
102
|
+
? Effect.fail(e)
|
|
103
|
+
: Worlds.anyPort.pipe(Effect.flatMap((fresh) => Effect.sync(() => writePort(dir, fresh)).pipe(Effect.andThen(launchOnFreePort(launch, dir, fresh, named, times - 1)))))));
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { EnvironmentModel } from "@orthograph/compiler";
|
|
2
|
+
/** The names this environment may invent a value for: the ones declared `generated`. A stored secret is a person's to set, never made up. */
|
|
3
|
+
export declare const generatedNames: (secrets: EnvironmentModel["secrets"]) => ReadonlyArray<string>;
|
|
4
|
+
/**
|
|
5
|
+
* `secrets.env`, mode 0600: Better Auth's `AUTH_SECRET` and every `generated` secret the environment names. A value that is
|
|
6
|
+
* already there stays (so a restart keeps sessions valid), as does every other line (a stored secret a person set); a new
|
|
7
|
+
* generated name, or one with an empty value, gets a generated one. Values never reach a command line.
|
|
8
|
+
*/
|
|
9
|
+
export declare const ensureSecrets: (file: string, generated: ReadonlyArray<string>) => void;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// An environment's secrets: made once, kept in a file only its owner reads, and passed to wrangler as that file.
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
const parse = (text) => new Map(text.split("\n").flatMap((line) => {
|
|
5
|
+
const at = line.indexOf("=");
|
|
6
|
+
return at > 0 ? [[line.slice(0, at), line.slice(at + 1)]] : [];
|
|
7
|
+
}));
|
|
8
|
+
/** The names this environment may invent a value for: the ones declared `generated`. A stored secret is a person's to set, never made up. */
|
|
9
|
+
export const generatedNames = (secrets) => Object.entries(secrets).flatMap(([name, how]) => (how === "generated" ? [name] : []));
|
|
10
|
+
/**
|
|
11
|
+
* `secrets.env`, mode 0600: Better Auth's `AUTH_SECRET` and every `generated` secret the environment names. A value that is
|
|
12
|
+
* already there stays (so a restart keeps sessions valid), as does every other line (a stored secret a person set); a new
|
|
13
|
+
* generated name, or one with an empty value, gets a generated one. Values never reach a command line.
|
|
14
|
+
*/
|
|
15
|
+
export const ensureSecrets = (file, generated) => {
|
|
16
|
+
const have = existsSync(file) ? parse(readFileSync(file, "utf8")) : new Map();
|
|
17
|
+
const made = new Map(have);
|
|
18
|
+
for (const name of ["AUTH_SECRET", ...generated])
|
|
19
|
+
if ((made.get(name) ?? "") === "")
|
|
20
|
+
made.set(name, randomBytes(32).toString("hex"));
|
|
21
|
+
writeFileSync(file, `${[...made].map(([name, value]) => `${name}=${value}`).join("\n")}\n`, { mode: 0o600 });
|
|
22
|
+
chmodSync(file, 0o600);
|
|
23
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { EnvironmentFailed, type Status } from "../types.ts";
|
|
3
|
+
export declare const NAME: RegExp;
|
|
4
|
+
export declare const failed: (message: string) => EnvironmentFailed;
|
|
5
|
+
export declare const io: <A>(what: string, run: () => A) => Effect.Effect<A, EnvironmentFailed, never>;
|
|
6
|
+
export declare const dirOf: (root: string, name: string) => string;
|
|
7
|
+
export declare const status: (root: string, name: string) => Effect.Effect<Status, EnvironmentFailed>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Whether an environment runs, found again from what it left on disk.
|
|
2
|
+
import { Names } from "orthograph/server";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { Effect } from "effect";
|
|
6
|
+
import { EnvironmentFailed } from "../types.js";
|
|
7
|
+
import { telemetryDir } from "./collector.js";
|
|
8
|
+
import { ServerConfig } from "#modules/server-config/service.js";
|
|
9
|
+
import { files, groupAlive, isWrangler, readPid, readPort } from "./process.js";
|
|
10
|
+
export const NAME = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
|
|
11
|
+
export const failed = (message) => new EnvironmentFailed({ message });
|
|
12
|
+
export const io = (what, run) => Effect.try({ try: run, catch: (e) => failed(`${what}: ${String(e).replace(/^Error: /, "")}`) });
|
|
13
|
+
export const dirOf = (root, name) => join(resolve(root), Names.folder, "environments", name);
|
|
14
|
+
export const status = (root, name) => Effect.gen(function* () {
|
|
15
|
+
if (!NAME.test(name))
|
|
16
|
+
return yield* failed(`"${name}" isn't an environment name`);
|
|
17
|
+
const dir = dirOf(root, name);
|
|
18
|
+
const pid = readPid(dir);
|
|
19
|
+
if (pid === undefined || !(yield* groupAlive(pid)) || !isWrangler(pid, dir))
|
|
20
|
+
return { state: "down", name };
|
|
21
|
+
const port = readPort(dir);
|
|
22
|
+
if (port === undefined)
|
|
23
|
+
return { state: "down", name };
|
|
24
|
+
const record = files(dir).bundle;
|
|
25
|
+
const bundle = existsSync(record) ? yield* io("its bundle record", () => JSON.parse(readFileSync(record, "utf8"))) : {};
|
|
26
|
+
const telemetry = telemetryDir(dir);
|
|
27
|
+
// Its own collector's address is in its config's vars: where prove can send the journey's span.
|
|
28
|
+
const config = existsSync(files(dir).config) ? ServerConfig.parse(readFileSync(files(dir).config, "utf8")) : {};
|
|
29
|
+
const collector = config.vars?.OTLP_URL;
|
|
30
|
+
return { state: "up", name, url: `http://127.0.0.1:${port}`, port, pid, ...bundle, ...(existsSync(telemetry) ? { telemetry } : {}), ...(collector ? { collector } : {}) };
|
|
31
|
+
});
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { Effect } from "effect";
|
|
4
|
+
import { Compiler, nodeSource } from "@orthograph/compiler";
|
|
5
|
+
import { Build } from "#modules/build/service.js";
|
|
6
|
+
import { Collectors, privateKeys } from "#modules/telemetry/service.js";
|
|
7
|
+
import { Sinks } from "#modules/sinks/service.js";
|
|
8
|
+
import { Worlds } from "#modules/world/service.js";
|
|
9
|
+
import { telemetryDir } from "./internal/collector.js";
|
|
10
|
+
import { environmentConfig, logbookOf, portalOf } from "./internal/config.js";
|
|
11
|
+
import { startLogbook } from "./internal/logbook.js";
|
|
12
|
+
import { choosePort, files, launchOnFreePort, reap, writePort } from "./internal/process.js";
|
|
13
|
+
import { NAME, dirOf, failed, io, status } from "./internal/status.js";
|
|
14
|
+
import { verify } from "./internal/identity.js";
|
|
15
|
+
import { ensureSecrets, generatedNames } from "./internal/secrets.js";
|
|
16
|
+
/** The environment as the blueprint declares it, and only one a long-lived workerd can run the revision's bundle for. */
|
|
17
|
+
const declared = (root, name) => Effect.gen(function* () {
|
|
18
|
+
if (!NAME.test(name))
|
|
19
|
+
return yield* failed(`"${name}" isn't an environment name`);
|
|
20
|
+
const model = yield* Compiler.model.pipe(Effect.provide(nodeSource(root)), Effect.mapError((e) => failed(e._tag === "BlueprintInvalid" ? `the blueprint is invalid:\n - ${e.problems.join("\n - ")}` : e.message)));
|
|
21
|
+
const environment = model.environments?.[name];
|
|
22
|
+
const known = Object.keys(model.environments ?? {}).filter((n) => n !== "local");
|
|
23
|
+
if (!environment)
|
|
24
|
+
return yield* failed(`no environment "${name}" in blueprint/environments/ (there is ${known.join(", ") || "none"})`);
|
|
25
|
+
if (name === "local")
|
|
26
|
+
return yield* failed(`"local" is not kept running: it is what \`ortho dev\` and \`ortho prove --env local\` start`);
|
|
27
|
+
return { environment, model, strip: privateKeys(model) };
|
|
28
|
+
});
|
|
29
|
+
const up = ({ root: given, name, port, revision, policy, env, logbook: givenLogbook }) => Effect.gen(function* () {
|
|
30
|
+
const root = resolve(given);
|
|
31
|
+
const dir = dirOf(root, name);
|
|
32
|
+
if (name === "logbook") {
|
|
33
|
+
if (!NAME.test(name))
|
|
34
|
+
return yield* failed(`"${name}" isn't an environment name`);
|
|
35
|
+
const running = yield* status(root, name);
|
|
36
|
+
if (running.state === "up")
|
|
37
|
+
return running;
|
|
38
|
+
if (!policy)
|
|
39
|
+
return yield* failed("the logbook needs a policy: ORTHO_OIDC_ISSUER, ORTHO_OIDC_REPOSITORY, ORTHO_OIDC_REF and ORTHO_OIDC_WORKFLOW");
|
|
40
|
+
return yield* startLogbook(dir, port, policy);
|
|
41
|
+
}
|
|
42
|
+
const { environment, model, strip } = yield* declared(root, name);
|
|
43
|
+
// An environment that hosts worlds, or that another is promoted from (so it is proved where it runs), records telemetry
|
|
44
|
+
// in a collector of its own, which lives until `down` (D3 #52, #91).
|
|
45
|
+
const hosts = environment.lifetimeMs !== null;
|
|
46
|
+
const records = hosts || Object.values(model.environments ?? {}).some((e) => e.promotesFrom === name);
|
|
47
|
+
const f = files(dir);
|
|
48
|
+
yield* io(`${dir}`, () => mkdirSync(f.state, { recursive: true }));
|
|
49
|
+
const now = yield* status(root, name);
|
|
50
|
+
// The portal route reads the logbook: the one asked for, else the one running here (D3 #131).
|
|
51
|
+
const book = yield* status(root, "logbook");
|
|
52
|
+
const logbook = givenLogbook ?? (book.state === "up" ? book.url : undefined);
|
|
53
|
+
const held = existsSync(f.config) ? logbookOf(readFileSync(f.config, "utf8")) : undefined;
|
|
54
|
+
const requested = revision === undefined ? undefined : yield* Build.find(root, revision).pipe(Effect.mapError((e) => failed(e.message)));
|
|
55
|
+
if (now.state === "up" && (revision === undefined || (revision === now.revision && requested?.sha256 === now.sha256)) && (!records || now.telemetry !== undefined) && held === logbook)
|
|
56
|
+
return now;
|
|
57
|
+
// Not running, or running another bundle: whatever is left of it goes first. The state stays.
|
|
58
|
+
yield* reap(dir);
|
|
59
|
+
const rev = revision ?? (yield* Build.revision(root).pipe(Effect.mapError((e) => failed(e.message))));
|
|
60
|
+
const kept = yield* Build.find(root, rev).pipe(Effect.mapError((e) => failed(e.message)));
|
|
61
|
+
const built = kept ?? (revision !== undefined
|
|
62
|
+
? yield* failed(`revision ${rev} has no artefact: run \`ortho build\` at that commit`)
|
|
63
|
+
: yield* Build.build(root, env).pipe(Effect.mapError((e) => failed(e.message))));
|
|
64
|
+
const base = join(root, "generated/server/wrangler.jsonc");
|
|
65
|
+
if (!existsSync(base))
|
|
66
|
+
return yield* failed(`${base} is missing: run nx sync first`);
|
|
67
|
+
const chosen = yield* choosePort(dir, port).pipe(Effect.mapError(failed));
|
|
68
|
+
const otlp = records
|
|
69
|
+
? yield* Collectors.launch({ dir: telemetryDir(dir), strip }).pipe(Effect.mapError((e) => failed(`${name}'s collector didn't start: ${e.message}`)))
|
|
70
|
+
: undefined;
|
|
71
|
+
const portal = portalOf(built);
|
|
72
|
+
yield* io(`${dir}`, () => {
|
|
73
|
+
ensureSecrets(f.secrets, generatedNames(environment.secrets));
|
|
74
|
+
writeFileSync(f.config, environmentConfig(root, readFileSync(base, "utf8"), {
|
|
75
|
+
name, revision: built.revision, sha256: built.sha256, main: built.main, ...(portal === undefined ? {} : { portal }), ...(otlp ? { otlp } : {}), ...(hosts ? { worlds: true } : {}), ...(logbook ? { logbook } : {}),
|
|
76
|
+
}));
|
|
77
|
+
writeFileSync(f.bundle, JSON.stringify({ revision: built.revision, sha256: built.sha256 }) + "\n");
|
|
78
|
+
writePort(dir, chosen);
|
|
79
|
+
});
|
|
80
|
+
// The environment's sinks, read by name now and handed to its process alone: never in its config or its secrets file.
|
|
81
|
+
const sinks = yield* Sinks.resolve({ sinks: environment.telemetry ?? [{ sink: "local" }], env: env ?? {} });
|
|
82
|
+
const launched = yield* launchOnFreePort((at) => Worlds.launch({
|
|
83
|
+
config: f.config, state: f.state, port: at, log: f.log, pidFile: f.pid, envFile: f.secrets, secretEnv: sinks.secretEnv, ready: "/_ortho/bundle",
|
|
84
|
+
}), dir, chosen, port !== undefined).pipe(Effect.tapError(() => reap(dir)), Effect.mapError((e) => failed(`${name} didn't start: ${e.message}`)));
|
|
85
|
+
return {
|
|
86
|
+
state: "up", name, url: launched.url, port: Number(new URL(launched.url).port), pid: launched.pid, revision: built.revision, sha256: built.sha256,
|
|
87
|
+
...(records ? { telemetry: telemetryDir(dir) } : {}),
|
|
88
|
+
...(otlp ? { collector: otlp } : {}),
|
|
89
|
+
...(sinks.notes.length > 0 ? { notes: sinks.notes } : {}),
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
const down = ({ root, name }) => Effect.gen(function* () {
|
|
93
|
+
if (!NAME.test(name))
|
|
94
|
+
return yield* failed(`"${name}" isn't an environment name`);
|
|
95
|
+
yield* reap(dirOf(root, name));
|
|
96
|
+
});
|
|
97
|
+
export const Environments = { up, down, verify, status: ({ root, name }) => status(root, name) };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type Effect } from "effect";
|
|
2
|
+
declare const EnvironmentFailed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
3
|
+
readonly _tag: "EnvironmentFailed";
|
|
4
|
+
} & Readonly<A>;
|
|
5
|
+
export declare class EnvironmentFailed extends EnvironmentFailed_base<{
|
|
6
|
+
readonly message: string;
|
|
7
|
+
}> {
|
|
8
|
+
}
|
|
9
|
+
export type Status = {
|
|
10
|
+
readonly state: "down";
|
|
11
|
+
readonly name: string;
|
|
12
|
+
} | {
|
|
13
|
+
readonly state: "up";
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly url: string;
|
|
16
|
+
readonly port: number;
|
|
17
|
+
readonly pid: number;
|
|
18
|
+
/** The bundle it runs. The logbook is its own worker, built from source, and has none. */
|
|
19
|
+
readonly revision?: string;
|
|
20
|
+
readonly sha256?: string;
|
|
21
|
+
/** Where its own collector writes, for an environment that hosts worlds. */
|
|
22
|
+
readonly telemetry?: string;
|
|
23
|
+
/** The OTLP/HTTP address of that collector. */
|
|
24
|
+
readonly collector?: string;
|
|
25
|
+
/** From a start: a telemetry sink that was left out, and why (never a value). One line each. */
|
|
26
|
+
readonly notes?: ReadonlyArray<string>;
|
|
27
|
+
};
|
|
28
|
+
export type Up = Extract<Status, {
|
|
29
|
+
state: "up";
|
|
30
|
+
}>;
|
|
31
|
+
/** What the logbook trusts, from `ORTHO_OIDC_*` (D3 #33). `ref` may list several, as a comma-separated allow-list. */
|
|
32
|
+
export interface LogbookSetup {
|
|
33
|
+
readonly issuer: string;
|
|
34
|
+
readonly repository: string;
|
|
35
|
+
readonly refs: ReadonlyArray<string>;
|
|
36
|
+
readonly workflows: ReadonlyArray<string>;
|
|
37
|
+
}
|
|
38
|
+
export interface EnvironmentsApi {
|
|
39
|
+
/**
|
|
40
|
+
* Start environment `name` on a revision's bundle, building the revision first when it has no artefact. Everything it
|
|
41
|
+
* keeps is under `.ortho/environments/<name>/`: its generated wrangler config, `secrets.env` (mode 0600), its
|
|
42
|
+
* `state/`, `pid`, `port` and wrangler's log. An environment already running is left alone, unless a `revision` is
|
|
43
|
+
* asked for that it isn't running: it is then restarted on that bundle with its state kept. `port` defaults to the one
|
|
44
|
+
* it last had, then to any free port. An environment whose blueprint declares a `lifetime` hosts worlds: it gets a
|
|
45
|
+
* collector of its own (`telemetry/`, a container removed by `down`) and opens `/_world/worlds` (D3 #50).
|
|
46
|
+
*
|
|
47
|
+
* `logbook` is the logbook's own worker (L2.03), always started with a `policy` and never from a revision.
|
|
48
|
+
*/
|
|
49
|
+
readonly up: (options: {
|
|
50
|
+
readonly root: string;
|
|
51
|
+
readonly name: string;
|
|
52
|
+
readonly port?: number;
|
|
53
|
+
/** Default: the project's current revision. */
|
|
54
|
+
readonly revision?: string;
|
|
55
|
+
/** For `logbook` only: who may write to it. */
|
|
56
|
+
readonly policy?: LogbookSetup;
|
|
57
|
+
/** The process environment, for the telemetry sinks' tokens (`AXIOM_TOKEN`); only an entry file reads it. */
|
|
58
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
59
|
+
/** Where the logbook is, for the portal route an environment serves (`ORTHO_LOGBOOK_URL`). Default: the running `logbook` environment, if there is one (D3 #131). */
|
|
60
|
+
readonly logbook?: string;
|
|
61
|
+
}) => Effect.Effect<Up, EnvironmentFailed>;
|
|
62
|
+
/** Stop it, and everything it started. An environment that isn't running is not an error. */
|
|
63
|
+
readonly down: (options: {
|
|
64
|
+
readonly root: string;
|
|
65
|
+
readonly name: string;
|
|
66
|
+
}) => Effect.Effect<void, EnvironmentFailed>;
|
|
67
|
+
/** Verify the same live process still serves the expected revision and bytes; a restart, even back to the same bytes, fails. */
|
|
68
|
+
readonly verify: (options: {
|
|
69
|
+
readonly root: string;
|
|
70
|
+
readonly name: string;
|
|
71
|
+
readonly pid: number;
|
|
72
|
+
readonly revision: string;
|
|
73
|
+
readonly sha256: string;
|
|
74
|
+
}) => Effect.Effect<void, EnvironmentFailed>;
|
|
75
|
+
readonly status: (options: {
|
|
76
|
+
readonly root: string;
|
|
77
|
+
readonly name: string;
|
|
78
|
+
}) => Effect.Effect<Status, EnvironmentFailed>;
|
|
79
|
+
}
|
|
80
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { PerOperation } from "../types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* 1. Span answers keep their declared shape, including an answer the server refused to send. Fields kept out of
|
|
4
|
+
* telemetry come from the observed response, when there is one. A present schema-valued field uses that response's
|
|
5
|
+
* unambiguous type. The same eval checks for values that should never appear in traces (`secrets.ts`).
|
|
6
|
+
*/
|
|
7
|
+
export declare const answerShape: PerOperation;
|
|
8
|
+
/** 2. Every refusal is one the operation declares (its errors, its machine's, NotAllowed), and its answer carries its code. */
|
|
9
|
+
export declare const declaredErrors: PerOperation;
|
|
10
|
+
/** 3. Every move ends in a declared state, and the stored state is where it ended. */
|
|
11
|
+
export declare const machinePath: PerOperation;
|
|
12
|
+
/** 4. Every move that happened journalled its event. */
|
|
13
|
+
export declare const events: PerOperation;
|
|
14
|
+
/** 5. Who may call: decided from the world's facts before the call, never from what the server did. */
|
|
15
|
+
export declare const whoMayCall: PerOperation;
|
|
16
|
+
/** 6. Every required step of an answered call ran in its own span; all observed steps ran in declared order. */
|
|
17
|
+
export declare const steps: PerOperation;
|
|
18
|
+
/** 9. Every declared refusal, and every rule's refusal (the runtime's own, G5), has the log that decided it, inside the operation's span. A rule's refusal names its rule on the span (`refusal.invariant`, its full name): log text is redacted of hidden values, so it is never matched. */
|
|
19
|
+
export declare const explainability: PerOperation;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Evals 1 to 6 and 9: each looks at every call of one operation.
|
|
2
|
+
import { Schema } from "effect";
|
|
3
|
+
import { listItemFields, structOf, traceable, wireStruct } from "orthograph/server";
|
|
4
|
+
import { answered, attr, replayed, subtree, where } from "./evidence.js";
|
|
5
|
+
import { secretsIn } from "./secrets.js";
|
|
6
|
+
const verdict = (name, operation, failures, notes = []) => ({ eval: name, operation, failures, notes });
|
|
7
|
+
const expectation = (f) => !f ? "nothing" : f.value.type === "id" ? `${f.value.prefix}_<id>` : f.value.type === "uint" ? "a whole number, as text" : f.value.type === "text" ? `text up to ${f.value.max}` : "its schema";
|
|
8
|
+
/** A span keeps an object answer as JSON text; a field declared by its schema (a page's `items`, `next`) is read back from it. */
|
|
9
|
+
const fromJson = (text) => {
|
|
10
|
+
// Objects, arrays and null were written as JSON; a plain string (a cursor, "2") was written as itself.
|
|
11
|
+
if (typeof text !== "string" || !/^(\[|\{|null$)/.test(text))
|
|
12
|
+
return text;
|
|
13
|
+
const parsed = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown))(text);
|
|
14
|
+
return parsed._tag === "Some" ? parsed.value : text;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* 1. Span answers keep their declared shape, including an answer the server refused to send. Fields kept out of
|
|
18
|
+
* telemetry come from the observed response, when there is one. A present schema-valued field uses that response's
|
|
19
|
+
* unambiguous type. The same eval checks for values that should never appear in traces (`secrets.ts`).
|
|
20
|
+
*/
|
|
21
|
+
export const answerShape = (op, evidence, { project }) => {
|
|
22
|
+
const operation = project.operations.get(op.name);
|
|
23
|
+
const declared = operation?.answer ?? {};
|
|
24
|
+
const traceItems = operation?.kind === "read" && operation.by === "list"
|
|
25
|
+
? Schema.Array(structOf(Object.fromEntries(Object.entries(listItemFields(operation.thing)).filter(([, field]) => traceable(field)))))
|
|
26
|
+
: undefined;
|
|
27
|
+
const shown = (key) => {
|
|
28
|
+
const field = declared[key];
|
|
29
|
+
return field !== undefined && traceable(field);
|
|
30
|
+
};
|
|
31
|
+
const failures = evidence.flatMap((e) => {
|
|
32
|
+
const fromSpan = Object.fromEntries(Object.entries(e.opSpan?.attrs ?? {}).filter(([k]) => k.startsWith("answer.")).map(([k, v]) => [k.slice(7), v]));
|
|
33
|
+
const hasResponse = answered(e) && e.call.body !== undefined;
|
|
34
|
+
const sent = answered(e) && typeof e.call.body === "object" && e.call.body !== null ? e.call.body : {};
|
|
35
|
+
const hidden = Object.fromEntries(Object.entries(sent).filter(([k]) => !shown(k)));
|
|
36
|
+
const answer = Object.keys(fromSpan).length > 0 ? { ...hidden, ...fromSpan } : answered(e) ? sent : undefined;
|
|
37
|
+
const leaks = secretsIn(op, operation, e);
|
|
38
|
+
if (!answer)
|
|
39
|
+
return leaks;
|
|
40
|
+
return [...leaks, ...Object.keys(op.answer).flatMap((k) => {
|
|
41
|
+
// A field with a declared visibility is cut from the answer of a caller who is not shown it (M1.35): absent is right.
|
|
42
|
+
// Present, it is still checked below. A public field has no visibility, so a public field that is missing still fails.
|
|
43
|
+
// An issued field (`Blueprint.issued`) is the exception: the call that issues it hands it to its own caller, so presence is required.
|
|
44
|
+
// Visibility decides what is displayed, never whether the field is there. The report names the field and never prints a value.
|
|
45
|
+
// The model decides: the compiler copies `issued` from the declaration into the model, and refuses it anywhere but a secret answer value.
|
|
46
|
+
const issued = op.answer[k]?.issued === true;
|
|
47
|
+
if (issued && hasResponse && !Object.hasOwn(answer, k))
|
|
48
|
+
return [`${where(e)}: answer.${k}: issued by ${op.name}, missing from its answer`];
|
|
49
|
+
if (hasResponse && !issued && op.answer[k]?.visibility !== undefined && !Object.hasOwn(answer, k))
|
|
50
|
+
return [];
|
|
51
|
+
// Live telemetry has no response and an external sink also drops email (D3 #120).
|
|
52
|
+
if (!hasResponse && (!shown(k) || k === "email"))
|
|
53
|
+
return [];
|
|
54
|
+
if (!hasResponse && k === "items" && traceItems !== undefined) {
|
|
55
|
+
const decoded = Schema.decodeUnknownExit(traceItems)(fromJson(answer[k]), { onExcessProperty: "error" });
|
|
56
|
+
return decoded._tag === "Success" ? [] : [`${where(e)}: answer.items: expected traceable item fields and state`];
|
|
57
|
+
}
|
|
58
|
+
// The wire's codec: a private or secret field the server cut for this caller may be absent, a public one never is.
|
|
59
|
+
const schema = wireStruct({ [k]: declared[k] }, { issuing: operation?.kind === "operation", ...(operation?.kind === "read" && operation.by === "list" ? { items: listItemFields(operation.thing) } : {}) });
|
|
60
|
+
const schemaValued = op.answer[k]?.value.type === "schema";
|
|
61
|
+
// An observed response disambiguates a schema-valued field only after the existing answer selection found it:
|
|
62
|
+
// a valid body cannot bless a public field missing from partial answer telemetry (D3 #82).
|
|
63
|
+
const got = schemaValued && hasResponse && Object.hasOwn(answer, k) ? sent[k] : answer[k];
|
|
64
|
+
// A field the answer leaves out is decoded as absent, not as `undefined` under its key: an optional one passes, a required one fails (#1018).
|
|
65
|
+
const held = Object.hasOwn(answer, k);
|
|
66
|
+
const rawFits = Schema.decodeUnknownExit(schema)(held ? { [k]: got } : {})._tag === "Success";
|
|
67
|
+
// Span-only strings are ambiguous: keep valid text before trying the encoded object/list representation.
|
|
68
|
+
const ok = rawFits || (held && !hasResponse && schemaValued && Schema.decodeUnknownExit(schema)({ [k]: fromJson(got) })._tag === "Success");
|
|
69
|
+
if (ok)
|
|
70
|
+
return [];
|
|
71
|
+
// A value kept out of telemetry is also kept out of the report.
|
|
72
|
+
const display = shown(k) && !(k === "items" && traceItems !== undefined) ? JSON.stringify(answer[k]) : "a value that does not fit (hidden from telemetry)";
|
|
73
|
+
return [`${where(e)}: answer.${k}: expected ${expectation(op.answer[k])}, got ${display}`];
|
|
74
|
+
})];
|
|
75
|
+
});
|
|
76
|
+
return verdict("answer shape", op.name, failures);
|
|
77
|
+
};
|
|
78
|
+
/** 2. Every refusal is one the operation declares (its errors, its machine's, NotAllowed), and its answer carries its code. */
|
|
79
|
+
export const declaredErrors = (op, evidence, { project }) => verdict("declared errors", op.name, evidence.flatMap((e) => {
|
|
80
|
+
if (!e.refusal)
|
|
81
|
+
return [];
|
|
82
|
+
if (!op.refusals.includes(e.refusal))
|
|
83
|
+
return [`${where(e)}: refused with ${e.refusal}, not one of ${op.refusals.join(", ")}`];
|
|
84
|
+
// The answer to a refusal is `{ _tag, code, ...fields }` (L2.P): the code beside the tag, as the model fixed it.
|
|
85
|
+
// Live telemetry has no response body. When one was observed, its missing/malformed tag cannot bypass the code check.
|
|
86
|
+
if (e.call.status < 400 || e.call.status >= 500 || e.call.body === undefined)
|
|
87
|
+
return [];
|
|
88
|
+
const body = typeof e.call.body === "object" && e.call.body !== null && !Array.isArray(e.call.body) ? e.call.body : undefined;
|
|
89
|
+
if (!body || body._tag !== e.refusal)
|
|
90
|
+
return [`${where(e)}: ${e.refusal} was answered without its declared refusal tag`];
|
|
91
|
+
const onSpan = e.opSpan?.attrs["refusal"];
|
|
92
|
+
if (typeof onSpan === "string" && onSpan !== body._tag)
|
|
93
|
+
return [`${where(e)}: response refusal ${e.refusal} disagrees with the operation's refusal span`];
|
|
94
|
+
const code = project.model.refusals[e.refusal];
|
|
95
|
+
if (code === undefined)
|
|
96
|
+
return [`${where(e)}: the model has no code for ${e.refusal}`];
|
|
97
|
+
return body.code !== code
|
|
98
|
+
? [`${where(e)}: ${e.refusal} was answered ${typeof body.code === "string" ? `with code ${body.code}` : "with no code"}, and the model's code for it is ${code}`]
|
|
99
|
+
: [];
|
|
100
|
+
}));
|
|
101
|
+
/** 3. Every move ends in a declared state, and the stored state is where it ended. */
|
|
102
|
+
export const machinePath = (op, evidence) => {
|
|
103
|
+
const move = op.move;
|
|
104
|
+
if (!move)
|
|
105
|
+
return verdict("machine path", op.name, []);
|
|
106
|
+
return verdict("machine path", op.name, evidence.flatMap((e) => {
|
|
107
|
+
if (replayed(e))
|
|
108
|
+
return [];
|
|
109
|
+
const to = attr(e, "move.to");
|
|
110
|
+
if (to !== undefined && !move.to.includes(String(to)))
|
|
111
|
+
return [`${where(e)}: ${move.key} ended in "${String(to)}", not one of ${move.to.join(", ")}`];
|
|
112
|
+
if (!answered(e))
|
|
113
|
+
return [];
|
|
114
|
+
if (to === undefined)
|
|
115
|
+
return [`${where(e)}: answered without making its move ${move.key}`];
|
|
116
|
+
if (e.stored !== to)
|
|
117
|
+
return [`${where(e)}: ${move.key} ended in "${String(to)}" but the stored state is ${e.stored === undefined ? "empty" : `"${e.stored}"`}`];
|
|
118
|
+
return [];
|
|
119
|
+
}));
|
|
120
|
+
};
|
|
121
|
+
/** 4. Every move that happened journalled its event. */
|
|
122
|
+
export const events = (op, evidence) => {
|
|
123
|
+
const move = op.move;
|
|
124
|
+
if (!move)
|
|
125
|
+
return verdict("events", op.name, []);
|
|
126
|
+
return verdict("events", op.name, evidence.flatMap((e) => answered(e) && !replayed(e) && !e.call.journal.some((j) => j.event === move.emits && j.move === move.key) ? [`${where(e)}: move ${move.key} emitted no ${move.emits}`] : []));
|
|
127
|
+
};
|
|
128
|
+
const allowedText = (op, payload) => op.allowed.map((a) => a.kind === "role-of" ? `${a.role.split(".").pop()} of ${a.path.split(".").pop()} ${String(payload[a.path.split(".")[0]] ?? "")}`.trim()
|
|
129
|
+
: a.kind === "role" ? a.role.split(".").pop() : a.kind).join(" or ");
|
|
130
|
+
/** 5. Who may call: decided from the world's facts before the call, never from what the server did. */
|
|
131
|
+
export const whoMayCall = (op, evidence) => verdict("who may call", op.name, evidence.flatMap((e) => {
|
|
132
|
+
const refusedForIt = e.refusal === "NotAllowed";
|
|
133
|
+
const caller = `caller ${e.call.actor} (person ${e.call.person})`;
|
|
134
|
+
if (!e.call.mayCall && !refusedForIt) {
|
|
135
|
+
const said = answered(e) ? "answered" : e.refusal ? `refused with ${e.refusal}` : `failed with ${e.call.status}`;
|
|
136
|
+
return [`${where(e)}: ${caller} lacks ${allowedText(op, e.call.payload)}, and was ${said}, not refused`];
|
|
137
|
+
}
|
|
138
|
+
if (e.call.mayCall && refusedForIt)
|
|
139
|
+
return [`${where(e)}: ${caller} has ${allowedText(op, e.call.payload)}, and was refused NotAllowed`];
|
|
140
|
+
return [];
|
|
141
|
+
}));
|
|
142
|
+
/** 6. Every required step of an answered call ran in its own span; all observed steps ran in declared order. */
|
|
143
|
+
export const steps = (op, evidence) => verdict("steps", op.name, evidence.flatMap((e) => {
|
|
144
|
+
if (!answered(e) || replayed(e))
|
|
145
|
+
return [];
|
|
146
|
+
const declared = Object.values(op.steps);
|
|
147
|
+
const ran = declared.flatMap((s) => {
|
|
148
|
+
const span = e.trace.spans.find((x) => x.name === s.name);
|
|
149
|
+
return span ? [{ name: s.name, start: span.start }] : [];
|
|
150
|
+
});
|
|
151
|
+
const missing = declared.filter((s) => !("optional" in s && s.optional === true) && !ran.some((r) => r.name === s.name))
|
|
152
|
+
.map((s) => `${where(e)}: declared step ${s.name} ran no span`);
|
|
153
|
+
const late = ran.slice(1).flatMap((r, i) => (r.start < ran[i].start ? [`${where(e)}: step ${r.name} ran before ${ran[i].name}, which is declared first`] : []));
|
|
154
|
+
return [...missing, ...late];
|
|
155
|
+
}));
|
|
156
|
+
/** 9. Every declared refusal, and every rule's refusal (the runtime's own, G5), has the log that decided it, inside the operation's span. A rule's refusal names its rule on the span (`refusal.invariant`, its full name): log text is redacted of hidden values, so it is never matched. */
|
|
157
|
+
export const explainability = (op, evidence) => verdict("explainability", op.name, evidence.flatMap((e) => {
|
|
158
|
+
const rule = e.refusal === undefined ? undefined : op.invariants?.[e.refusal];
|
|
159
|
+
if (!e.refusal || (!op.errors.includes(e.refusal) && rule === undefined))
|
|
160
|
+
return [];
|
|
161
|
+
const ids = new Set(subtree(e.trace, e.opSpan).map((s) => s.spanId));
|
|
162
|
+
if (!e.trace.logs.some((l) => ids.has(l.spanId)))
|
|
163
|
+
return [`${where(e)}: ${e.refusal} has no deciding log`];
|
|
164
|
+
if (rule === undefined)
|
|
165
|
+
return [];
|
|
166
|
+
const named = attr(e, "refusal.invariant");
|
|
167
|
+
return named === rule ? [] : [`${where(e)}: ${e.refusal} names ${typeof named === "string" ? named : "no rule"} on its span, not ${rule}`];
|
|
168
|
+
}));
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CallRecord } from "#modules/journeys/types.js";
|
|
2
|
+
import type { Span, Trace } from "#modules/telemetry/types.js";
|
|
3
|
+
import type { Evidence } from "../types.ts";
|
|
4
|
+
/** `grant-an-allowance "ada grants olga 500"`: where a failure happened. */
|
|
5
|
+
export declare const where: (e: Pick<Evidence, "call">) => string;
|
|
6
|
+
export declare const answered: (e: Evidence) => boolean;
|
|
7
|
+
/** Every span under the operation's span, itself included. */
|
|
8
|
+
export declare const subtree: (trace: Trace, root: Span | undefined) => ReadonlyArray<Span>;
|
|
9
|
+
/** A span attribute anywhere in the operation's subtree: `move.to` is written on whichever span made the move. */
|
|
10
|
+
export declare const attr: (e: Evidence, key: string) => unknown;
|
|
11
|
+
export declare const gather: (calls: ReadonlyArray<CallRecord>, traces: ReadonlyMap<string, Trace>) => ReadonlyArray<Evidence>;
|
|
12
|
+
/** A call the server answered from a request it already committed: it ran nothing, so it moved nothing. */
|
|
13
|
+
export declare const replayed: (e: Evidence) => boolean;
|