@syntropika/tembra-sdk 0.1.0 → 0.2.1

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.
@@ -2,7 +2,7 @@ import { Lifetime, ReloadStatus, Status } from "../bridge/identifiers.ts";
2
2
  import type { Invocation, KernelOrb, KernelPort } from "../bridge/kernel.ts";
3
3
  import type { Codec } from "../codecs/json.ts";
4
4
  import type { Context } from "../runtime/context.ts";
5
- import type { Readable } from "../state.ts";
5
+ import type { Readable, State } from "../state.ts";
6
6
  import type { Declaration } from "./declaration.ts";
7
7
 
8
8
  export type Completion<T> = T | PromiseLike<T>;
@@ -102,6 +102,50 @@ export interface ReferenceBase<T = unknown> {
102
102
  }
103
103
  export type DynamicReference = ReferenceBase<any> & Record<string, any>;
104
104
 
105
+ type EnvironmentState<Environment> = 0 extends 1 & Environment
106
+ ? unknown
107
+ : Environment extends State<infer Value>
108
+ ? Value
109
+ : Environment extends object
110
+ ? {
111
+ [Member in keyof Environment]-?: Environment[Member] extends State<infer Value>
112
+ ? Value
113
+ : never;
114
+ }[keyof Environment]
115
+ : never;
116
+
117
+ type ServiceState<Service> = Service extends { create: (...args: never[]) => infer Environment }
118
+ ? [EnvironmentState<Environment>] extends [never]
119
+ ? unknown
120
+ : EnvironmentState<Environment>
121
+ : unknown;
122
+
123
+ type ArgumentTail<Arguments extends unknown[]> = Arguments extends []
124
+ ? []
125
+ : Arguments extends [unknown?, ...infer Rest]
126
+ ? Rest
127
+ : [];
128
+
129
+ type BusinessArguments<Arguments extends unknown[]> = ArgumentTail<ArgumentTail<Arguments>>;
130
+
131
+ // An optional tuple suffix after a rest parameter would also admit Context in the middle.
132
+ type CallArguments<Arguments extends unknown[]> = number extends Arguments["length"]
133
+ ? Arguments | [...Arguments, Context]
134
+ : [...Arguments, context?: Context];
135
+
136
+ type ConsumerMethod<Method> = Method extends (...args: infer Arguments) => infer Result
137
+ ? (...args: CallArguments<BusinessArguments<Arguments>>) => Promise<Awaited<Result>>
138
+ : never;
139
+
140
+ /** A managed reference inferred from one service's methods and explicitly returned State handles. */
141
+ export type ServiceReference<Service extends ServiceDefinition> = ReferenceBase<
142
+ ServiceState<Service>
143
+ > & {
144
+ [Method in Exclude<keyof Service["methods"], keyof ReferenceBase | "then">]: ConsumerMethod<
145
+ Service["methods"][Method]
146
+ >;
147
+ };
148
+
105
149
  export interface AcquisitionOptions {
106
150
  apiVersion?: number;
107
151
  methods?: readonly string[];
package/src/host.ts CHANGED
@@ -6,6 +6,9 @@ import type {
6
6
  HostOptions,
7
7
  ReloadOptions,
8
8
  ResourceOptions,
9
+ DynamicReference,
10
+ ServiceDefinition,
11
+ ServiceReference,
9
12
  } from "./authoring/types.ts";
10
13
  import { KernelOp } from "./bridge/protocol.ts";
11
14
  import { Context } from "./runtime/context.ts";
@@ -59,12 +62,40 @@ export class Host {
59
62
  }
60
63
 
61
64
  /** Acquire a reference before its asynchronous activation completes. */
62
- hold(service: string, key: string | readonly string[], options?: AcquisitionOptions) {
65
+ hold<const Service extends ServiceDefinition>(
66
+ service: Service,
67
+ key: string | readonly string[],
68
+ options?: AcquisitionOptions,
69
+ ): ServiceReference<Service>;
70
+ hold(
71
+ service: string,
72
+ key: string | readonly string[],
73
+ options?: AcquisitionOptions,
74
+ ): DynamicReference;
75
+ hold(
76
+ service: string | ServiceDefinition,
77
+ key: string | readonly string[],
78
+ options?: AcquisitionOptions,
79
+ ) {
63
80
  return this.session.handles.hold(service, key, options);
64
81
  }
65
82
 
66
83
  /** Acquire a reference and wait for activation. */
67
- get(service: string, key: string | readonly string[], options?: AcquisitionOptions) {
84
+ get<const Service extends ServiceDefinition>(
85
+ service: Service,
86
+ key: string | readonly string[],
87
+ options?: AcquisitionOptions,
88
+ ): Promise<ServiceReference<Service>>;
89
+ get(
90
+ service: string,
91
+ key: string | readonly string[],
92
+ options?: AcquisitionOptions,
93
+ ): Promise<DynamicReference>;
94
+ get(
95
+ service: string | ServiceDefinition,
96
+ key: string | readonly string[],
97
+ options?: AcquisitionOptions,
98
+ ) {
68
99
  return this.session.handles.get(service, key, options);
69
100
  }
70
101
 
@@ -11,8 +11,11 @@ export interface Transport {
11
11
  send(frame: Uint8Array): void | Promise<void>;
12
12
  /** Register frame and connection callbacks until detached. */
13
13
  listen(receive: (frame: Uint8Array) => void, closed: (error?: unknown) => void): () => void;
14
- /** Close the underlying connection. */
15
- close(): void;
14
+ /**
15
+ * Close after channel listeners detach, handling or ignoring the supplied terminal cause.
16
+ * Wrap platform methods; do not forward this cause to WebSocket.close(code), destroy(error), or end.
17
+ */
18
+ close(cause?: unknown): void;
16
19
  }
17
20
  export interface Limits {
18
21
  codec?: Codec;
@@ -61,7 +64,7 @@ export class Channel {
61
64
  throw new TembraError(Errors.Invalid.RpcFrame);
62
65
  receive(message);
63
66
  } catch (error) {
64
- options.onError?.(error);
67
+ this.#report(error);
65
68
  this.close(error);
66
69
  }
67
70
  },
@@ -69,6 +72,13 @@ export class Channel {
69
72
  );
70
73
  }
71
74
 
75
+ /** Report adapter failures without letting a reporter prevent connection cleanup. */
76
+ #report(error: unknown): void {
77
+ try {
78
+ this.options.onError?.(error);
79
+ } catch {}
80
+ }
81
+
72
82
  /** Encode and size-check a message before transport delivery. */
73
83
  async send(message: Wire): Promise<void> {
74
84
  if (this.closed) throw new TembraError(Errors.Gone.Connection);
@@ -81,8 +91,17 @@ export class Channel {
81
91
  close(error: unknown = new TembraError(Errors.Gone.Connection)): void {
82
92
  if (this.closed) return;
83
93
  this.closed = true;
84
- this.#detach?.();
85
- this.transport.close();
86
- this.ended(error);
94
+ try {
95
+ this.#detach?.();
96
+ } catch (detachError) {
97
+ this.#report(detachError);
98
+ }
99
+ try {
100
+ this.transport.close(error);
101
+ } catch (closeError) {
102
+ this.#report(closeError);
103
+ } finally {
104
+ this.ended(error);
105
+ }
87
106
  }
88
107
  }
@@ -48,7 +48,17 @@ export class RemoteHost {
48
48
  }
49
49
 
50
50
  /** Correlate one bounded remote request with optional cancellation. */
51
- async request(op: RpcOp, payload: unknown, signal?: AbortSignal): Promise<any> {
51
+ request(op: RpcOp, payload: unknown, signal?: AbortSignal): Promise<any> {
52
+ return this.#request(op, payload, signal);
53
+ }
54
+
55
+ /** Apply a response before resolving its caller so following frames see acquired state. */
56
+ async #request(
57
+ op: RpcOp,
58
+ payload: unknown,
59
+ signal?: AbortSignal,
60
+ received?: (value: any) => void,
61
+ ): Promise<any> {
52
62
  signal?.throwIfAborted();
53
63
  if (this.#pending.size >= this.channel.maxPending)
54
64
  throw new TembraError(Errors.Exhausted.PendingRequests);
@@ -56,14 +66,35 @@ export class RemoteHost {
56
66
  if (!Number.isSafeInteger(id)) throw new TembraError(Errors.Exhausted.RequestIds);
57
67
  let abort: (() => void) | undefined;
58
68
  const result = new Promise((resolve, reject) => {
59
- this.#pending.set(id, { resolve, reject });
69
+ const pending = {
70
+ resolve: (value: any) => {
71
+ try {
72
+ received?.(value);
73
+ resolve(value);
74
+ } catch (error) {
75
+ if (op === RpcOp.Get) this.#release(value?.reference);
76
+ reject(error);
77
+ }
78
+ },
79
+ reject,
80
+ };
81
+ this.#pending.set(id, pending);
60
82
  abort = () => {
61
- this.#pending.delete(id);
83
+ if (this.#pending.get(id) !== pending) return;
84
+ if (op === RpcOp.Get) {
85
+ this.#pending.set(id, {
86
+ resolve: (value) => this.#release(value?.reference),
87
+ reject: () => {},
88
+ });
89
+ } else {
90
+ this.#pending.delete(id);
91
+ }
62
92
  reject(signal?.reason ?? new TembraError(Errors.Cancelled.Request));
63
93
  void this.channel.send({ op: RpcOp.Cancel, payload: { id } }).catch(() => {});
64
94
  };
65
95
  signal?.addEventListener("abort", abort, { once: true });
66
96
  void this.channel.send({ id, op, payload }).catch((error) => {
97
+ if (this.#pending.get(id) !== pending) return;
67
98
  this.#pending.delete(id);
68
99
  reject(error);
69
100
  });
@@ -75,6 +106,17 @@ export class RemoteHost {
75
106
  }
76
107
  }
77
108
 
109
+ /** Release a late or unusable acquisition within the normal pending-request budget. */
110
+ #release(reference: unknown): void {
111
+ if (!Number.isSafeInteger(reference) || (reference as number) <= 0 || this.channel.closed)
112
+ return;
113
+ void this.request(RpcOp.Release, { reference }).catch((error) => {
114
+ try {
115
+ this.channel.options.onError?.(error);
116
+ } catch {}
117
+ });
118
+ }
119
+
78
120
  /** Request remote orb metadata without service activation. */
79
121
  installedOrbs(): Promise<unknown> {
80
122
  return this.request(RpcOp.Describe, null);
@@ -86,21 +128,34 @@ export class RemoteHost {
86
128
  key: string | readonly string[],
87
129
  options: { signal?: AbortSignal } = {},
88
130
  ): 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
131
  let released = false;
96
132
  const check = () => {
97
133
  if (released) throw new TembraError(Errors.Released.Reference);
98
134
  if (this.channel.closed) throw new TembraError(Errors.Gone.Connection);
99
135
  };
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);
136
+ let state: RemoteState | undefined;
137
+ const acquired = await this.#request(
138
+ RpcOp.Get,
139
+ { service, key: typeof key === "string" ? [key] : key },
140
+ options.signal,
141
+ (value) => {
142
+ if (
143
+ !value ||
144
+ !Number.isSafeInteger(value.reference) ||
145
+ value.reference <= 0 ||
146
+ !Array.isArray(value.methods) ||
147
+ !value.methods.every((method: unknown) => typeof method === "string")
148
+ )
149
+ throw new TembraError(Errors.Invalid.RpcFrame);
150
+ if (Object.hasOwn(value, "state")) {
151
+ state = new RemoteState(value.state, check, (error) =>
152
+ this.channel.options.onError?.(error),
153
+ );
154
+ this.#states.set(value.reference, state);
155
+ }
156
+ },
157
+ );
158
+ const id = acquired.reference as number;
104
159
  const target = {
105
160
  ready: Promise.resolve(),
106
161
  /** Read connection-aware status without sending a request. */
@@ -2,7 +2,12 @@ import { ContextKey, ContextKind, readContextValue } from "../context-key.ts";
2
2
  import { KernelOp } from "../bridge/protocol.ts";
3
3
  import { Errors } from "../errors.ts";
4
4
 
5
- import type { AcquisitionOptions, DynamicReference } from "../authoring/types.ts";
5
+ import type {
6
+ AcquisitionOptions,
7
+ DynamicReference,
8
+ ServiceDefinition,
9
+ ServiceReference,
10
+ } from "../authoring/types.ts";
6
11
  import type { Invocation } from "../bridge/kernel.ts";
7
12
  import { TembraError } from "../error.ts";
8
13
  import type { Session } from "./session.ts";
@@ -76,9 +81,19 @@ export class Context {
76
81
  }
77
82
 
78
83
  /** Acquire a reference whose claim ends with this root. */
84
+ get<const Service extends ServiceDefinition>(
85
+ service: Service,
86
+ key: string | readonly string[],
87
+ options?: AcquisitionOptions,
88
+ ): Promise<ServiceReference<Service>>;
79
89
  get(
80
90
  service: string,
81
91
  key: string | readonly string[],
92
+ options?: AcquisitionOptions,
93
+ ): Promise<DynamicReference>;
94
+ get(
95
+ service: string | ServiceDefinition,
96
+ key: string | readonly string[],
82
97
  options: AcquisitionOptions = {},
83
98
  ): Promise<DynamicReference> {
84
99
  this.check();
@@ -1,4 +1,5 @@
1
1
  import { consumerState } from "../authoring/declaration.ts";
2
+ import { serviceAcquisition } from "../authoring/services.ts";
2
3
  import type {
3
4
  AcquisitionOptions,
4
5
  DynamicReference,
@@ -96,11 +97,18 @@ export class References {
96
97
 
97
98
  /** Acquire ownership and create a local service handle. */
98
99
  hold(
99
- service: string,
100
+ definition: string | ServiceDefinition,
100
101
  key: string | readonly string[],
101
102
  options: AcquisitionOptions = {},
102
103
  ctx?: Context,
103
104
  ): DynamicReference {
105
+ let service: string;
106
+ if (typeof definition === "string") service = definition;
107
+ else {
108
+ const acquisition = serviceAcquisition(definition, options);
109
+ service = acquisition.name;
110
+ options = acquisition.options;
111
+ }
104
112
  const session = this.session;
105
113
  if (ctx) context(ctx, session);
106
114
  session.kernel.command(KernelOp.Tick, { now: session.now() });
@@ -248,7 +256,7 @@ export class References {
248
256
 
249
257
  /** Release the acquired claim if activation fails. */
250
258
  async get(
251
- service: string,
259
+ service: string | ServiceDefinition,
252
260
  key: string | readonly string[],
253
261
  options: AcquisitionOptions = {},
254
262
  ctx?: Context,