@syntropika/tembra-sdk 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +47 -2
- package/dist/authoring/declaration.d.ts +47 -0
- package/dist/authoring/hooks.d.ts +11 -0
- package/dist/authoring/orb.d.ts +3 -0
- package/dist/authoring/types.d.ts +166 -0
- package/dist/bridge/identifiers.d.ts +207 -0
- package/dist/bridge/kernel.d.ts +117 -0
- package/dist/bridge/protocol.d.ts +181 -0
- package/dist/browser.d.ts +21 -0
- package/dist/browser.js +3282 -0
- package/dist/codec.d.ts +1 -0
- package/dist/codecs/json.d.ts +13 -0
- package/dist/codecs/msgpack.d.ts +3 -0
- package/dist/context-key.d.ts +35 -0
- package/dist/coordinator.d.ts +1 -0
- package/dist/coordinator.js +543 -0
- package/dist/embedded.d.ts +1 -0
- package/dist/embedded.js +1 -0
- package/dist/error.d.ts +13 -0
- package/dist/errors.d.ts +122 -0
- package/dist/hooks.d.ts +1 -0
- package/dist/host.d.ts +96 -0
- package/dist/host.js +3225 -0
- package/dist/identifiers.d.ts +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +833 -0
- package/dist/infrastructure/coordinator.d.ts +13 -0
- package/dist/infrastructure/manager.d.ts +23 -0
- package/dist/infrastructure/rpc/channel.d.ts +52 -0
- package/dist/infrastructure/rpc/client.d.ts +20 -0
- package/dist/infrastructure/rpc/server.d.ts +10 -0
- package/dist/infrastructure/rpc/state.d.ts +16 -0
- package/dist/kernel.d.ts +1 -0
- package/dist/manager.d.ts +1 -0
- package/dist/manager.js +390 -0
- package/dist/msgpack.d.ts +1 -0
- package/dist/msgpack.js +635 -0
- package/dist/node.d.ts +14 -0
- package/dist/node.js +3283 -0
- package/dist/orb.d.ts +1 -0
- package/dist/protocol.d.ts +1 -0
- package/dist/rpc.d.ts +3 -0
- package/dist/rpc.js +1036 -0
- package/dist/runtime/activities.d.ts +30 -0
- package/dist/runtime/calls.d.ts +22 -0
- package/dist/runtime/context.d.ts +37 -0
- package/dist/runtime/declaration.d.ts +1 -0
- package/dist/runtime/lifecycle.d.ts +28 -0
- package/dist/runtime/orbs.d.ts +39 -0
- package/dist/runtime/programs.d.ts +31 -0
- package/dist/runtime/records.d.ts +107 -0
- package/dist/runtime/references.d.ts +38 -0
- package/dist/runtime/reload.d.ts +17 -0
- package/dist/runtime/resources.d.ts +24 -0
- package/dist/runtime/scopes.d.ts +35 -0
- package/dist/runtime/session.d.ts +69 -0
- package/dist/state/binding.d.ts +28 -0
- package/dist/state/selection.d.ts +21 -0
- package/dist/state/types.d.ts +35 -0
- package/dist/state.d.ts +2 -0
- package/dist/telemetry.d.ts +23 -0
- package/dist/telemetry.js +27 -0
- package/dist/tooling/build.d.ts +3 -0
- package/dist/tooling/index.d.ts +2 -0
- package/dist/tooling/index.js +181 -0
- package/dist/tooling/resolver.d.ts +5 -0
- package/dist/tooling/typecheck.d.ts +2 -0
- package/dist/tooling/types.d.ts +29 -0
- package/dist/types.d.ts +1 -0
- package/dist/values.d.ts +23 -0
- package/package.json +103 -4
- package/src/authoring/declaration.ts +220 -0
- package/src/authoring/hooks.ts +101 -0
- package/src/authoring/orb.ts +77 -0
- package/src/authoring/types.ts +212 -0
- package/src/bridge/identifiers.ts +212 -0
- package/src/bridge/kernel.ts +117 -0
- package/src/bridge/protocol.ts +193 -0
- package/src/browser.ts +59 -0
- package/src/codec.ts +1 -0
- package/src/codecs/json.ts +147 -0
- package/src/codecs/msgpack.ts +26 -0
- package/src/context-key.ts +94 -0
- package/src/coordinator.ts +1 -0
- package/src/embedded.ts +293 -0
- package/src/error.ts +50 -0
- package/src/errors.ts +237 -0
- package/src/hooks.ts +1 -0
- package/src/host.ts +142 -0
- package/src/identifiers.ts +1 -0
- package/src/index.ts +22 -0
- package/src/infrastructure/coordinator.ts +76 -0
- package/src/infrastructure/manager.ts +77 -0
- package/src/infrastructure/rpc/channel.ts +88 -0
- package/src/infrastructure/rpc/client.ts +161 -0
- package/src/infrastructure/rpc/server.ts +201 -0
- package/src/infrastructure/rpc/state.ts +70 -0
- package/src/kernel.ts +1 -0
- package/src/manager.ts +1 -0
- package/src/msgpack.ts +1 -0
- package/src/node.ts +53 -0
- package/src/orb.ts +1 -0
- package/src/protocol.ts +1 -0
- package/src/rpc.ts +3 -0
- package/src/runtime/activities.ts +197 -0
- package/src/runtime/calls.ts +165 -0
- package/src/runtime/context.ts +113 -0
- package/src/runtime/declaration.ts +1 -0
- package/src/runtime/lifecycle.ts +227 -0
- package/src/runtime/orbs.ts +292 -0
- package/src/runtime/programs.ts +274 -0
- package/src/runtime/records.ts +127 -0
- package/src/runtime/references.ts +398 -0
- package/src/runtime/reload.ts +161 -0
- package/src/runtime/resources.ts +157 -0
- package/src/runtime/scopes.ts +210 -0
- package/src/runtime/session.ts +181 -0
- package/src/state/binding.ts +157 -0
- package/src/state/selection.ts +122 -0
- package/src/state/types.ts +47 -0
- package/src/state.ts +2 -0
- package/src/telemetry.ts +45 -0
- package/src/tooling/build.ts +83 -0
- package/src/tooling/index.ts +8 -0
- package/src/tooling/resolver.ts +95 -0
- package/src/tooling/typecheck.ts +32 -0
- package/src/tooling/types.ts +32 -0
- package/src/types.ts +1 -0
- package/src/values.ts +85 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { Declaration } from "../authoring/declaration.ts";
|
|
2
|
+
import { orb } from "../authoring/orb.ts";
|
|
3
|
+
import type { ContributionHandler, OrbDefinition, Participant } from "../authoring/types.ts";
|
|
4
|
+
import { Lifetime } from "../bridge/identifiers.ts";
|
|
5
|
+
import type { HookObservation, KernelOrb, Reload } from "../bridge/kernel.ts";
|
|
6
|
+
import { EnvironmentPhase, KernelOp, OwnerKind } from "../bridge/protocol.ts";
|
|
7
|
+
import { refuse, TembraError } from "../error.ts";
|
|
8
|
+
import { Errors } from "../errors.ts";
|
|
9
|
+
import { Context, context as checkedContext, issuedContext } from "./context.ts";
|
|
10
|
+
import type { Environment, OrbRecord } from "./records.ts";
|
|
11
|
+
import type { Session } from "./session.ts";
|
|
12
|
+
|
|
13
|
+
export class Orbs {
|
|
14
|
+
readonly records = new Map<number, OrbRecord>();
|
|
15
|
+
readonly operations = new Map<number, { orb: OrbRecord; handler: ContributionHandler }>();
|
|
16
|
+
#ready = new Map<number, Promise<void>>();
|
|
17
|
+
#ordinals = new Map<string, number>();
|
|
18
|
+
|
|
19
|
+
/** Retain local implementations and contribution callbacks. */
|
|
20
|
+
constructor(readonly session: Session) {}
|
|
21
|
+
|
|
22
|
+
/** Capture definitions and encode their kernel-owned contracts. */
|
|
23
|
+
declarations(definitions: readonly OrbDefinition[]): {
|
|
24
|
+
definitions: OrbDefinition[];
|
|
25
|
+
metadata: unknown[];
|
|
26
|
+
} {
|
|
27
|
+
const captured = definitions.map((definition) => orb(definition));
|
|
28
|
+
const current = this.session.kernel.command<KernelOrb[]>(KernelOp.Orbs);
|
|
29
|
+
const lookup = (name: string) => captured.find((f) => f.name === name);
|
|
30
|
+
const metadata = captured.map((definition) => {
|
|
31
|
+
if (
|
|
32
|
+
!this.session.kernel.features.views &&
|
|
33
|
+
Object.values(definition.services ?? {}).some((service) => service.access)
|
|
34
|
+
)
|
|
35
|
+
throw new TembraError(Errors.Unsupported.Views);
|
|
36
|
+
const requires = Object.entries(definition.requires ?? {}).map(([alias, requirement]) => {
|
|
37
|
+
const name = requirement.orb ?? alias;
|
|
38
|
+
const provider = lookup(name);
|
|
39
|
+
const info = current.find((f) => f.name === name);
|
|
40
|
+
const names = provider
|
|
41
|
+
? Object.keys(provider.services ?? {})
|
|
42
|
+
: (info?.services.map((s) => s.name) ?? []);
|
|
43
|
+
const service = names.includes(alias) ? alias : names.length === 1 ? names[0] : undefined;
|
|
44
|
+
if (requirement.methods && !service)
|
|
45
|
+
refuse(Errors.Invalid.DependencyService, `Use explicit services for ${name}`);
|
|
46
|
+
return {
|
|
47
|
+
orb: name,
|
|
48
|
+
apiVersion: requirement.apiVersion,
|
|
49
|
+
services:
|
|
50
|
+
requirement.services ??
|
|
51
|
+
(requirement.methods ? { [service!]: requirement.methods } : {}),
|
|
52
|
+
hooks: requirement.hooks ?? [],
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
for (const [alias, hooks] of Object.entries(definition.contributes ?? {})) {
|
|
56
|
+
const requirement = definition.requires?.[alias];
|
|
57
|
+
if (!requirement) refuse(Errors.Invalid.HookDependency, alias);
|
|
58
|
+
for (const [hook, contribution] of Object.entries(hooks)) {
|
|
59
|
+
if (!requirement.hooks?.includes(hook)) refuse(Errors.Invalid.HookDependency, hook);
|
|
60
|
+
const priority = typeof contribution === "function" ? 0 : (contribution.priority ?? 0);
|
|
61
|
+
if (!Number.isInteger(priority) || priority < -0x8000_0000 || priority > 0x7fff_ffff)
|
|
62
|
+
refuse(Errors.Invalid.Priority);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
name: definition.name,
|
|
67
|
+
apiVersion: definition.apiVersion,
|
|
68
|
+
requires,
|
|
69
|
+
hooks: Object.keys(definition.hooks ?? {}),
|
|
70
|
+
services: Object.entries(definition.services ?? {}).map(([name, service]) => ({
|
|
71
|
+
name,
|
|
72
|
+
methods: Object.keys(service.methods),
|
|
73
|
+
lifetime: service.lifetime ?? Lifetime.Referenced,
|
|
74
|
+
linger: service.linger ?? 0,
|
|
75
|
+
})),
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
return { definitions: captured, metadata };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Commit new orb metadata before opening its scopes. */
|
|
82
|
+
async install(definitions: readonly OrbDefinition[]): Promise<void> {
|
|
83
|
+
const current = this.session.kernel.command<KernelOrb[]>(KernelOp.Orbs);
|
|
84
|
+
if (definitions.some((f) => current.some((installed) => installed.name === f.name)))
|
|
85
|
+
refuse(Errors.Invalid.OrbInstalled, "Use reload to replace an installed orb");
|
|
86
|
+
const prepared = this.declarations(definitions);
|
|
87
|
+
const reload = this.session.kernel.command<Reload>(KernelOp.Prepare, {
|
|
88
|
+
orbs: prepared.metadata,
|
|
89
|
+
});
|
|
90
|
+
this.session.kernel.command(KernelOp.Commit, { ticket: reload.id });
|
|
91
|
+
const records = reload.orbs.map((info) => ({
|
|
92
|
+
info,
|
|
93
|
+
definition: prepared.definitions.find((f) => f.name === info.name)!,
|
|
94
|
+
}));
|
|
95
|
+
for (const record of records) this.records.set(record.info.id, record);
|
|
96
|
+
for (const record of records) this.registerContributions(record);
|
|
97
|
+
await Promise.all(records.map((record) => this.ready(record)));
|
|
98
|
+
for (const record of records) {
|
|
99
|
+
for (const service of record.info.services.filter((s) => s.lifetime === Lifetime.Host)) {
|
|
100
|
+
const reference = await this.session.handles.get(service.name, "main", {
|
|
101
|
+
principal: "host",
|
|
102
|
+
});
|
|
103
|
+
reference.release();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
this.session.lifecycle.flush();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Declare one shared scope for this orb version. */
|
|
110
|
+
scope(record: OrbRecord): Environment {
|
|
111
|
+
if (record.scope) return record.scope;
|
|
112
|
+
const environment = this.session.scopes.environment(
|
|
113
|
+
{ kind: OwnerKind.Orb, id: record.info.owner },
|
|
114
|
+
record,
|
|
115
|
+
);
|
|
116
|
+
record.scope = environment;
|
|
117
|
+
try {
|
|
118
|
+
const value = record.definition.create?.(new Declaration(this.session, environment)) ?? {};
|
|
119
|
+
if (value && typeof (value as { then?: unknown }).then === "function")
|
|
120
|
+
refuse(Errors.Invalid.AsyncFactory);
|
|
121
|
+
environment.value = value;
|
|
122
|
+
} finally {
|
|
123
|
+
environment.phase = EnvironmentPhase.Prepared;
|
|
124
|
+
this.session.programs.register(environment);
|
|
125
|
+
}
|
|
126
|
+
return environment;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Share pending activation and clean up failed orb scopes. */
|
|
130
|
+
ready(record: OrbRecord): Promise<void> {
|
|
131
|
+
if (record.scope?.phase === EnvironmentPhase.Live) return Promise.resolve();
|
|
132
|
+
let ready = this.#ready.get(record.info.id);
|
|
133
|
+
if (!ready) {
|
|
134
|
+
ready = (async () => {
|
|
135
|
+
try {
|
|
136
|
+
await this.session.scopes.readyHostScope();
|
|
137
|
+
if (record.scope?.phase === EnvironmentPhase.Closed) delete record.scope;
|
|
138
|
+
const scope = this.scope(record);
|
|
139
|
+
await this.session.programs.activate(scope.id);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (record.scope) {
|
|
142
|
+
await this.session.programs.cleanup([record.scope]);
|
|
143
|
+
delete record.scope;
|
|
144
|
+
}
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
})();
|
|
148
|
+
this.#ready.set(record.info.id, ready);
|
|
149
|
+
const clear = () => {
|
|
150
|
+
if (this.#ready.get(record.info.id) === ready) this.#ready.delete(record.info.id);
|
|
151
|
+
};
|
|
152
|
+
ready.then(clear, clear);
|
|
153
|
+
}
|
|
154
|
+
return ready;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Register callback identities with stable contribution order. */
|
|
158
|
+
registerContributions(record: OrbRecord): void {
|
|
159
|
+
for (const [alias, hooks] of Object.entries(record.definition.contributes ?? {})) {
|
|
160
|
+
const requirement = record.definition.requires![alias]!;
|
|
161
|
+
const target = requirement.orb ?? alias;
|
|
162
|
+
for (const [hook, contribution] of Object.entries(hooks)) {
|
|
163
|
+
const operation = this.session.kernel.command<number>(KernelOp.Allocate);
|
|
164
|
+
const key = JSON.stringify([record.info.name, target, hook]);
|
|
165
|
+
if (!this.#ordinals.has(key))
|
|
166
|
+
this.#ordinals.set(
|
|
167
|
+
key,
|
|
168
|
+
this.session.kernel.command<number>(KernelOp.ContributionOrdinal),
|
|
169
|
+
);
|
|
170
|
+
this.operations.set(operation, {
|
|
171
|
+
orb: record,
|
|
172
|
+
handler: typeof contribution === "function" ? contribution : contribution.handle,
|
|
173
|
+
});
|
|
174
|
+
this.session.kernel.command(KernelOp.Contribute, {
|
|
175
|
+
orb: record.info.id,
|
|
176
|
+
target,
|
|
177
|
+
hook,
|
|
178
|
+
operation,
|
|
179
|
+
priority: typeof contribution === "function" ? 0 : (contribution.priority ?? 0),
|
|
180
|
+
ordinal: this.#ordinals.get(key),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Validate the caller and execute the kernel's admitted hook plan. */
|
|
187
|
+
async runHook(
|
|
188
|
+
environment: Environment,
|
|
189
|
+
name: string,
|
|
190
|
+
context: Context,
|
|
191
|
+
input: unknown,
|
|
192
|
+
): Promise<unknown> {
|
|
193
|
+
context = checkedContext(context, this.session);
|
|
194
|
+
const definition = environment.orb.definition.hooks?.[name];
|
|
195
|
+
if (!definition) refuse(Errors.Invalid.Hook, name);
|
|
196
|
+
const plan = this.session.kernel.command<number[]>(KernelOp.HookPlan, {
|
|
197
|
+
root: context.root,
|
|
198
|
+
target: environment.orb.info.name,
|
|
199
|
+
hook: name,
|
|
200
|
+
});
|
|
201
|
+
const participants: Participant[] = plan.map((operation) => async (ctx, input, next) => {
|
|
202
|
+
return this.runContribution(operation, ctx, input, next);
|
|
203
|
+
});
|
|
204
|
+
return definition.run(context, input, participants);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Await the kernel's single owner-bound hook observation, including after cancellation.
|
|
208
|
+
* The observation starts with an empty metadata frame. It does not revive the source context.
|
|
209
|
+
* Host/owner cleanup can cancel it; physical work remains tracked until it settles.
|
|
210
|
+
*/
|
|
211
|
+
async observe(
|
|
212
|
+
environment: Environment,
|
|
213
|
+
name: string,
|
|
214
|
+
operation: number,
|
|
215
|
+
source: Context,
|
|
216
|
+
input: unknown,
|
|
217
|
+
): Promise<void> {
|
|
218
|
+
source = issuedContext(source, this.session);
|
|
219
|
+
const definition = environment.orb.definition.hooks?.[name];
|
|
220
|
+
if (!definition) refuse(Errors.Invalid.Hook, name);
|
|
221
|
+
if (!source.invocation) throw new TembraError(Errors.Forbidden.ObservationSource);
|
|
222
|
+
const admitted = this.session.kernel.command<HookObservation>(KernelOp.BeginHookObservation, {
|
|
223
|
+
source: source.invocation.id,
|
|
224
|
+
orb: environment.orb.info.id,
|
|
225
|
+
operation,
|
|
226
|
+
...(environment.object ? { object: environment.object.id } : {}),
|
|
227
|
+
hook: name,
|
|
228
|
+
});
|
|
229
|
+
await this.session.track(
|
|
230
|
+
this.session.calls.root(
|
|
231
|
+
async () => {
|
|
232
|
+
try {
|
|
233
|
+
const context = new Context(
|
|
234
|
+
this.session,
|
|
235
|
+
admitted.invocation.root,
|
|
236
|
+
admitted.invocation,
|
|
237
|
+
);
|
|
238
|
+
const participants: Participant[] = admitted.plan.map(
|
|
239
|
+
(operation) => async (ctx, input, next) =>
|
|
240
|
+
this.runContribution(operation, ctx, input, next),
|
|
241
|
+
);
|
|
242
|
+
await definition.run(context, input, participants);
|
|
243
|
+
} finally {
|
|
244
|
+
this.session.lifecycle.finishCall(admitted.invocation.id);
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
false,
|
|
248
|
+
admitted.invocation.root,
|
|
249
|
+
),
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Execute a participant from either adapter under its own managed orb invocation. */
|
|
254
|
+
async runContribution(
|
|
255
|
+
operation: number,
|
|
256
|
+
ctx: Context,
|
|
257
|
+
input: unknown,
|
|
258
|
+
next?: (input: unknown) => Promise<unknown>,
|
|
259
|
+
): Promise<unknown> {
|
|
260
|
+
ctx = checkedContext(ctx, this.session);
|
|
261
|
+
const contributor = this.operations.get(operation);
|
|
262
|
+
if (!contributor) {
|
|
263
|
+
const native = this.session.options.native;
|
|
264
|
+
if (native?.hasContribution?.(operation) && native.contribute)
|
|
265
|
+
return native.contribute(operation, ctx, input);
|
|
266
|
+
throw new TembraError(Errors.Gone.Contribution);
|
|
267
|
+
}
|
|
268
|
+
const scope = contributor.orb.scope;
|
|
269
|
+
if (!scope) throw new TembraError(Errors.Unavailable.OrbScope);
|
|
270
|
+
return this.session.calls.owned(
|
|
271
|
+
scope,
|
|
272
|
+
operation,
|
|
273
|
+
(entered) => contributor.handler(entered, input, next),
|
|
274
|
+
ctx,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Clean up a retired version before removing its callbacks. */
|
|
279
|
+
retire(id: number): void {
|
|
280
|
+
const scopes = this.session.kernel.command<number[]>(KernelOp.ScopesForOrb, { orb: id });
|
|
281
|
+
const cleanup = this.session.programs.cleanupScopes(scopes);
|
|
282
|
+
this.session.track(
|
|
283
|
+
cleanup.then(() => {
|
|
284
|
+
for (const [operation, contribution] of this.operations)
|
|
285
|
+
if (contribution.orb.info.id === id) this.operations.delete(operation);
|
|
286
|
+
this.records.delete(id);
|
|
287
|
+
this.#ready.delete(id);
|
|
288
|
+
}),
|
|
289
|
+
true,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { Code } from "../bridge/identifiers.ts";
|
|
2
|
+
import {
|
|
3
|
+
ActionType,
|
|
4
|
+
EffectType,
|
|
5
|
+
EnvironmentPhase,
|
|
6
|
+
KernelOp,
|
|
7
|
+
OwnerKind,
|
|
8
|
+
} from "../bridge/protocol.ts";
|
|
9
|
+
import { Errors } from "../errors.ts";
|
|
10
|
+
|
|
11
|
+
import type { Action, Effect } from "../bridge/kernel.ts";
|
|
12
|
+
import { failure, TembraError } from "../error.ts";
|
|
13
|
+
import { validate } from "../state.ts";
|
|
14
|
+
import type { Environment, ResourceRecord } from "./records.ts";
|
|
15
|
+
import { deferred } from "./records.ts";
|
|
16
|
+
import type { Session } from "./session.ts";
|
|
17
|
+
|
|
18
|
+
/** Bound callback error text without emitting isolated UTF-16 surrogates. */
|
|
19
|
+
function errorText(value: string, limit: number): string {
|
|
20
|
+
return value.slice(0, limit).replace(/[\uD800-\uDFFF]/gu, "\uFFFD");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Language effects only. The Rust program owns readiness, ordering, gates and recovery decisions. */
|
|
24
|
+
export class Programs {
|
|
25
|
+
readonly scopes = new Map<number, Environment>();
|
|
26
|
+
#pending = new Map<number, ReturnType<typeof deferred<void>>>();
|
|
27
|
+
|
|
28
|
+
/** Retain effect scopes and pending program completions. */
|
|
29
|
+
constructor(readonly session: Session) {}
|
|
30
|
+
|
|
31
|
+
/** Describe a declared scope to the Rust lifecycle engine. */
|
|
32
|
+
register(environment: Environment): void {
|
|
33
|
+
const parent =
|
|
34
|
+
environment.owner.kind === OwnerKind.Host
|
|
35
|
+
? undefined
|
|
36
|
+
: environment.object
|
|
37
|
+
? environment.orb.scope
|
|
38
|
+
: this.session.hostScope;
|
|
39
|
+
this.session.kernel.command(KernelOp.ScopeRegister, {
|
|
40
|
+
scope: environment.id,
|
|
41
|
+
owner: environment.owner,
|
|
42
|
+
orb: environment.orb.info.id,
|
|
43
|
+
parents: parent ? [parent.id] : [],
|
|
44
|
+
dependencies: [...environment.dependencies.values()].map(
|
|
45
|
+
(reference) => this.session.handles.reference(reference).id,
|
|
46
|
+
),
|
|
47
|
+
resources: [...environment.resources.values()].map((resource) => resource.id),
|
|
48
|
+
stateVersion: environment.state?.options.version ?? (environment.state ? 1 : undefined),
|
|
49
|
+
migrate: Boolean(environment.state?.options.migrate),
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Activate an already registered scope and wait for its program. */
|
|
54
|
+
activate(scope: number): Promise<void> {
|
|
55
|
+
return this.run(this.session.kernel.command<number>(KernelOp.ScopeActivate, { scope }));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Ask the kernel to retire existing scopes and await completion. */
|
|
59
|
+
cleanup(environments: readonly Environment[]): Promise<void> {
|
|
60
|
+
const scopes = environments
|
|
61
|
+
.map((environment) => environment.id)
|
|
62
|
+
.filter((scope) => this.session.kernel.command<boolean>(KernelOp.ScopeExists, { scope }));
|
|
63
|
+
return this.cleanupScopes(scopes);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Run cleanup for kernel-issued scope identities without resolving JS callbacks. */
|
|
67
|
+
cleanupScopes(scopes: readonly number[]): Promise<void> {
|
|
68
|
+
return scopes.length
|
|
69
|
+
? this.run(this.session.kernel.command<number>(KernelOp.ScopesCleanup, { scopes }))
|
|
70
|
+
: Promise.resolve();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Keep both adapters informed when they await the same kernel activation. */
|
|
74
|
+
pending(program: number): boolean {
|
|
75
|
+
return this.#pending.has(program);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Share one completion promise for a kernel program. */
|
|
79
|
+
run(program: number): Promise<void> {
|
|
80
|
+
const pending = this.#pending.get(program);
|
|
81
|
+
if (pending) return pending.promise;
|
|
82
|
+
const completion = deferred<void>();
|
|
83
|
+
this.#pending.set(program, completion);
|
|
84
|
+
try {
|
|
85
|
+
this.session.kernel.command(KernelOp.ProgramRun, { program });
|
|
86
|
+
this.session.lifecycle.flush();
|
|
87
|
+
} catch (error) {
|
|
88
|
+
this.#pending.delete(program);
|
|
89
|
+
completion.reject(error);
|
|
90
|
+
}
|
|
91
|
+
return completion.promise;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Dispatches opaque engine requests and acknowledges physical callback settlement. */
|
|
95
|
+
dispatch(action: Action): void {
|
|
96
|
+
if (action.type === ActionType.Execute) {
|
|
97
|
+
this.session.track(
|
|
98
|
+
Promise.allSettled(action.effects!.map((effect) => this.execute(effect))).then(
|
|
99
|
+
(settled) => {
|
|
100
|
+
// Reserve fixed envelope overhead, then budget worst-case JSON escaping (6 bytes/code unit).
|
|
101
|
+
const limit = Math.max(
|
|
102
|
+
0,
|
|
103
|
+
Math.min(
|
|
104
|
+
2048,
|
|
105
|
+
Math.floor((1024 * 1024 - 128 - settled.length * 96) / (12 * settled.length)),
|
|
106
|
+
),
|
|
107
|
+
);
|
|
108
|
+
const results = settled.map((result) => {
|
|
109
|
+
if (result.status === "fulfilled") return { value: result.value ?? null };
|
|
110
|
+
try {
|
|
111
|
+
const { code, reason, message } = failure(result.reason);
|
|
112
|
+
if (
|
|
113
|
+
!Object.values(Code).includes(code) ||
|
|
114
|
+
typeof reason !== "string" ||
|
|
115
|
+
typeof message !== "string"
|
|
116
|
+
)
|
|
117
|
+
return { error: Errors.Unavailable.Callback };
|
|
118
|
+
return {
|
|
119
|
+
error: {
|
|
120
|
+
code,
|
|
121
|
+
reason: errorText(reason, limit),
|
|
122
|
+
message: errorText(message, limit),
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
} catch {
|
|
126
|
+
// Even a mutated Error with throwing getters must acknowledge physical settlement.
|
|
127
|
+
return { error: Errors.Unavailable.Callback };
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
this.session.kernel.command(KernelOp.ProgramCompleteStep, {
|
|
131
|
+
program: action.id,
|
|
132
|
+
results,
|
|
133
|
+
});
|
|
134
|
+
this.session.lifecycle.flush();
|
|
135
|
+
},
|
|
136
|
+
),
|
|
137
|
+
);
|
|
138
|
+
} else if (action.type === ActionType.CancelEffects) {
|
|
139
|
+
for (const effect of action.effects!) {
|
|
140
|
+
if (effect.type !== EffectType.Open && effect.type !== EffectType.Restore) continue;
|
|
141
|
+
const resource = this.session.resources.find(effect.resource!);
|
|
142
|
+
if (resource) resource.controller.abort(new TembraError(Errors.Cancelled.EngineEffect));
|
|
143
|
+
else if (this.session.options.native?.cancelEffect) {
|
|
144
|
+
const cancel = this.session.options.native.cancelEffect.bind(this.session.options.native);
|
|
145
|
+
this.session
|
|
146
|
+
.track(Promise.resolve().then(() => cancel(effect)))
|
|
147
|
+
.catch((error) => this.session.report(error));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} else {
|
|
151
|
+
const completion = this.#pending.get(action.id);
|
|
152
|
+
this.#pending.delete(action.id);
|
|
153
|
+
if (action.error) {
|
|
154
|
+
const error = new TembraError(action.error);
|
|
155
|
+
if (completion) completion.reject(error);
|
|
156
|
+
else {
|
|
157
|
+
this.session.cleanupErrors.push(error);
|
|
158
|
+
this.session.report(error);
|
|
159
|
+
}
|
|
160
|
+
} else completion?.resolve();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Resolve a live or recently closed resource callback record. */
|
|
165
|
+
private resource(id: number): ResourceRecord {
|
|
166
|
+
const direct = this.session.resources.find(id);
|
|
167
|
+
if (direct) return direct;
|
|
168
|
+
throw new TembraError(Errors.Gone.Resource);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Execute a language effect without deciding lifecycle order. */
|
|
172
|
+
private async execute(effect: Effect): Promise<number | void> {
|
|
173
|
+
const environment = effect.scope === undefined ? undefined : this.scopes.get(effect.scope);
|
|
174
|
+
if (effect.scope !== undefined && !environment && this.session.options.native)
|
|
175
|
+
return this.session.options.native.effect(effect);
|
|
176
|
+
if (
|
|
177
|
+
(effect.type === EffectType.Close || effect.type === EffectType.Open) &&
|
|
178
|
+
!this.session.resources.find(effect.resource!) &&
|
|
179
|
+
this.session.options.native
|
|
180
|
+
)
|
|
181
|
+
return this.session.options.native.effect(effect);
|
|
182
|
+
switch (effect.type) {
|
|
183
|
+
case EffectType.Open:
|
|
184
|
+
await this.resource(effect.resource!).start();
|
|
185
|
+
break;
|
|
186
|
+
case EffectType.Close:
|
|
187
|
+
await this.session.resources.close(this.resource(effect.resource!));
|
|
188
|
+
break;
|
|
189
|
+
case EffectType.Restore:
|
|
190
|
+
await this.session.resources.reopen(this.resource(effect.previous!), effect.resource!);
|
|
191
|
+
break;
|
|
192
|
+
case EffectType.Stop:
|
|
193
|
+
if (environment) await this.session.activities.stop(environment);
|
|
194
|
+
break;
|
|
195
|
+
case EffectType.Prepare: {
|
|
196
|
+
if (!environment) throw new TembraError(Errors.Gone.Scope);
|
|
197
|
+
this.session.activities.prepare(
|
|
198
|
+
environment,
|
|
199
|
+
effect.previous ? this.scopes.get(effect.previous) : undefined,
|
|
200
|
+
);
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
case EffectType.Validate:
|
|
204
|
+
validate(this.session.value(effect.value!), environment!.state!.options);
|
|
205
|
+
break;
|
|
206
|
+
case EffectType.Initialize:
|
|
207
|
+
return this.candidate(environment!, environment!.state!.initial);
|
|
208
|
+
case EffectType.Migrate: {
|
|
209
|
+
const state = environment!.state!;
|
|
210
|
+
return this.candidate(
|
|
211
|
+
environment!,
|
|
212
|
+
state.options.migrate!(this.session.value(effect.value!), effect.version!),
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
case EffectType.Adopt: {
|
|
216
|
+
const orbs = new Map<number, Environment["orb"]>();
|
|
217
|
+
for (const pair of effect.replacements!) {
|
|
218
|
+
if (!pair.next) continue;
|
|
219
|
+
const next = this.scopes.get(pair.next)!;
|
|
220
|
+
for (const [resource, declaration] of next.resourceDeclarations ?? [])
|
|
221
|
+
resource.options = declaration;
|
|
222
|
+
delete next.resourceDeclarations;
|
|
223
|
+
orbs.set(next.orb.info.id, next.orb);
|
|
224
|
+
if (next.object) {
|
|
225
|
+
if (next.state) next.object.binding = next.state.binding;
|
|
226
|
+
next.object.orb = next.orb.info.id;
|
|
227
|
+
next.object.versions.set(next.orb.info.id, next);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
for (const record of orbs.values()) {
|
|
231
|
+
this.session.orbs.records.set(record.info.id, record);
|
|
232
|
+
this.session.orbs.registerContributions(record);
|
|
233
|
+
}
|
|
234
|
+
for (const pair of effect.replacements!) {
|
|
235
|
+
const next = pair.next ? this.scopes.get(pair.next) : undefined;
|
|
236
|
+
if (next?.object) this.session.handles.refreshReferences(next.object, next.orb);
|
|
237
|
+
}
|
|
238
|
+
for (const pair of effect.replacements!)
|
|
239
|
+
if (pair.next) this.scopes.get(pair.next)?.state?.publish?.();
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
case EffectType.Start:
|
|
243
|
+
if (environment) {
|
|
244
|
+
this.session.activities.start(environment);
|
|
245
|
+
if (environment.object) environment.object.live = true;
|
|
246
|
+
}
|
|
247
|
+
break;
|
|
248
|
+
case EffectType.Drop: {
|
|
249
|
+
if (!environment) break;
|
|
250
|
+
for (const reference of environment.dependencies.values())
|
|
251
|
+
this.session.handles.revoke(this.session.handles.reference(reference).id);
|
|
252
|
+
environment.dependencies.clear();
|
|
253
|
+
for (const resource of environment.resources.values())
|
|
254
|
+
this.session.resources.closedRecords.delete(resource.id);
|
|
255
|
+
environment.phase = EnvironmentPhase.Closed;
|
|
256
|
+
if (environment.object) environment.object.versions.delete(environment.orb.info.id);
|
|
257
|
+
this.scopes.delete(environment.id);
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
default:
|
|
261
|
+
throw new TembraError(Errors.Unsupported.EngineEffect, effect.type);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Validate and retain candidate state before later publication. */
|
|
266
|
+
private candidate(environment: Environment, candidate: unknown): number {
|
|
267
|
+
const state = environment.state!;
|
|
268
|
+
const value = validate(candidate, state.options);
|
|
269
|
+
const id = this.session.values.put(value);
|
|
270
|
+
state.publish = () =>
|
|
271
|
+
this.session.publish(state.binding.adopt(state.binding.prepare(value), value));
|
|
272
|
+
return id;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Completion,
|
|
3
|
+
DynamicReference,
|
|
4
|
+
EventSource,
|
|
5
|
+
OrbDefinition,
|
|
6
|
+
ListenerOptions,
|
|
7
|
+
Resource,
|
|
8
|
+
ResourceOptions,
|
|
9
|
+
TaskScope,
|
|
10
|
+
} from "../authoring/types.ts";
|
|
11
|
+
import type { KernelOrb, Owner } from "../bridge/kernel.ts";
|
|
12
|
+
import { EnvironmentPhase } from "../bridge/protocol.ts";
|
|
13
|
+
import type { StateBinding, StateOptions } from "../state.ts";
|
|
14
|
+
import type { Context } from "./context.ts";
|
|
15
|
+
|
|
16
|
+
export interface OrbRecord {
|
|
17
|
+
info: KernelOrb;
|
|
18
|
+
definition: OrbDefinition;
|
|
19
|
+
scope?: Environment;
|
|
20
|
+
ticket?: number | undefined;
|
|
21
|
+
}
|
|
22
|
+
export interface Address {
|
|
23
|
+
service: string;
|
|
24
|
+
key: string[];
|
|
25
|
+
principal: string;
|
|
26
|
+
}
|
|
27
|
+
export interface ObjectRecord {
|
|
28
|
+
id: number;
|
|
29
|
+
address: Address;
|
|
30
|
+
orb: number;
|
|
31
|
+
versions: Map<number, Environment>;
|
|
32
|
+
activation: Promise<void>;
|
|
33
|
+
live?: boolean;
|
|
34
|
+
binding?: StateBinding<any>;
|
|
35
|
+
error?: unknown;
|
|
36
|
+
disposing?: Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
export interface Environment {
|
|
39
|
+
id: number;
|
|
40
|
+
owner: Owner;
|
|
41
|
+
orb: OrbRecord;
|
|
42
|
+
object?: ObjectRecord;
|
|
43
|
+
phase: EnvironmentPhase;
|
|
44
|
+
value: any;
|
|
45
|
+
dependencies: Map<string, DynamicReference>;
|
|
46
|
+
resources: Map<string, ResourceRecord>;
|
|
47
|
+
resourceDeclarations?: Map<ResourceRecord, ResourceOptions<any>>;
|
|
48
|
+
tasks: TaskDefinition[];
|
|
49
|
+
listeners: ListenerDefinition[];
|
|
50
|
+
state?: {
|
|
51
|
+
initial: any;
|
|
52
|
+
options: StateOptions<any>;
|
|
53
|
+
binding: StateBinding<any>;
|
|
54
|
+
publish?: () => void;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export interface ResourceRecord {
|
|
58
|
+
id: number;
|
|
59
|
+
name: string;
|
|
60
|
+
options: ResourceOptions<any>;
|
|
61
|
+
handle: Resource<any>;
|
|
62
|
+
dependencies: number[];
|
|
63
|
+
/** Share one physical resource-open operation. */
|
|
64
|
+
start(): Promise<void>;
|
|
65
|
+
started?: Promise<void>;
|
|
66
|
+
controller: AbortController;
|
|
67
|
+
value?: number;
|
|
68
|
+
closed?: Promise<void>;
|
|
69
|
+
/** Rebind a restored resource to its new kernel identity. */
|
|
70
|
+
reset(id: number): void;
|
|
71
|
+
}
|
|
72
|
+
export interface TaskDefinition {
|
|
73
|
+
/** Run the task callback under its scope's cancellation signal. */
|
|
74
|
+
start(scope: TaskScope): Completion<void>;
|
|
75
|
+
running?: TaskRecord;
|
|
76
|
+
}
|
|
77
|
+
export interface TaskRecord {
|
|
78
|
+
id: number;
|
|
79
|
+
controller: AbortController;
|
|
80
|
+
done: Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
export interface ListenerDefinition {
|
|
83
|
+
name: string;
|
|
84
|
+
source: EventSource<any> | (() => EventSource<any>);
|
|
85
|
+
handle: (context: Context, value: any) => unknown;
|
|
86
|
+
options: ListenerOptions;
|
|
87
|
+
running?: ListenerRecord;
|
|
88
|
+
}
|
|
89
|
+
export interface ListenerRecord {
|
|
90
|
+
id: number;
|
|
91
|
+
/** Remove the source subscription. */
|
|
92
|
+
detach(): void;
|
|
93
|
+
done?: Promise<void>;
|
|
94
|
+
definition: ListenerDefinition;
|
|
95
|
+
environment: Environment;
|
|
96
|
+
stopped: boolean;
|
|
97
|
+
}
|
|
98
|
+
export interface ReferenceRecord {
|
|
99
|
+
id: number;
|
|
100
|
+
object: number;
|
|
101
|
+
address: Address;
|
|
102
|
+
ready: Promise<void>;
|
|
103
|
+
methods: Set<string>;
|
|
104
|
+
requiredMethods: ReadonlySet<string>;
|
|
105
|
+
stateCleanups: Set<() => void>;
|
|
106
|
+
nativeOwned?: boolean;
|
|
107
|
+
context?: Context;
|
|
108
|
+
released: boolean;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Create a promise with explicit completion functions. */
|
|
112
|
+
export function deferred<T>(): {
|
|
113
|
+
promise: Promise<T>;
|
|
114
|
+
/** Settle the shared completion with its result. */
|
|
115
|
+
resolve(value: T): void;
|
|
116
|
+
/** Reject the shared completion without an unhandled rejection. */
|
|
117
|
+
reject(error: unknown): void;
|
|
118
|
+
} {
|
|
119
|
+
let resolve!: (value: T) => void;
|
|
120
|
+
let reject!: (error: unknown) => void;
|
|
121
|
+
const promise = new Promise<T>((accept, refuse) => {
|
|
122
|
+
resolve = accept;
|
|
123
|
+
reject = refuse;
|
|
124
|
+
});
|
|
125
|
+
promise.catch(() => {});
|
|
126
|
+
return { promise, resolve, reject };
|
|
127
|
+
}
|