@telorun/kernel 0.56.0 → 0.58.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/controllers/module/import-controller.d.ts.map +1 -1
- package/dist/controllers/module/import-controller.js +7 -3
- package/dist/controllers/module/import-controller.js.map +1 -1
- package/dist/controllers/resource-definition/resource-definition-controller.d.ts +1 -0
- package/dist/controllers/resource-definition/resource-definition-controller.d.ts.map +1 -1
- package/dist/controllers/resource-definition/resource-definition-controller.js +10 -1
- package/dist/controllers/resource-definition/resource-definition-controller.js.map +1 -1
- package/dist/evaluation-context.d.ts +57 -2
- package/dist/evaluation-context.d.ts.map +1 -1
- package/dist/evaluation-context.js +209 -8
- package/dist/evaluation-context.js.map +1 -1
- package/dist/kernel.d.ts.map +1 -1
- package/dist/kernel.js +6 -3
- package/dist/kernel.js.map +1 -1
- package/dist/manifest-schemas.d.ts +8 -0
- package/dist/manifest-schemas.d.ts.map +1 -1
- package/dist/manifest-schemas.js +6 -0
- package/dist/manifest-schemas.js.map +1 -1
- package/dist/module-context.d.ts +8 -0
- package/dist/module-context.d.ts.map +1 -1
- package/dist/module-context.js +20 -5
- package/dist/module-context.js.map +1 -1
- package/dist/observed-state.d.ts +94 -0
- package/dist/observed-state.d.ts.map +1 -0
- package/dist/observed-state.js +148 -0
- package/dist/observed-state.js.map +1 -0
- package/dist/resource-context.d.ts +50 -1
- package/dist/resource-context.d.ts.map +1 -1
- package/dist/resource-context.js +56 -12
- package/dist/resource-context.js.map +1 -1
- package/dist/transports/oci/oci-ref.d.ts +1 -1
- package/dist/transports/oci/oci-ref.d.ts.map +1 -1
- package/dist/transports/oci/oci-ref.js +1 -1
- package/dist/transports/oci/oci-ref.js.map +1 -1
- package/dist/transports/oci/oci-transport.d.ts.map +1 -1
- package/dist/transports/oci/oci-transport.js +7 -10
- package/dist/transports/oci/oci-transport.js.map +1 -1
- package/dist/transports/registry-transport.d.ts.map +1 -1
- package/dist/transports/registry-transport.js +3 -8
- package/dist/transports/registry-transport.js.map +1 -1
- package/package.json +3 -3
- package/src/controllers/module/import-controller.ts +12 -3
- package/src/controllers/resource-definition/resource-definition-controller.ts +14 -0
- package/src/evaluation-context.ts +253 -8
- package/src/kernel.ts +5 -0
- package/src/manifest-schemas.ts +6 -0
- package/src/module-context.ts +19 -5
- package/src/observed-state.ts +210 -0
- package/src/resource-context.ts +55 -11
- package/src/transports/oci/oci-ref.ts +8 -1
- package/src/transports/oci/oci-transport.ts +12 -9
- package/src/transports/registry-transport.ts +4 -6
|
@@ -26,6 +26,11 @@ import {
|
|
|
26
26
|
} from "@telorun/sdk";
|
|
27
27
|
import { RuntimeError } from "@telorun/sdk";
|
|
28
28
|
import { evalPathCovers } from "@telorun/analyzer";
|
|
29
|
+
import {
|
|
30
|
+
acceptReportedStatus,
|
|
31
|
+
buildPublishedProps,
|
|
32
|
+
diagnoseObservedStateAccess,
|
|
33
|
+
} from "./observed-state.js";
|
|
29
34
|
|
|
30
35
|
export { resourceKey };
|
|
31
36
|
|
|
@@ -165,6 +170,70 @@ export function buildResolvedProperties(
|
|
|
165
170
|
*/
|
|
166
171
|
const cancellationStore = new AsyncLocalStorage<InvokeContext>();
|
|
167
172
|
|
|
173
|
+
/**
|
|
174
|
+
* Instances whose `run()` has been dispatched. Reporting observed state before
|
|
175
|
+
* this is an error (see observed-state.ts).
|
|
176
|
+
*
|
|
177
|
+
* Keyed on the instance rather than on `(context, name)` because the context
|
|
178
|
+
* that STARTS a resource is not always the one that OWNS it: an importer's
|
|
179
|
+
* `targets:` can name a library's exported instance, and the library's own
|
|
180
|
+
* `ctx.setStatus()` — publishing into the context where its name lives — has to
|
|
181
|
+
* see that it started.
|
|
182
|
+
*/
|
|
183
|
+
const startedInstances = new WeakSet<object>();
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The last observed state each instance reported. Sticky: it stays until the
|
|
187
|
+
* resource is torn down, so a dispatch that reports nothing leaves the previous
|
|
188
|
+
* reading in place — a listener's bound address does not stop being true between
|
|
189
|
+
* calls. Keyed by instance for the same reason as `startedInstances`, and
|
|
190
|
+
* because a scope's per-run instances are distinct by construction, which is
|
|
191
|
+
* what keeps two concurrent runs from observing each other's readings.
|
|
192
|
+
*/
|
|
193
|
+
const reportedStatus = new WeakMap<object, Record<string, unknown>>();
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Instances whose `run()` has RETURNED. A long-lived Service never appears here
|
|
197
|
+
* — its `run()` stays pending for the process lifetime — which is exactly the
|
|
198
|
+
* distinction the reader needs: a Runnable that finished and reported nothing
|
|
199
|
+
* for a field it declares is a producer defect, while a Service that is still
|
|
200
|
+
* coming up is ordering, and telling those apart is not something the reader
|
|
201
|
+
* can do from the manifest.
|
|
202
|
+
*/
|
|
203
|
+
const completedInstances = new WeakSet<object>();
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The published value for an instance the caller resolved itself, rather than
|
|
207
|
+
* one reached by name through a context's own `resourceInstances`. The
|
|
208
|
+
* cross-module export path uses it: an importer surfaces a library's exported
|
|
209
|
+
* instances under `resources.<Alias>.<name>`, which crosses the boundary
|
|
210
|
+
* without passing through the owner's `resources` map — and must still carry the
|
|
211
|
+
* reading the instance reported, under the same rules.
|
|
212
|
+
*
|
|
213
|
+
* `kind` is already canonical (`<module>.<Kind>`) on that path, so the resolver
|
|
214
|
+
* needs no alias table.
|
|
215
|
+
*/
|
|
216
|
+
export async function publishedPropsOf(
|
|
217
|
+
kind: string,
|
|
218
|
+
name: string,
|
|
219
|
+
instance: ResourceInstance,
|
|
220
|
+
getDefinition: ((kind: string) => ResourceDefinition | undefined) | undefined,
|
|
221
|
+
): Promise<Record<string, unknown>> {
|
|
222
|
+
const snap =
|
|
223
|
+
typeof instance.snapshot === "function"
|
|
224
|
+
? ((await Promise.resolve(instance.snapshot())) as Record<string, unknown> | undefined)
|
|
225
|
+
: undefined;
|
|
226
|
+
return buildPublishedProps(snap, {
|
|
227
|
+
kind,
|
|
228
|
+
name,
|
|
229
|
+
module: kind.split(".")[0],
|
|
230
|
+
statusSchema: getDefinition?.(kind)?.status,
|
|
231
|
+
status: reportedStatus.get(instance),
|
|
232
|
+
started: startedInstances.has(instance),
|
|
233
|
+
completed: completedInstances.has(instance),
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
168
237
|
/**
|
|
169
238
|
* The ambient dispatch context, for §7.2's automatic trace correlation: a record
|
|
170
239
|
* emitted inside an active span carries that span's ids without the controller
|
|
@@ -194,6 +263,14 @@ function compileWalker(value: unknown): Walker {
|
|
|
194
263
|
} catch (error) {
|
|
195
264
|
const expr = compiled.source ? `\${{ ${compiled.source} }}` : "unknown expression";
|
|
196
265
|
const msg = error instanceof Error ? error.message : String(error);
|
|
266
|
+
// Reading observed state that was never reported is its own failure with
|
|
267
|
+
// its own remedy, so it does not degrade into a bare "No such key".
|
|
268
|
+
const observed = compiled.source
|
|
269
|
+
? describeObservedStateFailure(compiled.source, ctx, msg)
|
|
270
|
+
: null;
|
|
271
|
+
if (observed) {
|
|
272
|
+
throw new RuntimeError("ERR_OBSERVED_STATE_UNAVAILABLE", `${expr}: ${observed}`);
|
|
273
|
+
}
|
|
197
274
|
const hint = compiled.source ? describeFailedAccess(compiled.source, ctx, msg) : null;
|
|
198
275
|
const suffix = hint ? `\n ${hint}` : "";
|
|
199
276
|
throw new Error(`Expression ${expr} failed: ${msg}${suffix}`);
|
|
@@ -334,8 +411,87 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
334
411
|
return this._createInstance;
|
|
335
412
|
}
|
|
336
413
|
|
|
337
|
-
/** Called after init() when a resource snapshot is available. Overridden by
|
|
338
|
-
|
|
414
|
+
/** Called after init() when a resource snapshot is available. Overridden by
|
|
415
|
+
* ModuleContext, and by a scope child (which keeps its own per-run map). */
|
|
416
|
+
protected onResourceSnapshotted(name: string, snap: Record<string, unknown>): void {
|
|
417
|
+
this.snapshotSink?.(name, snap);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Where published snapshots go for a context that has no `resources` map of
|
|
421
|
+
* its own — set by `createScopeHandle` on the per-run child so scope-local
|
|
422
|
+
* resources publish like any other. */
|
|
423
|
+
protected snapshotSink: ((name: string, snap: Record<string, unknown>) => void) | undefined;
|
|
424
|
+
|
|
425
|
+
/** Record that an instance has started. Republished so a read that arrives
|
|
426
|
+
* before the resource reports gets the "still running" message rather than
|
|
427
|
+
* the "never started" one. */
|
|
428
|
+
private async markStarted(name: string, instance: ResourceInstance): Promise<void> {
|
|
429
|
+
if (startedInstances.has(instance)) return;
|
|
430
|
+
startedInstances.add(instance);
|
|
431
|
+
await this.publishSnapshot(name);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Record what a resource observed and republish. Validated against the kind's
|
|
436
|
+
* `status:` here, at the point the claim is made, so an invalid report names
|
|
437
|
+
* the call that made it rather than surfacing at some later publication.
|
|
438
|
+
*
|
|
439
|
+
* Replaces rather than merges: this is the resource's observed state now. A
|
|
440
|
+
* declared field this call omits reads as missing, which is the truth — a
|
|
441
|
+
* sometimes-absent field is declared nullable and reported as `null`.
|
|
442
|
+
*/
|
|
443
|
+
async setResourceStatus(name: string, status: Record<string, unknown>): Promise<void> {
|
|
444
|
+
const entry = this.resourceInstances.get(name) ?? this.createdInstances.get(name);
|
|
445
|
+
if (!entry) return;
|
|
446
|
+
const kind = entry.resource.kind as string;
|
|
447
|
+
if (!startedInstances.has(entry.instance)) {
|
|
448
|
+
throw new RuntimeError(
|
|
449
|
+
"ERR_OBSERVED_STATE_BEFORE_START",
|
|
450
|
+
`${kind} '${name}' reported observed state before it started. init() performs no I/O, so there is nothing observed to report there — call setStatus() from run(), or from a handler it reaches.`,
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
reportedStatus.set(
|
|
454
|
+
entry.instance,
|
|
455
|
+
acceptReportedStatus(status, { kind, name, statusSchema: this.statusSchemaOf(kind) }),
|
|
456
|
+
);
|
|
457
|
+
await this.publishSnapshot(name);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** The kind's effective `status:` — already folded through `extends` and
|
|
461
|
+
* stamped onto the definition at registration, in the scope that DECLARED it
|
|
462
|
+
* (`resource-definition-controller`). Only the kind's own alias is resolved
|
|
463
|
+
* here, in the reading module's scope, which is where it was written. */
|
|
464
|
+
private statusSchemaOf(kind: string): Record<string, any> | undefined {
|
|
465
|
+
const def = this.getDefinition?.(this.resolveKindSafe(kind)) ?? this.getDefinition?.(kind);
|
|
466
|
+
return def?.status;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Re-read a resource's `snapshot()` and republish it, joined with whatever
|
|
471
|
+
* observed state the resource has reported. The single publication path — the
|
|
472
|
+
* post-init capture, the post-run publication, the post-invoke refresh and
|
|
473
|
+
* every `setStatus()` all land here.
|
|
474
|
+
*/
|
|
475
|
+
async publishSnapshot(name: string): Promise<void> {
|
|
476
|
+
const entry = this.resourceInstances.get(name) ?? this.createdInstances.get(name);
|
|
477
|
+
if (!entry?.instance.snapshot) return;
|
|
478
|
+
const snap = (await Promise.resolve(entry.instance.snapshot())) as
|
|
479
|
+
| Record<string, unknown>
|
|
480
|
+
| undefined;
|
|
481
|
+
const kind = entry.resource.kind as string;
|
|
482
|
+
this.onResourceSnapshotted(
|
|
483
|
+
name,
|
|
484
|
+
buildPublishedProps(snap, {
|
|
485
|
+
kind,
|
|
486
|
+
name,
|
|
487
|
+
module: entry.resource.metadata?.module as string | undefined,
|
|
488
|
+
statusSchema: this.statusSchemaOf(kind),
|
|
489
|
+
status: reportedStatus.get(entry.instance),
|
|
490
|
+
started: startedInstances.has(entry.instance),
|
|
491
|
+
completed: completedInstances.has(entry.instance),
|
|
492
|
+
}),
|
|
493
|
+
);
|
|
494
|
+
}
|
|
339
495
|
|
|
340
496
|
get context(): Record<string, unknown> {
|
|
341
497
|
return this._context;
|
|
@@ -425,6 +581,7 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
425
581
|
this.emit,
|
|
426
582
|
);
|
|
427
583
|
child.resolveImportedInstance = (alias, name) => this.resolveImportedInstance(alias, name);
|
|
584
|
+
child.kindResolver = (kind) => this.resolveKindSafe(kind);
|
|
428
585
|
return this.spawnChild(child);
|
|
429
586
|
}
|
|
430
587
|
|
|
@@ -528,10 +685,13 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
528
685
|
);
|
|
529
686
|
}
|
|
530
687
|
if (instance.init) await instance.init(ctx);
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
688
|
+
// Publish BEFORE registering: publication can fail (a kind returning
|
|
689
|
+
// the reserved `status` key without declaring it, a report that does
|
|
690
|
+
// not match `status:`), and a resource that failed must not be left
|
|
691
|
+
// reachable through `getInstance` / Phase 5 injection / teardown.
|
|
692
|
+
// `publishSnapshot` looks the instance up in `createdInstances` too,
|
|
693
|
+
// so it resolves fine from here.
|
|
694
|
+
await this.publishSnapshot(name);
|
|
535
695
|
this.resourceInstances.set(name, { resource, instance });
|
|
536
696
|
this.createdInstances.delete(name);
|
|
537
697
|
errors.delete(name);
|
|
@@ -639,6 +799,18 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
639
799
|
parent.emit,
|
|
640
800
|
),
|
|
641
801
|
);
|
|
802
|
+
child.kindResolver = (kind) => parent.resolveKindSafe(kind);
|
|
803
|
+
|
|
804
|
+
// Per-run map of the scope's OWN resources. Fresh per run, so two
|
|
805
|
+
// concurrent runs of the same sequence never observe each other's.
|
|
806
|
+
// The enclosing module's map is layered in at read time, not copied
|
|
807
|
+
// here: `setResource` replaces `_resources` wholesale on every publish,
|
|
808
|
+
// so a snapshot taken at scope entry would go stale the moment an outer
|
|
809
|
+
// resource republished (a post-invoke refresh, a later boot target).
|
|
810
|
+
const scopeLocal = new Map<string, Record<string, unknown>>();
|
|
811
|
+
child.snapshotSink = (name, snap) => {
|
|
812
|
+
scopeLocal.set(name, snap);
|
|
813
|
+
};
|
|
642
814
|
|
|
643
815
|
// Propagate injection hook: extend getInstance to also resolve parent singleton instances.
|
|
644
816
|
if (parent.preInitHook) {
|
|
@@ -684,6 +856,22 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
684
856
|
`Resource '${name}' not found in scope or outer context. Available scoped: ${[...child.resourceInstances.keys()].join(", ")}`,
|
|
685
857
|
);
|
|
686
858
|
},
|
|
859
|
+
async run(name: string): Promise<void> {
|
|
860
|
+
// Through the child context's chokepoint, so a scope target is
|
|
861
|
+
// traced, records that it started, and publishes its snapshot —
|
|
862
|
+
// exactly like a boot target. A scope target is always a
|
|
863
|
+
// with-resource, so it lives in the child.
|
|
864
|
+
await child.run(name);
|
|
865
|
+
},
|
|
866
|
+
get resources(): Record<string, unknown> {
|
|
867
|
+
// Merged on read so the outer half stays live; scope-local names
|
|
868
|
+
// win, matching `getInstance`'s order so CEL and `!ref` agree.
|
|
869
|
+
const merged: Record<string, unknown> = {
|
|
870
|
+
...((parent._context.resources as Record<string, unknown> | undefined) ?? {}),
|
|
871
|
+
};
|
|
872
|
+
for (const [name, snap] of scopeLocal) merged[name] = snap;
|
|
873
|
+
return merged;
|
|
874
|
+
},
|
|
687
875
|
};
|
|
688
876
|
return await fn(scope);
|
|
689
877
|
} finally {
|
|
@@ -716,6 +904,13 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
716
904
|
|
|
717
905
|
for (const [key, { resource, instance }] of this.teardownOrder()) {
|
|
718
906
|
const label = `${resource.kind}.${resource.metadata.name}`;
|
|
907
|
+
// A reading belongs to the run that produced it. The WeakMap would drop it
|
|
908
|
+
// with the instance anyway; clearing here also covers an instance something
|
|
909
|
+
// else still holds, so a torn-down resource can never keep publishing what
|
|
910
|
+
// it observed in a previous life.
|
|
911
|
+
reportedStatus.delete(instance);
|
|
912
|
+
startedInstances.delete(instance);
|
|
913
|
+
completedInstances.delete(instance);
|
|
719
914
|
try {
|
|
720
915
|
if (instance.teardown) await instance.teardown();
|
|
721
916
|
} catch (err) {
|
|
@@ -979,6 +1174,10 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
979
1174
|
// `run()` — side effects only, no outputs. Prefer `invoke()` when both
|
|
980
1175
|
// exist so a dual-capability instance (e.g. Run.Sequence) keeps invoke
|
|
981
1176
|
// semantics and returns its `steps`/`outputs`.
|
|
1177
|
+
// A pure Runnable reached through an `invoke:` slot runs exactly as it
|
|
1178
|
+
// would from a `targets:` list, so it starts here too — its observed state
|
|
1179
|
+
// must not stay withheld just because the dispatch slot was a different one.
|
|
1180
|
+
if (typeof instance.invoke !== "function") await this.markStarted(name, instance);
|
|
982
1181
|
const call = () =>
|
|
983
1182
|
typeof instance.invoke === "function"
|
|
984
1183
|
? (instance.invoke as (i: any, c?: InvokeContext) => any)(inputs as any, invokeCtx)
|
|
@@ -986,6 +1185,7 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
986
1185
|
const outputs = await (invokeCtx === ambient
|
|
987
1186
|
? call()
|
|
988
1187
|
: cancellationStore.run(invokeCtx, call));
|
|
1188
|
+
if (typeof instance.invoke !== "function") completedInstances.add(instance);
|
|
989
1189
|
await this.emit(`${name}.Invoked`, span("end", "ok", { inputs, outputs }));
|
|
990
1190
|
return outputs;
|
|
991
1191
|
} catch (err) {
|
|
@@ -1047,9 +1247,15 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
1047
1247
|
* kind unchanged. A typed seam (overridden in `ModuleContext`), matching the
|
|
1048
1248
|
* `traceRootScope()` pattern, rather than reaching across the boundary. */
|
|
1049
1249
|
protected resolveKindSafe(kind: string): string {
|
|
1050
|
-
return kind;
|
|
1250
|
+
return this.kindResolver?.(kind) ?? kind;
|
|
1051
1251
|
}
|
|
1052
1252
|
|
|
1253
|
+
/** Alias-kind resolver inherited from the context that spawned this one. A
|
|
1254
|
+
* scope / template child holds no import table of its own, but its resources
|
|
1255
|
+
* are written with the declaring module's aliases (`Observed.Listener`), so
|
|
1256
|
+
* definition lookups there have to go through the parent's table. */
|
|
1257
|
+
kindResolver: ((kind: string) => string) | undefined;
|
|
1258
|
+
|
|
1053
1259
|
private capabilityOf(kind: string): string | undefined {
|
|
1054
1260
|
const resolved = this.resolveKindSafe(kind);
|
|
1055
1261
|
return this.getDefinition?.(resolved)?.capability ?? this.getDefinition?.(kind)?.capability;
|
|
@@ -1224,6 +1430,12 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
1224
1430
|
|
|
1225
1431
|
if (tracing) await this.emit(`${name}.Running`, span("start", undefined, {}));
|
|
1226
1432
|
|
|
1433
|
+
// Marked before the call, not after: a Service's `run()` stays pending for
|
|
1434
|
+
// the process lifetime, and reporting what it discovered while listening is
|
|
1435
|
+
// the whole point — `ctx.setStatus()` is an error until the resource counts
|
|
1436
|
+
// as started, so this has to happen first.
|
|
1437
|
+
await this.markStarted(name, instance);
|
|
1438
|
+
|
|
1227
1439
|
try {
|
|
1228
1440
|
// Runnable: run inside the ALS scope so nested invokes inherit the token and
|
|
1229
1441
|
// trace id (skip the redundant `run` when the token is already ambient).
|
|
@@ -1231,6 +1443,10 @@ export class EvaluationContext implements IEvaluationContext {
|
|
|
1231
1443
|
// its long-lived async work does not capture this scope.
|
|
1232
1444
|
const call = () => (instance.run as (c?: InvokeContext) => Promise<void>)(invokeCtx);
|
|
1233
1445
|
await (isService || invokeCtx === ambient ? call() : cancellationStore.run(invokeCtx, call));
|
|
1446
|
+
// A one-shot Runnable that discovered something during run() publishes it
|
|
1447
|
+
// without an explicit call; a Service never reaches this until teardown.
|
|
1448
|
+
completedInstances.add(instance);
|
|
1449
|
+
await this.publishSnapshot(name);
|
|
1234
1450
|
await this.emit(`${name}.Run`, span("end", "ok", {}));
|
|
1235
1451
|
} catch (err) {
|
|
1236
1452
|
if (isCancellationError(err)) {
|
|
@@ -1438,6 +1654,35 @@ export function describeFailedAccess(
|
|
|
1438
1654
|
ctx: unknown,
|
|
1439
1655
|
msg: string,
|
|
1440
1656
|
): string | null {
|
|
1657
|
+
const failure = locateFailedAccess(source, ctx, msg);
|
|
1658
|
+
if (!failure) return null;
|
|
1659
|
+
return `at ${failure.walked}: ${describeMissingAccess(failure.container, failure.missingKey)}`;
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
/**
|
|
1663
|
+
* The observed-state message for a failed access, or null when the failure has
|
|
1664
|
+
* nothing to do with observed state (the caller then falls back to the generic
|
|
1665
|
+
* enrichment above). See `observed-state.ts` for why "has not started" and
|
|
1666
|
+
* "started but reported nothing" are two different messages.
|
|
1667
|
+
*/
|
|
1668
|
+
export function describeObservedStateFailure(
|
|
1669
|
+
source: string,
|
|
1670
|
+
ctx: unknown,
|
|
1671
|
+
msg: string,
|
|
1672
|
+
): string | null {
|
|
1673
|
+
const failure = locateFailedAccess(source, ctx, msg);
|
|
1674
|
+
if (!failure) return null;
|
|
1675
|
+
return diagnoseObservedStateAccess(failure.container, failure.missingKey);
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
/** Walk a dotted CEL access path against the activation and stop at the node
|
|
1679
|
+
* whose key was missing. Null when the error isn't a key-access failure, the
|
|
1680
|
+
* source isn't a plain access path, or the path doesn't match the activation. */
|
|
1681
|
+
function locateFailedAccess(
|
|
1682
|
+
source: string,
|
|
1683
|
+
ctx: unknown,
|
|
1684
|
+
msg: string,
|
|
1685
|
+
): { container: unknown; missingKey: string; walked: string } | null {
|
|
1441
1686
|
const m = /^No such key:\s*(\S+)/.exec(msg);
|
|
1442
1687
|
if (!m) return null;
|
|
1443
1688
|
const missingKey = m[1];
|
|
@@ -1463,7 +1708,7 @@ export function describeFailedAccess(
|
|
|
1463
1708
|
!(tok.name in (current as Record<string, unknown>))
|
|
1464
1709
|
) {
|
|
1465
1710
|
if (tok.name !== missingKey) return null;
|
|
1466
|
-
return
|
|
1711
|
+
return { container: current, missingKey, walked: walked.join("") };
|
|
1467
1712
|
}
|
|
1468
1713
|
current = (current as Record<string, unknown>)[tok.name];
|
|
1469
1714
|
walked.push("." + tok.name);
|
package/src/kernel.ts
CHANGED
|
@@ -1030,6 +1030,7 @@ export class Kernel implements IKernel {
|
|
|
1030
1030
|
resource: ResourceManifest,
|
|
1031
1031
|
args?: ParsedArgs,
|
|
1032
1032
|
ownerPrefix = "",
|
|
1033
|
+
owningContext?: IEvaluationContext,
|
|
1033
1034
|
): ResourceContext {
|
|
1034
1035
|
return new ResourceContextImpl(
|
|
1035
1036
|
this,
|
|
@@ -1042,6 +1043,7 @@ export class Kernel implements IKernel {
|
|
|
1042
1043
|
this.stderr,
|
|
1043
1044
|
args,
|
|
1044
1045
|
ownerPrefix,
|
|
1046
|
+
owningContext ?? moduleContext,
|
|
1045
1047
|
);
|
|
1046
1048
|
}
|
|
1047
1049
|
|
|
@@ -1189,6 +1191,9 @@ export class Kernel implements IKernel {
|
|
|
1189
1191
|
processedResource,
|
|
1190
1192
|
parsedArgs,
|
|
1191
1193
|
evalContext.ownerPrefix,
|
|
1194
|
+
// Snapshot publication targets the context that OWNS the instance — for a
|
|
1195
|
+
// `with:`-scoped resource that is the per-run scope child, not the module.
|
|
1196
|
+
evalContext,
|
|
1192
1197
|
);
|
|
1193
1198
|
const instance = await controller.create(processedResource, ctx);
|
|
1194
1199
|
if (!instance) return null;
|
package/src/manifest-schemas.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import AjvModule from "ajv";
|
|
2
2
|
import addFormats from "ajv-formats";
|
|
3
|
+
// One definition of the `status:` block's shape, shared with `telo check` — the
|
|
4
|
+
// `required:` restriction is reported by the analyzer, which can name the fix.
|
|
5
|
+
import { OBSERVED_STATE_SCHEMA } from "@telorun/analyzer";
|
|
3
6
|
const Ajv = AjvModule.default ?? AjvModule;
|
|
4
7
|
|
|
5
8
|
// Re-export the shared ResourceRef fragment from the templating package
|
|
@@ -74,6 +77,7 @@ const baseDefinition = {
|
|
|
74
77
|
capability: { type: "string" },
|
|
75
78
|
extends: { type: "string", pattern: EXTENDS_ALIAS_PATTERN },
|
|
76
79
|
schema: { type: "object", additionalProperties: true },
|
|
80
|
+
status: OBSERVED_STATE_SCHEMA,
|
|
77
81
|
controllers: { type: "array", items: { type: "string" } },
|
|
78
82
|
throws: throwsSchema,
|
|
79
83
|
},
|
|
@@ -157,6 +161,8 @@ export const ResourceAbstractSchema = {
|
|
|
157
161
|
metadata: metadataSchema,
|
|
158
162
|
capability: { type: "string" },
|
|
159
163
|
schema: { type: "object", additionalProperties: true },
|
|
164
|
+
// A contract may mandate what its implementations report.
|
|
165
|
+
status: OBSERVED_STATE_SCHEMA,
|
|
160
166
|
},
|
|
161
167
|
not: {
|
|
162
168
|
anyOf: [{ required: ["controllers"] }, { required: ["throws"] }],
|
package/src/module-context.ts
CHANGED
|
@@ -219,6 +219,21 @@ export class ModuleContext extends EvaluationContext implements IModuleContext {
|
|
|
219
219
|
this.setResource(name, snap);
|
|
220
220
|
}
|
|
221
221
|
|
|
222
|
+
/**
|
|
223
|
+
* A cross-module exported instance has no entry of its own here — it surfaces
|
|
224
|
+
* under `resources.<alias>.<name>`, published by the `Telo.Import` that owns
|
|
225
|
+
* it. So republishing such a name means republishing that import, which is
|
|
226
|
+
* what makes an exported service's observed state readable once the IMPORTER's
|
|
227
|
+
* `targets:` starts it.
|
|
228
|
+
*/
|
|
229
|
+
override async publishSnapshot(name: string): Promise<void> {
|
|
230
|
+
await super.publishSnapshot(name);
|
|
231
|
+
if (this.resourceInstances.has(name)) return;
|
|
232
|
+
for (const [alias, scope] of this.importedScopes) {
|
|
233
|
+
if (scope.names.has(name)) await super.publishSnapshot(alias);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
222
237
|
/**
|
|
223
238
|
* Register an imported module under the given alias, gated to the kind names it
|
|
224
239
|
* exports (its `exports.kinds`). Only listed kinds resolve; an empty list exports
|
|
@@ -493,11 +508,10 @@ export class ModuleContext extends EvaluationContext implements IModuleContext {
|
|
|
493
508
|
ctx?: InvokeContext,
|
|
494
509
|
): Promise<any> {
|
|
495
510
|
const result = await super.invoke(kind, name, inputs, ctx);
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
}
|
|
511
|
+
// Same publication path as the post-init capture and `setStatus()`:
|
|
512
|
+
// one shape, one target, so a declared `status:` is a guarantee on every
|
|
513
|
+
// path rather than on some of them.
|
|
514
|
+
await this.publishSnapshot(name);
|
|
501
515
|
return result;
|
|
502
516
|
}
|
|
503
517
|
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import AjvModule from "ajv";
|
|
2
|
+
import { detachSnapshotValue, OBSERVED_STATE_KEY, RuntimeError } from "@telorun/sdk";
|
|
3
|
+
|
|
4
|
+
const Ajv = AjvModule.default ?? AjvModule;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Publication of a resource's **observed state** — what it learns while running,
|
|
8
|
+
* as opposed to what its author configured.
|
|
9
|
+
*
|
|
10
|
+
* The two arrive by different routes and this module keeps them apart.
|
|
11
|
+
* Configured state is pulled from `snapshot()`; observed state is pushed through
|
|
12
|
+
* `ResourceContext.setStatus()`, validated against the kind's `status:`, and
|
|
13
|
+
* held by the kernel until the resource is torn down. Publication then joins
|
|
14
|
+
* them: the flat half at `resources.<name>.<field>`, the reported half at
|
|
15
|
+
* `resources.<name>.status.<field>`.
|
|
16
|
+
*
|
|
17
|
+
* Holding the reported value (rather than re-deriving it) is what makes the
|
|
18
|
+
* reading *sticky*: a resource that learned its address once does not stop
|
|
19
|
+
* knowing it because a later dispatch had nothing new to say.
|
|
20
|
+
*
|
|
21
|
+
* A non-enumerable {@link OBSERVED_STATE_INFO} marker rides along on the
|
|
22
|
+
* published objects so a failed CEL read can say *why* the value is missing —
|
|
23
|
+
* "has not started", "still running" and "finished and never reported it" need
|
|
24
|
+
* different actions from the reader. It is a Symbol, so no CEL member access
|
|
25
|
+
* can reach it.
|
|
26
|
+
*/
|
|
27
|
+
export const OBSERVED_STATE_INFO = Symbol("telo.observedState");
|
|
28
|
+
|
|
29
|
+
export interface ObservedStateInfo {
|
|
30
|
+
/** The kind as written on the resource doc (`OAuthClient.RedirectListener`). */
|
|
31
|
+
kind: string;
|
|
32
|
+
name: string;
|
|
33
|
+
/** Owning module, named in the "defect in someone else's module" message. */
|
|
34
|
+
module?: string;
|
|
35
|
+
/** The fields the kind declares it reports. */
|
|
36
|
+
fields: string[];
|
|
37
|
+
/** True once the resource's `run()` has been dispatched. */
|
|
38
|
+
started: boolean;
|
|
39
|
+
/** True once its `run()` has RETURNED. Never true for a long-lived Service,
|
|
40
|
+
* whose `run()` stays pending — which is what separates "still coming up"
|
|
41
|
+
* from "finished and reported nothing". */
|
|
42
|
+
completed: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Read the marker off a published props / status object, if it carries one. */
|
|
46
|
+
export function observedStateInfo(value: unknown): ObservedStateInfo | undefined {
|
|
47
|
+
if (value === null || typeof value !== "object") return undefined;
|
|
48
|
+
return (value as Record<symbol, ObservedStateInfo>)[OBSERVED_STATE_INFO];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function mark(target: Record<string, unknown>, info: ObservedStateInfo): void {
|
|
52
|
+
Object.defineProperty(target, OBSERVED_STATE_INFO, {
|
|
53
|
+
value: info,
|
|
54
|
+
enumerable: false,
|
|
55
|
+
configurable: true,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
60
|
+
// Compiling a status schema costs ~ms and a resource may report repeatedly, so
|
|
61
|
+
// keep the validator keyed on the schema object it came from. The kind's folded
|
|
62
|
+
// `status:` is stamped once at registration, so this hits.
|
|
63
|
+
const validators = new WeakMap<object, ReturnType<typeof ajv.compile>>();
|
|
64
|
+
|
|
65
|
+
function validatorFor(schema: Record<string, any>): ReturnType<typeof ajv.compile> {
|
|
66
|
+
let compiled = validators.get(schema);
|
|
67
|
+
if (!compiled) {
|
|
68
|
+
compiled = ajv.compile(schema);
|
|
69
|
+
validators.set(schema, compiled);
|
|
70
|
+
}
|
|
71
|
+
return compiled;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The field names a `status:` schema declares, in declaration order. */
|
|
75
|
+
export function declaredStatusFields(schema: Record<string, any> | undefined): string[] {
|
|
76
|
+
const props = schema?.properties;
|
|
77
|
+
return props && typeof props === "object" ? Object.keys(props) : [];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Check a reported value against the kind's declared `status:` and detach it
|
|
82
|
+
* from the controller. Called by `setStatus`, so an invalid report is refused at
|
|
83
|
+
* the point it is made rather than at some later publication.
|
|
84
|
+
*/
|
|
85
|
+
export function acceptReportedStatus(
|
|
86
|
+
status: Record<string, unknown>,
|
|
87
|
+
opts: { kind: string; name: string; statusSchema?: Record<string, any> },
|
|
88
|
+
): Record<string, unknown> {
|
|
89
|
+
if (!opts.statusSchema) {
|
|
90
|
+
throw new RuntimeError(
|
|
91
|
+
"ERR_OBSERVED_STATE_UNDECLARED",
|
|
92
|
+
`${opts.kind} '${opts.name}' reported observed state, but the kind declares no 'status:' block. Declare it on the Telo.Definition (or on an abstract it extends) naming the fields this kind reports.`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const validate = validatorFor(opts.statusSchema);
|
|
96
|
+
if (!validate(status)) {
|
|
97
|
+
const detail = (validate.errors ?? [])
|
|
98
|
+
.map((e) => `${e.instancePath || "/"} ${e.message ?? "is invalid"}`)
|
|
99
|
+
.join("; ");
|
|
100
|
+
throw new RuntimeError(
|
|
101
|
+
"ERR_OBSERVED_STATE_INVALID",
|
|
102
|
+
`${opts.kind} '${opts.name}' reported observed state that does not match its declared 'status:': ${detail}`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
return detachSnapshotValue(status) as Record<string, unknown>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface PublishOptions {
|
|
109
|
+
kind: string;
|
|
110
|
+
name: string;
|
|
111
|
+
module?: string;
|
|
112
|
+
/** The kind's effective `status:` (folded through `extends`), or undefined
|
|
113
|
+
* when nothing in the chain declares one. */
|
|
114
|
+
statusSchema?: Record<string, any>;
|
|
115
|
+
/** The last value the resource reported, or undefined if it has reported
|
|
116
|
+
* none. Already validated and detached by {@link acceptReportedStatus}. */
|
|
117
|
+
status?: Record<string, unknown>;
|
|
118
|
+
/** Whether the resource's `run()` has been dispatched. */
|
|
119
|
+
started: boolean;
|
|
120
|
+
/** Whether its `run()` has returned. */
|
|
121
|
+
completed: boolean;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Turn a `snapshot()` result plus the last reported status into the value
|
|
126
|
+
* published at `resources.<name>`.
|
|
127
|
+
*
|
|
128
|
+
* Throws `ERR_OBSERVED_STATE_KEY_COLLISION` when a kind that declares `status:`
|
|
129
|
+
* also returns a flat field of that name — the two would land on the same key,
|
|
130
|
+
* and silently letting one win is worse than refusing. A kind that declares no
|
|
131
|
+
* `status:` may use the name freely.
|
|
132
|
+
*/
|
|
133
|
+
export function buildPublishedProps(
|
|
134
|
+
snapshot: Record<string, unknown> | undefined,
|
|
135
|
+
opts: PublishOptions,
|
|
136
|
+
): Record<string, unknown> {
|
|
137
|
+
const flat = (detachSnapshotValue(snapshot ?? {}) ?? {}) as Record<string, unknown>;
|
|
138
|
+
|
|
139
|
+
if (!opts.statusSchema) return flat;
|
|
140
|
+
|
|
141
|
+
if (OBSERVED_STATE_KEY in flat) {
|
|
142
|
+
throw new RuntimeError(
|
|
143
|
+
"ERR_OBSERVED_STATE_KEY_COLLISION",
|
|
144
|
+
`${opts.kind} '${opts.name}' returns a '${OBSERVED_STATE_KEY}' field from snapshot(), but the kind declares a 'status:' block, which publishes at that same key. Rename the snapshot field, or drop the 'status:' declaration if the value is configuration rather than something the resource observes.`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const info: ObservedStateInfo = {
|
|
149
|
+
kind: opts.kind,
|
|
150
|
+
name: opts.name,
|
|
151
|
+
module: opts.module,
|
|
152
|
+
fields: declaredStatusFields(opts.statusSchema),
|
|
153
|
+
started: opts.started,
|
|
154
|
+
completed: opts.completed,
|
|
155
|
+
};
|
|
156
|
+
mark(flat, info);
|
|
157
|
+
|
|
158
|
+
// Absent until the resource reports — so a read before then lands on a
|
|
159
|
+
// message that says which of the three things went wrong, rather than on a
|
|
160
|
+
// placeholder indistinguishable from a real reading.
|
|
161
|
+
if (!opts.status) return flat;
|
|
162
|
+
|
|
163
|
+
const published: Record<string, unknown> = { ...opts.status };
|
|
164
|
+
mark(published, info);
|
|
165
|
+
flat[OBSERVED_STATE_KEY] = published;
|
|
166
|
+
return flat;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The message for a failed `resources.<name>.status…` read, or null when the
|
|
171
|
+
* failure has nothing to do with observed state.
|
|
172
|
+
*
|
|
173
|
+
* `container` is the value the access chain reached, `missingKey` the key that
|
|
174
|
+
* was not there. Each cause gets its own message because they need different
|
|
175
|
+
* actions from the reader, and the kernel — which records both whether the
|
|
176
|
+
* resource started and whether its `run()` returned — is the only party that
|
|
177
|
+
* can tell them apart:
|
|
178
|
+
*
|
|
179
|
+
* - not started → order the `targets:` so it runs first;
|
|
180
|
+
* - started, still running → the read raced a resource that is still coming up
|
|
181
|
+
* (a Service binding asynchronously); reorder or read later;
|
|
182
|
+
* - `run()` returned and it never reported → the producing module declares
|
|
183
|
+
* something it does not report, and no edit here fixes that.
|
|
184
|
+
*/
|
|
185
|
+
export function diagnoseObservedStateAccess(
|
|
186
|
+
container: unknown,
|
|
187
|
+
missingKey: string,
|
|
188
|
+
): string | null {
|
|
189
|
+
const info = observedStateInfo(container);
|
|
190
|
+
if (!info) return null;
|
|
191
|
+
|
|
192
|
+
if (missingKey === OBSERVED_STATE_KEY) {
|
|
193
|
+
if (!info.started) {
|
|
194
|
+
return `'${info.name}' reports ${formatFields(info.fields)} only while it is running, and it has not started yet. Read reported values where the call happens — a step's inputs:, a request's url, a route handler, or a returns: expression — and make sure '${info.name}' is listed in the targets: that runs before this value is read.`;
|
|
195
|
+
}
|
|
196
|
+
return info.completed
|
|
197
|
+
? `'${info.name}' finished running without ever reporting its observed state, which ${info.kind} declares it reports (${formatFields(info.fields)}). This is a defect in the ${info.module ?? "producing"} module — it never called setStatus, and no change to this manifest will fix it.`
|
|
198
|
+
: `'${info.name}' has started but has not reported its observed state yet — it is still running, so this read raced it. Move the read after the point where '${info.name}' has reported.`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (info.fields.includes(missingKey)) {
|
|
202
|
+
return `'${info.name}' reported observed state without '${missingKey}', which ${info.kind} declares it reports. Every declared field is mandatory once the resource has run — this is a defect in the ${info.module ?? "producing"} module, and no change to this manifest will fix it.`;
|
|
203
|
+
}
|
|
204
|
+
return `'${info.name}' reports no '${missingKey}'. It reports ${formatFields(info.fields)}.`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function formatFields(fields: string[]): string {
|
|
208
|
+
if (fields.length === 0) return "no observed state";
|
|
209
|
+
return fields.map((f) => `'${f}'`).join(", ");
|
|
210
|
+
}
|