@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
package/src/host.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { orb } from "./authoring/orb.ts";
|
|
2
|
+
import type {
|
|
3
|
+
AcquisitionOptions,
|
|
4
|
+
Completion,
|
|
5
|
+
OrbDefinition,
|
|
6
|
+
HostOptions,
|
|
7
|
+
ReloadOptions,
|
|
8
|
+
ResourceOptions,
|
|
9
|
+
} from "./authoring/types.ts";
|
|
10
|
+
import { KernelOp } from "./bridge/protocol.ts";
|
|
11
|
+
import { Context } from "./runtime/context.ts";
|
|
12
|
+
import { Session } from "./runtime/session.ts";
|
|
13
|
+
|
|
14
|
+
/** The application facade. Platform entrypoints provide its metadata kernel and module loader. */
|
|
15
|
+
export class Host {
|
|
16
|
+
readonly session: Session;
|
|
17
|
+
|
|
18
|
+
/** Create the shared session for this host. */
|
|
19
|
+
constructor(options: HostOptions) {
|
|
20
|
+
this.session = new Session(options);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read the configured host name. */
|
|
24
|
+
get name() {
|
|
25
|
+
return this.session.name;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Read the capabilities compiled into the Rust kernel. */
|
|
29
|
+
get features() {
|
|
30
|
+
return this.session.kernel.features;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Install new orbs and activate their required scopes. */
|
|
34
|
+
install(definition: OrbDefinition | readonly OrbDefinition[]): Promise<void> {
|
|
35
|
+
return this.session.orbs.install(
|
|
36
|
+
Array.isArray(definition) ? definition : [definition as OrbDefinition],
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Load an orb with the host's module loader, then install it. */
|
|
41
|
+
async load(location: string | URL): Promise<void> {
|
|
42
|
+
if (!this.session.options.load) throw new Error("This host has no module loader");
|
|
43
|
+
await this.install(await this.session.options.load(location));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Prepare and commit a replacement using the kernel's lifecycle order. */
|
|
47
|
+
reload(definitions: readonly OrbDefinition[], options?: ReloadOptions) {
|
|
48
|
+
return this.session.replacements.replace(definitions, options);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Build a replacement candidate without adopting it. */
|
|
52
|
+
prepare(definitions: readonly OrbDefinition[], options?: ReloadOptions) {
|
|
53
|
+
return this.session.replacements.prepare(definitions, options);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Remove named orbs through the replacement lifecycle. */
|
|
57
|
+
remove(names: readonly string[], options?: ReloadOptions) {
|
|
58
|
+
return this.session.replacements.replace([], options, names);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Acquire a reference before its asynchronous activation completes. */
|
|
62
|
+
hold(service: string, key: string | readonly string[], options?: AcquisitionOptions) {
|
|
63
|
+
return this.session.handles.hold(service, key, options);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Acquire a reference and wait for activation. */
|
|
67
|
+
get(service: string, key: string | readonly string[], options?: AcquisitionOptions) {
|
|
68
|
+
return this.session.handles.get(service, key, options);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Run an operation with one principal and bounded context lifetime. */
|
|
72
|
+
root<T>(
|
|
73
|
+
operation: (context: Context) => Completion<T>,
|
|
74
|
+
options: { principal?: string } = {},
|
|
75
|
+
): Promise<T> {
|
|
76
|
+
return this.session.calls.root(operation, false, undefined, options.principal);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Declare a resource owned by this host. */
|
|
80
|
+
resource<T>(name: string, options: ResourceOptions<T>) {
|
|
81
|
+
return this.session.scopes.resource(name, options);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Read current kernel counts and pending JS work. */
|
|
85
|
+
diagnostics() {
|
|
86
|
+
return this.session.lifecycle.diagnostics();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Drain errors collected by the host. */
|
|
90
|
+
errors() {
|
|
91
|
+
return this.session.errors.splice(0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Drain sampled call records. */
|
|
95
|
+
traces() {
|
|
96
|
+
return this.session.telemetry?.drain() ?? [];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Describe installed orbs without activating their services. */
|
|
100
|
+
installedOrbs() {
|
|
101
|
+
return this.session.kernel
|
|
102
|
+
.command<import("./bridge/kernel.ts").KernelOrb[]>(KernelOp.Orbs)
|
|
103
|
+
.map((info) => {
|
|
104
|
+
const definition = this.session.orbs.records.get(info.id)?.definition;
|
|
105
|
+
const description = Object.freeze({
|
|
106
|
+
...info,
|
|
107
|
+
hookCapabilities: Object.fromEntries(
|
|
108
|
+
info.hooks.map((name) => [name, definition?.hooks?.[name]?.capabilities ?? []]),
|
|
109
|
+
),
|
|
110
|
+
});
|
|
111
|
+
return Object.freeze({
|
|
112
|
+
...info,
|
|
113
|
+
/** Return captured metadata without activating services. */
|
|
114
|
+
describe: () => description,
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Wait for physical work and cleanup before releasing the kernel. */
|
|
120
|
+
close(): Promise<void> {
|
|
121
|
+
return this.session.lifecycle.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Create a host with an explicitly supplied platform adapter. */
|
|
126
|
+
export function createHost(options: HostOptions): Host {
|
|
127
|
+
return new Host(options);
|
|
128
|
+
}
|
|
129
|
+
export { orb };
|
|
130
|
+
|
|
131
|
+
export {
|
|
132
|
+
Code,
|
|
133
|
+
HookCapability,
|
|
134
|
+
Lifetime,
|
|
135
|
+
Reason,
|
|
136
|
+
ReloadStatus,
|
|
137
|
+
Status,
|
|
138
|
+
} from "./bridge/identifiers.ts";
|
|
139
|
+
|
|
140
|
+
export { Errors, type ErrorDescriptor } from "./errors.ts";
|
|
141
|
+
|
|
142
|
+
export type { KernelPort } from "./bridge/kernel.ts";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./bridge/identifiers.ts";
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type { Declaration } from "./authoring/declaration.ts";
|
|
2
|
+
export { orb } from "./authoring/orb.ts";
|
|
3
|
+
export { bail, middleware, parallel, series, waterfall } from "./authoring/hooks.ts";
|
|
4
|
+
export type * from "./authoring/types.ts";
|
|
5
|
+
export { jsonCodec } from "./codecs/json.ts";
|
|
6
|
+
export type { Codec } from "./codecs/json.ts";
|
|
7
|
+
export { TembraError } from "./error.ts";
|
|
8
|
+
export type { Context } from "./runtime/context.ts";
|
|
9
|
+
export type { Readable, State, StateOptions } from "./state.ts";
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
Code,
|
|
13
|
+
HookCapability,
|
|
14
|
+
Lifetime,
|
|
15
|
+
Reason,
|
|
16
|
+
ReloadStatus,
|
|
17
|
+
Status,
|
|
18
|
+
} from "./bridge/identifiers.ts";
|
|
19
|
+
|
|
20
|
+
export { Errors, type ErrorDescriptor } from "./errors.ts";
|
|
21
|
+
|
|
22
|
+
export { ContextKey, ContextKind, opaqueFrom, type OpaqueContextValue } from "./context-key.ts";
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { CoordinationDecision } from "../bridge/protocol.ts";
|
|
2
|
+
import { Errors } from "../errors.ts";
|
|
3
|
+
|
|
4
|
+
import { TembraError } from "../error.ts";
|
|
5
|
+
|
|
6
|
+
export interface Participant<T> {
|
|
7
|
+
/** Prepare this participant without publishing its changes. */
|
|
8
|
+
prepare(signal: AbortSignal): Promise<T>;
|
|
9
|
+
/** Publish this participant's prepared changes. */
|
|
10
|
+
commit(ticket: T): Promise<void>;
|
|
11
|
+
/** Release this participant's uncommitted candidate. */
|
|
12
|
+
abort(ticket: T): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Bounded direct participants. A commit decision is not a durable distributed transaction. */
|
|
16
|
+
export async function coordinate<T>(
|
|
17
|
+
participants: readonly Participant<T>[],
|
|
18
|
+
options: { deadline?: number; maxParticipants?: number } = {},
|
|
19
|
+
): Promise<void> {
|
|
20
|
+
const deadline = options.deadline ?? 5000;
|
|
21
|
+
if (
|
|
22
|
+
participants.length > (options.maxParticipants ?? 32) ||
|
|
23
|
+
!Number.isFinite(deadline) ||
|
|
24
|
+
deadline <= 0
|
|
25
|
+
)
|
|
26
|
+
throw new TembraError(Errors.Invalid.CoordinationLimits);
|
|
27
|
+
const controller = new AbortController();
|
|
28
|
+
const prepared = new Map<Participant<T>, T>();
|
|
29
|
+
let decision: CoordinationDecision = CoordinationDecision.Preparing;
|
|
30
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
31
|
+
const preparation = Promise.all(
|
|
32
|
+
participants.map(async (participant) => {
|
|
33
|
+
const ticket = await participant.prepare(controller.signal);
|
|
34
|
+
if (decision === CoordinationDecision.Abort) await participant.abort(ticket);
|
|
35
|
+
else prepared.set(participant, ticket);
|
|
36
|
+
}),
|
|
37
|
+
);
|
|
38
|
+
try {
|
|
39
|
+
await Promise.race([
|
|
40
|
+
preparation,
|
|
41
|
+
new Promise<never>((_, reject) => {
|
|
42
|
+
timer = setTimeout(
|
|
43
|
+
() => reject(new TembraError(Errors.Conflict.PrepareDeadline)),
|
|
44
|
+
deadline,
|
|
45
|
+
);
|
|
46
|
+
}),
|
|
47
|
+
]);
|
|
48
|
+
decision = CoordinationDecision.Commit;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
decision = CoordinationDecision.Abort;
|
|
51
|
+
controller.abort(error);
|
|
52
|
+
const aborted = await Promise.allSettled(
|
|
53
|
+
[...prepared].map(([participant, ticket]) => participant.abort(ticket)),
|
|
54
|
+
);
|
|
55
|
+
preparation.catch(() => {});
|
|
56
|
+
const errors = aborted
|
|
57
|
+
.filter((result) => result.status === "rejected")
|
|
58
|
+
.map((result) => result.reason);
|
|
59
|
+
if (errors.length)
|
|
60
|
+
throw new AggregateError([error, ...errors], "Preparation and cleanup failed");
|
|
61
|
+
throw error;
|
|
62
|
+
} finally {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
65
|
+
const committed = await Promise.allSettled(
|
|
66
|
+
[...prepared].map(([participant, ticket]) => participant.commit(ticket)),
|
|
67
|
+
);
|
|
68
|
+
const errors = committed
|
|
69
|
+
.filter((result) => result.status === "rejected")
|
|
70
|
+
.map((result) => result.reason);
|
|
71
|
+
if (errors.length)
|
|
72
|
+
throw new AggregateError(
|
|
73
|
+
errors,
|
|
74
|
+
"Commit was decided but some participants did not acknowledge it",
|
|
75
|
+
);
|
|
76
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { Errors } from "../errors.ts";
|
|
2
|
+
|
|
3
|
+
import { TembraError } from "../error.ts";
|
|
4
|
+
import type { Host } from "../host.ts";
|
|
5
|
+
|
|
6
|
+
/** Explicit infrastructure lifecycle. Replacing a host creates new memory and references. */
|
|
7
|
+
export class HostManager {
|
|
8
|
+
#hosts = new Map<string, Host>();
|
|
9
|
+
#pending = new Map<string, Promise<Host>>();
|
|
10
|
+
|
|
11
|
+
/** Read an existing host without starting it. */
|
|
12
|
+
get(name: string): Host | undefined {
|
|
13
|
+
return this.#hosts.get(name);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Share one pending creation for each host name. */
|
|
17
|
+
start(name: string, create: () => Promise<Host> | Host): Promise<Host> {
|
|
18
|
+
const existing = this.#hosts.get(name);
|
|
19
|
+
if (existing) return Promise.resolve(existing);
|
|
20
|
+
const pending = this.#pending.get(name);
|
|
21
|
+
if (pending) return pending;
|
|
22
|
+
const operation = Promise.resolve()
|
|
23
|
+
.then(create)
|
|
24
|
+
.then((host) => {
|
|
25
|
+
this.#hosts.set(name, host);
|
|
26
|
+
return host;
|
|
27
|
+
})
|
|
28
|
+
.finally(() => {
|
|
29
|
+
this.#pending.delete(name);
|
|
30
|
+
});
|
|
31
|
+
this.#pending.set(name, operation);
|
|
32
|
+
return operation;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Remove the named host and wait for its cleanup. */
|
|
36
|
+
async stop(name: string): Promise<void> {
|
|
37
|
+
await this.#pending.get(name);
|
|
38
|
+
const host = this.#hosts.get(name);
|
|
39
|
+
if (!host) return;
|
|
40
|
+
this.#hosts.delete(name);
|
|
41
|
+
await host.close();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Close the old host before creating its replacement. */
|
|
45
|
+
async replace(name: string, create: () => Promise<Host> | Host): Promise<Host> {
|
|
46
|
+
await this.stop(name);
|
|
47
|
+
return this.start(name, create);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Wait for every managed host and report cleanup failures together. */
|
|
51
|
+
async close(): Promise<void> {
|
|
52
|
+
const names = new Set([...this.#hosts.keys(), ...this.#pending.keys()]);
|
|
53
|
+
const results = await Promise.allSettled([...names].map((name) => this.stop(name)));
|
|
54
|
+
const errors = results
|
|
55
|
+
.filter((result) => result.status === "rejected")
|
|
56
|
+
.map((result) => result.reason);
|
|
57
|
+
if (errors.length) throw new AggregateError(errors, "Host cleanup failed");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Route acquisitions to an application-selected host. */
|
|
62
|
+
export function router<
|
|
63
|
+
H extends {
|
|
64
|
+
/** Acquire a reference from the selected host. */
|
|
65
|
+
get(service: string, key: string | readonly string[], options?: any): any;
|
|
66
|
+
},
|
|
67
|
+
>(hosts: ReadonlyMap<string, H>, route: (service: string, key: readonly string[]) => string) {
|
|
68
|
+
return {
|
|
69
|
+
/** Choose the destination host before acquiring the reference. */
|
|
70
|
+
get(service: string, key: string | readonly string[], options?: any): ReturnType<H["get"]> {
|
|
71
|
+
const name = route(service, typeof key === "string" ? [key] : key);
|
|
72
|
+
const host = hosts.get(name);
|
|
73
|
+
if (!host) throw new TembraError(Errors.Unavailable.Route, name);
|
|
74
|
+
return host.get(service, key, options);
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Code } from "../../bridge/identifiers.ts";
|
|
2
|
+
import { RpcEvent, RpcOp } from "../../bridge/protocol.ts";
|
|
3
|
+
import type { Codec } from "../../codecs/json.ts";
|
|
4
|
+
import { jsonCodec } from "../../codecs/json.ts";
|
|
5
|
+
import { failure, TembraError } from "../../error.ts";
|
|
6
|
+
import { Errors } from "../../errors.ts";
|
|
7
|
+
|
|
8
|
+
/** Adapters for WebSocket, MessagePort, or an application channel implement this byte boundary. */
|
|
9
|
+
export interface Transport {
|
|
10
|
+
/** Send one encoded frame through the application transport. */
|
|
11
|
+
send(frame: Uint8Array): void | Promise<void>;
|
|
12
|
+
/** Register frame and connection callbacks until detached. */
|
|
13
|
+
listen(receive: (frame: Uint8Array) => void, closed: (error?: unknown) => void): () => void;
|
|
14
|
+
/** Close the underlying connection. */
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|
|
17
|
+
export interface Limits {
|
|
18
|
+
codec?: Codec;
|
|
19
|
+
maxFrame?: number;
|
|
20
|
+
maxPending?: number;
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
export interface Wire {
|
|
24
|
+
id?: number;
|
|
25
|
+
op?: RpcOp;
|
|
26
|
+
payload?: any;
|
|
27
|
+
ok?: any;
|
|
28
|
+
error?: { code: Code; reason: string; message: string };
|
|
29
|
+
event?: RpcEvent;
|
|
30
|
+
}
|
|
31
|
+
/** Produce the portable fields of a structured error. */
|
|
32
|
+
export function errorValue(error: unknown) {
|
|
33
|
+
const value = failure(error);
|
|
34
|
+
return { code: value.code, reason: value.reason, message: value.message };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class Channel {
|
|
38
|
+
readonly codec: Codec;
|
|
39
|
+
readonly maxFrame: number;
|
|
40
|
+
readonly maxPending: number;
|
|
41
|
+
closed = false;
|
|
42
|
+
#detach: () => void;
|
|
43
|
+
|
|
44
|
+
/** Attach the transport with frame limits and the chosen codec. */
|
|
45
|
+
constructor(
|
|
46
|
+
readonly transport: Transport,
|
|
47
|
+
readonly options: Limits,
|
|
48
|
+
receive: (message: Wire) => void,
|
|
49
|
+
readonly ended: (error: unknown) => void,
|
|
50
|
+
) {
|
|
51
|
+
this.codec = options.codec ?? jsonCodec;
|
|
52
|
+
this.maxFrame = options.maxFrame ?? 1024 * 1024;
|
|
53
|
+
this.maxPending = options.maxPending ?? 128;
|
|
54
|
+
this.#detach = transport.listen(
|
|
55
|
+
(frame) => {
|
|
56
|
+
if (this.closed) return;
|
|
57
|
+
try {
|
|
58
|
+
if (frame.length > this.maxFrame) throw new TembraError(Errors.Exhausted.FrameSize);
|
|
59
|
+
const message = this.codec.deserialize(frame);
|
|
60
|
+
if (!message || typeof message !== "object" || Array.isArray(message))
|
|
61
|
+
throw new TembraError(Errors.Invalid.RpcFrame);
|
|
62
|
+
receive(message);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
options.onError?.(error);
|
|
65
|
+
this.close(error);
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
(error) => this.close(error),
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Encode and size-check a message before transport delivery. */
|
|
73
|
+
async send(message: Wire): Promise<void> {
|
|
74
|
+
if (this.closed) throw new TembraError(Errors.Gone.Connection);
|
|
75
|
+
const frame = this.codec.serialize(message);
|
|
76
|
+
if (frame.length > this.maxFrame) throw new TembraError(Errors.Exhausted.FrameSize);
|
|
77
|
+
await this.transport.send(frame);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Detach the transport and reject connection work once. */
|
|
81
|
+
close(error: unknown = new TembraError(Errors.Gone.Connection)): void {
|
|
82
|
+
if (this.closed) return;
|
|
83
|
+
this.closed = true;
|
|
84
|
+
this.#detach?.();
|
|
85
|
+
this.transport.close();
|
|
86
|
+
this.ended(error);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { DynamicReference } from "../../authoring/types.ts";
|
|
2
|
+
import { Status } from "../../bridge/identifiers.ts";
|
|
3
|
+
import { RpcEvent, RpcOp } from "../../bridge/protocol.ts";
|
|
4
|
+
import { TembraError } from "../../error.ts";
|
|
5
|
+
import { Errors } from "../../errors.ts";
|
|
6
|
+
import type { Context } from "../../runtime/context.ts";
|
|
7
|
+
|
|
8
|
+
import { Channel, type Limits, type Transport } from "./channel.ts";
|
|
9
|
+
import { RemoteState } from "./state.ts";
|
|
10
|
+
|
|
11
|
+
/** A lost connection revokes its references. Reconnect by creating a peer and acquiring current state. */
|
|
12
|
+
export class RemoteHost {
|
|
13
|
+
readonly channel: Channel;
|
|
14
|
+
#next = 0;
|
|
15
|
+
#pending = new Map<
|
|
16
|
+
number,
|
|
17
|
+
{
|
|
18
|
+
/** Deliver the response to its pending caller. */
|
|
19
|
+
resolve(value: any): void;
|
|
20
|
+
/** Reject the caller when its request or connection fails. */
|
|
21
|
+
reject(error: unknown): void;
|
|
22
|
+
}
|
|
23
|
+
>();
|
|
24
|
+
#states = new Map<number, RemoteState>();
|
|
25
|
+
|
|
26
|
+
/** Attach response routing and revoke state on disconnect. */
|
|
27
|
+
constructor(transport: Transport, options: Limits = {}) {
|
|
28
|
+
this.channel = new Channel(
|
|
29
|
+
transport,
|
|
30
|
+
options,
|
|
31
|
+
(message) => {
|
|
32
|
+
if (message.event === RpcEvent.State) {
|
|
33
|
+
this.#states.get(message.payload.reference)?.adopt(message.payload.value);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const pending = message.id && this.#pending.get(message.id);
|
|
37
|
+
if (!pending) return;
|
|
38
|
+
this.#pending.delete(message.id!);
|
|
39
|
+
if (message.error) pending.reject(new TembraError(message.error));
|
|
40
|
+
else pending.resolve(message.ok);
|
|
41
|
+
},
|
|
42
|
+
(error) => {
|
|
43
|
+
for (const pending of this.#pending.values()) pending.reject(error);
|
|
44
|
+
this.#pending.clear();
|
|
45
|
+
this.#states.clear();
|
|
46
|
+
},
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Correlate one bounded remote request with optional cancellation. */
|
|
51
|
+
async request(op: RpcOp, payload: unknown, signal?: AbortSignal): Promise<any> {
|
|
52
|
+
signal?.throwIfAborted();
|
|
53
|
+
if (this.#pending.size >= this.channel.maxPending)
|
|
54
|
+
throw new TembraError(Errors.Exhausted.PendingRequests);
|
|
55
|
+
const id = ++this.#next;
|
|
56
|
+
if (!Number.isSafeInteger(id)) throw new TembraError(Errors.Exhausted.RequestIds);
|
|
57
|
+
let abort: (() => void) | undefined;
|
|
58
|
+
const result = new Promise((resolve, reject) => {
|
|
59
|
+
this.#pending.set(id, { resolve, reject });
|
|
60
|
+
abort = () => {
|
|
61
|
+
this.#pending.delete(id);
|
|
62
|
+
reject(signal?.reason ?? new TembraError(Errors.Cancelled.Request));
|
|
63
|
+
void this.channel.send({ op: RpcOp.Cancel, payload: { id } }).catch(() => {});
|
|
64
|
+
};
|
|
65
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
66
|
+
void this.channel.send({ id, op, payload }).catch((error) => {
|
|
67
|
+
this.#pending.delete(id);
|
|
68
|
+
reject(error);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
try {
|
|
72
|
+
return await result;
|
|
73
|
+
} finally {
|
|
74
|
+
if (abort) signal?.removeEventListener("abort", abort);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Request remote orb metadata without service activation. */
|
|
79
|
+
installedOrbs(): Promise<unknown> {
|
|
80
|
+
return this.request(RpcOp.Describe, null);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Acquire a remote reference and its current state snapshot. */
|
|
84
|
+
async get(
|
|
85
|
+
service: string,
|
|
86
|
+
key: string | readonly string[],
|
|
87
|
+
options: { signal?: AbortSignal } = {},
|
|
88
|
+
): Promise<DynamicReference> {
|
|
89
|
+
const acquired = await this.request(
|
|
90
|
+
RpcOp.Get,
|
|
91
|
+
{ service, key: typeof key === "string" ? [key] : key },
|
|
92
|
+
options.signal,
|
|
93
|
+
);
|
|
94
|
+
const id = acquired.reference as number;
|
|
95
|
+
let released = false;
|
|
96
|
+
const check = () => {
|
|
97
|
+
if (released) throw new TembraError(Errors.Released.Reference);
|
|
98
|
+
if (this.channel.closed) throw new TembraError(Errors.Gone.Connection);
|
|
99
|
+
};
|
|
100
|
+
const state = Object.hasOwn(acquired, "state")
|
|
101
|
+
? new RemoteState(acquired.state, check, (error) => this.channel.options.onError?.(error))
|
|
102
|
+
: undefined;
|
|
103
|
+
if (state) this.#states.set(id, state);
|
|
104
|
+
const target = {
|
|
105
|
+
ready: Promise.resolve(),
|
|
106
|
+
/** Read connection-aware status without sending a request. */
|
|
107
|
+
get status() {
|
|
108
|
+
return released ? Status.Released : peer.channel.closed ? Status.Gone : Status.Live;
|
|
109
|
+
},
|
|
110
|
+
/** Read the local mirror while the remote reference remains valid. */
|
|
111
|
+
get state() {
|
|
112
|
+
check();
|
|
113
|
+
if (!state) throw new TembraError(Errors.Invalid.State);
|
|
114
|
+
return state;
|
|
115
|
+
},
|
|
116
|
+
/** Release the remote claim once and stop retaining its state. */
|
|
117
|
+
release: () => {
|
|
118
|
+
if (released) return;
|
|
119
|
+
released = true;
|
|
120
|
+
this.#states.delete(id);
|
|
121
|
+
void this.request(RpcOp.Release, { reference: id }).catch((error) =>
|
|
122
|
+
this.channel.options.onError?.(error),
|
|
123
|
+
);
|
|
124
|
+
},
|
|
125
|
+
/** Reject opaque resources that cannot cross the transport. */
|
|
126
|
+
opaque() {
|
|
127
|
+
throw new TembraError(
|
|
128
|
+
Errors.Unsupported.RemoteOpaque,
|
|
129
|
+
"Opaque resources are local to their language environment",
|
|
130
|
+
);
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
const peer = this;
|
|
134
|
+
return new Proxy(target, {
|
|
135
|
+
/** Expose only methods included in the acquired remote contract. */
|
|
136
|
+
get: (target, property, receiver) => {
|
|
137
|
+
if (property === "then") return undefined;
|
|
138
|
+
if (Object.hasOwn(target, property)) return Reflect.get(target, property, receiver);
|
|
139
|
+
if (typeof property !== "string" || !acquired.methods.includes(property)) return undefined;
|
|
140
|
+
return async (...arguments_: unknown[]) => {
|
|
141
|
+
check();
|
|
142
|
+
const last = arguments_.at(-1) as Context | undefined;
|
|
143
|
+
const signal =
|
|
144
|
+
last && typeof last.check === "function" && "signal" in last
|
|
145
|
+
? (arguments_.pop() as Context).signal
|
|
146
|
+
: undefined;
|
|
147
|
+
return this.request(
|
|
148
|
+
RpcOp.Call,
|
|
149
|
+
{ reference: id, method: property, arguments: arguments_ },
|
|
150
|
+
signal,
|
|
151
|
+
);
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
}) as DynamicReference;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Close the connection and reject pending requests. */
|
|
158
|
+
close(): void {
|
|
159
|
+
this.channel.close();
|
|
160
|
+
}
|
|
161
|
+
}
|