@north-light/api 0.3.751 → 0.3.753
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/environments.d.ts +37 -0
- package/dist/api/dto/health.d.ts +3 -0
- package/dist/api/routes.d.ts +2 -0
- package/dist/api/routes.js +2 -0
- package/dist/commands/sys/daemon.js +8 -3
- package/dist/core/canvas/canvas.d.ts +1 -1
- package/dist/core/canvas/canvas.js +14 -4
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/environments.js +3 -2
- package/dist/core/graph/objects.d.ts +3 -1
- package/dist/core/graph/objects.js +2 -2
- package/dist/core/import/load/copy.js +47 -23
- package/dist/core/import/load/keys.d.ts +5 -0
- package/dist/core/import/load/keys.js +77 -0
- package/dist/core/ledger/charges.js +3 -3
- package/dist/core/ledger/chunks.js +1 -1
- package/dist/core/ledger/read.js +1 -1
- package/dist/core/ledger/types.d.ts +4 -0
- package/dist/core/profiles/manifest.d.ts +5 -0
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/providers/audit.js +2 -2
- package/dist/core/providers/call.d.ts +2 -0
- package/dist/core/providers/call.js +2 -2
- package/dist/core/providers/receipts.d.ts +2 -0
- package/dist/core/providers/receipts.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
- package/dist/core/runtime/runner/blaxel/image-build.js +42 -44
- package/dist/daemon/api/handlers/providers.d.ts +2 -0
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/api/operations.js +4 -0
- package/dist/daemon/manage.js +3 -2
- package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
- package/dist/daemon/reconcilers/recipe-image.js +9 -1
- package/package.json +1 -1
package/dist/api/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
2
|
-
export declare const CONTRACT_LEVEL = "1.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.77";
|
|
3
3
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
4
4
|
export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
|
|
5
5
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.77';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -27,3 +27,40 @@ export interface SetProfileEnvironmentRequest {
|
|
|
27
27
|
/** Also let the environment's sandboxes merge pull requests; false (the default) gives contents write only. Builds no new image. */
|
|
28
28
|
allow_pull_request_write?: boolean;
|
|
29
29
|
}
|
|
30
|
+
/** An app's environment (`/v1/environments`): a profile of the app with its own blaxel environment, paid by the app. */
|
|
31
|
+
export interface AppEnvironmentDTO {
|
|
32
|
+
/** The environment's name, unique per app; it is the name of its profile. */
|
|
33
|
+
name: string;
|
|
34
|
+
profile_id: string;
|
|
35
|
+
environment_id: string;
|
|
36
|
+
/** Who pays for runs in it: the app itself (`app:<id>`). */
|
|
37
|
+
payer: string;
|
|
38
|
+
setup_script: string | null;
|
|
39
|
+
pi_packages: string | null;
|
|
40
|
+
memory_mb: number;
|
|
41
|
+
recipe_revision: number;
|
|
42
|
+
}
|
|
43
|
+
/** `POST /v1/environments` body. Same name and same recipe returns the existing environment (200); a different recipe is `409 conflict` (use patch). */
|
|
44
|
+
export interface CreateAppEnvironmentRequest {
|
|
45
|
+
name: string;
|
|
46
|
+
/** A principal the calling app speaks for (its namespace), or the owner of a grant to the app that names itself payer; `invalid_request` otherwise. */
|
|
47
|
+
payer: string;
|
|
48
|
+
recipe?: {
|
|
49
|
+
/** Not supported for an app yet: a non-empty list is `400 repositories_not_supported`. */
|
|
50
|
+
repositories?: string[];
|
|
51
|
+
setup_script?: string | null;
|
|
52
|
+
pi_packages?: string | null;
|
|
53
|
+
/** 2048, 4096 or 8192; default 2048. */
|
|
54
|
+
memory_mb?: number;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** `PATCH /v1/environments/{name}` body; a field left out keeps its value. */
|
|
58
|
+
export interface PatchAppEnvironmentRequest {
|
|
59
|
+
repositories?: string[];
|
|
60
|
+
setup_script?: string | null;
|
|
61
|
+
pi_packages?: string | null;
|
|
62
|
+
memory_mb?: number;
|
|
63
|
+
}
|
|
64
|
+
export interface AppEnvironmentListDTO {
|
|
65
|
+
environments: AppEnvironmentDTO[];
|
|
66
|
+
}
|
package/dist/api/dto/health.d.ts
CHANGED
|
@@ -12,6 +12,9 @@ export interface HealthDTO {
|
|
|
12
12
|
link_connected?: boolean;
|
|
13
13
|
/** Present on a machine-role daemon only: false when this computer has no person sign-in, so it opens no link and runs no agent or cron. */
|
|
14
14
|
signed_in?: boolean;
|
|
15
|
+
/** Present on a machine-role daemon only: id of the runtime generation it was launched from, null when it runs from a source checkout. That
|
|
16
|
+
* daemon serves no `/v1/status`, so `crtr sys daemon status` reads its generation here. */
|
|
17
|
+
generation_id?: string | null;
|
|
15
18
|
/** Present while corpus migration or normal daemon startup is incomplete. */
|
|
16
19
|
startup_blocked?: string;
|
|
17
20
|
/** Always present; only `ready` admits normal daemon work. */
|
package/dist/api/routes.d.ts
CHANGED
|
@@ -160,6 +160,8 @@ export declare const routes: {
|
|
|
160
160
|
readonly appEnvVar: (variable: string) => string;
|
|
161
161
|
readonly profileEnv: (name: string) => string;
|
|
162
162
|
readonly profileEnvVar: (name: string, variable: string) => string;
|
|
163
|
+
readonly environments: () => string;
|
|
164
|
+
readonly environment: (name: string) => string;
|
|
163
165
|
readonly profileEnvironment: (name: string) => string;
|
|
164
166
|
readonly settings: () => string;
|
|
165
167
|
readonly modelAuths: () => string;
|
package/dist/api/routes.js
CHANGED
|
@@ -188,6 +188,8 @@ export const routes = {
|
|
|
188
188
|
appEnvVar: (variable) => `${V}/apps/self/env/${encodeURIComponent(variable)}`,
|
|
189
189
|
profileEnv: (name) => `${V}/profiles/${name}/env`,
|
|
190
190
|
profileEnvVar: (name, variable) => `${V}/profiles/${name}/env/${variable}`,
|
|
191
|
+
environments: () => `${V}/environments`,
|
|
192
|
+
environment: (name) => `${V}/environments/${name}`,
|
|
191
193
|
profileEnvironment: (name) => `${V}/profiles/${name}/environment`,
|
|
192
194
|
// Person settings
|
|
193
195
|
settings: () => `${V}/settings`,
|
|
@@ -13,6 +13,7 @@ import { DaemonNotPreparedError, probeDaemonHealth, probeErrorMessage, spawnDaem
|
|
|
13
13
|
import { isDaemonRunning, readPidfile, isPidAlive } from '../../daemon/pidfile.js';
|
|
14
14
|
import { cliClient } from '../api-client.js';
|
|
15
15
|
import { readMachineConfig } from '../../daemon/machine-link/config.js';
|
|
16
|
+
import { apiSocketPath } from '../../core/canvas/paths.js';
|
|
16
17
|
import { localClient } from '../../api/node-transport.js';
|
|
17
18
|
import { defineSysBranch } from './branch.js';
|
|
18
19
|
import { selectedGeneration } from './shared.js';
|
|
@@ -156,9 +157,13 @@ const daemonAdmit = defineLeaf({
|
|
|
156
157
|
});
|
|
157
158
|
// daemon status
|
|
158
159
|
/** The generation id the live daemon reports on `/v1/status`; undefined when it reports none or cannot be asked. */
|
|
159
|
-
|
|
160
|
+
/** The generation this computer's daemon runs. It asks this computer's daemon socket, never a node's relay, which on an imported Mac answers
|
|
161
|
+
* for the shared control plane. A machine-role daemon serves no `/v1/status` and reports its generation in `/healthz` instead. */
|
|
162
|
+
async function servingGenerationId(health) {
|
|
163
|
+
if (health.generation_id !== undefined)
|
|
164
|
+
return health.generation_id ?? undefined;
|
|
160
165
|
try {
|
|
161
|
-
const status = await localClient({ autostart: false }).status();
|
|
166
|
+
const status = await localClient({ autostart: false, socketPath: apiSocketPath() }).status();
|
|
162
167
|
return status.generation_id ?? undefined;
|
|
163
168
|
}
|
|
164
169
|
catch {
|
|
@@ -193,7 +198,7 @@ const daemonStatus = defineLeaf({
|
|
|
193
198
|
return { running: false };
|
|
194
199
|
try {
|
|
195
200
|
const health = await probeDaemonHealth();
|
|
196
|
-
const serving = await servingGenerationId();
|
|
201
|
+
const serving = await servingGenerationId(health);
|
|
197
202
|
const selected = selectedGeneration().generation?.id;
|
|
198
203
|
return {
|
|
199
204
|
running: true,
|
|
@@ -183,7 +183,7 @@ export declare const terminalPlacementResidueSql = "SELECT\n node_id, creat
|
|
|
183
183
|
export declare function listTerminalPlacementResidue(): Promise<TerminalPlacementResidue[]>;
|
|
184
184
|
/** The daemon's complete supervision set. Live rows participate regardless of
|
|
185
185
|
* PID; terminal rows participate only while they retain a PID or freeze mark. */
|
|
186
|
-
export declare const nodesForSupervisionSql
|
|
186
|
+
export declare const nodesForSupervisionSql: string;
|
|
187
187
|
export declare function listNodesForSupervision(): Promise<NodeRow[]>;
|
|
188
188
|
/** A parked resident the runtime may reopen when wake mail reaches it: `done` +
|
|
189
189
|
* `intent='parked'`, resident, no final latch, and not being deleted. Finalized,
|
|
@@ -80,6 +80,16 @@ const turnOpen = (r) => r['turn_open_at'] != null && r['turn_closed_at'] == null
|
|
|
80
80
|
/** Whether the engine behind an open turn is alive. A cloud role never hosts a broker (it runs on a Mac or in a sandbox),
|
|
81
81
|
* so a pid probe on this host always fails there and the execution row is the only liveness record. */
|
|
82
82
|
const engineLive = (pidPresentHere) => pidPresentHere || isCloudRole();
|
|
83
|
+
/** The `node_rows` columns `rowFrom` reads. Whole-table scans select these, never `*`: the view also carries each node's
|
|
84
|
+
* initial prompt, launch config and tool summaries (about 60 KB per finished node in prod), which no `NodeRow` holds. */
|
|
85
|
+
const NODE_ROW_COLUMNS = `node_id, name, description, cycles, kind, mode, lifecycle, status, cwd, host_kind, profile_id, scopes_json, isolated,
|
|
86
|
+
grantee, sub, grant_id, client_id, metadata_json, run_id, event_cursor, last_activity_at, caused_by, last_turn_error_json, deleting_at,
|
|
87
|
+
parent, created, intent, cycle_pending, frozen_at, respawn_failures, respawn_not_before, launched_at, last_settled_at, terminal_reason,
|
|
88
|
+
final_report, finalized_at, outcome_kind, outcome_reason, outcome_at, outcome_revision, outcome_detail_json, deadline_at,
|
|
89
|
+
telemetry_tokens_in, telemetry_context_tokens, telemetry_last_activity, telemetry_updated_at, pi_pid, pi_pid_identity,
|
|
90
|
+
"window", tmux_session, pane, turn_open_at, turn_closed_at,
|
|
91
|
+
fault_id, fault_link, fault_op, fault_kind, fault_message, fault_since, fault_operation_id, fault_anchor_entry_id,
|
|
92
|
+
fault_retry_disposition, fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at, fault_provider_error_json`;
|
|
83
93
|
function rowFrom(r) {
|
|
84
94
|
const node = {
|
|
85
95
|
node_id: r['node_id'],
|
|
@@ -670,7 +680,7 @@ export async function listNodes(filter) {
|
|
|
670
680
|
if (filter?.withRecordedPidOrFrozen === true)
|
|
671
681
|
clauses.push('(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)');
|
|
672
682
|
const rows = await (await openDb())
|
|
673
|
-
.prepareUncached(`SELECT
|
|
683
|
+
.prepareUncached(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows WHERE ${clauses.join(' AND ')} ORDER BY created`)
|
|
674
684
|
.all(...params);
|
|
675
685
|
return rows.map(rowFrom);
|
|
676
686
|
}
|
|
@@ -702,7 +712,7 @@ export const nodesForSupervisionSql = `WITH candidates AS MATERIALIZED (
|
|
|
702
712
|
SELECT node_id FROM executions
|
|
703
713
|
WHERE state != 'exited' AND state = 'running' AND pid IS NOT NULL
|
|
704
714
|
)
|
|
705
|
-
SELECT v
|
|
715
|
+
SELECT ${NODE_ROW_COLUMNS.split(',').map((c) => `v.${c.trim()}`).join(', ')} FROM candidates c CROSS JOIN node_rows v
|
|
706
716
|
WHERE v.node_id = c.node_id
|
|
707
717
|
AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
708
718
|
AND v.kind != 'human'
|
|
@@ -1109,13 +1119,13 @@ export async function pruneNodes(opts) {
|
|
|
1109
1119
|
const quiet = (row) => lastActivityMs(row) < cutoffMs;
|
|
1110
1120
|
const toPruned = (row) => ({ node_id: row.node_id, status: row.status, created: row.created });
|
|
1111
1121
|
const watchedOwners = await ownersOfWatchedDocuments();
|
|
1112
|
-
const terminal = (await filterAsync((await db.prepare(`SELECT
|
|
1122
|
+
const terminal = (await filterAsync((await db.prepare(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows
|
|
1113
1123
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
1114
1124
|
ORDER BY created`)
|
|
1115
1125
|
.all(cutoff))
|
|
1116
1126
|
.map(rowFrom), async (row) => await isCollectible(row, { pastTtl: true }) && quiet(row) && !watchedOwners.has(row.node_id) && !await opts.held(row.node_id)))
|
|
1117
1127
|
.map(toPruned);
|
|
1118
|
-
const stale = !includeStale ? [] : (await filterAsync((await db.prepare(`SELECT
|
|
1128
|
+
const stale = !includeStale ? [] : (await filterAsync((await db.prepare(`SELECT ${NODE_ROW_COLUMNS} FROM node_rows
|
|
1119
1129
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
1120
1130
|
ORDER BY created`)
|
|
1121
1131
|
.all(cutoff))
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 38;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 38;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -11,9 +11,10 @@ import { setCloudProfileWriter } from './profiles/manifest.js';
|
|
|
11
11
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
12
12
|
export async function createProfileBlaxelEnvironment(db, spec) {
|
|
13
13
|
const app = await ownerForGrantee(db, spec.grantee);
|
|
14
|
-
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
|
|
14
|
+
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app, { noActsFor: spec.person.startsWith('app:') });
|
|
15
15
|
const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
|
|
16
|
-
|
|
16
|
+
if (!spec.person.startsWith('app:'))
|
|
17
|
+
await writeActsFor(db, object.id, spec.person); // an app environment is kept for no person
|
|
17
18
|
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
|
|
18
19
|
if (spec.recipe !== undefined)
|
|
19
20
|
await writeEnvironmentRecipe(db, object.id, spec.recipe);
|
|
@@ -22,7 +22,9 @@ export declare const ownerLockKey: (scheme: string, externalId: string, person?:
|
|
|
22
22
|
* holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
|
|
23
23
|
* by a different identity of the same type throws `conflict` naming both; it is
|
|
24
24
|
* never renamed silently. */
|
|
25
|
-
export declare function ensureOwner(db: CanvasDb, type: OwnerType, scheme: string, externalId: string, handle: string, owner?: ObjectRow
|
|
25
|
+
export declare function ensureOwner(db: CanvasDb, type: OwnerType, scheme: string, externalId: string, handle: string, owner?: ObjectRow, options?: {
|
|
26
|
+
noActsFor?: boolean;
|
|
27
|
+
}): Promise<ObjectRow>;
|
|
26
28
|
/** Give the live profile object of `profileId` the handle `handle`, so `[[handle/x]]` links,
|
|
27
29
|
* `owner=` listings and `--owner profile:<handle>` follow a profile rename. Refuses with
|
|
28
30
|
* `conflict` — before changing anything — when another live profile object holds the handle.
|
|
@@ -26,7 +26,7 @@ export const ownerLockKey = (scheme, externalId, person = '') => `owner:${person
|
|
|
26
26
|
* holding the same remote or path each get their own repo. Handles are unique per owner type: a handle already held
|
|
27
27
|
* by a different identity of the same type throws `conflict` naming both; it is
|
|
28
28
|
* never renamed silently. */
|
|
29
|
-
export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
|
|
29
|
+
export async function ensureOwner(db, type, scheme, externalId, handle, owner, options = {}) {
|
|
30
30
|
if (!OWNER_TYPES.has(type))
|
|
31
31
|
throw new Error(`ensureOwner: ${type} is not an owner type`);
|
|
32
32
|
// An owner that exists needs no lock: taking one here would acquire it outside the order a peer ingest locked its keys in.
|
|
@@ -57,7 +57,7 @@ export async function ensureOwner(db, type, scheme, externalId, handle, owner) {
|
|
|
57
57
|
await writeActsFor(db, created.id, userSubject(externalId).id);
|
|
58
58
|
else if (type === 'repo')
|
|
59
59
|
await writeActsFor(db, created.id, userSubject(person).id);
|
|
60
|
-
else if (type === 'profile')
|
|
60
|
+
else if (type === 'profile' && options.noActsFor !== true)
|
|
61
61
|
await writeActsFor(db, created.id, userSubject(await personIdAsync()).id);
|
|
62
62
|
return created;
|
|
63
63
|
}
|
|
@@ -6,6 +6,9 @@ import { BODIES_TABLE, COPIED_TABLES, KEY_MAPPED_TABLES } from '../bundle/layout
|
|
|
6
6
|
import { q, rowKey, topologicalOrder } from './catalog.js';
|
|
7
7
|
import { fillEnvironments } from './prepare.js';
|
|
8
8
|
import { ImportLaneError } from './stage.js';
|
|
9
|
+
import { encodeKeyBatches } from './keys.js';
|
|
10
|
+
/** Rows per INSERT. The staged table is read in ordinal ranges, so a statement returns at most this many keys to JS. */
|
|
11
|
+
const COPY_BATCH = 20_000;
|
|
9
12
|
const sq = (schema, table) => `${q(schema)}.${q(table)}`;
|
|
10
13
|
/** `import_manifest.inserted_keys`: a zstd-compressed JSON array of primary-key tuples (each value as text). */
|
|
11
14
|
export const encodeKeys = (keys) => zstdCompressSync(Buffer.from(JSON.stringify(keys)));
|
|
@@ -42,20 +45,41 @@ export async function copyRows(input) {
|
|
|
42
45
|
result.inserted[table] = keys.length;
|
|
43
46
|
await db.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encodeKeys(keys));
|
|
44
47
|
};
|
|
48
|
+
/** Numbers the staged rows `from` (a FROM/WHERE tail over alias `s`) in `order`, in Postgres: the ordinal table `_ord` holds each row's ctid and number. */
|
|
49
|
+
const number = async (table, order, where) => {
|
|
50
|
+
await db.exec(`DROP TABLE IF EXISTS ${S('_ord')}; CREATE TABLE ${S('_ord')} AS SELECT s.ctid AS row_id, (row_number() OVER (ORDER BY ${order}))::bigint AS n FROM ${S(table)} s${where}; CREATE INDEX ON ${S('_ord')} (n)`);
|
|
51
|
+
return Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S('_ord')}`).get()).n);
|
|
52
|
+
};
|
|
53
|
+
/** Runs `insert(low, high)` for each ordinal range of `total` rows (it returns that range's keys) and writes the keys to the table's manifest row, compressed as they arrive. */
|
|
54
|
+
const inBatches = async (table, total, insert, record = true) => {
|
|
55
|
+
let inserted = 0;
|
|
56
|
+
const batches = (async function* () {
|
|
57
|
+
for (let low = 0; low < total; low += COPY_BATCH) {
|
|
58
|
+
const keys = await insert(low, low + COPY_BATCH);
|
|
59
|
+
inserted += keys.length;
|
|
60
|
+
yield keys;
|
|
61
|
+
}
|
|
62
|
+
})();
|
|
63
|
+
const encoded = await encodeKeyBatches(batches);
|
|
64
|
+
if (record)
|
|
65
|
+
await db.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encoded);
|
|
66
|
+
return inserted;
|
|
67
|
+
};
|
|
45
68
|
// The two identity-keyed tables first (nothing references them by a foreign key): the target numbers them in source order and the key map remembers it.
|
|
46
69
|
// One statement per table: each staged row takes the next number of the target's identity sequence (in source order), is inserted under it, and is
|
|
47
70
|
// recorded in the key map under its source key, so the pairing is explicit and no row costs a round trip.
|
|
48
71
|
for (const [table, column] of Object.entries(KEY_MAPPED_TABLES)) {
|
|
49
72
|
const info = catalog.tables.get(table);
|
|
50
73
|
const columns = info.columns.filter((c) => c !== column);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
74
|
+
// Source order is the numbering order: each batch takes the next numbers of the target's identity sequence, so batches in ordinal order keep the pairing.
|
|
75
|
+
const total = await number(table, `s.${q(column)}::bigint`, '');
|
|
76
|
+
const inserted = await inBatches(table, total, async (low, high) => (await db.prepareUncached(`WITH src AS MATERIALIZED (
|
|
77
|
+
SELECT s.source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}
|
|
78
|
+
FROM (SELECT s.${q(column)}::text AS source_key, ${columns.map((c) => `s.${q(c)}`).join(', ')}, o.n FROM ${S(table)} s JOIN ${S('_ord')} o ON o.row_id = s.ctid WHERE o.n > ${low} AND o.n <= ${high} ORDER BY o.n) s),
|
|
54
79
|
ins AS (INSERT INTO ${T(table)} (${q(column)}, ${columns.map(q).join(', ')}) SELECT target_key, ${columns.map(q).join(', ')} FROM src RETURNING 1),
|
|
55
80
|
km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
|
|
56
|
-
SELECT target_key FROM km ORDER BY target_key::bigint`)
|
|
57
|
-
|
|
58
|
-
await manifest(table, rows.map((r) => [r.target_key]));
|
|
81
|
+
SELECT target_key FROM km ORDER BY target_key::bigint`).all(T(table), column, source.installId, table)).map((r) => [r.target_key]));
|
|
82
|
+
result.inserted[table] = inserted;
|
|
59
83
|
}
|
|
60
84
|
// `review_comments.created_seq` follows its event.
|
|
61
85
|
await db.prepareUncached(`UPDATE ${S('review_comments')} c SET created_seq = m.target_key::bigint FROM import_key_map m
|
|
@@ -84,26 +108,29 @@ export async function copyRows(input) {
|
|
|
84
108
|
const orderBy = info.identity.length > 0 ? info.identity.map((c) => `s.${q(c)}`).join(', ') : pk.map((c) => `s.${q(c)}`).join(', ');
|
|
85
109
|
let select = columns.map((c) => `s.${q(c)}`);
|
|
86
110
|
let where = '';
|
|
111
|
+
let last = 0;
|
|
87
112
|
if (table === 'messages') {
|
|
88
113
|
// `messages.seq` is a plain unique column: advance the counter once by the number of new rows and number them from the old value.
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
114
|
+
where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T('messages')} t WHERE t.message_id = s.message_id)`;
|
|
115
|
+
}
|
|
116
|
+
// A table with no primary key is keyed by all its columns: a row the target already holds with equal columns is skipped.
|
|
117
|
+
const keyless = info.primaryKey.length === 0;
|
|
118
|
+
if (keyless)
|
|
119
|
+
where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T(table)} t WHERE ${pk.map((c) => `t.${q(c)} IS NOT DISTINCT FROM s.${q(c)}`).join(' AND ')})`;
|
|
120
|
+
// The rows to insert are decided and numbered once, before the first batch, so a batch never sees an earlier batch's rows as already in the target.
|
|
121
|
+
const total = await number(table, table === 'messages' ? 's.seq' : orderBy, where);
|
|
122
|
+
if (table === 'messages') {
|
|
123
|
+
if (total === 0) {
|
|
93
124
|
result.inserted[table] = 0;
|
|
94
125
|
await manifest(table, []);
|
|
95
126
|
continue;
|
|
96
127
|
}
|
|
97
|
-
|
|
98
|
-
select = columns.map((c) => c === 'seq' ? `${last -
|
|
128
|
+
last = Number((await db.prepare('UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq').get(total)).seq);
|
|
129
|
+
select = columns.map((c) => c === 'seq' ? `${last - total} + o.n` : `s.${q(c)}`);
|
|
99
130
|
}
|
|
100
131
|
const returning = pk.map((c) => `${q(c)}::text`).join(', ');
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
if (keyless)
|
|
104
|
-
where = ` WHERE NOT EXISTS (SELECT 1 FROM ${T(table)} t WHERE ${pk.map((c) => `t.${q(c)} IS NOT DISTINCT FROM s.${q(c)}`).join(' AND ')})`;
|
|
105
|
-
const inserted = await db.prepareUncached(`INSERT INTO ${T(table)} (${columns.map(q).join(', ')}) SELECT ${select.join(', ')} FROM ${S(table)} s${where}
|
|
106
|
-
ORDER BY ${orderBy}${keyless ? '' : ` ON CONFLICT (${pk.map(q).join(', ')}) DO NOTHING`} RETURNING ${returning}`).all();
|
|
132
|
+
const insertedCount = await inBatches(table, total, async (low, high) => (await db.prepareUncached(`INSERT INTO ${T(table)} (${columns.map(q).join(', ')}) SELECT ${select.join(', ')} FROM ${S(table)} s JOIN ${S('_ord')} o ON o.row_id = s.ctid WHERE o.n > ${low} AND o.n <= ${high}
|
|
133
|
+
ORDER BY o.n${keyless ? '' : ` ON CONFLICT (${pk.map(q).join(', ')}) DO NOTHING`} RETURNING ${returning}`).all()).map((row) => Object.values(row)), table !== BODIES_TABLE);
|
|
107
134
|
// `ON CONFLICT DO NOTHING` kept the target's row for a key it already held: that row must hold the same text (the pre-check compared them earlier, outside this transaction).
|
|
108
135
|
if (table === BODIES_TABLE) {
|
|
109
136
|
const clash = await db.prepareUncached(`SELECT s.hash FROM ${S(table)} s JOIN ${T(table)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();
|
|
@@ -112,11 +139,8 @@ export async function copyRows(input) {
|
|
|
112
139
|
}
|
|
113
140
|
}
|
|
114
141
|
// `bodies` rows are never deleted (design-fleet D106), so a rollback must not remove them: no manifest row. The hash is the key on both sides.
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
else
|
|
118
|
-
await manifest(table, inserted.map((row) => Object.values(row)));
|
|
119
|
-
result.mapped[table] = staged - inserted.length;
|
|
142
|
+
result.inserted[table] = insertedCount;
|
|
143
|
+
result.mapped[table] = staged - insertedCount;
|
|
120
144
|
}
|
|
121
145
|
for (const f of filled)
|
|
122
146
|
await db.prepare(`INSERT INTO ${S('_filled')} VALUES (?, ?::jsonb)`).run(f.table, JSON.stringify(f.key));
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const KEY_BATCH = 5000;
|
|
2
|
+
/** Compress the batches into one `inserted_keys` value. */
|
|
3
|
+
export declare function encodeKeyBatches(batches: AsyncIterable<string[][]>): Promise<Buffer>;
|
|
4
|
+
/** The tuples of an `inserted_keys` value, `size` at a time. */
|
|
5
|
+
export declare function keyBatches(data: Buffer, size?: number): AsyncGenerator<string[][]>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Manifest keys without whole-account arrays. `import_manifest.inserted_keys` is a zstd-compressed JSON array of primary-key tuples; the streaming writer puts one tuple per
|
|
2
|
+
// line (`[`, `k1,`, `k2`, `]`: still one valid JSON array, so `decodeKeys` reads it) and the streaming reader yields batches of tuples, so memory is one batch plus the compressed bytes.
|
|
3
|
+
// An array written in one line by an earlier release is read whole.
|
|
4
|
+
import { createZstdCompress, createZstdDecompress } from 'node:zlib';
|
|
5
|
+
import { once } from 'node:events';
|
|
6
|
+
export const KEY_BATCH = 5000;
|
|
7
|
+
/** Compress the batches into one `inserted_keys` value. */
|
|
8
|
+
export async function encodeKeyBatches(batches) {
|
|
9
|
+
const zst = createZstdCompress();
|
|
10
|
+
const out = [];
|
|
11
|
+
zst.on('data', (chunk) => out.push(chunk));
|
|
12
|
+
const done = once(zst, 'end');
|
|
13
|
+
const put = async (text) => { if (!zst.write(text, 'utf8'))
|
|
14
|
+
await once(zst, 'drain'); };
|
|
15
|
+
await put('[\n');
|
|
16
|
+
let first = true;
|
|
17
|
+
for await (const batch of batches) {
|
|
18
|
+
if (batch.length === 0)
|
|
19
|
+
continue;
|
|
20
|
+
await put((first ? '' : ',\n') + batch.map((key) => JSON.stringify(key)).join(',\n'));
|
|
21
|
+
first = false;
|
|
22
|
+
}
|
|
23
|
+
await put('\n]');
|
|
24
|
+
zst.end();
|
|
25
|
+
await done;
|
|
26
|
+
return Buffer.concat(out);
|
|
27
|
+
}
|
|
28
|
+
/** The tuples of an `inserted_keys` value, `size` at a time. */
|
|
29
|
+
export async function* keyBatches(data, size = KEY_BATCH) {
|
|
30
|
+
const zst = createZstdDecompress({ chunkSize: 1 << 20 });
|
|
31
|
+
zst.end(data);
|
|
32
|
+
let pending = '';
|
|
33
|
+
let batch = [];
|
|
34
|
+
let streaming;
|
|
35
|
+
let legacy = [];
|
|
36
|
+
for await (const chunk of zst) {
|
|
37
|
+
if (streaming === false) {
|
|
38
|
+
legacy.push(chunk);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
pending += chunk.toString('utf8');
|
|
42
|
+
if (streaming === undefined) {
|
|
43
|
+
if (pending.length < 2)
|
|
44
|
+
continue;
|
|
45
|
+
streaming = pending.startsWith('[\n') || pending === '[]';
|
|
46
|
+
if (!streaming) {
|
|
47
|
+
legacy.push(Buffer.from(pending));
|
|
48
|
+
pending = '';
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let at = pending.indexOf('\n');
|
|
53
|
+
while (at !== -1) {
|
|
54
|
+
const line = pending.slice(0, at).replace(/,$/, '');
|
|
55
|
+
pending = pending.slice(at + 1);
|
|
56
|
+
if (line !== '[' && line !== ']' && line !== '') {
|
|
57
|
+
batch.push(JSON.parse(line));
|
|
58
|
+
if (batch.length >= size) {
|
|
59
|
+
yield batch;
|
|
60
|
+
batch = [];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
at = pending.indexOf('\n');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (streaming === false || streaming === undefined) {
|
|
67
|
+
const all = legacy.length > 0 ? JSON.parse(Buffer.concat(legacy).toString('utf8')) : (pending === '' ? [] : JSON.parse(pending));
|
|
68
|
+
for (let i = 0; i < all.length; i += size)
|
|
69
|
+
yield all.slice(i, i + size);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const tail = pending.replace(/,$/, '').trim();
|
|
73
|
+
if (tail !== '' && tail !== ']' && tail !== '[')
|
|
74
|
+
batch.push(JSON.parse(tail));
|
|
75
|
+
if (batch.length > 0)
|
|
76
|
+
yield batch;
|
|
77
|
+
}
|
|
@@ -5,8 +5,8 @@ import { takePercent } from './rates.js';
|
|
|
5
5
|
import { usageMonth } from './months.js';
|
|
6
6
|
/** The id of a tool charge: the receipt-level idempotency key, so two providers' receipt ids never collide. */
|
|
7
7
|
export const receiptChargeId = (provider, receiptId) => `receipt:${provider}:${receiptId}`;
|
|
8
|
-
const COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger';
|
|
9
|
-
const PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true';
|
|
8
|
+
const COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger, actor';
|
|
9
|
+
const PLACEHOLDERS = '?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true, ?';
|
|
10
10
|
/** Write one charge row; the `charges` trigger (schema delta 007) adds it to `charge_totals`. A refused row is stored with
|
|
11
11
|
* usd 0 and never rolled up; a take row (written only while `CRTR_LEDGER_TAKE_PCT` > 0) is stored and never rolled up. Inside a
|
|
12
12
|
* caller's `withCanvasWrite` it joins that transaction. */
|
|
@@ -22,7 +22,7 @@ export async function writeCharge(input) {
|
|
|
22
22
|
rowId, input.request ?? null, at.toISOString(), month, kind, what, input.units == null ? null : JSON.stringify(input.units), rowUsd,
|
|
23
23
|
input.payer, funding, input.sub ?? null, input.grantee, input.node ?? null, input.run ?? null, input.provider ?? null,
|
|
24
24
|
input.causedBy ?? null, input.vendorRef ?? null, refused === null ? null : JSON.stringify(refused), input.account ?? null, input.billedUsd ?? null,
|
|
25
|
-
null, null, null, null
|
|
25
|
+
null, null, null, null, input.actor ?? null
|
|
26
26
|
];
|
|
27
27
|
const inserted = await db.prepare(`INSERT INTO charges (${COLUMNS}) VALUES (${PLACEHOLDERS}) ON CONFLICT (id) DO NOTHING`)
|
|
28
28
|
.run(...row(id, input.kind, input.what, usd, input.funding));
|
|
@@ -5,7 +5,7 @@ import { zstdDecompressSync } from 'node:zlib';
|
|
|
5
5
|
import { blobStore } from '../blobs/index.js';
|
|
6
6
|
import { openDb } from '../canvas/db.js';
|
|
7
7
|
import { chargeOf } from './charges.js';
|
|
8
|
-
const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source'];
|
|
8
|
+
const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source', 'actor'];
|
|
9
9
|
/** The moved rows of a month (or of every month), from month `since` on, read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
|
|
10
10
|
export class ChunkRows {
|
|
11
11
|
since;
|
package/dist/core/ledger/read.js
CHANGED
|
@@ -9,7 +9,7 @@ import { chargeOf } from './charges.js';
|
|
|
9
9
|
import { ChunkRows } from './chunks.js';
|
|
10
10
|
import { listLimits } from './limits.js';
|
|
11
11
|
import { resetAt, usageMonth } from './months.js';
|
|
12
|
-
const CHARGE_COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source';
|
|
12
|
+
const CHARGE_COLUMNS = 'id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, actor';
|
|
13
13
|
/** `usage.get` for one grantee and month, computed from `charges`. `by_model` and `app_paid.by_model` group the `model` rows
|
|
14
14
|
* of a `user:` / `app:` payer by `what`, with token sums from `units` and `usd_equivalent` null when every row's `usd` is null.
|
|
15
15
|
* `usd_equivalent` is what the grant's limit reads: every `user:` payer charge for this grantee, model and tool, refused and
|
|
@@ -21,6 +21,8 @@ export interface Charge {
|
|
|
21
21
|
payer: string;
|
|
22
22
|
funding: Funding;
|
|
23
23
|
sub: string | null;
|
|
24
|
+
/** The principal that presented the call; null when unknown. */
|
|
25
|
+
actor: string | null;
|
|
24
26
|
grantee: string;
|
|
25
27
|
node: string | null;
|
|
26
28
|
run: string | null;
|
|
@@ -52,6 +54,8 @@ export interface ChargeInput {
|
|
|
52
54
|
payer: string;
|
|
53
55
|
funding: Funding;
|
|
54
56
|
sub?: string | null;
|
|
57
|
+
/** The principal that presented the call (`Principal.actor`). */
|
|
58
|
+
actor?: string | null;
|
|
55
59
|
grantee: string;
|
|
56
60
|
node?: string | null;
|
|
57
61
|
run?: string | null;
|
|
@@ -62,6 +62,7 @@ export type CloudProfileWriter = (spec: {
|
|
|
62
62
|
profileId: string;
|
|
63
63
|
grantee: string;
|
|
64
64
|
person: string;
|
|
65
|
+
payer?: string;
|
|
65
66
|
memoryMb?: number;
|
|
66
67
|
recipe?: EnvironmentRecipeInput;
|
|
67
68
|
}, insert: (environmentId: string) => Promise<void>) => Promise<void>;
|
|
@@ -86,6 +87,10 @@ export declare function createProfile(name: string, projects?: ProfileProject[],
|
|
|
86
87
|
grantee?: string;
|
|
87
88
|
/** Memory of the cloud environment created with the profile; ignored off a cloud role. */
|
|
88
89
|
memoryMb?: number;
|
|
90
|
+
/** An app environment: the app is the person the environment acts for and the payer (cloud role only). */
|
|
91
|
+
appEnvironment?: boolean;
|
|
92
|
+
/** The environment's payer (default: the app). */
|
|
93
|
+
payer?: string;
|
|
89
94
|
/** Recipe written with the cloud environment, in the same write as the profile row. */
|
|
90
95
|
recipe?: EnvironmentRecipeInput;
|
|
91
96
|
}): Promise<ProfileEntry>;
|
|
@@ -367,7 +367,7 @@ export async function createProfile(name, projects = [], opts = {}) {
|
|
|
367
367
|
else if (cloudProfileWriter === null)
|
|
368
368
|
throw new Error('a cloud role has no profile environment writer registered');
|
|
369
369
|
else
|
|
370
|
-
await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: personId(), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
|
|
370
|
+
await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: opts.appEnvironment === true ? profileApp(manifest) : personId(), ...(opts.appEnvironment === true ? { payer: opts.payer ?? profileApp(manifest) } : {}), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
|
|
371
371
|
return { profileId, manifest };
|
|
372
372
|
}
|
|
373
373
|
export async function ensureAppProfile(grantee) {
|
|
@@ -9,8 +9,8 @@ export async function writeProviderAudit(row) {
|
|
|
9
9
|
const chain = sub && grantee ? [sub, grantee, `runtime:${runtimeId()}`] : null;
|
|
10
10
|
await (await openDb()).prepare(`INSERT INTO audit_rows
|
|
11
11
|
(request_id, time, grantee, sub, client_id, class, operation, scope_checked,
|
|
12
|
-
outcome, node_id, run_id, resource, initiator_chain, provider, tool, jti, receipt_id, responder, question_id)
|
|
13
|
-
VALUES (?, ?, ?, ?, ?, ?, 'provider.call', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.request_id, new Date().toISOString(), grantee, sub, caller.client_id, caller.class, row.scope_checked ?? null, row.outcome, caller.node_id, caller.run_id, `${row.provider} ${row.tool}`, chain ? JSON.stringify(chain) : null, row.provider, row.tool, row.jti ?? null, row.receipt_id ?? null, row.responder ?? null, row.question_id ?? null);
|
|
12
|
+
outcome, node_id, run_id, resource, initiator_chain, provider, tool, jti, receipt_id, responder, question_id, actor)
|
|
13
|
+
VALUES (?, ?, ?, ?, ?, ?, 'provider.call', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.request_id, new Date().toISOString(), grantee, sub, caller.client_id, caller.class, row.scope_checked ?? null, row.outcome, caller.node_id, caller.run_id, `${row.provider} ${row.tool}`, chain ? JSON.stringify(chain) : null, row.provider, row.tool, row.jti ?? null, row.receipt_id ?? null, row.responder ?? null, row.question_id ?? null, caller.actor ?? null);
|
|
14
14
|
}
|
|
15
15
|
export async function listAudit(grantee, filters) {
|
|
16
16
|
const where = [];
|
|
@@ -35,6 +35,8 @@ export interface ProviderResponseContext {
|
|
|
35
35
|
/** The calling node, and the `Crtr-Caused-By` the call arrived with; null when none. */
|
|
36
36
|
node_id: string | null;
|
|
37
37
|
caused_by: string | null;
|
|
38
|
+
/** The caller's presenting principal; null when none. */
|
|
39
|
+
actor?: string | null;
|
|
38
40
|
jti: string;
|
|
39
41
|
status: number;
|
|
40
42
|
headers: Record<string, string | string[] | undefined>;
|
|
@@ -285,7 +285,7 @@ export async function callProvider(caller, rawInput, request) {
|
|
|
285
285
|
const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub, environmentPayer: await environmentPayerOfNode(caller.node_id) });
|
|
286
286
|
const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee, provider: `app:${bundle.id}` });
|
|
287
287
|
if (refusal !== null) {
|
|
288
|
-
await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee,
|
|
288
|
+
await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, actor: caller.actor ?? null, grantee: chargeGrantee,
|
|
289
289
|
node: caller.node_id, run: caller.run_id, provider: `app:${bundle.id}`, causedBy: request.causedBy ?? null, refused: refusedMark(refusal) });
|
|
290
290
|
throw refusalError(refusal);
|
|
291
291
|
}
|
|
@@ -317,7 +317,7 @@ export async function callProvider(caller, rawInput, request) {
|
|
|
317
317
|
}
|
|
318
318
|
// R7 receives every response, including errors, before the mapping.
|
|
319
319
|
receiptId ??= await onProviderResponse({ provider: bundle.id, tool: input.tool, request_id: requestId, run_id: caller.run_id,
|
|
320
|
-
sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
|
|
320
|
+
sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, actor: caller.actor ?? null, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
|
|
321
321
|
responder = response.headers['crtr-responder'];
|
|
322
322
|
if (response.status === 401)
|
|
323
323
|
discardFile(token.key);
|
|
@@ -15,6 +15,8 @@ type ReceiptCall = {
|
|
|
15
15
|
/** The calling node and the call's `Crtr-Caused-By`; null when none. */
|
|
16
16
|
node_id: string | null;
|
|
17
17
|
caused_by: string | null;
|
|
18
|
+
/** The caller's presenting principal; null when none. */
|
|
19
|
+
actor?: string | null;
|
|
18
20
|
};
|
|
19
21
|
/**
|
|
20
22
|
* A provider's informational receipts must belong to the call that carried them. The header is one
|
|
@@ -42,7 +42,7 @@ export async function acceptProviderReceipt(value, call) {
|
|
|
42
42
|
for (const receipt of accepted) {
|
|
43
43
|
// One row per receipt, keyed by (provider, receipt id): a repeat delivery writes nothing and adds nothing.
|
|
44
44
|
await writeCharge({ id: receiptChargeId(call.provider, receipt.receipt_id), request: call.request_id, kind: 'tool', what: `${call.provider}:${call.tool}`,
|
|
45
|
-
units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub,
|
|
45
|
+
units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub, actor: call.actor ?? null,
|
|
46
46
|
grantee: call.ledger_grantee ?? call.grantee, node: call.node_id, run: call.run_id, provider: `app:${call.provider}`, causedBy: call.caused_by, vendorRef: receipt.receipt_id });
|
|
47
47
|
}
|
|
48
48
|
});
|
|
@@ -28,32 +28,31 @@ export declare const RUN_USER_NPMRC: string[];
|
|
|
28
28
|
/** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
|
|
29
29
|
* this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
|
|
30
30
|
export declare const RUN_USER_NPMRC_ENV = "ENV NPM_CONFIG_USERCONFIG=/home/crtr/.npmrc";
|
|
31
|
-
|
|
31
|
+
/** The build argument that carries the GitHub installation token into the build stage. */
|
|
32
|
+
export declare const GIT_TOKEN_ARG = "CRTR_GIT_TOKEN";
|
|
32
33
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
33
34
|
export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
|
|
34
35
|
export declare const SETUP_FAILED_FILE = "/work/.crtr/setup-failed";
|
|
35
36
|
/** `gh` for a sandbox: /usr/local/bin comes before /usr/bin, so this wrapper runs first. It asks git's credential helper (set at sandbox start, so it reaches the control plane's
|
|
36
37
|
* git-credential route) for a fresh installation token, exports it as GH_TOKEN for this one call and runs the real gh. No token is stored on disk. */
|
|
37
38
|
export declare const GH_WRAPPER_PATH = "/usr/local/bin/gh";
|
|
38
|
-
/**
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
39
|
+
/** Throws when a repository's name, full name or branch could escape its place in the Dockerfile. */
|
|
40
|
+
export declare function assertRepositoryShape(repo: RecipeRepository): void;
|
|
41
|
+
/** The Dockerfile for a recipe revision. Pure. Two stages: `build` clones the repositories and runs the setup script as root; the final image copies
|
|
42
|
+
* only the installed trees out of it, never `/root`. Each token the build stage needs is declared there as an ARG (its value comes from `.env.build`
|
|
43
|
+
* in the upload) and never in the final stage, so no token is in a layer of the final image. */
|
|
44
|
+
export declare function recipeDockerfile(recipe: Recipe, revision: number, packagesToken?: boolean, gitToken?: boolean): string;
|
|
43
45
|
export interface PrepareBuildDirInput {
|
|
44
46
|
recipe: Recipe;
|
|
45
47
|
revision: number;
|
|
46
|
-
/** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. */
|
|
48
|
+
/** A GitHub installation token limited to the recipe's repositories, or null for a source that needs none. It goes only into `.env.build`. */
|
|
47
49
|
token: string | null;
|
|
48
50
|
/** The packages token (`NODE_AUTH_TOKEN`) for the build stage, or null. It goes only into `.env.build` of the upload. */
|
|
49
51
|
packagesToken?: string | null;
|
|
50
52
|
/** An empty directory. */
|
|
51
53
|
dir: string;
|
|
52
|
-
git?: GitRunner;
|
|
53
|
-
/** The clone URL of a repository; the default is `https://github.com/<full name>.git`. */
|
|
54
|
-
cloneUrl?: (githubFullName: string) => string;
|
|
55
54
|
}
|
|
56
|
-
/**
|
|
55
|
+
/** Writes the Dockerfile, `blaxel.toml`, the setup script and `.env.build` into `dir`. Clones nothing: the build stage on Blaxel does. */
|
|
57
56
|
export declare function prepareBuildDir(input: PrepareBuildDirInput): Promise<void>;
|
|
58
57
|
/** A zip of every file under `dir` (deflate, unix modes kept so scripts stay executable). Empty directories are not carried. */
|
|
59
58
|
export declare function zipDirectory(dir: string): Buffer;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
// src/core/runtime/runner/blaxel/image-build.ts — the recipe image: Dockerfile writer, build-directory
|
|
1
|
+
// src/core/runtime/runner/blaxel/image-build.ts — the recipe image: Dockerfile writer, build-directory writer, Blaxel image build (C-A5, D25/D93/D94).
|
|
2
2
|
//
|
|
3
3
|
// An environment recipe (repositories, pi packages, setup script) becomes one Blaxel sandbox image per recipe revision. The control plane
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
|
|
9
|
-
import { constants as fsConstants, lstatSync,
|
|
4
|
+
// writes a small build directory (Dockerfile, setup script, `blaxel.toml`, `.env.build`), zips it and uploads it to Blaxel's build API. The
|
|
5
|
+
// repositories are cloned by the build stage on Blaxel, never on the control plane, so a large repository costs the control plane nothing.
|
|
6
|
+
// The short-lived GitHub installation token reaches that stage as the build argument `CRTR_GIT_TOKEN` (its value only in `.env.build`), as
|
|
7
|
+
// the packages token does: the final stage declares no ARG and copies only the installed trees, so neither token is in the final image.
|
|
8
|
+
// `fetch` is injectable so the unit lane runs the whole flow against fakes.
|
|
9
|
+
import { constants as fsConstants, lstatSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs';
|
|
10
10
|
import { join, relative } from 'node:path';
|
|
11
11
|
import { crc32, deflateRawSync } from 'node:zlib';
|
|
12
12
|
import { BlaxelApiError } from './client.js';
|
|
@@ -34,7 +34,8 @@ export const RUN_USER_NPMRC = [
|
|
|
34
34
|
* this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
|
|
35
35
|
export const RUN_USER_NPMRC_ENV = `ENV NPM_CONFIG_USERCONFIG=/home/${RUN_USER}/.npmrc`;
|
|
36
36
|
const writeRunUserNpmrc = () => `printf '%s\\n' ${RUN_USER_NPMRC.map((l) => `'${l}'`).join(' ')} > /home/${RUN_USER}/.npmrc`;
|
|
37
|
-
|
|
37
|
+
/** The build argument that carries the GitHub installation token into the build stage. */
|
|
38
|
+
export const GIT_TOKEN_ARG = 'CRTR_GIT_TOKEN';
|
|
38
39
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
39
40
|
export const SETUP_LOG_FILE = '/work/.crtr/setup.log';
|
|
40
41
|
export const SETUP_FAILED_FILE = '/work/.crtr/setup-failed';
|
|
@@ -52,10 +53,27 @@ const lines = (text) => (text ?? '').split('\n').map((l) => l.trim()).filter((l)
|
|
|
52
53
|
/** A RUN step that cannot fail the build (Blaxel hangs on a failed step and its build log is unreadable): its output goes to `SETUP_LOG_FILE` and a
|
|
53
54
|
* failure appends `<label> exited <status>` to `SETUP_FAILED_FILE`, which the sandbox start script refuses to start on. */
|
|
54
55
|
const guarded = (label, command) => `RUN { ${command}; } >> ${SETUP_LOG_FILE} 2>&1 || echo ${shellQuote(label)} "exited $?" >> ${SETUP_FAILED_FILE}`;
|
|
55
|
-
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
|
|
56
|
+
/** A repository's clone step in the build stage. Blobless (`--filter=blob:none`): full history, file contents fetched for the checkout only, so a
|
|
57
|
+
* large repository stays small in the image while `git log` and branching still work; older contents are fetched on demand through the sandbox's
|
|
58
|
+
* credential helper. The token is handed to git as a config entry of that one process: not in the URL, not in `.git/config`. */
|
|
59
|
+
const cloneStep = (repo, revision, withToken) => {
|
|
60
|
+
const auth = withToken ? `-c http.https://github.com/.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${GIT_TOKEN_ARG}" | base64 | tr -d '\\n')" ` : '';
|
|
61
|
+
// `: r<revision>` keeps a rebuild from reusing a cached clone layer of an earlier revision.
|
|
62
|
+
return guarded(`clone ${repo.github_full_name}`, `: r${Math.trunc(revision)}; GIT_TERMINAL_PROMPT=0 git ${auth}clone --quiet --filter=blob:none --branch ${shellQuote(repo.default_branch)} ${shellQuote(`https://github.com/${repo.github_full_name}.git`)} ${shellQuote(`/work/${repo.name}`)}`);
|
|
63
|
+
};
|
|
64
|
+
/** Throws when a repository's name, full name or branch could escape its place in the Dockerfile. */
|
|
65
|
+
export function assertRepositoryShape(repo) {
|
|
66
|
+
if (!/^[A-Za-z0-9._-]+$/.test(repo.name) || repo.name === '.' || repo.name === '..')
|
|
67
|
+
throw new Error(`repository name ${JSON.stringify(repo.name)} is not a plain directory name`);
|
|
68
|
+
if (!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo.github_full_name))
|
|
69
|
+
throw new Error(`repository ${JSON.stringify(repo.github_full_name)} is not an owner/name pair`);
|
|
70
|
+
if (repo.default_branch === '' || /[\s\x00-\x1f'"`$\\]/.test(repo.default_branch))
|
|
71
|
+
throw new Error(`branch ${JSON.stringify(repo.default_branch)} of ${repo.github_full_name} is not a plain branch name`);
|
|
72
|
+
}
|
|
73
|
+
/** The Dockerfile for a recipe revision. Pure. Two stages: `build` clones the repositories and runs the setup script as root; the final image copies
|
|
74
|
+
* only the installed trees out of it, never `/root`. Each token the build stage needs is declared there as an ARG (its value comes from `.env.build`
|
|
75
|
+
* in the upload) and never in the final stage, so no token is in a layer of the final image. */
|
|
76
|
+
export function recipeDockerfile(recipe, revision, packagesToken = false, gitToken = false) {
|
|
59
77
|
const packages = lines(recipe.pi_packages);
|
|
60
78
|
const hasScript = recipe.setup_script !== null && recipe.setup_script.trim() !== '';
|
|
61
79
|
const base = [
|
|
@@ -65,10 +83,12 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
65
83
|
`COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
|
|
66
84
|
`RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /work/.crtr ${RECIPE_PI_AGENT_DIR} && chown -R ${RUN_USER} /work /var/lib/crtr`,
|
|
67
85
|
];
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
86
|
+
for (const repo of recipe.repositories)
|
|
87
|
+
assertRepositoryShape(repo);
|
|
88
|
+
const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...(gitToken && recipe.repositories.length > 0 ? [`ARG ${GIT_TOKEN_ARG}`] : []), ...base.slice(1), `RUN rm -f ${SETUP_FAILED_FILE} ${SETUP_LOG_FILE}`, guarded('npm install -g pnpm', 'npm install -g pnpm && mkdir -p /var/lib/postgresql')];
|
|
89
|
+
// A failed clone fails no step (see `guarded`): it is in the setup log, and the sandbox start script refuses to start on it.
|
|
90
|
+
for (const repo of recipe.repositories)
|
|
91
|
+
out.push(cloneStep(repo, revision, gitToken));
|
|
72
92
|
if (packages.length > 0)
|
|
73
93
|
out.push(guarded('npm install pi', `npm install -g @earendil-works/pi-coding-agent@${PI_VERSION}`));
|
|
74
94
|
if (hasScript)
|
|
@@ -99,37 +119,15 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
|
|
|
99
119
|
out.push(RUN_USER_NPMRC_ENV, `USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
|
|
100
120
|
return out.join('\n');
|
|
101
121
|
}
|
|
102
|
-
|
|
103
|
-
const child = spawn('git', args, { cwd, env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: '0' }, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
104
|
-
let stderr = '';
|
|
105
|
-
child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
|
|
106
|
-
child.on('error', reject);
|
|
107
|
-
child.on('close', (code) => { if (code === 0)
|
|
108
|
-
resolve();
|
|
109
|
-
else
|
|
110
|
-
reject(new Error(`git ${args[0]} failed (${code}): ${stderr.slice(0, 300)}`)); });
|
|
111
|
-
});
|
|
112
|
-
/** Clones each repository into `<dir>/repos/<name>` and writes the Dockerfile and the setup script beside it. */
|
|
122
|
+
/** Writes the Dockerfile, `blaxel.toml`, the setup script and `.env.build` into `dir`. Clones nothing: the build stage on Blaxel does. */
|
|
113
123
|
export async function prepareBuildDir(input) {
|
|
114
|
-
const git = input.git ?? runGit;
|
|
115
124
|
const packagesToken = input.packagesToken ?? null;
|
|
116
|
-
const
|
|
117
|
-
mkdirSync(join(input.dir, REPOS_DIR), { recursive: true });
|
|
118
|
-
// The token travels as a git config entry in the clone process's environment: not in argv, not written to `.git/config`.
|
|
119
|
-
const auth = input.token === null ? {} : {
|
|
120
|
-
GIT_CONFIG_COUNT: '1',
|
|
121
|
-
GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
|
|
122
|
-
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${input.token}`).toString('base64')}`,
|
|
123
|
-
};
|
|
124
|
-
for (const repo of input.recipe.repositories) {
|
|
125
|
-
if (!/^[A-Za-z0-9._-]+$/.test(repo.name) || repo.name === '.' || repo.name === '..')
|
|
126
|
-
throw new Error(`repository name ${JSON.stringify(repo.name)} is not a plain directory name`);
|
|
127
|
-
await git(['clone', '--quiet', '--branch', repo.default_branch, cloneUrl(repo.github_full_name), join(REPOS_DIR, repo.name)], auth, input.dir);
|
|
128
|
-
}
|
|
125
|
+
const gitToken = input.recipe.repositories.length > 0 ? input.token : null;
|
|
129
126
|
writeFileSync(join(input.dir, BLAXEL_TOML_FILE), BLAXEL_TOML);
|
|
130
|
-
writeFileSync(join(input.dir, 'Dockerfile'), recipeDockerfile(input.recipe, input.revision, packagesToken !== null));
|
|
131
|
-
|
|
132
|
-
|
|
127
|
+
writeFileSync(join(input.dir, 'Dockerfile'), recipeDockerfile(input.recipe, input.revision, packagesToken !== null, gitToken !== null));
|
|
128
|
+
const buildEnv = [...(packagesToken !== null ? [`NODE_AUTH_TOKEN=${packagesToken}`] : []), ...(gitToken !== null ? [`${GIT_TOKEN_ARG}=${gitToken}`] : [])];
|
|
129
|
+
if (buildEnv.length > 0)
|
|
130
|
+
writeFileSync(join(input.dir, '.env.build'), `${buildEnv.join('\n')}\n`, { mode: 0o600 });
|
|
133
131
|
if (input.recipe.setup_script !== null && input.recipe.setup_script.trim() !== '')
|
|
134
132
|
writeFileSync(join(input.dir, SETUP_SCRIPT_FILE), input.recipe.setup_script.endsWith('\n') ? input.recipe.setup_script : `${input.recipe.setup_script}\n`);
|
|
135
133
|
}
|
|
@@ -13,6 +13,8 @@ export interface ProviderCaller {
|
|
|
13
13
|
sub: string | null;
|
|
14
14
|
grantee: string | null;
|
|
15
15
|
client_id: string | null;
|
|
16
|
+
/** The principal that presented the call (`Principal.actor`); absent when the caller is not a token presenter. */
|
|
17
|
+
actor?: string;
|
|
16
18
|
resolved: readonly string[] | null;
|
|
17
19
|
nodeScopes: readonly string[] | null;
|
|
18
20
|
run_id: string | null;
|
|
@@ -65,7 +65,7 @@ export async function callerFromRequest(principal) {
|
|
|
65
65
|
run_id: principal.run ?? (await getNode(principal.node))?.run_id ?? null, node_id: principal.node };
|
|
66
66
|
}
|
|
67
67
|
export function callerFromApp(principal) {
|
|
68
|
-
return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
|
|
68
|
+
return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, actor: principal.actor, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
|
|
69
69
|
}
|
|
70
70
|
/** A provider scope `<provider>:<group>` (the identity grammar's `provider`
|
|
71
71
|
* selector kind). `covers()` grants such a scope only by exact equality. */
|
|
@@ -195,6 +195,10 @@ export const OPERATIONS = [
|
|
|
195
195
|
{ name: 'profile.env.remove', method: 'DELETE', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
|
196
196
|
{ name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
|
|
197
197
|
{ name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
|
|
198
|
+
{ name: 'environment.create', method: 'POST', path: '/v1/environments', classes: ['app'], resource: 'profile' },
|
|
199
|
+
{ name: 'environment.list', method: 'GET', path: '/v1/environments', classes: ['app', 'person'], resource: 'profile' },
|
|
200
|
+
{ name: 'environment.patch', method: 'PATCH', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
|
|
201
|
+
{ name: 'environment.delete', method: 'DELETE', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
|
|
198
202
|
{ name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
|
199
203
|
{ name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker', 'cron'], resource: 'profile', stage: 'chat' },
|
|
200
204
|
{ name: 'profiles.get.118', method: 'GET', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
|
package/dist/daemon/manage.js
CHANGED
|
@@ -8,7 +8,7 @@ import { createRequire } from 'node:module';
|
|
|
8
8
|
import { dirname, join } from 'node:path';
|
|
9
9
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
10
10
|
import { existsSync, lstatSync, mkdirSync, openSync, closeSync, fstatSync, readSync } from 'node:fs';
|
|
11
|
-
import { crtrHome } from '../core/canvas/paths.js';
|
|
11
|
+
import { apiSocketPath, crtrHome } from '../core/canvas/paths.js';
|
|
12
12
|
import { listProcessTable } from '../core/canvas/pid.js';
|
|
13
13
|
import { bindDaemonEventSource, eventSource } from '../core/events/source.js';
|
|
14
14
|
import { hostExecPath } from '../core/runtime/branded-host.js';
|
|
@@ -245,7 +245,8 @@ const DAEMON_HEALTH_PROBE_TIMEOUT_MS = 1_000;
|
|
|
245
245
|
/** Make one `/healthz` observation without client-side recovery. The caller owns the availability window, so this probe cannot extend it. */
|
|
246
246
|
export async function probeDaemonHealth(timeoutMs = DAEMON_HEALTH_PROBE_TIMEOUT_MS) {
|
|
247
247
|
const probeTimeoutMs = Math.min(timeoutMs, DAEMON_HEALTH_PROBE_TIMEOUT_MS);
|
|
248
|
-
|
|
248
|
+
// This computer's daemon socket, never a node's `CRTR_API_SOCKET` relay: inside a node on an imported Mac that relay answers for the shared control plane.
|
|
249
|
+
return localClient({ autostart: false, timeoutMs: probeTimeoutMs, socketPath: apiSocketPath() }).probeHealthz(probeTimeoutMs);
|
|
249
250
|
}
|
|
250
251
|
export function probeErrorMessage(error) {
|
|
251
252
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -40,6 +40,8 @@ export interface RecipeImageDeps {
|
|
|
40
40
|
deleteImage?: (name: string) => Promise<void>;
|
|
41
41
|
now?: () => number;
|
|
42
42
|
}
|
|
43
|
+
/** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
|
|
44
|
+
export declare function removeLeftoverBuildDirs(root?: string): void;
|
|
43
45
|
export declare class RecipeImageReconciler {
|
|
44
46
|
private readonly deps;
|
|
45
47
|
constructor(deps?: RecipeImageDeps);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// the image with every tag (a 404 is done); success clears all four image columns, so a later undelete finds an unbuilt environment and
|
|
13
13
|
// the build pass rebuilds it; failure writes `image_error` and a retry time in `image_building_at`, as a failed build does. A build that
|
|
14
14
|
// finishes after the environment was deleted records nothing and deletes the image it made.
|
|
15
|
-
import { mkdtempSync } from 'node:fs';
|
|
15
|
+
import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
|
|
16
16
|
import { tmpdir } from 'node:os';
|
|
17
17
|
import { join } from 'node:path';
|
|
18
18
|
import { hasUnseenWakeMail } from '../../core/canvas/deliveries.js';
|
|
@@ -62,6 +62,12 @@ async function defaultBuild(input, config) {
|
|
|
62
62
|
removeBuildDir(dir);
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
|
+
/** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
|
|
66
|
+
export function removeLeftoverBuildDirs(root = tmpdir()) {
|
|
67
|
+
for (const name of readdirSync(root))
|
|
68
|
+
if (name.startsWith('crtr-recipe-image-'))
|
|
69
|
+
rmSync(join(root, name), { recursive: true, force: true });
|
|
70
|
+
}
|
|
65
71
|
export class RecipeImageReconciler {
|
|
66
72
|
deps;
|
|
67
73
|
constructor(deps = {}) {
|
|
@@ -148,6 +154,8 @@ export class RecipeImageReconciler {
|
|
|
148
154
|
const person = await (await openDb()).prepare('SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1').get(environmentId);
|
|
149
155
|
if (person === undefined)
|
|
150
156
|
throw new Error(`no profile runs in environment ${environmentId}, so there is no person to take a GitHub token for`);
|
|
157
|
+
// Recorded before the build so a process that dies mid-build leaves the reason; success clears it.
|
|
158
|
+
await (await openDb()).prepare('UPDATE environments SET image_error = ? WHERE object = ? AND image_building_at = ?').run(`the build of revision ${revision} started and its process exited before it finished`, environmentId, currentLease());
|
|
151
159
|
const input = { environmentId, revision, recipe, person: person.person };
|
|
152
160
|
built = await (this.deps.build ?? ((i) => defaultBuild(i, blaxelConfigFromEnv())))(input);
|
|
153
161
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.753",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|