@telorun/kernel 0.59.0 → 0.61.0
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/bundle/files-integrity.d.ts +21 -12
- package/dist/bundle/files-integrity.d.ts.map +1 -1
- package/dist/bundle/files-integrity.js +27 -14
- package/dist/bundle/files-integrity.js.map +1 -1
- package/dist/bundle/module-artifact.d.ts +134 -0
- package/dist/bundle/module-artifact.d.ts.map +1 -0
- package/dist/bundle/module-artifact.js +300 -0
- package/dist/bundle/module-artifact.js.map +1 -0
- package/dist/bundle/module-manifest.d.ts +12 -4
- package/dist/bundle/module-manifest.d.ts.map +1 -1
- package/dist/bundle/module-manifest.js +8 -4
- package/dist/bundle/module-manifest.js.map +1 -1
- package/dist/controller-loader.d.ts +3 -2
- package/dist/controller-loader.d.ts.map +1 -1
- package/dist/controller-loader.js +8 -8
- package/dist/controller-loader.js.map +1 -1
- package/dist/controller-loaders/bundle-loader.d.ts +8 -6
- package/dist/controller-loaders/bundle-loader.d.ts.map +1 -1
- package/dist/controller-loaders/bundle-loader.js +52 -13
- package/dist/controller-loaders/bundle-loader.js.map +1 -1
- package/dist/controller-loaders/npm-loader.d.ts +0 -18
- package/dist/controller-loaders/npm-loader.d.ts.map +1 -1
- package/dist/controller-loaders/npm-loader.js +3 -190
- package/dist/controller-loaders/npm-loader.js.map +1 -1
- package/dist/controllers/resource-definition/resource-definition-controller.d.ts.map +1 -1
- package/dist/controllers/resource-definition/resource-definition-controller.js +6 -1
- package/dist/controllers/resource-definition/resource-definition-controller.js.map +1 -1
- package/dist/controllers/resource-definition/resource-inherited-controller.d.ts.map +1 -1
- package/dist/controllers/resource-definition/resource-inherited-controller.js +57 -10
- package/dist/controllers/resource-definition/resource-inherited-controller.js.map +1 -1
- package/dist/controllers/type/json-schema-controller.d.ts +8 -0
- package/dist/controllers/type/json-schema-controller.d.ts.map +1 -0
- package/dist/controllers/type/json-schema-controller.js +91 -0
- package/dist/controllers/type/json-schema-controller.js.map +1 -0
- package/dist/directory-lock.d.ts +27 -0
- package/dist/directory-lock.d.ts.map +1 -0
- package/dist/directory-lock.js +205 -0
- package/dist/directory-lock.js.map +1 -0
- package/dist/evaluation-context.d.ts +5 -0
- package/dist/evaluation-context.d.ts.map +1 -1
- package/dist/evaluation-context.js +63 -33
- package/dist/evaluation-context.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/init-failure-diagnostics.d.ts +61 -0
- package/dist/init-failure-diagnostics.d.ts.map +1 -0
- package/dist/init-failure-diagnostics.js +141 -0
- package/dist/init-failure-diagnostics.js.map +1 -0
- package/dist/invocation-contract-binding.d.ts +105 -0
- package/dist/invocation-contract-binding.d.ts.map +1 -0
- package/dist/invocation-contract-binding.js +296 -0
- package/dist/invocation-contract-binding.js.map +1 -0
- package/dist/kernel.d.ts +49 -0
- package/dist/kernel.d.ts.map +1 -1
- package/dist/kernel.js +117 -6
- package/dist/kernel.js.map +1 -1
- package/dist/manifest-sources/local-manifest-cache-source.d.ts +1 -1
- package/dist/manifest-sources/local-manifest-cache-source.d.ts.map +1 -1
- package/dist/manifest-sources/local-manifest-cache-source.js +1 -1
- package/dist/manifest-sources/local-manifest-cache-source.js.map +1 -1
- package/dist/module-context.d.ts.map +1 -1
- package/dist/module-context.js +21 -0
- package/dist/module-context.js.map +1 -1
- package/dist/resource-context.d.ts +61 -0
- package/dist/resource-context.d.ts.map +1 -1
- package/dist/resource-context.js +131 -0
- package/dist/resource-context.js.map +1 -1
- package/dist/schema-compiled-values.d.ts +9 -1
- package/dist/schema-compiled-values.d.ts.map +1 -1
- package/dist/schema-compiled-values.js +55 -16
- package/dist/schema-compiled-values.js.map +1 -1
- package/dist/schema-validator.d.ts.map +1 -1
- package/dist/schema-validator.js +15 -1
- package/dist/schema-validator.js.map +1 -1
- package/dist/transports/oci/oci-client.d.ts +28 -1
- package/dist/transports/oci/oci-client.d.ts.map +1 -1
- package/dist/transports/oci/oci-client.js +24 -1
- package/dist/transports/oci/oci-client.js.map +1 -1
- package/dist/transports/oci/oci-transport.d.ts +20 -14
- package/dist/transports/oci/oci-transport.d.ts.map +1 -1
- package/dist/transports/oci/oci-transport.js +105 -46
- package/dist/transports/oci/oci-transport.js.map +1 -1
- package/dist/transports/registry-transport.d.ts +7 -2
- package/dist/transports/registry-transport.d.ts.map +1 -1
- package/dist/transports/registry-transport.js +8 -33
- package/dist/transports/registry-transport.js.map +1 -1
- package/dist/transports/transport-registry.d.ts +5 -4
- package/dist/transports/transport-registry.d.ts.map +1 -1
- package/dist/transports/transport-registry.js +4 -4
- package/dist/transports/transport-registry.js.map +1 -1
- package/dist/transports/transport.d.ts +27 -19
- package/dist/transports/transport.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/bundle/files-integrity.ts +34 -14
- package/src/bundle/module-artifact.ts +375 -0
- package/src/bundle/module-manifest.ts +22 -6
- package/src/controller-loader.ts +9 -4
- package/src/controller-loaders/bundle-loader.ts +57 -11
- package/src/controller-loaders/npm-loader.ts +3 -209
- package/src/controllers/resource-definition/resource-definition-controller.ts +19 -0
- package/src/controllers/resource-definition/resource-inherited-controller.ts +69 -10
- package/src/controllers/type/json-schema-controller.ts +114 -0
- package/src/directory-lock.ts +225 -0
- package/src/evaluation-context.ts +81 -32
- package/src/index.ts +11 -2
- package/src/init-failure-diagnostics.ts +169 -0
- package/src/invocation-contract-binding.ts +392 -0
- package/src/kernel.ts +149 -6
- package/src/manifest-sources/local-manifest-cache-source.ts +1 -1
- package/src/module-context.ts +27 -0
- package/src/resource-context.ts +138 -0
- package/src/schema-compiled-values.ts +55 -15
- package/src/schema-validator.ts +15 -1
- package/src/transports/oci/oci-client.ts +32 -1
- package/src/transports/oci/oci-transport.ts +122 -51
- package/src/transports/registry-transport.ts +10 -38
- package/src/transports/transport-registry.ts +5 -5
- package/src/transports/transport.ts +32 -19
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { NOOP_LOGGER, type Logger } from "@telorun/sdk";
|
|
2
|
+
import * as fs from "fs/promises";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The cross-process lock guarding mutation of a shared cache directory.
|
|
8
|
+
*
|
|
9
|
+
* Two consumers hold it for the same reason — several Telo processes (and, in
|
|
10
|
+
* one process, several concurrent resolutions) may decide to populate the same
|
|
11
|
+
* directory at the same moment: `NpmControllerLoader` around its install root,
|
|
12
|
+
* and `ModuleArtifact` around a module's extracted layers. One implementation
|
|
13
|
+
* rather than two, because the reclaim rule below is subtle enough that two
|
|
14
|
+
* copies would drift.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A held lock is refreshed (its mtime bumped) every {@link LOCK_HEARTBEAT_MS}
|
|
19
|
+
* by the holder. Staleness is judged purely by mtime age — a lock older than
|
|
20
|
+
* this means the holder stopped heartbeating (crashed, was killed, or its
|
|
21
|
+
* container vanished), so it is safe to reclaim. This deliberately does NOT
|
|
22
|
+
* probe the recorded PID for liveness: PID identity is meaningless across
|
|
23
|
+
* container restarts and PID namespaces (deterministic PID reuse makes an
|
|
24
|
+
* unrelated process look like the dead holder on the same hostname), which is
|
|
25
|
+
* exactly what deadlocked container boots. The `{pid, host}` in the lock body
|
|
26
|
+
* is diagnostics for humans, never a reclaim signal. Must be comfortably
|
|
27
|
+
* larger than the heartbeat interval so a briefly-descheduled holder (GC
|
|
28
|
+
* pause, busy event loop) is not reclaimed out from under itself.
|
|
29
|
+
*/
|
|
30
|
+
const LOCK_STALE_MS = 30_000;
|
|
31
|
+
|
|
32
|
+
/** How often the holder refreshes the lock mtime while `fn` runs. Well under
|
|
33
|
+
* {@link LOCK_STALE_MS} so several heartbeats are missed before a live holder
|
|
34
|
+
* is ever judged stale. */
|
|
35
|
+
const LOCK_HEARTBEAT_MS = 5_000;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Total wall-clock cap for waiting on the lock — enough for a slow first
|
|
39
|
+
* populate on a peer process to finish, short enough that a genuinely
|
|
40
|
+
* deadlocked CI job fails loudly rather than hanging for hours. The retry
|
|
41
|
+
* interval trades wakeup latency vs. wasted polls; 500ms is well below the
|
|
42
|
+
* lock holder's typical hold time.
|
|
43
|
+
*/
|
|
44
|
+
const LOCK_WAIT_MAX_MS = 5 * 60_000;
|
|
45
|
+
const LOCK_RETRY_MS = 500;
|
|
46
|
+
|
|
47
|
+
/** After this long waiting on a lock, emit one line so a slow wait is visible
|
|
48
|
+
* instead of looking like a silent hang. */
|
|
49
|
+
const LOCK_WAIT_NOTICE_MS = 2_000;
|
|
50
|
+
|
|
51
|
+
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* In-process serialization ahead of the filesystem lock.
|
|
55
|
+
*
|
|
56
|
+
* Without it, N concurrent callers for the same directory all reach the fs lock,
|
|
57
|
+
* N-1 sit in the retry loop, and each crossing {@link LOCK_WAIT_NOTICE_MS}
|
|
58
|
+
* prints the wait notice — a notice whose whole point is "another *process* is
|
|
59
|
+
* populating this", printed when the holder is us. (`telo install` fanning 52
|
|
60
|
+
* controllers out through one `Promise.allSettled` printed 51 of them.)
|
|
61
|
+
*
|
|
62
|
+
* Queuing here means exactly one caller per process reaches the fs lock, so the
|
|
63
|
+
* notice regains its cross-process meaning and the losers do no I/O at all. The
|
|
64
|
+
* fs lock is untouched and still provides the cross-process guarantee.
|
|
65
|
+
*/
|
|
66
|
+
const localQueues = new Map<string, Promise<unknown>>();
|
|
67
|
+
|
|
68
|
+
function withLocalQueue<T>(dir: string, fn: () => Promise<T>): Promise<T> {
|
|
69
|
+
const prev = localQueues.get(dir) ?? Promise.resolve();
|
|
70
|
+
// Run on both settle paths: one failure must not wedge the queue.
|
|
71
|
+
const run = prev.then(fn, fn);
|
|
72
|
+
// The stored tail never rejects — a failure neither poisons followers nor
|
|
73
|
+
// surfaces as an unhandled rejection on the chain copy.
|
|
74
|
+
const tail = run.then(
|
|
75
|
+
() => {},
|
|
76
|
+
() => {},
|
|
77
|
+
);
|
|
78
|
+
localQueues.set(dir, tail);
|
|
79
|
+
// Drop the entry once nothing further is queued, so a long-lived process that
|
|
80
|
+
// touches many directories doesn't retain a promise per directory forever.
|
|
81
|
+
void tail.then(() => {
|
|
82
|
+
if (localQueues.get(dir) === tail) localQueues.delete(dir);
|
|
83
|
+
});
|
|
84
|
+
return run;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Acquire the lock for `dir` and run `fn` under it: first the in-process queue
|
|
89
|
+
* above, then the cross-process filesystem lock. `label` names the operation in
|
|
90
|
+
* the wait notice and timeout error (e.g. "controller install", "module layer").
|
|
91
|
+
*/
|
|
92
|
+
export async function withDirectoryLock<T>(
|
|
93
|
+
dir: string,
|
|
94
|
+
label: string,
|
|
95
|
+
fn: () => Promise<T>,
|
|
96
|
+
log: Logger = NOOP_LOGGER,
|
|
97
|
+
): Promise<T> {
|
|
98
|
+
return withLocalQueue(dir, () => withFileLock(dir, label, fn, log));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Acquire a process-portable lock on `<dir>/.lock` and execute fn while
|
|
103
|
+
* holding it. `fs.open(path, 'wx')` is atomic on POSIX and Windows, so
|
|
104
|
+
* concurrent processes serialize naturally.
|
|
105
|
+
*
|
|
106
|
+
* Liveness is a heartbeat: the holder bumps the lock's mtime every
|
|
107
|
+
* {@link LOCK_HEARTBEAT_MS} while `fn` runs, and a waiter reclaims a lock whose
|
|
108
|
+
* mtime is older than {@link LOCK_STALE_MS} (holder crashed/killed/vanished).
|
|
109
|
+
* mtime age is the *only* reclaim signal — the recorded `{pid, host}` is
|
|
110
|
+
* diagnostics, never probed for liveness, because PID identity is unreliable
|
|
111
|
+
* across container restarts and PID namespaces (the failure that deadlocked
|
|
112
|
+
* container boots). Reclaim is via atomic rename to a unique tombstone so two
|
|
113
|
+
* waiters that both see the lock stale can't both win.
|
|
114
|
+
*
|
|
115
|
+
* The lock guards *writes* into the directory. It does NOT serialize reads of
|
|
116
|
+
* already-populated content — those run lock-free against a stable tree.
|
|
117
|
+
*/
|
|
118
|
+
async function withFileLock<T>(
|
|
119
|
+
dir: string,
|
|
120
|
+
label: string,
|
|
121
|
+
fn: () => Promise<T>,
|
|
122
|
+
log: Logger,
|
|
123
|
+
): Promise<T> {
|
|
124
|
+
const lockPath = path.join(dir, ".lock");
|
|
125
|
+
|
|
126
|
+
await fs.mkdir(dir, { recursive: true });
|
|
127
|
+
|
|
128
|
+
const lockBody = JSON.stringify({ pid: process.pid, host: os.hostname(), startedAt: Date.now() });
|
|
129
|
+
let handle: import("fs/promises").FileHandle | null = null;
|
|
130
|
+
const waitedSince = Date.now();
|
|
131
|
+
let noticed = false;
|
|
132
|
+
while (true) {
|
|
133
|
+
try {
|
|
134
|
+
handle = await fs.open(lockPath, "wx");
|
|
135
|
+
await handle.writeFile(lockBody);
|
|
136
|
+
break;
|
|
137
|
+
} catch (err: any) {
|
|
138
|
+
if (err?.code !== "EEXIST") throw err;
|
|
139
|
+
// Lock exists. Reclaim it only if its heartbeat has gone silent.
|
|
140
|
+
if (await reclaimIfStale(lockPath)) continue;
|
|
141
|
+
const waited = Date.now() - waitedSince;
|
|
142
|
+
if (waited > LOCK_WAIT_MAX_MS) {
|
|
143
|
+
throw new Error(
|
|
144
|
+
`[telo] timed out waiting for ${label} lock at ${lockPath} ` +
|
|
145
|
+
`(held >${LOCK_WAIT_MAX_MS / 60_000} min with a live heartbeat). ` +
|
|
146
|
+
`Inspect the lock file or remove it manually if no other Telo process is running.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
if (!noticed && waited > LOCK_WAIT_NOTICE_MS) {
|
|
150
|
+
noticed = true;
|
|
151
|
+
log.info(`waiting for ${label} lock`, { "telo.lock.path": lockPath });
|
|
152
|
+
}
|
|
153
|
+
await sleep(LOCK_RETRY_MS);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Keep the lock fresh while `fn` runs so a slow-but-live operation is never
|
|
158
|
+
// reclaimed. `unref` so the heartbeat can't by itself keep the process alive.
|
|
159
|
+
const heartbeat = setInterval(() => {
|
|
160
|
+
const now = new Date();
|
|
161
|
+
fs.utimes(lockPath, now, now).catch(() => {});
|
|
162
|
+
}, LOCK_HEARTBEAT_MS);
|
|
163
|
+
heartbeat.unref?.();
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
return await fn();
|
|
167
|
+
} finally {
|
|
168
|
+
clearInterval(heartbeat);
|
|
169
|
+
// The fd close races nothing important: if it fails, the FD is reaped on
|
|
170
|
+
// process exit. The unlink is the dangerous one — a non-ENOENT failure
|
|
171
|
+
// (permissions, read-only mount) means every subsequent kernel waits
|
|
172
|
+
// LOCK_STALE_MS before reclaiming. Surface it so the cause is visible
|
|
173
|
+
// rather than hiding behind a silent hang.
|
|
174
|
+
await handle!.close().catch(() => {});
|
|
175
|
+
try {
|
|
176
|
+
await fs.rm(lockPath, { force: true });
|
|
177
|
+
} catch (err: any) {
|
|
178
|
+
if (err?.code !== "ENOENT") {
|
|
179
|
+
log.warn(`failed to release ${label} lock`, { "telo.lock.path": lockPath }, { error: err });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* If the lock at `lockPath` is stale (mtime older than {@link LOCK_STALE_MS}, so
|
|
187
|
+
* its holder stopped heartbeating), atomically claim and remove it and return
|
|
188
|
+
* true; otherwise return false. The claim is a `rename` to a unique tombstone:
|
|
189
|
+
* `rename` is atomic and fails for all but one racer, so two processes that
|
|
190
|
+
* both observe the same stale lock cannot both reclaim it — the loser's rename
|
|
191
|
+
* throws ENOENT (the file is already gone) and it simply retries the open.
|
|
192
|
+
*/
|
|
193
|
+
async function reclaimIfStale(lockPath: string): Promise<boolean> {
|
|
194
|
+
let stat: import("fs").Stats;
|
|
195
|
+
try {
|
|
196
|
+
stat = await fs.stat(lockPath);
|
|
197
|
+
} catch (err: any) {
|
|
198
|
+
// Race: lock vanished while we inspected it. Retry the open immediately.
|
|
199
|
+
if (err?.code === "ENOENT") return true;
|
|
200
|
+
throw err;
|
|
201
|
+
}
|
|
202
|
+
if (Date.now() - stat.mtimeMs < LOCK_STALE_MS) return false;
|
|
203
|
+
|
|
204
|
+
// Stale — the holder's heartbeat is silent. Claim via atomic rename; only one
|
|
205
|
+
// racer wins, the rest get ENOENT and fall back to retrying the open.
|
|
206
|
+
const tombstone = `${lockPath}.stale.${process.pid}.${stat.mtimeMs}`;
|
|
207
|
+
try {
|
|
208
|
+
await fs.rename(lockPath, tombstone);
|
|
209
|
+
} catch (err: any) {
|
|
210
|
+
if (err?.code === "ENOENT") return true; // another waiter reclaimed it first
|
|
211
|
+
throw err;
|
|
212
|
+
}
|
|
213
|
+
await fs.rm(tombstone, { force: true });
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Internals exposed for the lock's own tests (acquire/release, stale reclaim,
|
|
219
|
+
* heartbeat, in-process queuing). Not part of the kernel's public API.
|
|
220
|
+
*/
|
|
221
|
+
export const __testing__ = {
|
|
222
|
+
reclaimIfStale,
|
|
223
|
+
LOCK_STALE_MS,
|
|
224
|
+
LOCK_HEARTBEAT_MS,
|
|
225
|
+
};
|
|
@@ -26,6 +26,12 @@ import {
|
|
|
26
26
|
} from "@telorun/sdk";
|
|
27
27
|
import { RuntimeError } from "@telorun/sdk";
|
|
28
28
|
import { evalPathCovers } from "@telorun/analyzer";
|
|
29
|
+
import {
|
|
30
|
+
classifyInitFailures,
|
|
31
|
+
renderInitFailureText,
|
|
32
|
+
summarizeInitFailures,
|
|
33
|
+
type FailedResource,
|
|
34
|
+
} from "./init-failure-diagnostics.js";
|
|
29
35
|
import {
|
|
30
36
|
acceptReportedStatus,
|
|
31
37
|
buildPublishedProps,
|
|
@@ -93,6 +99,16 @@ function collectResourceRefs(resource: ResourceManifest): ResourceRef[] {
|
|
|
93
99
|
return [...found.values()];
|
|
94
100
|
}
|
|
95
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Project resource refs onto the names they depend on IN THIS CONTEXT. A local
|
|
104
|
+
* ref is its own name; a cross-module `Alias.name` ref depends on the local
|
|
105
|
+
* `Telo.Import` resource named by the alias, since that is the resource whose
|
|
106
|
+
* failure would strand it. Used to attribute an init failure to its cause.
|
|
107
|
+
*/
|
|
108
|
+
function localDependencyNames(refs: ResourceRef[]): string[] {
|
|
109
|
+
return refs.map((r) => (r.alias && r.alias !== "Self" ? r.alias : r.name));
|
|
110
|
+
}
|
|
111
|
+
|
|
96
112
|
/**
|
|
97
113
|
* Build a resource's resolved properties for the debug stream — its config "after
|
|
98
114
|
* templating", with `${{ }}` / `!cel` reduced to concrete values. The manifest is
|
|
@@ -343,6 +359,12 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
343
359
|
/** Resources queued for initialization on this context node. */
|
|
344
360
|
private pendingResources: ResourceManifest[] = [];
|
|
345
361
|
|
|
362
|
+
/** Per-resource dependency names, captured at create() time — BEFORE Phase-5
|
|
363
|
+
* injection swaps refs for live instances, so the walk sees plain objects and
|
|
364
|
+
* cannot wander into a controller's (possibly cyclic) object graph. Read only
|
|
365
|
+
* when init fails, to attribute each failure to its cause. */
|
|
366
|
+
private readonly resourceDependencies = new Map<string, string[]>();
|
|
367
|
+
|
|
346
368
|
/**
|
|
347
369
|
* Optional hook called between create() and init() for each resource.
|
|
348
370
|
* Set by the kernel to inject live instances into reference fields.
|
|
@@ -616,7 +638,10 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
616
638
|
*/
|
|
617
639
|
async initializeResources(): Promise<void> {
|
|
618
640
|
const MAX_PASSES = 10;
|
|
619
|
-
const errors = new Map<
|
|
641
|
+
const errors = new Map<
|
|
642
|
+
string,
|
|
643
|
+
{ message: string; code?: string; details?: string; children?: RuntimeDiagnostic[] }
|
|
644
|
+
>();
|
|
620
645
|
|
|
621
646
|
let pass = 1;
|
|
622
647
|
do {
|
|
@@ -641,6 +666,8 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
641
666
|
errors.delete(name);
|
|
642
667
|
progress = true;
|
|
643
668
|
const createdRes = created.resource;
|
|
669
|
+
const refs = collectResourceRefs(createdRes);
|
|
670
|
+
this.resourceDependencies.set(name, localDependencyNames(refs));
|
|
644
671
|
const payload: Record<string, unknown> = {
|
|
645
672
|
resource: {
|
|
646
673
|
kind: createdRes.kind,
|
|
@@ -649,7 +676,7 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
649
676
|
id: this.resourceId(createdRes.kind, createdRes.metadata.name),
|
|
650
677
|
},
|
|
651
678
|
...(this.owner ? { owner: this.owner } : {}),
|
|
652
|
-
dependencies: this.qualifyDeps(
|
|
679
|
+
dependencies: this.qualifyDeps(refs),
|
|
653
680
|
};
|
|
654
681
|
// `properties` (the resolved config) is a second full config walk plus
|
|
655
682
|
// a secret scrub. Build it lazily: the EventBus short-circuits when
|
|
@@ -682,6 +709,7 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
682
709
|
? this.resolveImportedInstance(alias, n)
|
|
683
710
|
: this.resourceInstances.get(n)?.instance,
|
|
684
711
|
(n) => this.hasManifest(n) && !this.resourceInstances.has(n),
|
|
712
|
+
this,
|
|
685
713
|
);
|
|
686
714
|
}
|
|
687
715
|
if (instance.init) await instance.init(ctx);
|
|
@@ -694,6 +722,9 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
694
722
|
await this.publishSnapshot(name);
|
|
695
723
|
this.resourceInstances.set(name, { resource, instance });
|
|
696
724
|
this.createdInstances.delete(name);
|
|
725
|
+
// Read only on failure, and this one succeeded — drop it rather than
|
|
726
|
+
// holding a dep-name array per resource for the context's lifetime.
|
|
727
|
+
this.resourceDependencies.delete(name);
|
|
697
728
|
errors.delete(name);
|
|
698
729
|
progress = true;
|
|
699
730
|
await this.emit(`${resource.kind}.${resource.metadata.name}.Initialized`, {
|
|
@@ -715,38 +746,33 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
715
746
|
} while (pass <= MAX_PASSES);
|
|
716
747
|
|
|
717
748
|
if (this.pendingResources.length > 0 || this.createdInstances.size > 0) {
|
|
718
|
-
const
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
}
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
749
|
+
const toFailure = (name: string, kind: string, deps: string[]): FailedResource => {
|
|
750
|
+
const info = errors.get(name) ?? { message: "Unknown error" };
|
|
751
|
+
return {
|
|
752
|
+
resource: name,
|
|
753
|
+
kind,
|
|
754
|
+
message: info.message,
|
|
755
|
+
details: info.details,
|
|
756
|
+
code: info.code,
|
|
757
|
+
children: info.children,
|
|
758
|
+
deps,
|
|
759
|
+
};
|
|
760
|
+
};
|
|
761
|
+
const failures: FailedResource[] = [
|
|
762
|
+
// A resource that never got created was never injected either, so its
|
|
763
|
+
// manifest still carries plain `{kind, name}` refs — walk it here rather
|
|
764
|
+
// than relying on the create-time capture it never reached.
|
|
765
|
+
...this.pendingResources.map((r) =>
|
|
766
|
+
toFailure(r.metadata.name, r.kind, localDependencyNames(collectResourceRefs(r))),
|
|
767
|
+
),
|
|
768
|
+
...[...this.createdInstances].map(([name, { resource }]) =>
|
|
769
|
+
toFailure(name, resource.kind, this.resourceDependencies.get(name) ?? []),
|
|
770
|
+
),
|
|
739
771
|
];
|
|
740
|
-
const
|
|
741
|
-
.map((d) => {
|
|
742
|
-
const head = ` ${d.kind ? `${d.kind} ` : ""}${d.resource}: ${d.message}${d.code ? ` [${d.code}]` : ""}`;
|
|
743
|
-
const extra = d.details ? "\n" + d.details.split("\n").map((l) => ` ${l}`).join("\n") : "";
|
|
744
|
-
return head + extra;
|
|
745
|
-
})
|
|
746
|
-
.join("\n");
|
|
772
|
+
const diagnostics = classifyInitFailures(failures);
|
|
747
773
|
throw new RuntimeError(
|
|
748
774
|
"ERR_RESOURCE_INITIALIZATION_FAILED",
|
|
749
|
-
|
|
775
|
+
`${summarizeInitFailures(diagnostics)}:\n${renderInitFailureText(diagnostics)}`,
|
|
750
776
|
diagnostics,
|
|
751
777
|
);
|
|
752
778
|
}
|
|
@@ -815,7 +841,7 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
815
841
|
// Propagate injection hook: extend getInstance to also resolve parent singleton instances.
|
|
816
842
|
if (parent.preInitHook) {
|
|
817
843
|
const parentHook = parent.preInitHook;
|
|
818
|
-
child.preInitHook = (resource, childGetInstance, childIsPending) => {
|
|
844
|
+
child.preInitHook = (resource, childGetInstance, childIsPending, owner) => {
|
|
819
845
|
parentHook(
|
|
820
846
|
resource,
|
|
821
847
|
(name, alias) => {
|
|
@@ -836,6 +862,9 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
836
862
|
// Only a scope-local dependency can still be pending — an outer resource
|
|
837
863
|
// is live by the time a scope opens — so the child's own predicate suffices.
|
|
838
864
|
childIsPending,
|
|
865
|
+
// Forwarded, not replaced by `child`: a `with:` nested inside a scoped
|
|
866
|
+
// resource must still resolve kinds against the scope it opened in.
|
|
867
|
+
owner,
|
|
839
868
|
);
|
|
840
869
|
};
|
|
841
870
|
}
|
|
@@ -1761,11 +1790,31 @@ function formatErrorForDiagnostic(err: unknown): {
|
|
|
1761
1790
|
message: string;
|
|
1762
1791
|
code?: string;
|
|
1763
1792
|
details?: string;
|
|
1793
|
+
children?: RuntimeDiagnostic[];
|
|
1764
1794
|
} {
|
|
1765
1795
|
if (!(err instanceof Error)) {
|
|
1766
1796
|
return { message: String(err) };
|
|
1767
1797
|
}
|
|
1768
1798
|
|
|
1799
|
+
// A nested context's aggregate (an import initializing its library's
|
|
1800
|
+
// resources) already carries a classified diagnostic list. Keep it structured
|
|
1801
|
+
// instead of letting the cause-chain walk flatten it into this entry's
|
|
1802
|
+
// message: the child's root causes stay distinguishable from the child's own
|
|
1803
|
+
// cascade, and the error count sees the real leaves rather than one import.
|
|
1804
|
+
// The headline is re-derived from the diagnostics, never recovered by parsing
|
|
1805
|
+
// the message the child already rendered from them.
|
|
1806
|
+
if (
|
|
1807
|
+
err instanceof RuntimeError &&
|
|
1808
|
+
err.code === "ERR_RESOURCE_INITIALIZATION_FAILED" &&
|
|
1809
|
+
err.diagnostics?.length
|
|
1810
|
+
) {
|
|
1811
|
+
return {
|
|
1812
|
+
message: summarizeInitFailures(err.diagnostics),
|
|
1813
|
+
code: err.code,
|
|
1814
|
+
children: err.diagnostics,
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1769
1818
|
const detailLines: string[] = [];
|
|
1770
1819
|
const seen = new Set<unknown>();
|
|
1771
1820
|
let current: unknown = err;
|
package/src/index.ts
CHANGED
|
@@ -23,11 +23,19 @@ export {
|
|
|
23
23
|
export { makeTarGz, readTarGz, type BundleEntry } from "./bundle/tar.js";
|
|
24
24
|
export {
|
|
25
25
|
computeFilesIntegrity,
|
|
26
|
-
|
|
26
|
+
injectLayerIndex,
|
|
27
27
|
type PayloadFile,
|
|
28
28
|
} from "./bundle/files-integrity.js";
|
|
29
|
+
export {
|
|
30
|
+
ModuleArtifact,
|
|
31
|
+
moduleArtifactFor,
|
|
32
|
+
moduleDirectoryFor,
|
|
33
|
+
hostPlatformTarget,
|
|
34
|
+
type MaterializedLayer,
|
|
35
|
+
} from "./bundle/module-artifact.js";
|
|
36
|
+
export { readOwnerManifest, type OwnerManifest } from "./bundle/module-manifest.js";
|
|
29
37
|
export type {
|
|
30
|
-
|
|
38
|
+
PayloadLayer,
|
|
31
39
|
PublishBundle,
|
|
32
40
|
PublishResult,
|
|
33
41
|
PublishOptions,
|
|
@@ -39,6 +47,7 @@ export { ModuleContext } from "./module-context.js";
|
|
|
39
47
|
export { ManifestRegistry as Registry } from "./registry.js";
|
|
40
48
|
export { ResourceURI } from "./resource-uri.js";
|
|
41
49
|
export type { RuntimeDiagnostic } from "@telorun/sdk";
|
|
50
|
+
export { describeBlockedGroup, groupBlockedResources } from "./init-failure-diagnostics.js";
|
|
42
51
|
|
|
43
52
|
// Structured logging — the runtime half of kernel/specs/logging.md. The record
|
|
44
53
|
// model, severity scale, and `Logger` surface live in `@telorun/sdk`; these are
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { RuntimeDiagnostic } from "@telorun/sdk";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Codes that mean "this resource never got its turn": the multi-pass init loop
|
|
5
|
+
* deferred it because a dependency had not initialized, so it never produced a
|
|
6
|
+
* failure of its own. This is the ONLY signal that an entry may be collapsed —
|
|
7
|
+
* see {@link classifyInitFailures}.
|
|
8
|
+
*/
|
|
9
|
+
const DEPENDENCY_PENDING_CODES = new Set([
|
|
10
|
+
"ERR_LOCAL_REF_PENDING",
|
|
11
|
+
"ERR_CROSS_MODULE_REF_PENDING",
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
/** One resource that did not reach the `Initialized` state, with the outbound
|
|
15
|
+
* edges (names of resources in the SAME context) captured for it. */
|
|
16
|
+
export interface FailedResource {
|
|
17
|
+
resource: string;
|
|
18
|
+
kind?: string;
|
|
19
|
+
message: string;
|
|
20
|
+
details?: string;
|
|
21
|
+
code?: string;
|
|
22
|
+
children?: RuntimeDiagnostic[];
|
|
23
|
+
deps: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Split a failed-resource set into the ones that failed on their own (root
|
|
28
|
+
* causes) and the ones that only failed because something else in the set did.
|
|
29
|
+
*
|
|
30
|
+
* A dependency chain of any length produces one real error and N shadows of it,
|
|
31
|
+
* and the shadows outnumber the cause — reporting them flat buries the only
|
|
32
|
+
* line a reader can act on.
|
|
33
|
+
*
|
|
34
|
+
* **What makes an entry derived is its CODE, never its edges.** Only a
|
|
35
|
+
* {@link DEPENDENCY_PENDING_CODES} deferral says "this resource never ran, so
|
|
36
|
+
* it has nothing of its own to report". A reference edge into the failure set
|
|
37
|
+
* proves an edge exists, not that this entry's failure came from it: a resource
|
|
38
|
+
* can reference a failed dependency AND fail its own schema validation, and
|
|
39
|
+
* collapsing it there would swallow a real, independent error the author has to
|
|
40
|
+
* fix — the second half of a two-error session they would only discover on the
|
|
41
|
+
* next run. (Nor is the edge trustworthy on its own terms: `collectResourceRefs`
|
|
42
|
+
* walks `with:`-scoped inline declarations, whose names resolve scope-locally,
|
|
43
|
+
* so a scoped `!ref Db` can collide with a failed module-level `Db`.)
|
|
44
|
+
*
|
|
45
|
+
* Edges are used for ATTRIBUTION only — they name which failure a deferred
|
|
46
|
+
* entry is waiting on. `blockedBy` is the ROOT of the chain, not the immediate
|
|
47
|
+
* blocker, since that is the name a reader has to go fix; the walk stops at the
|
|
48
|
+
* first entry that is not itself derived. A deferral with no visible edge (a
|
|
49
|
+
* `${{ resources.X }}` read the ref walk cannot see) is still derived, just
|
|
50
|
+
* unattributed.
|
|
51
|
+
*
|
|
52
|
+
* Classification never hides everything: if no entry survives as a root (every
|
|
53
|
+
* failure is a deferral), the whole set is reported unclassified.
|
|
54
|
+
*
|
|
55
|
+
* Returns diagnostics ordered root causes first, then the derived entries.
|
|
56
|
+
*/
|
|
57
|
+
export function classifyInitFailures(failures: FailedResource[]): RuntimeDiagnostic[] {
|
|
58
|
+
const failed = new Set(failures.map((f) => f.resource));
|
|
59
|
+
|
|
60
|
+
const derived = new Set(
|
|
61
|
+
failures.filter((f) => f.code && DEPENDENCY_PENDING_CODES.has(f.code)).map((f) => f.resource),
|
|
62
|
+
);
|
|
63
|
+
// Attribution edges are collected for EVERY entry, derived or not: a chain
|
|
64
|
+
// walk has to pass through an entry to reach the root beyond it.
|
|
65
|
+
const edgeBlocker = new Map<string, string>();
|
|
66
|
+
for (const f of failures) {
|
|
67
|
+
const dep = f.deps.find((n) => n !== f.resource && failed.has(n));
|
|
68
|
+
if (dep !== undefined) edgeBlocker.set(f.resource, dep);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const rootCauseOf = (name: string): string | undefined => {
|
|
72
|
+
const seen = new Set<string>([name]);
|
|
73
|
+
let current = edgeBlocker.get(name);
|
|
74
|
+
while (current !== undefined && !seen.has(current)) {
|
|
75
|
+
if (!derived.has(current)) return current;
|
|
76
|
+
seen.add(current);
|
|
77
|
+
current = edgeBlocker.get(current);
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const toDiagnostic = (f: FailedResource, isDerived: boolean): RuntimeDiagnostic => {
|
|
83
|
+
const blockedBy = isDerived ? rootCauseOf(f.resource) : undefined;
|
|
84
|
+
return {
|
|
85
|
+
resource: f.resource,
|
|
86
|
+
kind: f.kind,
|
|
87
|
+
message: f.message,
|
|
88
|
+
details: f.details,
|
|
89
|
+
code: f.code,
|
|
90
|
+
...(f.children?.length ? { children: f.children } : {}),
|
|
91
|
+
...(isDerived ? { derived: true, ...(blockedBy ? { blockedBy } : {}) } : {}),
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const roots = failures.filter((f) => !derived.has(f.resource));
|
|
96
|
+
if (roots.length === 0) return failures.map((f) => toDiagnostic(f, false));
|
|
97
|
+
|
|
98
|
+
return [
|
|
99
|
+
...roots.map((f) => toDiagnostic(f, false)),
|
|
100
|
+
...failures.filter((f) => derived.has(f.resource)).map((f) => toDiagnostic(f, true)),
|
|
101
|
+
];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Group the derived entries by the root cause they hang off, so a renderer can
|
|
105
|
+
* collapse each chain to a single line instead of repeating one failure N
|
|
106
|
+
* times. Entries whose blocker could not be named group under `undefined`. */
|
|
107
|
+
export function groupBlockedResources(
|
|
108
|
+
diagnostics: RuntimeDiagnostic[],
|
|
109
|
+
): Map<string | undefined, string[]> {
|
|
110
|
+
const groups = new Map<string | undefined, string[]>();
|
|
111
|
+
for (const d of diagnostics) {
|
|
112
|
+
if (!d.derived) continue;
|
|
113
|
+
const key = d.blockedBy;
|
|
114
|
+
const names = groups.get(key) ?? [];
|
|
115
|
+
names.push(d.resource ?? "(unnamed)");
|
|
116
|
+
groups.set(key, names);
|
|
117
|
+
}
|
|
118
|
+
return groups;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** One collapsed line per blocked chain, e.g.
|
|
122
|
+
* `9 resources blocked by GrantDb: GrantStore, GoogleTokens, ...`. */
|
|
123
|
+
export function describeBlockedGroup(blockedBy: string | undefined, names: string[]): string {
|
|
124
|
+
const subject = `${names.length} resource${names.length !== 1 ? "s" : ""}`;
|
|
125
|
+
const blocker = blockedBy ?? "an uninitialized dependency";
|
|
126
|
+
return `${subject} blocked by ${blocker}: ${names.join(", ")}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The headline for a classified failure set. Shared by the aggregate error's
|
|
130
|
+
* own message and by the entry an importing context builds for it, so the two
|
|
131
|
+
* are never recovered by re-parsing each other's rendered text. */
|
|
132
|
+
export function summarizeInitFailures(diagnostics: RuntimeDiagnostic[]): string {
|
|
133
|
+
const total = diagnostics.length;
|
|
134
|
+
const roots = diagnostics.filter((d) => !d.derived).length;
|
|
135
|
+
const blocked = total - roots;
|
|
136
|
+
return (
|
|
137
|
+
`${total} resource${total !== 1 ? "s" : ""} failed to initialize` +
|
|
138
|
+
(blocked > 0 ? ` (${roots} root cause${roots !== 1 ? "s" : ""}, rest blocked)` : "")
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Render a classified failure set as the text body of the aggregate error
|
|
143
|
+
* message — root causes in full, each blocked chain collapsed to one line.
|
|
144
|
+
* Nested children recurse through this same function so a child list is
|
|
145
|
+
* traversed exactly once, groups included. */
|
|
146
|
+
export function renderInitFailureText(diagnostics: RuntimeDiagnostic[]): string {
|
|
147
|
+
const lines: string[] = [];
|
|
148
|
+
for (const d of diagnostics) {
|
|
149
|
+
if (!d.derived) {
|
|
150
|
+
lines.push(
|
|
151
|
+
` ${d.kind ? `${d.kind} ` : ""}${d.resource}: ${d.message}${d.code ? ` [${d.code}]` : ""}`,
|
|
152
|
+
);
|
|
153
|
+
if (d.details) lines.push(...d.details.split("\n").map((l) => ` ${l}`));
|
|
154
|
+
}
|
|
155
|
+
// A derived entry contributes no line of its own, but a nested context's
|
|
156
|
+
// root causes are not shadows of THIS context's failure — they still report.
|
|
157
|
+
if (d.children?.length) {
|
|
158
|
+
lines.push(
|
|
159
|
+
...renderInitFailureText(d.children)
|
|
160
|
+
.split("\n")
|
|
161
|
+
.map((l) => ` ${l}`),
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
for (const [blockedBy, names] of groupBlockedResources(diagnostics)) {
|
|
166
|
+
lines.push(` ${describeBlockedGroup(blockedBy, names)}`);
|
|
167
|
+
}
|
|
168
|
+
return lines.join("\n");
|
|
169
|
+
}
|