@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,201 @@
|
|
|
1
|
+
import type { DynamicReference } from "../../authoring/types.ts";
|
|
2
|
+
import { RpcEvent, RpcOp } from "../../bridge/protocol.ts";
|
|
3
|
+
import { TembraError } from "../../error.ts";
|
|
4
|
+
import { Errors } from "../../errors.ts";
|
|
5
|
+
import type { Host } from "../../host.ts";
|
|
6
|
+
import type { Context } from "../../runtime/context.ts";
|
|
7
|
+
|
|
8
|
+
import { Channel, errorValue, type Limits, type Transport } from "./channel.ts";
|
|
9
|
+
|
|
10
|
+
/** Trusted infrastructure supplies the principal and authorization policy; peers cannot choose it. */
|
|
11
|
+
export function serve(
|
|
12
|
+
host: Host,
|
|
13
|
+
transport: Transport,
|
|
14
|
+
options: Limits & {
|
|
15
|
+
principal: string;
|
|
16
|
+
allow?: (service: string, key: readonly string[]) => boolean;
|
|
17
|
+
},
|
|
18
|
+
): {
|
|
19
|
+
/** Stop the connection and release its remote claims. */
|
|
20
|
+
close(): void;
|
|
21
|
+
} {
|
|
22
|
+
type Claim = {
|
|
23
|
+
reference: DynamicReference;
|
|
24
|
+
methods: ReadonlySet<string>;
|
|
25
|
+
detach?: () => void;
|
|
26
|
+
pending?: unknown;
|
|
27
|
+
sending: boolean;
|
|
28
|
+
closed: boolean;
|
|
29
|
+
active: boolean;
|
|
30
|
+
};
|
|
31
|
+
const references = new Map<number, Claim>();
|
|
32
|
+
const calls = new Map<number, Context>();
|
|
33
|
+
const requests = new Map<number, { cancelled: boolean }>();
|
|
34
|
+
let next = 0;
|
|
35
|
+
let pending = 0;
|
|
36
|
+
const pump = (reference: number, record: Claim) => {
|
|
37
|
+
if (record.sending || !record.active || record.closed) return;
|
|
38
|
+
record.sending = true;
|
|
39
|
+
void (async () => {
|
|
40
|
+
while (Object.hasOwn(record, "pending") && !record.closed) {
|
|
41
|
+
const value = record.pending;
|
|
42
|
+
delete record.pending;
|
|
43
|
+
await channel.send({ event: RpcEvent.State, payload: { reference, value } });
|
|
44
|
+
}
|
|
45
|
+
})()
|
|
46
|
+
.catch((error) => channel.close(error))
|
|
47
|
+
.finally(() => {
|
|
48
|
+
record.sending = false;
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
const channel = new Channel(
|
|
52
|
+
transport,
|
|
53
|
+
options,
|
|
54
|
+
(message) => {
|
|
55
|
+
if (message.op === RpcOp.Cancel) {
|
|
56
|
+
const request = requests.get(message.payload?.id);
|
|
57
|
+
if (request) request.cancelled = true;
|
|
58
|
+
calls.get(message.payload?.id)?.cancel();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const id = message.id;
|
|
62
|
+
if (!Number.isSafeInteger(id) || !id || id <= 0 || !message.op) {
|
|
63
|
+
channel.close(new TembraError(Errors.Invalid.RpcRequest));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (pending >= channel.maxPending || requests.has(id)) {
|
|
67
|
+
void channel
|
|
68
|
+
.send({ id, error: errorValue(new TembraError(Errors.Exhausted.PendingRequests)) })
|
|
69
|
+
.catch(() => channel.close());
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
pending++;
|
|
73
|
+
const request = { cancelled: false };
|
|
74
|
+
requests.set(id, request);
|
|
75
|
+
void (async () => {
|
|
76
|
+
const payload = message.payload;
|
|
77
|
+
switch (message.op) {
|
|
78
|
+
case RpcOp.Describe:
|
|
79
|
+
return host.installedOrbs().map(({ describe, ...info }) => info);
|
|
80
|
+
case RpcOp.Get: {
|
|
81
|
+
if (
|
|
82
|
+
typeof payload?.service !== "string" ||
|
|
83
|
+
!Array.isArray(payload.key) ||
|
|
84
|
+
!payload.key.every((key: unknown) => typeof key === "string")
|
|
85
|
+
)
|
|
86
|
+
throw new TembraError(Errors.Invalid.Address);
|
|
87
|
+
if (options.allow && !options.allow(payload.service, payload.key))
|
|
88
|
+
throw new TembraError(Errors.Forbidden.Service);
|
|
89
|
+
if (references.size >= channel.maxPending)
|
|
90
|
+
throw new TembraError(Errors.Exhausted.RemoteReferences);
|
|
91
|
+
const reference = await host.get(payload.service, payload.key, {
|
|
92
|
+
principal: options.principal,
|
|
93
|
+
});
|
|
94
|
+
if (channel.closed || request.cancelled) {
|
|
95
|
+
reference.release();
|
|
96
|
+
throw new TembraError(Errors.Gone.Connection);
|
|
97
|
+
}
|
|
98
|
+
const referenceId = ++next;
|
|
99
|
+
const methods = new Set(host.session.handles.reference(reference).methods);
|
|
100
|
+
const record: Claim = {
|
|
101
|
+
reference,
|
|
102
|
+
methods,
|
|
103
|
+
sending: false,
|
|
104
|
+
closed: false,
|
|
105
|
+
active: false,
|
|
106
|
+
};
|
|
107
|
+
references.set(referenceId, record);
|
|
108
|
+
let snapshot: { state?: unknown } = {};
|
|
109
|
+
try {
|
|
110
|
+
snapshot = { state: reference.state.value };
|
|
111
|
+
let initial = true;
|
|
112
|
+
record.detach = reference.state.subscribe((value) => {
|
|
113
|
+
if (initial) {
|
|
114
|
+
initial = false;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
record.pending = value;
|
|
118
|
+
pump(referenceId, record);
|
|
119
|
+
});
|
|
120
|
+
} catch {
|
|
121
|
+
/* State is optional; method-only services remain portable. */
|
|
122
|
+
}
|
|
123
|
+
return { reference: referenceId, methods: [...methods], ...snapshot };
|
|
124
|
+
}
|
|
125
|
+
case RpcOp.Release: {
|
|
126
|
+
const record = references.get(payload?.reference);
|
|
127
|
+
if (record) {
|
|
128
|
+
record.closed = true;
|
|
129
|
+
record.detach?.();
|
|
130
|
+
record.reference.release();
|
|
131
|
+
references.delete(payload.reference);
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
case RpcOp.Call: {
|
|
136
|
+
const record = references.get(payload?.reference);
|
|
137
|
+
if (
|
|
138
|
+
!record ||
|
|
139
|
+
typeof payload.method !== "string" ||
|
|
140
|
+
!record.methods.has(payload.method) ||
|
|
141
|
+
!Array.isArray(payload.arguments) ||
|
|
142
|
+
typeof record.reference[payload.method] !== "function"
|
|
143
|
+
)
|
|
144
|
+
throw new TembraError(Errors.Forbidden.Method);
|
|
145
|
+
if (request.cancelled) throw new TembraError(Errors.Cancelled.Request);
|
|
146
|
+
return host.root(
|
|
147
|
+
async (ctx) => {
|
|
148
|
+
calls.set(id, ctx);
|
|
149
|
+
try {
|
|
150
|
+
return (
|
|
151
|
+
(await record.reference[payload.method](...payload.arguments, ctx)) ?? null
|
|
152
|
+
);
|
|
153
|
+
} finally {
|
|
154
|
+
calls.delete(id);
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
{ principal: options.principal },
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
default:
|
|
161
|
+
throw new TembraError(Errors.Invalid.RpcOperation);
|
|
162
|
+
}
|
|
163
|
+
})()
|
|
164
|
+
.then(
|
|
165
|
+
async (ok) => {
|
|
166
|
+
await channel.send({ id, ok });
|
|
167
|
+
if (message.op === RpcOp.Get) {
|
|
168
|
+
const record = references.get(ok.reference);
|
|
169
|
+
if (record) {
|
|
170
|
+
record.active = true;
|
|
171
|
+
pump(ok.reference, record);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
(error) => channel.send({ id, error: errorValue(error) }),
|
|
176
|
+
)
|
|
177
|
+
.catch((error) => channel.close(error))
|
|
178
|
+
.finally(() => {
|
|
179
|
+
pending--;
|
|
180
|
+
requests.delete(id);
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
() => {
|
|
184
|
+
for (const ctx of calls.values()) {
|
|
185
|
+
try {
|
|
186
|
+
ctx.cancel();
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
for (const record of references.values()) {
|
|
190
|
+
record.closed = true;
|
|
191
|
+
record.detach?.();
|
|
192
|
+
record.reference.release();
|
|
193
|
+
}
|
|
194
|
+
references.clear();
|
|
195
|
+
},
|
|
196
|
+
);
|
|
197
|
+
return {
|
|
198
|
+
/** Stop the transport and release its remote claims. */
|
|
199
|
+
close: () => channel.close(),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Readable } from "../../state.ts";
|
|
2
|
+
import { protect } from "../../values.ts";
|
|
3
|
+
|
|
4
|
+
export class RemoteState implements Readable<any> {
|
|
5
|
+
#value: any;
|
|
6
|
+
#listeners = new Set<(value: any) => void>();
|
|
7
|
+
|
|
8
|
+
/** Protect the initial remote snapshot and retain its validity check. */
|
|
9
|
+
constructor(
|
|
10
|
+
value: unknown,
|
|
11
|
+
readonly check: () => void,
|
|
12
|
+
readonly report: (error: unknown) => void,
|
|
13
|
+
) {
|
|
14
|
+
this.#value = protect(value);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Read the snapshot while the remote reference remains valid. */
|
|
18
|
+
get value(): any {
|
|
19
|
+
this.check();
|
|
20
|
+
return this.#value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Publish a protected remote snapshot to local observers. */
|
|
24
|
+
adopt(value: unknown): void {
|
|
25
|
+
this.#value = protect(value);
|
|
26
|
+
for (const listener of this.#listeners) {
|
|
27
|
+
try {
|
|
28
|
+
listener(this.#value);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
this.report(error);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Deliver the current snapshot, then subsequent updates. */
|
|
36
|
+
subscribe(listener: (value: any) => void): () => void {
|
|
37
|
+
this.check();
|
|
38
|
+
this.#listeners.add(listener);
|
|
39
|
+
listener(this.#value);
|
|
40
|
+
return () => {
|
|
41
|
+
this.#listeners.delete(listener);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Derive a readable value from the remote state. */
|
|
46
|
+
select<R>(compute: (value: any) => R): Readable<R> {
|
|
47
|
+
const source = this;
|
|
48
|
+
return {
|
|
49
|
+
/** Compute the selected value from the current remote snapshot. */
|
|
50
|
+
get value() {
|
|
51
|
+
return compute(source.value);
|
|
52
|
+
},
|
|
53
|
+
/** Compose another projection over the same remote source. */
|
|
54
|
+
select: (next) => source.select((value) => next(compute(value))),
|
|
55
|
+
/** Notify only when the selected value changes by identity. */
|
|
56
|
+
subscribe(listener) {
|
|
57
|
+
let initial = true;
|
|
58
|
+
let previous: R;
|
|
59
|
+
return source.subscribe((value) => {
|
|
60
|
+
const next = compute(value);
|
|
61
|
+
if (initial || !Object.is(previous, next)) {
|
|
62
|
+
initial = false;
|
|
63
|
+
previous = next;
|
|
64
|
+
listener(next);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
package/src/kernel.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./bridge/kernel.ts";
|
package/src/manager.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./infrastructure/manager.ts";
|
package/src/msgpack.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./codecs/msgpack.ts";
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { orb } from "./authoring/orb.ts";
|
|
5
|
+
import type { HostOptions } from "./authoring/types.ts";
|
|
6
|
+
import type { KernelPort } from "./bridge/kernel.ts";
|
|
7
|
+
import { Host } from "./host.ts";
|
|
8
|
+
|
|
9
|
+
export type NodeHostOptions = Omit<HostOptions, "kernel"> & { kernel?: KernelPort };
|
|
10
|
+
|
|
11
|
+
/** Uses the existing Node runtime; it never embeds a second JavaScript engine. */
|
|
12
|
+
export function createHost(options: NodeHostOptions = {}): Host {
|
|
13
|
+
const require = createRequire(import.meta.url);
|
|
14
|
+
const binding = options.kernel
|
|
15
|
+
? undefined
|
|
16
|
+
: (require("@syntropika/tembra-engine-node") as {
|
|
17
|
+
NodeKernel: new () => KernelPort;
|
|
18
|
+
});
|
|
19
|
+
return new Host({
|
|
20
|
+
...options,
|
|
21
|
+
kernel: options.kernel ?? new binding!.NodeKernel(),
|
|
22
|
+
load:
|
|
23
|
+
options.load ??
|
|
24
|
+
(async (location) => {
|
|
25
|
+
const url =
|
|
26
|
+
location instanceof URL
|
|
27
|
+
? location
|
|
28
|
+
: /^[a-z]+:/i.test(location)
|
|
29
|
+
? new URL(location)
|
|
30
|
+
: pathToFileURL(path.resolve(location));
|
|
31
|
+
if (!/\.m?js$/.test(url.pathname)) throw new Error("Load a prebuilt JavaScript orb bundle");
|
|
32
|
+
return orb(
|
|
33
|
+
(await import(url.href)).default as import("./authoring/types.ts").OrbDefinition,
|
|
34
|
+
);
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export { orb };
|
|
40
|
+
export type { Host };
|
|
41
|
+
|
|
42
|
+
export {
|
|
43
|
+
Code,
|
|
44
|
+
HookCapability,
|
|
45
|
+
Lifetime,
|
|
46
|
+
Reason,
|
|
47
|
+
ReloadStatus,
|
|
48
|
+
Status,
|
|
49
|
+
} from "./bridge/identifiers.ts";
|
|
50
|
+
|
|
51
|
+
export { Errors, type ErrorDescriptor } from "./errors.ts";
|
|
52
|
+
|
|
53
|
+
export { ContextKey, ContextKind, opaqueFrom, type OpaqueContextValue } from "./context-key.ts";
|
package/src/orb.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./authoring/orb.ts";
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./bridge/protocol.ts";
|
package/src/rpc.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { EnvironmentPhase, KernelOp } from "../bridge/protocol.ts";
|
|
2
|
+
import { Errors } from "../errors.ts";
|
|
3
|
+
|
|
4
|
+
import { refuse, TembraError } from "../error.ts";
|
|
5
|
+
import type { Environment, ListenerRecord, TaskDefinition, TaskRecord } from "./records.ts";
|
|
6
|
+
import type { Session } from "./session.ts";
|
|
7
|
+
|
|
8
|
+
export class Activities {
|
|
9
|
+
readonly tasks = new Map<number, TaskRecord>();
|
|
10
|
+
readonly listeners = new Map<number, ListenerRecord>();
|
|
11
|
+
#identities = new WeakMap<object, number>();
|
|
12
|
+
|
|
13
|
+
/** Keep task and listener callbacks for this session. */
|
|
14
|
+
constructor(readonly session: Session) {}
|
|
15
|
+
|
|
16
|
+
/** Attach declared sources using subscription identities issued by Rust. */
|
|
17
|
+
prepare(environment: Environment, previous?: Environment): void {
|
|
18
|
+
for (const definition of environment.listeners) {
|
|
19
|
+
const source =
|
|
20
|
+
typeof definition.source === "function" ? definition.source() : definition.source;
|
|
21
|
+
if (!source || typeof source.subscribe !== "function") refuse(Errors.Invalid.EventSource);
|
|
22
|
+
const id = this.session.kernel.command<number>(KernelOp.Listen, {
|
|
23
|
+
scope: environment.id,
|
|
24
|
+
previous: previous?.id,
|
|
25
|
+
name: definition.name,
|
|
26
|
+
source: this.identity(source),
|
|
27
|
+
sizing: definition.options.sizeOf ? this.identity(definition.options.sizeOf) : 0,
|
|
28
|
+
operation: this.session.kernel.command<number>(KernelOp.Allocate),
|
|
29
|
+
maxPending: definition.options.maxPending ?? 64,
|
|
30
|
+
...(definition.options.maxBytes ? { maxBytes: definition.options.maxBytes } : {}),
|
|
31
|
+
coalesce: "select" in source,
|
|
32
|
+
});
|
|
33
|
+
const existing = this.listeners.get(id);
|
|
34
|
+
if (existing) {
|
|
35
|
+
definition.running = existing;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const record: ListenerRecord = {
|
|
39
|
+
id,
|
|
40
|
+
definition,
|
|
41
|
+
environment,
|
|
42
|
+
stopped: false,
|
|
43
|
+
/** Allow safe stop before the source returns its detach callback. */
|
|
44
|
+
detach() {},
|
|
45
|
+
};
|
|
46
|
+
definition.running = record;
|
|
47
|
+
this.listeners.set(id, record);
|
|
48
|
+
try {
|
|
49
|
+
record.detach = source.subscribe((value) => {
|
|
50
|
+
if (record.stopped) return;
|
|
51
|
+
const payload = this.session.values.put(value);
|
|
52
|
+
try {
|
|
53
|
+
const bytes = definition.options.sizeOf?.(value) ?? 0;
|
|
54
|
+
if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > 0xffff_ffff)
|
|
55
|
+
throw new TembraError(Errors.Invalid.SubscriptionSize);
|
|
56
|
+
this.session.kernel.command(KernelOp.Enqueue, { subscription: id, payload, bytes });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
this.session.values.drop(payload);
|
|
59
|
+
this.session.report(error);
|
|
60
|
+
this.failed(id);
|
|
61
|
+
}
|
|
62
|
+
this.session.lifecycle.flush();
|
|
63
|
+
});
|
|
64
|
+
if (record.stopped) record.detach();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
this.stopListener(record);
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Start tasks and retarget listeners after scope adoption. */
|
|
73
|
+
start(environment: Environment): void {
|
|
74
|
+
environment.phase = EnvironmentPhase.Live;
|
|
75
|
+
for (const definition of environment.listeners) {
|
|
76
|
+
const record = definition.running!;
|
|
77
|
+
record.environment = environment;
|
|
78
|
+
record.definition = definition;
|
|
79
|
+
}
|
|
80
|
+
for (const task of environment.tasks) this.startTask(environment, task);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Run one task until its physical callback settles. */
|
|
84
|
+
private startTask(environment: Environment, definition: TaskDefinition): void {
|
|
85
|
+
if (definition.running || environment.phase !== EnvironmentPhase.Live || this.session.closing)
|
|
86
|
+
return;
|
|
87
|
+
const id = this.session.kernel.command<number>(KernelOp.Task, { owner: environment.owner });
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const operation = this.session.kernel.command<number>(KernelOp.Allocate);
|
|
90
|
+
const record: TaskRecord = { id, controller, done: Promise.resolve() };
|
|
91
|
+
definition.running = record;
|
|
92
|
+
this.tasks.set(id, record);
|
|
93
|
+
record.done = this.session.track(
|
|
94
|
+
Promise.resolve().then(async () => {
|
|
95
|
+
try {
|
|
96
|
+
await definition.start({
|
|
97
|
+
signal: controller.signal,
|
|
98
|
+
/** Issue operation authority under the task's retained version. */
|
|
99
|
+
root: (callback) => {
|
|
100
|
+
const root = this.session.kernel.command<number>(KernelOp.TaskRoot, {
|
|
101
|
+
task: id,
|
|
102
|
+
principal: this.session.principalFor(environment.object?.id ?? 0),
|
|
103
|
+
});
|
|
104
|
+
return this.session.calls.root(
|
|
105
|
+
() => this.session.calls.owned(environment, operation, callback, root),
|
|
106
|
+
false,
|
|
107
|
+
root,
|
|
108
|
+
);
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (!controller.signal.aborted) this.session.report(error);
|
|
113
|
+
} finally {
|
|
114
|
+
this.session.kernel.command(KernelOp.Tick, { now: this.session.now() });
|
|
115
|
+
this.session.kernel.command(KernelOp.FinishTask, { task: id });
|
|
116
|
+
this.tasks.delete(id);
|
|
117
|
+
delete definition.running;
|
|
118
|
+
this.session.lifecycle.flush();
|
|
119
|
+
}
|
|
120
|
+
}),
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Reuse one kernel identity for the same source or sizing callback. */
|
|
125
|
+
private identity(value: object): number {
|
|
126
|
+
let id = this.#identities.get(value);
|
|
127
|
+
if (id === undefined) {
|
|
128
|
+
id = this.session.kernel.command<number>(KernelOp.Allocate);
|
|
129
|
+
this.#identities.set(value, id);
|
|
130
|
+
}
|
|
131
|
+
return id;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Execute an admitted delivery and acknowledge physical settlement. */
|
|
135
|
+
deliver(subscription: number, payload: number, operation: number): void {
|
|
136
|
+
const record = this.listeners.get(subscription);
|
|
137
|
+
const job = Promise.resolve().then(async () => {
|
|
138
|
+
try {
|
|
139
|
+
if (!record) throw new TembraError(Errors.Gone.ListenerCallback);
|
|
140
|
+
await this.session.calls.owned(record.environment, operation, (ctx) =>
|
|
141
|
+
record.definition.handle(ctx, this.session.values.get(payload)),
|
|
142
|
+
);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
this.session.report(error);
|
|
145
|
+
} finally {
|
|
146
|
+
this.session.kernel.command(KernelOp.FinishDelivery, { subscription });
|
|
147
|
+
this.session.lifecycle.flush();
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
if (record) record.done = job;
|
|
151
|
+
this.session.track(job);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Stop a listener selected by the kernel. */
|
|
155
|
+
detach(id: number): void {
|
|
156
|
+
const record = this.listeners.get(id);
|
|
157
|
+
if (record) this.stopListener(record);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Signal task cancellation without releasing its ownership. */
|
|
161
|
+
cancel(id: number): void {
|
|
162
|
+
this.tasks.get(id)?.controller.abort(new TembraError(Errors.Cancelled.Task));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Report queue exhaustion and stop its source listener. */
|
|
166
|
+
failed(id: number): void {
|
|
167
|
+
const record = this.listeners.get(id);
|
|
168
|
+
if (!record) return;
|
|
169
|
+
this.session.report(new TembraError(Errors.Exhausted.SubscriptionQueue));
|
|
170
|
+
this.stopListener(record);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Detach the source and release its kernel subscription once. */
|
|
174
|
+
private stopListener(record: ListenerRecord): void {
|
|
175
|
+
if (record.stopped) return;
|
|
176
|
+
record.stopped = true;
|
|
177
|
+
try {
|
|
178
|
+
record.detach();
|
|
179
|
+
} catch (error) {
|
|
180
|
+
this.session.report(error);
|
|
181
|
+
}
|
|
182
|
+
this.session.kernel.command(KernelOp.Unsubscribe, { subscription: record.id });
|
|
183
|
+
this.listeners.delete(record.id);
|
|
184
|
+
this.session.lifecycle.flush();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Wait for owned tasks and admitted deliveries to settle. */
|
|
188
|
+
async stop(environment: Environment): Promise<void> {
|
|
189
|
+
for (const definition of environment.tasks) {
|
|
190
|
+
if (definition.running)
|
|
191
|
+
this.session.kernel.command(KernelOp.StopTask, { task: definition.running.id });
|
|
192
|
+
}
|
|
193
|
+
this.session.lifecycle.flush();
|
|
194
|
+
await Promise.all(environment.tasks.map((task) => task.running?.done));
|
|
195
|
+
await Promise.all(environment.listeners.map((listener) => listener.running?.done));
|
|
196
|
+
}
|
|
197
|
+
}
|