@north-light/cli 0.3.672 → 0.3.673
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/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/execution-start.d.ts +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/core/pool-credential-store.d.ts +4 -0
- package/dist/core/pool-credential-store.js +1 -1
- package/dist/core/runtime/provider-credential-gate.d.ts +2 -2
- package/dist/core/runtime/provider-credential-gate.js +2 -2
- package/dist/core/runtime/runner/machine/call.d.ts +5 -0
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -1
- package/dist/core/runtime/spawn.d.ts +2 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/subscription-state.d.ts +2 -0
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.d.ts +12 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/execution-start.d.ts +9 -1
- package/dist/daemon/api/handlers/execution-start.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/machine-link/holder.js +4 -4
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/pool-credential-store.js +44 -25
- package/packages/crouter-api/dist/core/review/document.js +143 -0
- package/packages/crouter-api/dist/core/review/project.js +45 -0
- package/packages/crouter-api/dist/core/runtime/launch-recipe.js +45 -0
- package/packages/crouter-api/dist/core/runtime/provider-credential-gate.js +4 -4
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +96 -0
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +170 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +11 -2
- package/packages/crouter-api/dist/core/runtime/spawn.js +88 -3
- package/packages/crouter-api/dist/core/runtime/stop-signals.js +46 -0
- package/packages/crouter-api/dist/core/secrets/blaxel-launch.js +104 -0
- package/packages/crouter-api/dist/core/subscription-state.js +18 -2
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +701 -0
- package/packages/crouter-api/dist/daemon/api/handlers/execution-start.js +120 -0
- package/packages/crouter-api/dist/daemon/api/handlers/node-records.js +113 -0
- package/packages/crouter-api/dist/daemon/api/handlers/telemetry-record.js +34 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
- package/packages/crouter-api/dist/daemon/review/companion.js +29 -0
- package/packages/crouter-api/dist/daemon/review/deliver.js +13 -0
- package/packages/crouter-api/dist/daemon/review/finish.js +170 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// The restart rule for a yield. A running broker can start the next cycle itself unless the launch
|
|
2
|
+
// spec the node would be built with now differs from the one it was built with in anything but the
|
|
3
|
+
// model. The compared fields are the ones the warm pool keys on (warm-pool.ts `warmRecipeKey`):
|
|
4
|
+
// working directory, profile, tools, extensions, system prompt and the launch env.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { KICKOFF_ORIGIN_ENV } from './stamp/protocol.js';
|
|
7
|
+
/** Env the running process re-reads or is given at the start of every cycle, so a change in them is not a launch change. */
|
|
8
|
+
const CYCLE_ENV = new Set([
|
|
9
|
+
'CRTR_KIND', 'CRTR_MODE', 'CRTR_LIFECYCLE', 'CRTR_CYCLES', 'CRTR_MODEL_INTENT', 'CRTR_MODEL_EXACT',
|
|
10
|
+
'CRTR_EXECUTION_ID', 'CRTR_SUBTREE', 'CRTR_KICKOFF_MESSAGE_IDS', 'CRTR_NODE_DEADLINE_AT', KICKOFF_ORIGIN_ENV,
|
|
11
|
+
]);
|
|
12
|
+
/** The env a running broker re-applies at the start of each cycle (and deletes when the next launch spec no longer carries it). */
|
|
13
|
+
export const CYCLE_APPLIED_ENV = ['CRTR_KIND', 'CRTR_MODE', 'CRTR_LIFECYCLE', 'CRTR_CYCLES', 'CRTR_MODEL_INTENT', 'CRTR_NODE_DEADLINE_AT'];
|
|
14
|
+
function argvValues(argv, flag) {
|
|
15
|
+
const values = [];
|
|
16
|
+
for (let i = 0; i < argv.length; i++)
|
|
17
|
+
if (argv[i] === flag && i + 1 < argv.length)
|
|
18
|
+
values.push(argv[++i]);
|
|
19
|
+
return values;
|
|
20
|
+
}
|
|
21
|
+
/** Digest of everything in a launch invocation that a running broker cannot change in place. */
|
|
22
|
+
export function launchRecipeKey(inv) {
|
|
23
|
+
const env = Object.entries(inv.env).filter(([name]) => !CYCLE_ENV.has(name)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
24
|
+
const canonical = JSON.stringify([
|
|
25
|
+
inv.env['CRTR_NODE_CWD'] ?? null,
|
|
26
|
+
inv.env['CRTR_PROFILE_ID'] ?? null,
|
|
27
|
+
argvValues(inv.argv, '--tools'),
|
|
28
|
+
argvValues(inv.argv, '-e'),
|
|
29
|
+
argvValues(inv.argv, '--append-system-prompt'),
|
|
30
|
+
env,
|
|
31
|
+
inv.configSnapshot ?? null,
|
|
32
|
+
inv.scopes ?? null,
|
|
33
|
+
]);
|
|
34
|
+
return createHash('sha256').update(canonical).digest('hex').slice(0, 32);
|
|
35
|
+
}
|
|
36
|
+
/** Whether the process launched from `runningLaunchJson` can start a cycle for `next` without restarting. */
|
|
37
|
+
export function cycleCompatible(runningLaunchJson, nextLaunchJson) {
|
|
38
|
+
if (runningLaunchJson === null)
|
|
39
|
+
return false;
|
|
40
|
+
const running = JSON.parse(runningLaunchJson);
|
|
41
|
+
const next = JSON.parse(nextLaunchJson);
|
|
42
|
+
if (!Array.isArray(running.argv) || running.env === undefined || !Array.isArray(next.argv) || next.env === undefined)
|
|
43
|
+
return false;
|
|
44
|
+
return launchRecipeKey(running) === launchRecipeKey(next);
|
|
45
|
+
}
|
|
@@ -5,9 +5,9 @@ import { cliClient } from '../../commands/api-client.js';
|
|
|
5
5
|
import { hasProviderCredential } from '../provider-credential.js';
|
|
6
6
|
import { piAgentDir } from './package-health.js';
|
|
7
7
|
import { PROVIDER_ENV_KEYS } from './spawn-env.js';
|
|
8
|
-
let
|
|
9
|
-
/** The daemon, which owns the rows, registers its row-backed
|
|
10
|
-
export function registerGateCredentialStore(
|
|
8
|
+
let daemonSnapshot;
|
|
9
|
+
/** The daemon, which owns the rows, registers a builder of its row-backed read-only view (one read per table); every other process asks the daemon over /v1/model-auth. */
|
|
10
|
+
export function registerGateCredentialStore(snapshot) { daemonSnapshot = snapshot; }
|
|
11
11
|
/** Reads through to `store` once per provider (and one `list`) for the life of this wrapper. `ModelRuntime.create` asks for the same
|
|
12
12
|
* provider's credential many times while it builds its availability snapshot, and each ask is a database round trip. Writes are refused:
|
|
13
13
|
* this view exists for one read-only check. */
|
|
@@ -37,7 +37,7 @@ export async function hasConfiguredProviderCredential(profileEnvNames) {
|
|
|
37
37
|
}
|
|
38
38
|
const agentDir = piAgentDir();
|
|
39
39
|
const runtime = await ModelRuntime.create({
|
|
40
|
-
credentials: readOnceStore(
|
|
40
|
+
credentials: daemonSnapshot === undefined ? readOnceStore(new ApiCredentialStore(() => cliClient(), true)) : await daemonSnapshot(),
|
|
41
41
|
modelsPath: join(agentDir, 'models.json'),
|
|
42
42
|
});
|
|
43
43
|
return await hasProviderCredential(runtime, new ModelRegistry(runtime));
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// src/core/runtime/runner/blaxel/release-image.ts — the release image: one Blaxel sandbox image per crouter release, with the release unpacked in it.
|
|
2
|
+
//
|
|
3
|
+
// Without it every fresh sandbox of an environment with no recipe starts from `blaxel/base-image`, then at boot installs ripgrep and downloads,
|
|
4
|
+
// checks and unpacks the 48 MiB release (scripts/sandbox-bootstrap.sh). The release image carries all of that, so `sandbox-bootstrap.sh` finds
|
|
5
|
+
// `/opt/crtr/releases/<version>` complete and skips both. It is built where the release is published (the fleet-deploy `build` job for the gate's
|
|
6
|
+
// workspace, `accept` for production's: scripts/sandbox-release-image.mjs) from the same `runtime.tar.gz` the bootstrap would download, and found by
|
|
7
|
+
// the control plane through a pointer object next to the tarball, `releases/<version>/sandbox-image.json`. No pointer means no image: the launch
|
|
8
|
+
// falls back to the stock image and the download, as before.
|
|
9
|
+
//
|
|
10
|
+
// The image holds no secret and nothing per-person or per-environment (plugins and the start bundle depend on the person and arrive at boot).
|
|
11
|
+
// Daemon-free: the CI script imports this from `dist/`.
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { copyFileSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { buildImage, NODE_BASE_IMAGE, removeBuildDir, RUN_USER, SANDBOX_API_IMAGE } from './image-build.js';
|
|
17
|
+
/** Where the bootstrap keeps releases. Keep in step with `ROOT` in scripts/sandbox-bootstrap.sh. */
|
|
18
|
+
export const RELEASES_DIR = '/opt/crtr/releases';
|
|
19
|
+
/** Written into an unpacked release by the bootstrap and by this image: the sha256 of the tarball it came from. The bootstrap trusts a present release only when this equals the sha the wake names. */
|
|
20
|
+
export const RELEASE_SHA_FILE = '.sha256';
|
|
21
|
+
/** Written last into an unpacked release: it is complete. */
|
|
22
|
+
export const RELEASE_COMPLETE_FILE = '.complete';
|
|
23
|
+
export const RELEASE_TARBALL_FILE = 'runtime.tar.gz';
|
|
24
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
25
|
+
const VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/;
|
|
26
|
+
/** The pointer object's key in the release bucket, beside `runtime.tar.gz` and its sha256. */
|
|
27
|
+
export const releaseImageKey = (version) => `releases/${version}/sandbox-image.json`;
|
|
28
|
+
/** The Blaxel image name of a release: `0.3.668-delivery.1` -> `crtr-release-0-3-668-delivery-1`. Every release has its own image, so a release's image is deleted by name. */
|
|
29
|
+
export function releaseImageName(version) {
|
|
30
|
+
if (!VERSION.test(version))
|
|
31
|
+
throw new Error(`${JSON.stringify(version)} is not a release version`);
|
|
32
|
+
const name = `crtr-release-${version.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
|
33
|
+
if (name.length > 63)
|
|
34
|
+
throw new Error(`image name ${name} is longer than 63 characters`);
|
|
35
|
+
return name;
|
|
36
|
+
}
|
|
37
|
+
/** The Dockerfile of a release image. Pure. Two stages: the release is unpacked in the first, so the tarball is in no layer of the final image.
|
|
38
|
+
* The base is the recipe image's (node, sandbox-api, the `crtr` user), plus `ripgrep` (pi's grep tool) and `python3` (the stock image has it). */
|
|
39
|
+
export function releaseImageDockerfile(version, sha256) {
|
|
40
|
+
if (!SHA256.test(sha256))
|
|
41
|
+
throw new Error('sha256 must be 64 lowercase hex characters');
|
|
42
|
+
releaseImageName(version); // validates the version; it is spliced into shell below
|
|
43
|
+
const dir = `${RELEASES_DIR}/${version}`;
|
|
44
|
+
return [
|
|
45
|
+
`FROM ${NODE_BASE_IMAGE} AS release`,
|
|
46
|
+
`COPY ${RELEASE_TARBALL_FILE} /tmp/${RELEASE_TARBALL_FILE}`,
|
|
47
|
+
`RUN mkdir -p ${dir} && tar -xzf /tmp/${RELEASE_TARBALL_FILE} -C ${dir} && echo ${sha256} > ${dir}/${RELEASE_SHA_FILE} && : > ${dir}/${RELEASE_COMPLETE_FILE}`,
|
|
48
|
+
'',
|
|
49
|
+
`FROM ${NODE_BASE_IMAGE}`,
|
|
50
|
+
'RUN apk add --no-cache bash git curl ripgrep python3',
|
|
51
|
+
`COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
|
|
52
|
+
`RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${RUN_USER} /run/crtr /var/lib/crtr /work`,
|
|
53
|
+
'COPY --from=release /opt/crtr /opt/crtr',
|
|
54
|
+
'WORKDIR /work',
|
|
55
|
+
'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',
|
|
56
|
+
'',
|
|
57
|
+
].join('\n');
|
|
58
|
+
}
|
|
59
|
+
export function releaseImagePointerText(pointer) {
|
|
60
|
+
return `${JSON.stringify(pointer)}\n`;
|
|
61
|
+
}
|
|
62
|
+
/** The image a pointer names for `release` and the tarball `sha256` the wake carries. Throws on a malformed pointer, one for another release, or one built from another tarball: none is a reason to launch silently from the stock image. */
|
|
63
|
+
export function parseReleaseImagePointer(text, release, sha256) {
|
|
64
|
+
let value;
|
|
65
|
+
try {
|
|
66
|
+
value = JSON.parse(text);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new Error(`${releaseImageKey(release)} is not JSON`);
|
|
70
|
+
}
|
|
71
|
+
const pointer = value;
|
|
72
|
+
if (pointer === null || typeof pointer !== 'object' || typeof pointer.release !== 'string' || typeof pointer.sha256 !== 'string' || typeof pointer.image !== 'string' || pointer.image === '') {
|
|
73
|
+
throw new Error(`${releaseImageKey(release)} must hold {release, sha256, image}`);
|
|
74
|
+
}
|
|
75
|
+
if (pointer.release !== release)
|
|
76
|
+
throw new Error(`${releaseImageKey(release)} names release ${pointer.release}`);
|
|
77
|
+
if (pointer.sha256 !== sha256)
|
|
78
|
+
throw new Error(`${releaseImageKey(release)} was built from tarball ${pointer.sha256}, not ${sha256}`);
|
|
79
|
+
return pointer.image;
|
|
80
|
+
}
|
|
81
|
+
/** Builds the release's image in the workspace `config` names and returns its pointer. */
|
|
82
|
+
export async function buildReleaseImage(config, input, options = {}) {
|
|
83
|
+
const actual = createHash('sha256').update(readFileSync(input.tarball)).digest('hex');
|
|
84
|
+
if (actual !== input.sha256)
|
|
85
|
+
throw new Error(`${input.tarball} has sha256 ${actual}, not ${input.sha256}`);
|
|
86
|
+
const dir = mkdtempSync(join(tmpdir(), 'crtr-release-image-'));
|
|
87
|
+
try {
|
|
88
|
+
copyFileSync(input.tarball, join(dir, RELEASE_TARBALL_FILE));
|
|
89
|
+
writeFileSync(join(dir, 'Dockerfile'), releaseImageDockerfile(input.release, input.sha256));
|
|
90
|
+
const built = await buildImage(config, releaseImageName(input.release), dir, options);
|
|
91
|
+
return { pointer: { release: input.release, sha256: input.sha256, image: built.ref }, built };
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
removeBuildDir(dir);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// src/core/runtime/runner/blaxel/runner.ts — the Blaxel runner (design-fleet, Components: Runner; C-A2).
|
|
2
|
+
//
|
|
3
|
+
// One sandbox per node attempt (`executions.sandbox_name`, `<node id>-<attempt>`), one process per execution
|
|
4
|
+
// named `broker-<execution id>`. That process runs the bootstrap, which installs the release and runs
|
|
5
|
+
// `crtr-sandbox-start`; the start script stays as the broker's parent. The runner never reads the sandbox's
|
|
6
|
+
// own status as the freeze signal: a frozen broker reads `running` from the process status. It reads the
|
|
7
|
+
// sandbox `state` (STANDBY while frozen; reading it does not wake the sandbox) only in `sandboxState`, for
|
|
8
|
+
// the freeze measurement. The process status goes through the sandbox and so wakes it: `status` of an idle execution never asks.
|
|
9
|
+
import { openDb } from '../../../canvas/db.js';
|
|
10
|
+
import { mintExecutionToken } from '../../../canvas/node-tokens.js';
|
|
11
|
+
import { BlaxelApiError, isWorkloadUnavailable } from './client.js';
|
|
12
|
+
/** The broker listens here inside the sandbox; the private preview forwards it (`wss://<preview>/view`). */
|
|
13
|
+
export const BROKER_VIEW_PORT = 4180;
|
|
14
|
+
const VIEW_PREVIEW = 'view';
|
|
15
|
+
/** Where the bootstrap keeps the newest release it installed; the wake script is run from here. */
|
|
16
|
+
export const WAKE_COMMAND = 'node /opt/crtr/current/scripts/sandbox-start.mjs --wake';
|
|
17
|
+
/** `crtr-sandbox-start --wake` exits with this when no broker of the execution runs. */
|
|
18
|
+
export const EXIT_NO_BROKER = 3;
|
|
19
|
+
/** A failing start script prints a last line `crtr-sandbox-start: failed <reason>`; `status` reports the reason. */
|
|
20
|
+
export const FAILURE_LINE = /^crtr-sandbox-start: failed (\S+)/m;
|
|
21
|
+
/** How much of a failed process's output `status` carries: enough for the boot phase lines and the error that ended the start. */
|
|
22
|
+
const FAILURE_OUTPUT_CHARS = 2000;
|
|
23
|
+
export const brokerProcessName = (executionId) => `broker-${executionId}`;
|
|
24
|
+
export const sandboxNameFor = (execution) => execution.sandboxName ?? `${execution.nodeId}-${execution.attempt}`;
|
|
25
|
+
/** Every execution of a node that ran in a sandbox has one, named by `sandboxNameFor`: `start` creates it under that name and nothing
|
|
26
|
+
* writes `executions.sandbox_name`, so the column is null on every row and the name is `<node id>-<attempt>`. */
|
|
27
|
+
async function defaultSandboxNames(nodeId) {
|
|
28
|
+
const rows = await (await openDb()).prepare("SELECT execution_id, attempt, sandbox_name FROM executions WHERE node_id = ? AND runner = 'blaxel'").all(nodeId);
|
|
29
|
+
return [...new Set(rows.map((row) => sandboxNameFor({ executionId: row.execution_id, nodeId, attempt: Number(row.attempt), sandboxName: row.sandbox_name })))];
|
|
30
|
+
}
|
|
31
|
+
function failureOf(process) {
|
|
32
|
+
const text = `${process.logs}\n${process.stderr}\n${process.stdout}`;
|
|
33
|
+
const output = (process.stderr || process.logs || process.stdout || '').trim().slice(-FAILURE_OUTPUT_CHARS);
|
|
34
|
+
return { state: 'failed', reason: FAILURE_LINE.exec(text)?.[1] ?? 'start_failed', code: process.exitCode, ...(output === '' ? {} : { output }) };
|
|
35
|
+
}
|
|
36
|
+
export function createBlaxelRunner(deps) {
|
|
37
|
+
const { client } = deps;
|
|
38
|
+
const stopGraceMs = (deps.stopGraceS ?? 10) * 1000;
|
|
39
|
+
const previewTokens = new Map();
|
|
40
|
+
async function sandboxOf(execution) {
|
|
41
|
+
return await client.getSandbox(sandboxNameFor(execution));
|
|
42
|
+
}
|
|
43
|
+
/** Stops any broker of the execution still in the sandbox (SIGTERM, then SIGKILL after the grace) and reports whether none is left. */
|
|
44
|
+
async function brokerGone(sandbox, executionId) {
|
|
45
|
+
if (!/^[A-Za-z0-9_-]+$/.test(executionId))
|
|
46
|
+
throw new Error(`execution id ${JSON.stringify(executionId)} is not safe to name in a command`);
|
|
47
|
+
// A broker's argv is `broker-cli.js ... --epoch <execution> <node>`; `[b]` keeps the pattern from matching this command's own command line.
|
|
48
|
+
const graceS = Math.max(1, Math.ceil(stopGraceMs / 1000));
|
|
49
|
+
const command = `p='[b]roker-cli\\.js .*--epoch ${executionId}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${graceS * 5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;
|
|
50
|
+
return (await client.exec(sandbox, `stop-${executionId}-${Date.now()}`, command, graceS + 20)).exitCode === 0;
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
kind: 'blaxel',
|
|
54
|
+
async start(input) {
|
|
55
|
+
const context = await deps.launchContext(input);
|
|
56
|
+
const name = sandboxNameFor(input);
|
|
57
|
+
// "Name taken" means a previous attempt created it: the client adopts it.
|
|
58
|
+
const sandbox = await client.createSandbox({ name, image: context.image, memoryMb: context.memoryMb, ports: [{ name: VIEW_PREVIEW, target: BROKER_VIEW_PORT }] });
|
|
59
|
+
const process = brokerProcessName(input.executionId);
|
|
60
|
+
// A repeated call (a reconciler whose lease was taken) finds the process and adopts it: no second token.
|
|
61
|
+
const existing = await client.getProcess(sandbox, process);
|
|
62
|
+
if (existing?.status === 'running')
|
|
63
|
+
return { pid: null, exited: null };
|
|
64
|
+
await client.ensurePreview(name, VIEW_PREVIEW, BROKER_VIEW_PORT);
|
|
65
|
+
const token = await (deps.mintToken ?? ((i) => mintExecutionToken(i.executionId, i.nodeId)))(input);
|
|
66
|
+
// Reserved names win over a secret that tries to override them.
|
|
67
|
+
const env = { ...context.secrets,
|
|
68
|
+
CRTR_API_URL: context.apiUrl, CRTR_EXECUTION_ID: input.executionId, CRTR_NODE_TOKEN: token,
|
|
69
|
+
CRTR_RELEASE: input.release, CRTR_RELEASE_URL: context.releaseUrl, CRTR_RELEASE_SHA256: context.releaseSha256 };
|
|
70
|
+
await client.startProcess(sandbox, { name: process, command: deps.bootstrap(), env, waitForCompletion: false });
|
|
71
|
+
return { pid: null, exited: null };
|
|
72
|
+
},
|
|
73
|
+
async wake(execution) {
|
|
74
|
+
const sandbox = await sandboxOf(execution);
|
|
75
|
+
if (sandbox === null)
|
|
76
|
+
return 'no_broker';
|
|
77
|
+
// One process call thaws the sandbox and signals the broker; it carries no token.
|
|
78
|
+
try {
|
|
79
|
+
const result = await client.exec(sandbox, `wake-${execution.executionId}-${Date.now()}`, `${WAKE_COMMAND} ${execution.executionId}`, 30);
|
|
80
|
+
if (result.exitCode === 0)
|
|
81
|
+
return 'signalled';
|
|
82
|
+
if (result.exitCode === EXIT_NO_BROKER)
|
|
83
|
+
return 'no_broker';
|
|
84
|
+
throw new Error(`wake of ${execution.executionId} failed (exit ${result.exitCode}): ${(result.stderr || result.logs).slice(0, 300)}`);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (isWorkloadUnavailable(error))
|
|
88
|
+
return 'no_broker';
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
async stop(execution, _options) {
|
|
93
|
+
try {
|
|
94
|
+
const sandbox = await sandboxOf(execution);
|
|
95
|
+
if (sandbox === null)
|
|
96
|
+
return { confirmed: true };
|
|
97
|
+
const name = brokerProcessName(execution.executionId);
|
|
98
|
+
const running = async () => (await client.getProcess(sandbox, name))?.status === 'running';
|
|
99
|
+
if (await running()) {
|
|
100
|
+
// The tracked process is the start script (the bootstrap execs into it): SIGTERM reaches the broker through its handler.
|
|
101
|
+
await client.stopProcess(sandbox, name);
|
|
102
|
+
const deadline = Date.now() + stopGraceMs;
|
|
103
|
+
while (Date.now() < deadline && await running())
|
|
104
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
105
|
+
if (await running())
|
|
106
|
+
await client.killProcess(sandbox, name);
|
|
107
|
+
if (await running())
|
|
108
|
+
return { confirmed: false };
|
|
109
|
+
}
|
|
110
|
+
// A killed start script leaves its broker behind, so the answer is the broker's absence, not the process status.
|
|
111
|
+
return { confirmed: await brokerGone(sandbox, execution.executionId) };
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
if (isWorkloadUnavailable(error))
|
|
115
|
+
return { confirmed: true };
|
|
116
|
+
return { confirmed: false, error: error instanceof Error ? error : new Error(String(error)) };
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
async status(execution, options) {
|
|
120
|
+
try {
|
|
121
|
+
const sandbox = await sandboxOf(execution);
|
|
122
|
+
if (sandbox === null)
|
|
123
|
+
return { state: 'gone' };
|
|
124
|
+
// An idle broker's sandbox is frozen or freezing, and a request through it counts as activity that keeps it awake:
|
|
125
|
+
// the control plane's answer that the sandbox exists is all that is asked. A broker lost inside it is found at the next wake.
|
|
126
|
+
if (options?.idle === true)
|
|
127
|
+
return { state: 'running', pid: null };
|
|
128
|
+
const process = await client.getProcess(sandbox, brokerProcessName(execution.executionId));
|
|
129
|
+
if (process === null)
|
|
130
|
+
return { state: 'gone' };
|
|
131
|
+
if (process.status === 'running')
|
|
132
|
+
return { state: 'running', pid: null };
|
|
133
|
+
if (process.status === 'failed' || (process.status === 'completed' && process.exitCode !== 0))
|
|
134
|
+
return failureOf(process);
|
|
135
|
+
return { state: 'gone' };
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (isWorkloadUnavailable(error))
|
|
139
|
+
return { state: 'gone' };
|
|
140
|
+
return { state: 'unknown', error: error instanceof Error ? error.message : String(error) };
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
async delete(nodeId) {
|
|
144
|
+
for (const name of await (deps.sandboxNamesForNode ?? defaultSandboxNames)(nodeId))
|
|
145
|
+
await client.deleteSandbox(name);
|
|
146
|
+
},
|
|
147
|
+
async deleteExecution(execution) {
|
|
148
|
+
await client.deleteSandbox(sandboxNameFor(execution));
|
|
149
|
+
},
|
|
150
|
+
async viewerAddress(execution) {
|
|
151
|
+
const name = sandboxNameFor(execution);
|
|
152
|
+
const cached = previewTokens.get(name);
|
|
153
|
+
if (cached && cached.expiresAt - Date.now() > 5 * 60_000)
|
|
154
|
+
return viewer(cached.url, cached.token);
|
|
155
|
+
const url = await client.ensurePreview(name, VIEW_PREVIEW, BROKER_VIEW_PORT);
|
|
156
|
+
const expires = new Date(Date.now() + 60 * 60_000);
|
|
157
|
+
const { token } = await client.createPreviewToken(name, VIEW_PREVIEW, expires);
|
|
158
|
+
previewTokens.set(name, { url, token, expiresAt: expires.getTime() });
|
|
159
|
+
return viewer(url, token);
|
|
160
|
+
},
|
|
161
|
+
/** The sandbox `state` (`STANDBY` while frozen), read without waking it. Null when the sandbox is gone. Measurement only. */
|
|
162
|
+
async sandboxState(execution) {
|
|
163
|
+
return (await sandboxOf(execution))?.state ?? null;
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function viewer(previewUrl, token) {
|
|
168
|
+
return { kind: 'wss', url: `${previewUrl.replace(/^https:/, 'wss:')}/view`, headers: { 'x-blaxel-preview-token': token } };
|
|
169
|
+
}
|
|
170
|
+
export { BlaxelApiError };
|
|
@@ -16,7 +16,9 @@ export const MACHINE_CALL_TIMEOUT_S = {
|
|
|
16
16
|
'repo.identify': 15,
|
|
17
17
|
};
|
|
18
18
|
const REREAD_MS = 1000;
|
|
19
|
-
|
|
19
|
+
/** Write the `pending` call row and notify the link's holder, in the caller's transaction when it has one (the notification is delivered at its commit,
|
|
20
|
+
* so a call queued by a transaction that rolls back is never sent). No live link → MachineOfflineError, nothing written. Returns the call id for `awaitMachineCall`. */
|
|
21
|
+
export async function enqueueMachineCall(environmentId, op, args) {
|
|
20
22
|
const callId = randomUUID();
|
|
21
23
|
const now = new Date().toISOString();
|
|
22
24
|
const queued = await withCanvasWrite(async (db) => {
|
|
@@ -29,6 +31,13 @@ export async function callMachine(environmentId, op, args, options = {}) {
|
|
|
29
31
|
});
|
|
30
32
|
if (!queued)
|
|
31
33
|
throw new MachineOfflineError(environmentId, 'no live link');
|
|
34
|
+
return callId;
|
|
35
|
+
}
|
|
36
|
+
export async function callMachine(environmentId, op, args, options = {}) {
|
|
37
|
+
return await awaitMachineCall(environmentId, op, await enqueueMachineCall(environmentId, op, args), options);
|
|
38
|
+
}
|
|
39
|
+
/** Wait for the holder's answer to a queued call. */
|
|
40
|
+
export async function awaitMachineCall(environmentId, op, callId, options = {}) {
|
|
32
41
|
const deadline = Date.now() + (options.timeoutMs ?? MACHINE_CALL_TIMEOUT_S[op] * 1000);
|
|
33
42
|
// A settle signalled before the subscription is in place is caught by the first read below, which comes after it.
|
|
34
43
|
let wake;
|
|
@@ -86,7 +95,7 @@ async function waitForCall(environmentId, op, callId, deadline, rereadMs, pause)
|
|
|
86
95
|
/** Fail an open call as `machine_lost` when a holder claimed it, else `machine_offline` (never sent). Returns the claimed generation
|
|
87
96
|
* the row had (null: never claimed), or undefined when the call was already settled, which the caller reads again. */
|
|
88
97
|
async function failOpenCall(callId, message) {
|
|
89
|
-
const failed = await (await openDb()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?,
|
|
98
|
+
const failed = await (await openDb()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?, args_json = '{}',
|
|
90
99
|
result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
|
|
91
100
|
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`)
|
|
92
101
|
.get(new Date().toISOString(), JSON.stringify({ code: 'machine_offline', message, sent: false }), JSON.stringify({ code: 'machine_lost', message }), callId);
|
|
@@ -40,7 +40,17 @@ import { awaitBrokerViewSocket } from './view-socket.js';
|
|
|
40
40
|
import { readLogSnapshot } from '../events/read.js';
|
|
41
41
|
import { transition } from './lifecycle.js';
|
|
42
42
|
import { beginBootFaultAttempt } from '../canvas/recovery.js';
|
|
43
|
-
import { headlessBrokerHost } from './host.js';
|
|
43
|
+
import { headlessBrokerHost, brokerLaunchJson } from './host.js';
|
|
44
|
+
import { openDb, withCanvasWrite } from '../canvas/db.js';
|
|
45
|
+
import { warmNodeRepos } from '../graph/reader.js';
|
|
46
|
+
import { mintNodeToken } from '../canvas/node-tokens.js';
|
|
47
|
+
import { personIdAsync } from '../canvas/person.js';
|
|
48
|
+
import { recordLaunch } from '../canvas/canvas.js';
|
|
49
|
+
import { setExecutionLaunchJson } from '../canvas/executions.js';
|
|
50
|
+
import { acceptedRelease, remoteMachineEnvironmentOf } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
|
|
51
|
+
import { enqueueMachineCall, awaitMachineCall } from './runner/machine/call.js';
|
|
52
|
+
import { MachineLostError, MachineOfflineError } from './runner/machine/ops.js';
|
|
53
|
+
import { isDrained } from '../../daemon/drain.js';
|
|
44
54
|
import { ensureDaemon } from '../../daemon/manage.js';
|
|
45
55
|
import { readConfig } from '../config.js';
|
|
46
56
|
import { modelRequestFromConfig, unregisteredConcreteModel, unroutableConcreteModel } from '../model-routes.js';
|
|
@@ -260,6 +270,72 @@ export function resolveSpawner(parent, ctxNodeId, root) {
|
|
|
260
270
|
}
|
|
261
271
|
return spawner;
|
|
262
272
|
}
|
|
273
|
+
/** Launch a just-born node on its remote machine in two transactions: the node and execution rows are committed (as a birth always does), then one
|
|
274
|
+
* transaction renders the start data, mints the token and queues the `start` call; the call is awaited after that commit. The bundle's network work
|
|
275
|
+
* (GitHub token, blob store) runs before that transaction opens. 'failed': nothing started, the caller freezes the node for the lifecycle tick to wake.
|
|
276
|
+
* 'uncertain': the call was sent and its answer lost, so the Mac may have a broker: the execution stays launching and the node stays active, and the
|
|
277
|
+
* tick's `status` of that execution decides (the machine runner's rule). 'full': the daemon is drained or at its broker cap, so nothing was begun. */
|
|
278
|
+
async function startOnMachine(meta, environmentId, inv) {
|
|
279
|
+
// Loaded here: the handlers import the runtime that imports this module.
|
|
280
|
+
const { buildStartBundle } = await import('../../daemon/api/handlers/execution-start.js');
|
|
281
|
+
const { renderCarriedStart } = await import('../../daemon/api/handlers/broker-ops.js');
|
|
282
|
+
// The checks reviveNode makes before it begins an execution: a drained daemon starts nothing, and the execution cap is enforced by the insert.
|
|
283
|
+
if (await isDrained())
|
|
284
|
+
return 'full';
|
|
285
|
+
let executionId;
|
|
286
|
+
try {
|
|
287
|
+
executionId = await beginExecution(meta.node_id, { daemonEpoch: boundFleet().epoch(), cap: brokerThresholdsForDaemon().automaticReviveCap, runner: 'machine', release: acceptedRelease() });
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
if (error instanceof ExecutionCapReached)
|
|
291
|
+
return 'full';
|
|
292
|
+
emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
|
|
293
|
+
return 'failed';
|
|
294
|
+
}
|
|
295
|
+
let callId;
|
|
296
|
+
try {
|
|
297
|
+
inv.env = { ...inv.env, CRTR_EXECUTION_ID: executionId };
|
|
298
|
+
const launchJson = await brokerLaunchJson(meta.node_id, inv, meta.cwd);
|
|
299
|
+
await setExecutionLaunchJson(executionId, launchJson);
|
|
300
|
+
const execId = executionId;
|
|
301
|
+
await warmNodeRepos(await openDb(), meta.node_id);
|
|
302
|
+
const sub = meta.sub ?? await personIdAsync();
|
|
303
|
+
const bundle = await buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' });
|
|
304
|
+
callId = await withCanvasWrite(async (db) => {
|
|
305
|
+
// The reader is built here, after the goal and every birth write have landed, so the rendered bearings see them.
|
|
306
|
+
const start = await renderCarriedStart(meta.node_id);
|
|
307
|
+
const nodeToken = await mintNodeToken(db, execId, meta.node_id, new Date().toISOString());
|
|
308
|
+
return await enqueueMachineCall(environmentId, 'start', {
|
|
309
|
+
executionId: execId, nodeId: meta.node_id, attempt: 1, sandboxName: null, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
|
|
310
|
+
nodeToken, bundle, start,
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
|
|
316
|
+
await abortExecution(executionId, { reason: 'launch_failed' });
|
|
317
|
+
return 'failed';
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
await awaitMachineCall(environmentId, 'start', callId);
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
|
|
324
|
+
// Sent and unanswered (the link dropped, or the lease ran out): the Mac may have spawned the broker, so the execution and its token stay.
|
|
325
|
+
if (error instanceof MachineLostError || (error instanceof MachineOfflineError && error.sent))
|
|
326
|
+
return 'uncertain';
|
|
327
|
+
await abortExecution(executionId, { reason: 'launch_failed' });
|
|
328
|
+
return 'failed';
|
|
329
|
+
}
|
|
330
|
+
// The Mac has confirmed the start: a failure to record it must not end a running execution.
|
|
331
|
+
try {
|
|
332
|
+
await recordLaunch(meta.node_id, new Date().toISOString());
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
emitEvent({ level: 'warn', event: 'broker.create_start_record_failed', node_id: meta.node_id, error });
|
|
336
|
+
}
|
|
337
|
+
return 'started';
|
|
338
|
+
}
|
|
263
339
|
export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCreated) {
|
|
264
340
|
try {
|
|
265
341
|
ensureDaemon();
|
|
@@ -486,9 +562,18 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
|
|
|
486
562
|
// dormant with its goal kept, and the node-lifecycle lane wakes it through `reviveNode`, the one launch path that chooses the
|
|
487
563
|
// Blaxel or machine runner and runs the bill check.
|
|
488
564
|
if (await remoteEnvironmentOf(meta.profile_id ?? null) !== null) {
|
|
489
|
-
|
|
565
|
+
const frozenAt = new Date().toISOString();
|
|
566
|
+
// A create that asked to start, for a node on a machine this control plane reaches over a link: the start call carries everything the
|
|
567
|
+
// Mac needs, so the node is never left dormant for the lifecycle tick to wake.
|
|
568
|
+
const machine = opts.start === true ? await remoteMachineEnvironmentOf(meta.profile_id ?? null) : null;
|
|
569
|
+
if (machine !== null) {
|
|
570
|
+
const started = await startOnMachine(meta, machine, inv);
|
|
571
|
+
if (started === 'started' || started === 'uncertain')
|
|
572
|
+
return { node: meta, frozen: false, window: null, session: null };
|
|
573
|
+
}
|
|
574
|
+
await setFrozen(meta.node_id, frozenAt);
|
|
490
575
|
emitEvent({ level: 'info', event: 'broker.frozen', node_id: meta.node_id, fields: { reason: 'remote_environment' } });
|
|
491
|
-
return { node:
|
|
576
|
+
return { node: { ...meta, frozen_at: frozenAt }, frozen: true, window: null, session: null };
|
|
492
577
|
}
|
|
493
578
|
const slot = await fleet.reserveSlot(meta.node_id);
|
|
494
579
|
// The slot is held while the launcher measures the app's memory; a denial gives it back before freezing.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { jobDir } from '../canvas/paths.js';
|
|
4
|
+
const SIGNALS = ['pushedFinal'];
|
|
5
|
+
function signalPath(nodeId, signal) {
|
|
6
|
+
return join(jobDir(nodeId), `.${signal}`);
|
|
7
|
+
}
|
|
8
|
+
/** Which broker process a marker belongs to. `broker.ts` exports
|
|
9
|
+
* `CRTR_BROKER_PID` into its own env, so inside a broker this IS `process.pid`
|
|
10
|
+
* and every crtr command it spawns inherits the same value. Both the write and
|
|
11
|
+
* the read side go through this so a marker written by a command is recognized
|
|
12
|
+
* by the broker that consumes it — and so neither side is thrown off by an
|
|
13
|
+
* outer broker's pid leaking in through the environment. */
|
|
14
|
+
function brokerIdentity() {
|
|
15
|
+
return process.env['CRTR_BROKER_PID'] ?? String(process.pid);
|
|
16
|
+
}
|
|
17
|
+
/** Record a successful command outcome for this broker process. The stophook
|
|
18
|
+
* consumes the marker at settlement, so no broker-side canvas read is needed to
|
|
19
|
+
* recognize the command the node itself just completed. */
|
|
20
|
+
export function markStopSignal(nodeId, signal, identity = brokerIdentity()) {
|
|
21
|
+
mkdirSync(jobDir(nodeId), { recursive: true });
|
|
22
|
+
writeFileSync(signalPath(nodeId, signal), identity);
|
|
23
|
+
}
|
|
24
|
+
/** Consume command outcomes from this broker's just-settled turn. Markers from
|
|
25
|
+
* an earlier crashed broker are discarded rather than bleeding into its successor. */
|
|
26
|
+
export function consumeStopSignals(nodeId, identity = brokerIdentity()) {
|
|
27
|
+
const signals = { pushedFinal: false };
|
|
28
|
+
for (const signal of SIGNALS) {
|
|
29
|
+
const path = signalPath(nodeId, signal);
|
|
30
|
+
if (!existsSync(path))
|
|
31
|
+
continue;
|
|
32
|
+
const brokerPid = readFileSync(path, 'utf8').trim();
|
|
33
|
+
rmSync(path, { force: true });
|
|
34
|
+
if (brokerPid === identity)
|
|
35
|
+
signals[signal] = true;
|
|
36
|
+
}
|
|
37
|
+
return signals;
|
|
38
|
+
}
|
|
39
|
+
/** Discard any marker left by an earlier run of this same broker — a run that
|
|
40
|
+
* errored or was interrupted returns before settlement consumes its markers, and
|
|
41
|
+
* the pid stamp cannot tell those apart from the current run's. Called when a new
|
|
42
|
+
* user-directed run begins, never on an in-run retry. */
|
|
43
|
+
export function clearStopSignals(nodeId) {
|
|
44
|
+
for (const signal of SIGNALS)
|
|
45
|
+
rmSync(signalPath(nodeId, signal), { force: true });
|
|
46
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// The control plane's `BlaxelRunnerDeps.launchContext` (design-fleet, Components: Runner; C-D4): what a Blaxel `start` needs beyond the execution —
|
|
2
|
+
// the environment's image and memory, the API url, a signed release URL with its sha256, and the environment's opened secrets.
|
|
3
|
+
// Daemon-only: it reads the database and the secrets key.
|
|
4
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
5
|
+
import { openDb } from '../canvas/db.js';
|
|
6
|
+
import { blobStore } from '../blobs/index.js';
|
|
7
|
+
import { environmentOfNode, packagesTokenFor } from '../../daemon/api/environment-of.js';
|
|
8
|
+
import { EnvironmentImagePending } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
|
|
9
|
+
import { resolveEnvironmentImage } from '../../daemon/reconcilers/recipe-image.js';
|
|
10
|
+
import { parseReleaseImagePointer, releaseImageKey } from '../runtime/runner/blaxel/release-image.js';
|
|
11
|
+
import { environmentSecrets } from './environment-secrets.js';
|
|
12
|
+
import { environmentOwnerProfile, profileInApp } from './environment-owner.js';
|
|
13
|
+
export const BASE_IMAGE = 'blaxel/base-image:latest';
|
|
14
|
+
/** How long the signed release URL stays valid. */
|
|
15
|
+
export const RELEASE_URL_TTL_S = 15 * 60;
|
|
16
|
+
/** The sandbox image a launch starts from: the environment's recipe image when it has one; otherwise the release's own image (`releaseImage`, from the pointer object
|
|
17
|
+
* beside the release) when the release was published with one; otherwise the stock image, whose bootstrap installs the release at boot. */
|
|
18
|
+
export function launchImage(environment, releaseImage) {
|
|
19
|
+
if (environment.state === 'image')
|
|
20
|
+
return environment.ref;
|
|
21
|
+
return releaseImage ?? BASE_IMAGE;
|
|
22
|
+
}
|
|
23
|
+
export function releaseSignerFromEnv(env = process.env) {
|
|
24
|
+
const need = (name) => { const v = env[name]; if (!v)
|
|
25
|
+
throw new Error(`${name} is required to sign release URLs`); return v; };
|
|
26
|
+
return { bucket: need('CRTR_R2_BUCKET'), endpoint: need('CRTR_R2_ENDPOINT'), accessKeyId: need('CRTR_R2_ACCESS_KEY_ID'), secretAccessKey: need('CRTR_R2_SECRET_ACCESS_KEY') };
|
|
27
|
+
}
|
|
28
|
+
const sha256hex = (data) => createHash('sha256').update(data).digest('hex');
|
|
29
|
+
const hmac = (key, data) => createHmac('sha256', key).update(data).digest();
|
|
30
|
+
const encode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
31
|
+
/** A SigV4 query-signed GET (path style, region `auto`) of `key`, valid `ttlS` seconds from `now`. */
|
|
32
|
+
export function presignGet(signer, key, ttlS, now = new Date()) {
|
|
33
|
+
const base = new URL(signer.endpoint);
|
|
34
|
+
const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
|
|
35
|
+
const date = amzDate.slice(0, 8);
|
|
36
|
+
const scope = `${date}/auto/s3/aws4_request`;
|
|
37
|
+
const path = `/${encode(signer.bucket)}/${key.split('/').map(encode).join('/')}`;
|
|
38
|
+
const query = [
|
|
39
|
+
['X-Amz-Algorithm', 'AWS4-HMAC-SHA256'], ['X-Amz-Credential', `${signer.accessKeyId}/${scope}`], ['X-Amz-Date', amzDate],
|
|
40
|
+
['X-Amz-Expires', String(ttlS)], ['X-Amz-SignedHeaders', 'host'],
|
|
41
|
+
];
|
|
42
|
+
const canonicalQuery = query.sort(([a], [b]) => a < b ? -1 : 1).map(([k, v]) => `${encode(k)}=${encode(v)}`).join('&');
|
|
43
|
+
const request = ['GET', path, canonicalQuery, `host:${base.host}\n`, 'host', 'UNSIGNED-PAYLOAD'].join('\n');
|
|
44
|
+
const toSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256hex(request)].join('\n');
|
|
45
|
+
const signingKey = hmac(hmac(hmac(hmac(`AWS4${signer.secretAccessKey}`, date), 'auto'), 's3'), 'aws4_request');
|
|
46
|
+
const signature = createHmac('sha256', signingKey).update(toSign).digest('hex');
|
|
47
|
+
return `${base.origin}${path}?${canonicalQuery}&X-Amz-Signature=${signature}`;
|
|
48
|
+
}
|
|
49
|
+
/** Reads the control plane's settings from the environment: `CRTR_PUBLIC_API_URL` (where a sandbox reaches `/v1`) and the four `CRTR_R2_*` variables. */
|
|
50
|
+
export function blaxelLaunchDepsFromEnv(env = process.env) {
|
|
51
|
+
const apiUrl = env['CRTR_PUBLIC_API_URL'];
|
|
52
|
+
if (!apiUrl || !/^https?:\/\//.test(apiUrl))
|
|
53
|
+
throw new Error('CRTR_PUBLIC_API_URL must be an http(s) URL for the Blaxel runner');
|
|
54
|
+
return { apiUrl, signer: releaseSignerFromEnv(env) };
|
|
55
|
+
}
|
|
56
|
+
async function defaultReleaseSha(version) {
|
|
57
|
+
const bytes = await (await blobStore()).get(`releases/${version}/runtime.tar.gz.sha256`);
|
|
58
|
+
return bytes === null ? null : bytes.toString('utf8');
|
|
59
|
+
}
|
|
60
|
+
async function defaultReleaseImage(version) {
|
|
61
|
+
const bytes = await (await blobStore()).get(releaseImageKey(version));
|
|
62
|
+
return bytes === null ? null : bytes.toString('utf8');
|
|
63
|
+
}
|
|
64
|
+
export function createBlaxelLaunchContext(deps) {
|
|
65
|
+
return async (input) => {
|
|
66
|
+
const db = await openDb();
|
|
67
|
+
const node = await db.prepare('SELECT profile_id, grantee FROM node_rows WHERE node_id = ?').get(input.nodeId);
|
|
68
|
+
if (node === undefined)
|
|
69
|
+
throw new Error(`no node ${input.nodeId}`);
|
|
70
|
+
if (node.profile_id === null)
|
|
71
|
+
throw new Error(`node ${input.nodeId} has no profile, so it has no person`);
|
|
72
|
+
const person = await db.prepare('SELECT person FROM profiles WHERE id = ?').get(node.profile_id);
|
|
73
|
+
if (person === undefined)
|
|
74
|
+
throw new Error(`profile ${node.profile_id} has no row`);
|
|
75
|
+
const app = node.grantee ?? 'app:terminal';
|
|
76
|
+
const environmentId = await environmentOfNode(node.profile_id);
|
|
77
|
+
const image = await resolveEnvironmentImage(environmentId);
|
|
78
|
+
if (image.state === 'pending')
|
|
79
|
+
throw new EnvironmentImagePending(environmentId, image.error);
|
|
80
|
+
const environment = await db.prepare('SELECT memory_mb FROM environments WHERE object = ?').get(environmentId);
|
|
81
|
+
if (environment === undefined)
|
|
82
|
+
throw new Error(`no environment ${environmentId}`);
|
|
83
|
+
// The environment's owner is an app or a profile object; a profile's identity is `profile:<profile id>`.
|
|
84
|
+
const ownerProfile = await environmentOwnerProfile(environmentId);
|
|
85
|
+
const ownerInApp = ownerProfile !== null && await profileInApp(ownerProfile, app);
|
|
86
|
+
const sha = ((await (deps.releaseSha ?? defaultReleaseSha)(input.release)) ?? '').trim().split(/\s+/)[0] ?? '';
|
|
87
|
+
if (!/^[0-9a-f]{64}$/.test(sha))
|
|
88
|
+
throw new Error(`release ${input.release} has no sha256 object (releases/${input.release}/runtime.tar.gz.sha256)`);
|
|
89
|
+
// Only an environment with no recipe image can use the release image, so only then is the pointer read.
|
|
90
|
+
const pointer = image.state === 'base' ? await (deps.releaseImage ?? defaultReleaseImage)(input.release) : null;
|
|
91
|
+
const releaseImage = pointer === null ? null : parseReleaseImagePointer(pointer, input.release, sha);
|
|
92
|
+
const packagesToken = await packagesTokenFor(environmentId);
|
|
93
|
+
const secrets = await environmentSecrets({ person: person.person, app, ownerProfile, ownerProfileInApp: ownerInApp, includeDeployment: false });
|
|
94
|
+
return {
|
|
95
|
+
image: launchImage(image, releaseImage),
|
|
96
|
+
memoryMb: Number(environment.memory_mb),
|
|
97
|
+
apiUrl: deps.apiUrl,
|
|
98
|
+
releaseUrl: presignGet(deps.signer, `releases/${input.release}/runtime.tar.gz`, RELEASE_URL_TTL_S, deps.now?.()),
|
|
99
|
+
releaseSha256: sha,
|
|
100
|
+
// Profile rows merge last, so a profile's own NODE_AUTH_TOKEN wins.
|
|
101
|
+
secrets: packagesToken !== null ? { NODE_AUTH_TOKEN: packagesToken, ...secrets } : secrets,
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
}
|