@kinotic-ai/core 5.0.0-beta.3 → 5.0.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,103 +5,196 @@ class ServerInfo {
5
5
  useSSL;
6
6
  }
7
7
  function buildServerUrl(server, scheme) {
8
- return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
8
+ const host = server.host.includes(":") && !server.host.startsWith("[") ? "[" + server.host + "]" : server.host;
9
+ return scheme + (server.useSSL ? "s" : "") + "://" + host + (server.port ? ":" + server.port : "");
9
10
  }
10
11
  function buildBrokerUrl(server) {
11
- return buildServerUrl(server, "ws") + "/v1";
12
+ return buildServerUrl(server, "ws") + "/api/v1";
12
13
  }
13
14
  var SessionKeepAliveMode;
14
- ((SessionKeepAliveMode2) => {
15
- SessionKeepAliveMode2["NONE"] = "NONE";
16
- SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
17
- SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
15
+ ((SessionKeepAliveMode) => {
16
+ SessionKeepAliveMode["NONE"] = "NONE";
17
+ SessionKeepAliveMode["ACTIVITY"] = "ACTIVITY";
18
+ SessionKeepAliveMode["CONNECTION"] = "CONNECTION";
18
19
  })(SessionKeepAliveMode ||= {});
19
20
  // packages/core/src/api/event/IEventBus.ts
20
21
  var EventConstants;
21
- ((EventConstants2) => {
22
- EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
23
- EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
24
- EventConstants2["REPLY_TO_HEADER"] = "reply-to";
25
- EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
26
- EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
27
- EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
28
- EventConstants2["ORIGIN_CRI_HEADER"] = "__origin-cri";
29
- EventConstants2["ERROR_HEADER"] = "error";
30
- EventConstants2["COMPLETE_HEADER"] = "complete";
31
- EventConstants2["CONTROL_HEADER"] = "control";
32
- EventConstants2["CONTROL_VALUE_COMPLETE"] = "complete";
33
- EventConstants2["CONTROL_VALUE_CANCEL"] = "cancel";
34
- EventConstants2["CONTROL_VALUE_SUSPEND"] = "suspend";
35
- EventConstants2["CONTROL_VALUE_RESUME"] = "resume";
36
- EventConstants2["SERVICE_DESTINATION_PREFIX"] = "srv://";
37
- EventConstants2["SERVICE_DESTINATION_SCHEME"] = "srv";
38
- EventConstants2["STREAM_DESTINATION_PREFIX"] = "stream://";
39
- EventConstants2["STREAM_DESTINATION_SCHEME"] = "stream";
40
- EventConstants2["REPLY_DESTINATION_PREFIX"] = "reply://";
41
- EventConstants2["REPLY_DESTINATION_SCHEME"] = "reply";
42
- EventConstants2["CONTENT_JSON"] = "application/json";
43
- EventConstants2["CONTENT_TEXT"] = "text/plain";
44
- EventConstants2["CONTENT_OCTET_STREAM"] = "application/octet-stream";
45
- EventConstants2["TRACEPARENT_HEADER"] = "traceparent";
46
- EventConstants2["TRACESTATE_HEADER"] = "tracestate";
22
+ ((EventConstants) => {
23
+ EventConstants["CONTENT_TYPE_HEADER"] = "content-type";
24
+ EventConstants["CONTENT_LENGTH_HEADER"] = "content-length";
25
+ EventConstants["REPLY_TO_HEADER"] = "reply-to";
26
+ EventConstants["SENDER_HEADER"] = "sender";
27
+ EventConstants["CONNECTED_INFO_HEADER"] = "connected-info";
28
+ EventConstants["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
29
+ EventConstants["CORRELATION_ID_HEADER"] = "__correlation-id";
30
+ EventConstants["ORIGIN_CRI_HEADER"] = "__origin-cri";
31
+ EventConstants["ERROR_HEADER"] = "error";
32
+ EventConstants["COMPLETE_HEADER"] = "complete";
33
+ EventConstants["CONTROL_HEADER"] = "control";
34
+ EventConstants["CONTROL_VALUE_COMPLETE"] = "complete";
35
+ EventConstants["CONTROL_VALUE_CANCEL"] = "cancel";
36
+ EventConstants["CONTROL_VALUE_SUSPEND"] = "suspend";
37
+ EventConstants["CONTROL_VALUE_RESUME"] = "resume";
38
+ EventConstants["SERVICE_DESTINATION_PREFIX"] = "srv://";
39
+ EventConstants["SERVICE_DESTINATION_SCHEME"] = "srv";
40
+ EventConstants["STREAM_DESTINATION_PREFIX"] = "stream://";
41
+ EventConstants["STREAM_DESTINATION_SCHEME"] = "stream";
42
+ EventConstants["REPLY_DESTINATION_PREFIX"] = "reply://";
43
+ EventConstants["REPLY_DESTINATION_SCHEME"] = "reply";
44
+ EventConstants["CONTENT_JSON"] = "application/json";
45
+ EventConstants["CONTENT_TEXT"] = "text/plain";
46
+ EventConstants["CONTENT_OCTET_STREAM"] = "application/octet-stream";
47
+ EventConstants["TRACEPARENT_HEADER"] = "traceparent";
48
+ EventConstants["TRACESTATE_HEADER"] = "tracestate";
47
49
  })(EventConstants ||= {});
48
50
 
51
+ // packages/core/src/internal/api/Logger.ts
52
+ import debug from "debug";
53
+ function createDebugLogger(namespace) {
54
+ const debugLogger = debug(namespace);
55
+ return {
56
+ trace: (...args) => debugLogger("TRACE", ...args),
57
+ debug: (...args) => debugLogger("DEBUG", ...args),
58
+ info: (...args) => debugLogger("INFO", ...args),
59
+ warn: (...args) => debugLogger("WARN", ...args),
60
+ error: (...args) => debugLogger("ERROR", ...args)
61
+ };
62
+ }
63
+
49
64
  // packages/core/src/internal/api/StompConnectionManager.ts
50
- import { RxStomp } from "@stomp/rx-stomp";
65
+ import { RxStomp, RxStompState } from "@stomp/rx-stomp";
51
66
  import { ReconnectionTimeMode } from "@stomp/stompjs";
52
- import debug from "debug";
67
+ import debug2 from "debug";
53
68
  import { Subject } from "rxjs";
69
+ import { skip } from "rxjs/operators";
54
70
  import { v4 as uuidv4 } from "uuid";
71
+
72
+ // packages/core/src/internal/api/StompActivation.ts
73
+ class StompActivation {
74
+ _ended = false;
75
+ wake = null;
76
+ preparedSocket = null;
77
+ attempt = null;
78
+ failPending = null;
79
+ abortController = new AbortController;
80
+ subscriptions = [];
81
+ get ended() {
82
+ return this._ended;
83
+ }
84
+ get signal() {
85
+ return this.abortController.signal;
86
+ }
87
+ end() {
88
+ this._ended = true;
89
+ this.wake?.();
90
+ this.wake = null;
91
+ this.abortController.abort();
92
+ }
93
+ delay(ms) {
94
+ return new Promise((resolve) => {
95
+ const timer = setTimeout(() => {
96
+ this.wake = null;
97
+ resolve();
98
+ }, ms);
99
+ this.wake = () => {
100
+ clearTimeout(timer);
101
+ resolve();
102
+ };
103
+ });
104
+ }
105
+ own(subscription) {
106
+ this.subscriptions.push(subscription);
107
+ }
108
+ pending(fail) {
109
+ this.failPending = fail;
110
+ }
111
+ established() {
112
+ this.failPending = null;
113
+ }
114
+ failIfPending(reason) {
115
+ const fail = this.failPending;
116
+ this.failPending = null;
117
+ fail?.(reason);
118
+ }
119
+ unsubscribeAll() {
120
+ for (const subscription of this.subscriptions) {
121
+ subscription.unsubscribe();
122
+ }
123
+ this.subscriptions.length = 0;
124
+ }
125
+ }
126
+
127
+ // packages/core/src/internal/api/StompConnectionManager.ts
55
128
  var SESSION_CHECK_PATH = "/api/auth/me";
56
129
 
57
130
  class StompConnectionManager {
58
131
  lastWebsocketError = null;
59
132
  maxConnectionAttemptsReached = false;
60
- replyToCriChangedHandler = null;
61
- rxStomp = null;
133
+ connectionEndedHandler = null;
134
+ rxStomp = new RxStomp;
135
+ activation = null;
136
+ teardown = null;
62
137
  INITIAL_RECONNECT_DELAY = 2000;
63
138
  JITTER_MAX = 5000;
64
139
  MAX_RECONNECT_DELAY = 120000;
140
+ CONNECTION_TIMEOUT = 1e4;
65
141
  connectionAttempts = 0;
66
- debugLogger = debug("kinoitc:stomp");
67
- fatalErrorsSubject = new Subject;
68
- _fatalErrors = this.fatalErrorsSubject.asObservable();
142
+ debugLogger = debug2("kinotic:stomp");
143
+ connectionEstablishedSubject = new Subject;
144
+ connectionAttemptFailedSubject = new Subject;
69
145
  initialConnectionSuccessful = false;
70
- serverHeadersSubscription = null;
71
- stompErrorsSubscription = null;
72
- uuidv4 = uuidv4();
146
+ rxStompHasConnected = false;
73
147
  _replyToCri = null;
74
148
  get replyToCri() {
75
149
  return this._replyToCri;
76
150
  }
77
151
  get active() {
78
- return !!this.rxStomp;
152
+ return this.activation !== null;
79
153
  }
80
154
  get connected() {
81
- return this.rxStomp != null && this.rxStomp.connected();
155
+ return this.activation !== null && this.rxStomp.connected();
82
156
  }
83
- get fatalErrors() {
84
- return this._fatalErrors;
157
+ get connectionEstablished() {
158
+ return this.connectionEstablishedSubject.asObservable();
159
+ }
160
+ get connectionAttemptFailed() {
161
+ return this.connectionAttemptFailedSubject.asObservable();
85
162
  }
86
163
  async activate(options) {
87
164
  if (!options?.server?.host) {
88
165
  throw new Error("No host provided");
89
166
  }
90
- if (this.rxStomp) {
167
+ if (this.activation) {
168
+ throw new Error("Stomp connection already active");
169
+ }
170
+ await this.teardown;
171
+ if (this.activation) {
91
172
  throw new Error("Stomp connection already active");
92
173
  }
93
174
  const server = options.server;
94
175
  const credentialsResolver = options.credentials;
176
+ const activation = new StompActivation;
177
+ this.activation = activation;
95
178
  let headerAuth = false;
96
- if (!options.webSocketFactory) {
97
- if (!credentialsResolver) {
98
- throw new Error("No credentials supplied and no default resolution applied");
179
+ try {
180
+ if (!options.webSocketFactory) {
181
+ if (!credentialsResolver) {
182
+ throw new Error("No credentials supplied and no default resolution applied");
183
+ }
184
+ const resolved = await credentialsResolver.resolve(server);
185
+ if (resolved === null) {
186
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
187
+ }
188
+ headerAuth = resolved.authHeaders != null;
189
+ }
190
+ if (activation.ended) {
191
+ throw new Error("Deactivated before the connection was established");
99
192
  }
100
- const resolved = await credentialsResolver.resolve(server);
101
- if (resolved === null) {
102
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
193
+ } catch (e) {
194
+ if (this.activation === activation) {
195
+ this.activation = null;
103
196
  }
104
- headerAuth = resolved.authHeaders != null;
197
+ throw e;
105
198
  }
106
199
  return new Promise((resolve, reject) => {
107
200
  this.connectionAttempts = 0;
@@ -109,63 +202,29 @@ class StompConnectionManager {
109
202
  this.lastWebsocketError = null;
110
203
  this.maxConnectionAttemptsReached = false;
111
204
  const url = buildBrokerUrl(server);
112
- this.rxStomp = new RxStomp;
113
- let preparedSocket = null;
114
- const userWebSocketFactory = options.webSocketFactory;
115
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
205
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
206
+ const takePreparedSocket = () => {
207
+ const socket = activation.preparedSocket;
208
+ activation.preparedSocket = null;
209
+ return socket;
210
+ };
116
211
  const stompConfig = {
117
212
  brokerURL: url,
118
213
  connectHeaders: {
119
214
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
120
215
  },
121
- heartbeatIncoming: 120000,
216
+ heartbeatIncoming: 30000,
122
217
  heartbeatOutgoing: 30000,
218
+ connectionTimeout: this.CONNECTION_TIMEOUT,
123
219
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
124
220
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
125
221
  reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
126
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
127
- beforeConnect: async () => {
128
- if (!usesPreparedSocket) {
129
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
130
- try {
131
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
132
- if (res.status === 401) {
133
- await this.signalFatal(new Error("Authentication required"));
134
- return;
135
- }
136
- } catch {}
137
- }
138
- if (options?.maxConnectionAttempts) {
139
- this.connectionAttempts++;
140
- if (this.connectionAttempts > options.maxConnectionAttempts) {
141
- this.maxConnectionAttemptsReached = true;
142
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
143
- return;
144
- } else {
145
- await this.connectionJitterDelay();
146
- }
147
- } else {
148
- await this.connectionJitterDelay();
149
- }
150
- if (userWebSocketFactory) {
151
- try {
152
- preparedSocket = await userWebSocketFactory();
153
- } catch (e) {
154
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
155
- }
156
- } else if (headerAuth) {
157
- try {
158
- const resolved = await credentialsResolver.resolve(server);
159
- if (resolved?.authHeaders == null) {
160
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
161
- } else {
162
- const WS = WebSocket;
163
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
164
- }
165
- } catch (e) {
166
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
167
- }
168
- }
222
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
223
+ beforeConnect: () => {
224
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
225
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
226
+ activation.attempt = attempt.then(settled, settled);
227
+ return attempt;
169
228
  }
170
229
  };
171
230
  if (this.debugLogger.enabled) {
@@ -174,93 +233,209 @@ class StompConnectionManager {
174
233
  };
175
234
  }
176
235
  this.rxStomp.configure(stompConfig);
177
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
236
+ activation.own(this.rxStomp.webSocketErrors$.subscribe((value) => {
178
237
  this.lastWebsocketError = value;
179
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
180
- this.maxConnectionAttemptsReached = true;
181
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
182
- }
183
- });
184
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
238
+ }));
239
+ activation.own(this.rxStomp.stompErrors$.subscribe((frame) => {
185
240
  const stompError = new Error(frame.headers["message"], { cause: frame });
186
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
187
- });
188
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
189
- connectedSubscription.unsubscribe();
190
- initialFailureSubscription.unsubscribe();
191
- if (!this.initialConnectionSuccessful) {
192
- this.initialConnectionSuccessful = true;
193
- }
194
- });
195
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
196
- connectedSubscription.unsubscribe();
197
- initialFailureSubscription.unsubscribe();
198
- reject(err.message);
199
- });
200
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
241
+ this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
242
+ }));
243
+ activation.own(this.rxStomp.connected$.subscribe(() => {
244
+ activation.established();
245
+ this.initialConnectionSuccessful = true;
246
+ this.connectionAttempts = 0;
247
+ }));
248
+ activation.pending(reject);
249
+ activation.own(this.rxStomp.serverHeaders$.pipe(skip(this.rxStompHasConnected ? 1 : 0)).subscribe((value) => {
250
+ this.rxStompHasConnected = true;
201
251
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
202
252
  if (connectedInfoJson == null) {
203
253
  if (!this.initialConnectionSuccessful) {
204
- await this.deactivate();
205
- reject("Server did not return proper data for successful login");
254
+ this.failConnection(activation, new Error("Server did not return proper data for successful login"));
206
255
  }
207
256
  return;
208
257
  }
209
258
  const connectedInfo = JSON.parse(connectedInfoJson);
210
259
  if (connectedInfo.replyToId == null) {
211
260
  if (!this.initialConnectionSuccessful) {
212
- await this.deactivate();
213
- reject("Server did not return a replyToId for successful login");
261
+ this.failConnection(activation, new Error("Server did not return a replyToId for successful login"));
214
262
  }
215
263
  return;
216
264
  }
217
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
265
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + uuidv4() + "@kinotic.js.EventBus/replyHandler";
266
+ this._replyToCri = newReplyToCri;
218
267
  if (!this.initialConnectionSuccessful) {
219
- this._replyToCri = newReplyToCri;
220
268
  resolve(connectedInfo);
221
- } else if (this._replyToCri !== newReplyToCri) {
222
- this._replyToCri = newReplyToCri;
223
- this.replyToCriChangedHandler?.(newReplyToCri);
224
269
  }
225
- });
270
+ this.connectionEstablishedSubject.next(connectedInfo);
271
+ }));
272
+ let previousState = this.rxStomp.connectionState$.getValue();
273
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
274
+ if (state === RxStompState.CLOSED && this.activation === activation) {
275
+ if (previousState === RxStompState.OPEN) {
276
+ this.connectionEndedHandler?.(null);
277
+ } else if (previousState === RxStompState.CONNECTING) {
278
+ if (options.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
279
+ this.maxConnectionAttemptsReached = true;
280
+ this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
281
+ } else {
282
+ this.connectionAttemptFailedSubject.next();
283
+ }
284
+ }
285
+ }
286
+ previousState = state;
287
+ }));
226
288
  this.rxStomp.activate();
227
289
  });
228
290
  }
229
- async deactivate(force) {
230
- const rxStomp = this.rxStomp;
231
- if (rxStomp) {
232
- await rxStomp.deactivate({ force });
233
- if (this.rxStomp === rxStomp) {
234
- this.serverHeadersSubscription?.unsubscribe();
235
- this.serverHeadersSubscription = null;
236
- this.stompErrorsSubscription?.unsubscribe();
237
- this.stompErrorsSubscription = null;
238
- this.rxStomp = null;
239
- this._replyToCri = null;
291
+ async prepareAttempt(activation, options, server, headerAuth) {
292
+ const credentialsResolver = options.credentials;
293
+ const userWebSocketFactory = options.webSocketFactory;
294
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
295
+ const url = buildBrokerUrl(server);
296
+ if (!usesPreparedSocket) {
297
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
298
+ try {
299
+ const res = await fetch(sessionCheckUrl, {
300
+ credentials: "include",
301
+ signal: AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)])
302
+ });
303
+ if (res.status === 401) {
304
+ this.failConnection(activation, new Error("Authentication required"));
305
+ return;
306
+ }
307
+ } catch (e) {
308
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
309
+ }
310
+ }
311
+ if (options?.maxConnectionAttempts) {
312
+ this.connectionAttempts++;
313
+ }
314
+ await this.connectionJitterDelay(activation);
315
+ if (activation.ended) {
316
+ return;
317
+ }
318
+ if (userWebSocketFactory) {
319
+ try {
320
+ activation.preparedSocket = await userWebSocketFactory();
321
+ } catch (e) {
322
+ this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
323
+ }
324
+ } else if (headerAuth) {
325
+ try {
326
+ const resolved = await credentialsResolver.resolve(server);
327
+ if (resolved?.authHeaders == null) {
328
+ this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
329
+ } else {
330
+ const WS = WebSocket;
331
+ const socket = new WS(url, { headers: resolved.authHeaders });
332
+ this.endOnRejectedUpgrade(activation, socket);
333
+ activation.preparedSocket = socket;
334
+ }
335
+ } catch (e) {
336
+ this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
337
+ }
338
+ }
339
+ if (activation.ended && activation.preparedSocket) {
340
+ activation.preparedSocket.close();
341
+ activation.preparedSocket = null;
342
+ }
343
+ }
344
+ endOnRejectedUpgrade(activation, socket) {
345
+ const emitter = socket;
346
+ if (typeof emitter.on === "function") {
347
+ emitter.on("unexpected-response", (_request, response) => {
348
+ const status = response.statusCode ?? 0;
349
+ if (status >= 400 && status < 500) {
350
+ this.failConnection(activation, new Error("Connection rejected with status " + status));
351
+ }
352
+ socket.close();
353
+ });
354
+ }
355
+ }
356
+ deactivate(force, reason = null) {
357
+ const activation = this.activation;
358
+ let ret;
359
+ if (activation) {
360
+ this.activation = null;
361
+ activation.end();
362
+ const wasOpen = this.rxStomp.connected();
363
+ this._replyToCri = null;
364
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
365
+ activation.preparedSocket?.close();
366
+ activation.preparedSocket = null;
367
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
368
+ activation.unsubscribeAll();
369
+ this.teardown = null;
370
+ });
371
+ this.teardown = teardown;
372
+ if (wasOpen || reason !== null) {
373
+ this.connectionEndedHandler?.(reason);
240
374
  }
375
+ ret = teardown;
376
+ } else {
377
+ ret = this.teardown ?? Promise.resolve();
241
378
  }
242
- return;
379
+ return ret;
243
380
  }
244
- async connectionJitterDelay() {
381
+ async connectionJitterDelay(activation) {
245
382
  if (this.initialConnectionSuccessful) {
246
383
  const randomJitter = Math.random() * this.JITTER_MAX;
247
384
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
248
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
385
+ await activation.delay(randomJitter);
249
386
  }
250
387
  }
251
- async signalFatal(err) {
252
- this.debugLogger("Fatal error, deactivating connection: %O", err);
253
- await this.deactivate();
254
- this.fatalErrorsSubject.next(err);
388
+ failConnection(activation, err) {
389
+ if (!activation.ended) {
390
+ this.debugLogger("Connection failed, ending it: %O", err);
391
+ this.deactivate(undefined, err).catch((e) => this.debugLogger("Closing the failed connection failed: %O", e));
392
+ }
255
393
  }
256
394
  }
257
395
 
258
396
  // packages/core/src/api/event/EventBus.ts
259
397
  import { context, propagation } from "@opentelemetry/api";
260
- import { firstValueFrom, Observable as Observable2, Subject as Subject2, throwError } from "rxjs";
398
+ import { firstValueFrom, Observable as Observable2, Subject as Subject2 } from "rxjs";
261
399
  import { filter, map, multicast, tap } from "rxjs/operators";
262
400
  import { Optional } from "typescript-optional";
263
401
  import { v4 as uuidv42 } from "uuid";
402
+
403
+ // packages/core/src/api/event/RpcError.ts
404
+ class RpcError extends Error {
405
+ exceptionName;
406
+ exceptionClass;
407
+ constructor(message, exceptionName, exceptionClass) {
408
+ super(message);
409
+ this.name = "RpcError";
410
+ this.exceptionName = exceptionName;
411
+ this.exceptionClass = exceptionClass;
412
+ }
413
+ static fromEvent(reply) {
414
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
415
+ let ret;
416
+ const detail = describedException(reply);
417
+ if (detail !== undefined) {
418
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
419
+ } else {
420
+ ret = new RpcError(message, "", "");
421
+ }
422
+ return ret;
423
+ }
424
+ }
425
+ function describedException(reply) {
426
+ let ret = undefined;
427
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
428
+ try {
429
+ const parsed = JSON.parse(reply.getDataString());
430
+ if (parsed !== null && typeof parsed === "object") {
431
+ ret = parsed;
432
+ }
433
+ } catch {}
434
+ }
435
+ return ret;
436
+ }
437
+
438
+ // packages/core/src/api/event/EventBus.ts
264
439
  class Event {
265
440
  cri;
266
441
  headers;
@@ -299,24 +474,34 @@ class Event {
299
474
 
300
475
  class EventBus {
301
476
  serverInfo = null;
477
+ log = createDebugLogger("kinotic:EventBus");
302
478
  stompConnectionManager = new StompConnectionManager;
303
479
  connectionLifecycle = Promise.resolve();
304
- replyToCri = null;
480
+ disconnectRequests = 0;
305
481
  requestRepliesObservable = null;
306
482
  requestRepliesSubject = null;
307
483
  requestRepliesSubscription = null;
308
484
  activeCorrelationIds = new Set;
309
485
  recentlyReaped = new Set;
486
+ connectionEndedSubject = new Subject2;
310
487
  static REAP_DEBOUNCE_MS = 5000;
311
488
  constructor() {
312
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
313
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
314
- this.replyToCri = replyToCri;
315
- this.resetRequestReplies("Reply destination changed");
489
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
490
+ this.resetRequestReplies("Connection lost");
491
+ if (!this.stompConnectionManager.active) {
492
+ this.serverInfo = null;
493
+ }
494
+ this.connectionEndedSubject.next(reason);
316
495
  };
317
496
  }
318
- get fatalErrors() {
319
- return this.stompConnectionManager.fatalErrors;
497
+ get connectionEnded() {
498
+ return this.connectionEndedSubject.asObservable();
499
+ }
500
+ get connectionEstablished() {
501
+ return this.stompConnectionManager.connectionEstablished;
502
+ }
503
+ get connectionAttemptFailed() {
504
+ return this.stompConnectionManager.connectionAttemptFailed;
320
505
  }
321
506
  isConnectionActive() {
322
507
  return this.stompConnectionManager.active;
@@ -325,12 +510,14 @@ class EventBus {
325
510
  return this.stompConnectionManager.connected;
326
511
  }
327
512
  connect(options) {
513
+ const disconnectsWhenQueued = this.disconnectRequests;
328
514
  return this.serializeLifecycle(async () => {
515
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
516
+ throw new Error("Disconnected before the connection was started");
517
+ }
329
518
  if (!this.stompConnectionManager.active) {
330
- this.cleanup();
331
519
  const connectedInfo = await this.stompConnectionManager.activate(options);
332
520
  this.serverInfo = { ...options.server };
333
- this.replyToCri = this.stompConnectionManager.replyToCri;
334
521
  return connectedInfo;
335
522
  } else {
336
523
  throw new Error("Event Bus connection already active");
@@ -338,9 +525,12 @@ class EventBus {
338
525
  });
339
526
  }
340
527
  disconnect(force) {
528
+ this.disconnectRequests++;
529
+ const deactivated = this.stompConnectionManager.deactivate(force);
341
530
  return this.serializeLifecycle(async () => {
531
+ await deactivated;
342
532
  await this.stompConnectionManager.deactivate(force);
343
- this.cleanup();
533
+ this.serverInfo = null;
344
534
  });
345
535
  }
346
536
  serializeLifecycle(operation) {
@@ -349,7 +539,7 @@ class EventBus {
349
539
  return result;
350
540
  }
351
541
  send(event) {
352
- if (this.stompConnectionManager.rxStomp) {
542
+ if (this.stompConnectionManager.connected) {
353
543
  const headers = {};
354
544
  for (const [key, value] of event.headers.entries()) {
355
545
  headers[key] = value;
@@ -365,7 +555,8 @@ class EventBus {
365
555
  this.stompConnectionManager.rxStomp.publish({
366
556
  destination: event.cri,
367
557
  headers,
368
- binaryBody: event.data.orUndefined()
558
+ binaryBody: event.data.orUndefined(),
559
+ retryIfDisconnected: false
369
560
  });
370
561
  } else {
371
562
  throw this.createSendUnavailableError();
@@ -375,58 +566,65 @@ class EventBus {
375
566
  return firstValueFrom(this.requestStream(event, false));
376
567
  }
377
568
  requestStream(event, sendControlEvents = true) {
378
- if (this.stompConnectionManager?.rxStomp) {
379
- return new Observable2((subscriber) => {
380
- if (this.requestRepliesObservable == null) {
381
- this.requestRepliesSubject = new Subject2;
382
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
383
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
384
- }
385
- let serverSignaledCompletion = false;
386
- const correlationId = uuidv42();
387
- this.activeCorrelationIds.add(correlationId);
388
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
389
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
390
- })).subscribe({
391
- next(value) {
392
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
393
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
394
- serverSignaledCompletion = true;
395
- subscriber.complete();
396
- } else {
397
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
398
- }
399
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
569
+ return new Observable2((subscriber) => {
570
+ const replyToCri = this.stompConnectionManager.replyToCri;
571
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
572
+ subscriber.error(this.createSendUnavailableError());
573
+ return;
574
+ }
575
+ if (this.requestRepliesObservable == null) {
576
+ this.requestRepliesSubject = new Subject2;
577
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
578
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
579
+ }
580
+ let serverSignaledCompletion = false;
581
+ let replyDestinationReset = false;
582
+ const correlationId = uuidv42();
583
+ this.activeCorrelationIds.add(correlationId);
584
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
585
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
586
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
587
+ })).subscribe({
588
+ next(value) {
589
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
590
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
400
591
  serverSignaledCompletion = true;
401
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
592
+ if (value.data.isPresent() || !sendControlEvents) {
593
+ subscriber.next(value);
594
+ }
595
+ subscriber.complete();
402
596
  } else {
403
- subscriber.next(value);
597
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
404
598
  }
405
- },
406
- error(err) {
407
- subscriber.error(err);
408
- },
409
- complete() {
410
- subscriber.complete();
599
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
600
+ serverSignaledCompletion = true;
601
+ subscriber.error(RpcError.fromEvent(value));
602
+ } else {
603
+ subscriber.next(value);
411
604
  }
412
- });
413
- subscriber.add(defaultMessagesSubscription);
414
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
415
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
416
- this.send(event);
417
- return () => {
418
- this.activeCorrelationIds.delete(correlationId);
419
- if (sendControlEvents && !serverSignaledCompletion) {
420
- const controlEvent = new Event(event.cri);
421
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
422
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
423
- this.send(controlEvent);
605
+ },
606
+ error(err) {
607
+ replyDestinationReset = true;
608
+ subscriber.error(err);
609
+ },
610
+ complete() {
611
+ subscriber.complete();
612
+ }
613
+ });
614
+ subscriber.add(defaultMessagesSubscription);
615
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
616
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
617
+ this.send(event);
618
+ subscriber.add(() => {
619
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
620
+ try {
621
+ this.sendCancel(event.cri, correlationId);
622
+ } catch (e) {
623
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
424
624
  }
425
- };
625
+ }
426
626
  });
427
- } else {
428
- return throwError(() => this.createSendUnavailableError());
429
- }
627
+ });
430
628
  }
431
629
  listen(_serverInfo) {
432
630
  return Promise.reject("Not implemented");
@@ -434,10 +632,6 @@ class EventBus {
434
632
  observe(cri) {
435
633
  return this._observe(cri);
436
634
  }
437
- cleanup() {
438
- this.resetRequestReplies("Connection disconnected");
439
- this.serverInfo = null;
440
- }
441
635
  cancelIfUnexpected(value) {
442
636
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
443
637
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -448,13 +642,19 @@ class EventBus {
448
642
  return;
449
643
  }
450
644
  try {
451
- const cancelEvent = new Event(originCri);
452
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
453
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
454
- this.send(cancelEvent);
645
+ this.sendCancel(originCri, correlationId);
455
646
  this.recentlyReaped.add(correlationId);
456
647
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
457
- } catch {}
648
+ } catch (e) {
649
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
650
+ }
651
+ }
652
+ sendCancel(cri, correlationId) {
653
+ const cancelEvent = new Event(cri);
654
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
655
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
656
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
657
+ this.send(cancelEvent);
458
658
  }
459
659
  resetRequestReplies(reason) {
460
660
  if (this.requestRepliesSubject != null) {
@@ -469,29 +669,29 @@ class EventBus {
469
669
  }
470
670
  }
471
671
  createSendUnavailableError() {
472
- let ret = "You must call connect on the event bus before sending any request";
672
+ let ret;
473
673
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
474
674
  ret = "Max connection attempts reached event bus is not available";
675
+ } else if (this.stompConnectionManager.active) {
676
+ ret = "The event bus is not connected to the server";
677
+ } else {
678
+ ret = "You must call connect on the event bus before sending any request";
475
679
  }
476
680
  return new Error(ret);
477
681
  }
478
682
  _observe(cri) {
479
- if (this.stompConnectionManager?.rxStomp) {
480
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
481
- const headers = new Map;
482
- let destination = "";
483
- for (const prop of Object.keys(message.headers)) {
484
- if (prop === "destination") {
485
- destination = message.headers[prop];
486
- } else {
487
- headers.set(prop, message.headers[prop]);
488
- }
683
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
684
+ const headers = new Map;
685
+ let destination = "";
686
+ for (const prop of Object.keys(message.headers)) {
687
+ if (prop === "destination") {
688
+ destination = message.headers[prop];
689
+ } else {
690
+ headers.set(prop, message.headers[prop]);
489
691
  }
490
- return new Event(destination, headers, message.binaryBody);
491
- }));
492
- } else {
493
- throw this.createSendUnavailableError();
494
- }
692
+ }
693
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
694
+ }));
495
695
  }
496
696
  }
497
697
 
@@ -569,7 +769,8 @@ class SessionCredentialsResolver {
569
769
 
570
770
  // packages/core/src/internal/api/Util.ts
571
771
  var DEFAULT_PORT = 58503;
572
- var DEFAULT_HOST = "api.kinotic.com";
772
+ var DEFAULT_HOST = "api.kinotic.ai";
773
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
573
774
 
574
775
  class Util {
575
776
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -600,7 +801,6 @@ class Util {
600
801
  const location = typeof window !== "undefined" ? window.location : undefined;
601
802
  let host = server.host ?? env?.KINOTIC_SERVER_HOST;
602
803
  const hostFromLocation = host == null && location != null;
603
- const hostDefaulted = host == null && location == null;
604
804
  if (host == null) {
605
805
  host = location?.hostname ?? DEFAULT_HOST;
606
806
  }
@@ -611,7 +811,7 @@ class Util {
611
811
  } else if (hostFromLocation) {
612
812
  useSSL = location.protocol === "https:";
613
813
  } else {
614
- useSSL = hostDefaulted;
814
+ useSSL = !LOOPBACK_HOSTS.includes(host.toLowerCase());
615
815
  }
616
816
  }
617
817
  let port = server.port;
@@ -822,22 +1022,14 @@ class JsonArgumentResolver {
822
1022
  // packages/core/src/internal/api/ReturnValueConverter.ts
823
1023
  class BasicReturnValueConverter {
824
1024
  convert(incomingMetadata, returnValue) {
825
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
1025
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
1026
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
826
1027
  }
827
1028
  }
828
1029
 
829
- // packages/core/src/internal/api/Logger.ts
830
- import debug2 from "debug";
831
- function createDebugLogger(namespace) {
832
- const debugLogger = debug2(namespace);
833
- return {
834
- trace: (...args) => debugLogger("TRACE", ...args),
835
- debug: (...args) => debugLogger("DEBUG", ...args),
836
- info: (...args) => debugLogger("INFO", ...args),
837
- warn: (...args) => debugLogger("WARN", ...args),
838
- error: (...args) => debugLogger("ERROR", ...args)
839
- };
840
- }
1030
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1031
+ import { isObservable } from "rxjs";
1032
+ import { finalize } from "rxjs/operators";
841
1033
 
842
1034
  // packages/core/src/api/ServiceIdentifier.ts
843
1035
  class ServiceIdentifier {
@@ -874,6 +1066,9 @@ class ServiceIdentifier {
874
1066
  }
875
1067
  return this._cri;
876
1068
  }
1069
+ unscopedCri() {
1070
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1071
+ }
877
1072
  }
878
1073
 
879
1074
  // packages/core/src/api/ZoneUtil.ts
@@ -893,6 +1088,7 @@ function validateLabel(label) {
893
1088
 
894
1089
  // packages/core/src/api/KinoticDecorators.ts
895
1090
  var scopeFunctions = new WeakSet;
1091
+ var scopeOptionalFunctions = new WeakSet;
896
1092
  var versionRegistry = new WeakMap;
897
1093
  var zonesRegistry = new WeakMap;
898
1094
  var advertisedRegistry = new WeakMap;
@@ -930,6 +1126,23 @@ function resolveScope(instance) {
930
1126
  function Scope(value, _context) {
931
1127
  scopeFunctions.add(value);
932
1128
  }
1129
+ function ScopeOptional(value, _context) {
1130
+ scopeOptionalFunctions.add(value);
1131
+ }
1132
+ function scopeOptionalMethodNames(instance) {
1133
+ const ret = new Set;
1134
+ let proto = Object.getPrototypeOf(instance);
1135
+ while (proto && proto !== Object.prototype) {
1136
+ for (const key of Object.getOwnPropertyNames(proto)) {
1137
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1138
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1139
+ ret.add(key);
1140
+ }
1141
+ }
1142
+ proto = Object.getPrototypeOf(proto);
1143
+ }
1144
+ return ret;
1145
+ }
933
1146
  function Version(version) {
934
1147
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
935
1148
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -992,6 +1205,94 @@ function Publish(namespace, name, advertise = false) {
992
1205
  };
993
1206
  }
994
1207
 
1208
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1209
+ import opentelemetry, { context as context2, propagation as propagation2, trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
1210
+ // packages/core/package.json
1211
+ var package_default = {
1212
+ name: "@kinotic-ai/core",
1213
+ version: "5.0.0-beta.30",
1214
+ type: "module",
1215
+ files: [
1216
+ "dist"
1217
+ ],
1218
+ module: "./dist/index.js",
1219
+ main: "./dist/index.cjs",
1220
+ types: "./dist/index.d.ts",
1221
+ exports: {
1222
+ ".": {
1223
+ import: {
1224
+ types: "./dist/index.d.ts",
1225
+ default: "./dist/index.js"
1226
+ },
1227
+ require: {
1228
+ types: "./dist/index.d.cts",
1229
+ default: "./dist/index.cjs"
1230
+ }
1231
+ },
1232
+ "./node": {
1233
+ import: {
1234
+ types: "./dist/node/index.d.ts",
1235
+ default: "./dist/node/index.js"
1236
+ },
1237
+ require: {
1238
+ types: "./dist/node/index.d.cts",
1239
+ default: "./dist/node/index.cjs"
1240
+ }
1241
+ },
1242
+ "./package.json": "./package.json"
1243
+ },
1244
+ homepage: "https://github.com/kinotic-ai/kinotic",
1245
+ repository: {
1246
+ type: "git",
1247
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1248
+ directory: "kinotic-js/workspace/packages/core"
1249
+ },
1250
+ license: "Apache-2.0",
1251
+ publishConfig: {
1252
+ access: "public"
1253
+ },
1254
+ scripts: {
1255
+ "type-check": "tsc --noEmit",
1256
+ test: "vitest run",
1257
+ coverage: "vitest run --coverage",
1258
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1259
+ },
1260
+ devDependencies: {
1261
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1262
+ "@opentelemetry/resources": "^2.10.0",
1263
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1264
+ "@opentelemetry/sdk-node": "^0.221.0",
1265
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1266
+ "@types/debug": "^4.1.13",
1267
+ "@types/node": "^25.6.0",
1268
+ "@types/ws": "^8.18.0",
1269
+ "@vitest/coverage-v8": "^4.1.4",
1270
+ "@vitest/runner": "^4.1.4",
1271
+ "@vitest/ui": "^4.1.4",
1272
+ allure: "^3.19.1",
1273
+ "allure-vitest": "^3.13.0",
1274
+ dotenv: "^17.4.1",
1275
+ "properties-file": "^4.0.0",
1276
+ testcontainers: "^11.14.0",
1277
+ tslib: "^2.8.1",
1278
+ typescript: "^6.0.2",
1279
+ vitest: "^4.1.4"
1280
+ },
1281
+ dependencies: {
1282
+ "@kinotic-ai/idl": "workspace:^",
1283
+ "@opentelemetry/api": "^1.9.1",
1284
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1285
+ "@stomp/rx-stomp": "^2.4.0",
1286
+ "@stomp/stompjs": "^7.3.0",
1287
+ debug: "^4.4.3",
1288
+ "p-tap": "^4.0.0",
1289
+ rxjs: "^7.8.2",
1290
+ "typescript-optional": "3.0.0-alpha.3",
1291
+ uuid: "^13.0.0",
1292
+ ws: "^8.21.0"
1293
+ }
1294
+ };
1295
+
995
1296
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
996
1297
  class ServiceInvocationSupervisor {
997
1298
  log;
@@ -1003,7 +1304,13 @@ class ServiceInvocationSupervisor {
1003
1304
  serviceIdentifier;
1004
1305
  serviceInstance;
1005
1306
  methodSubscription = null;
1307
+ unscopedSubscription = null;
1308
+ activeStreams = new Map;
1309
+ connectionEndedSubscription = null;
1310
+ connectionGeneration = 0;
1006
1311
  methodMap;
1312
+ scopeOptionalMethods;
1313
+ tracer;
1007
1314
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1008
1315
  if (!serviceIdentifier)
1009
1316
  throw new Error("ServiceIdentifier must not be null");
@@ -1017,10 +1324,12 @@ class ServiceInvocationSupervisor {
1017
1324
  this.serviceInstance = serviceInstance;
1018
1325
  this._eventBus = eventBusService;
1019
1326
  this.interceptorProvider = interceptorProvider;
1020
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1327
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1021
1328
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1022
1329
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1023
1330
  this.methodMap = this.buildMethodMap(serviceInstance);
1331
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1332
+ this.tracer = opentelemetry.trace.getTracer(package_default.name, package_default.version);
1024
1333
  }
1025
1334
  isActive() {
1026
1335
  return this.active;
@@ -1040,7 +1349,22 @@ class ServiceInvocationSupervisor {
1040
1349
  }
1041
1350
  this.active = true;
1042
1351
  const criBase = this.serviceIdentifier.cri().baseResource();
1043
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1352
+ this.methodSubscription = this.subscribeAt(criBase);
1353
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1354
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1355
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1356
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1357
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1358
+ }
1359
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1360
+ this.connectionGeneration++;
1361
+ for (const stream of this.activeStreams.values()) {
1362
+ stream.subscription.unsubscribe();
1363
+ }
1364
+ });
1365
+ }
1366
+ subscribeAt(criBase) {
1367
+ return this._eventBus.observe(criBase).subscribe({
1044
1368
  next: async (event) => {
1045
1369
  await this.processEvent(event);
1046
1370
  },
@@ -1053,7 +1377,6 @@ class ServiceInvocationSupervisor {
1053
1377
  this.active = false;
1054
1378
  }
1055
1379
  });
1056
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1057
1380
  }
1058
1381
  stop() {
1059
1382
  if (!this.active) {
@@ -1062,6 +1385,15 @@ class ServiceInvocationSupervisor {
1062
1385
  this.active = false;
1063
1386
  this.methodSubscription?.unsubscribe();
1064
1387
  this.methodSubscription = null;
1388
+ this.unscopedSubscription?.unsubscribe();
1389
+ this.unscopedSubscription = null;
1390
+ this.connectionEndedSubscription?.unsubscribe();
1391
+ this.connectionEndedSubscription = null;
1392
+ const serviceName = this.serviceIdentifier.qualifiedName();
1393
+ for (const stream of this.activeStreams.values()) {
1394
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1395
+ stream.subscription.unsubscribe();
1396
+ }
1065
1397
  this.log.info("ServiceInvocationSupervisor stopped");
1066
1398
  }
1067
1399
  buildMethodMap(serviceInstance) {
@@ -1101,10 +1433,19 @@ class ServiceInvocationSupervisor {
1101
1433
  if (!correlationId) {
1102
1434
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1103
1435
  }
1104
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1436
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1437
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1438
+ const stream = this.activeStreams.get(correlationId);
1439
+ if (stream) {
1440
+ stream.subscription.unsubscribe();
1441
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1442
+ throw new Error(`Unknown control header value ${control}`);
1443
+ }
1444
+ }
1105
1445
  }
1106
1446
  async processInvocationRequest(event) {
1107
- const path = createCRI(event.cri).path();
1447
+ const incomingCri = createCRI(event.cri);
1448
+ const path = incomingCri.path();
1108
1449
  if (!path) {
1109
1450
  throw new Error("The methodId must not be blank");
1110
1451
  }
@@ -1112,49 +1453,175 @@ class ServiceInvocationSupervisor {
1112
1453
  if (!handlerMethod) {
1113
1454
  throw new Error(`No method resolved for methodId ${path}`);
1114
1455
  }
1456
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1457
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1458
+ }
1115
1459
  const methodName = path;
1116
- const args = this.argumentResolver.resolveArguments(event);
1117
- const injectContext = receivesContext(this.serviceInstance, methodName);
1118
- let context2 = {};
1119
- const interceptor = this.interceptorProvider();
1120
- if (interceptor) {
1460
+ const span = this.startInvocationSpan(event, methodName);
1461
+ const generation = this.connectionGeneration;
1462
+ try {
1463
+ const args = this.argumentResolver.resolveArguments(event);
1464
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1465
+ let serviceContext = {};
1466
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1467
+ if (sender) {
1468
+ serviceContext.participant = JSON.parse(sender);
1469
+ }
1470
+ const interceptor = this.interceptorProvider();
1471
+ if (interceptor) {
1472
+ try {
1473
+ serviceContext = await interceptor.intercept(event, serviceContext);
1474
+ } catch (e) {
1475
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1476
+ if (this.replyOwed(generation)) {
1477
+ this.handleException(event, new Error("Internal server error"));
1478
+ }
1479
+ this.failSpan(span, e);
1480
+ return;
1481
+ }
1482
+ }
1483
+ if (injectContext) {
1484
+ args.push(serviceContext);
1485
+ }
1486
+ const expectedArgsCount = handlerMethod.length;
1487
+ if (args.length !== expectedArgsCount) {
1488
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1489
+ }
1490
+ let result;
1121
1491
  try {
1122
- context2 = await interceptor.intercept(event, context2);
1492
+ result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
1493
+ if (result instanceof Promise) {
1494
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1495
+ this.failInvocation(event, e, span, generation);
1496
+ });
1497
+ } else {
1498
+ this.processMethodInvocationResult(event, result, span, generation);
1499
+ }
1123
1500
  } catch (e) {
1124
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1125
- this.handleException(event, new Error("Internal server error"));
1126
- return;
1501
+ this.failInvocation(event, e, span, generation);
1502
+ }
1503
+ } catch (e) {
1504
+ this.failSpan(span, e);
1505
+ throw e;
1506
+ }
1507
+ }
1508
+ startInvocationSpan(event, methodName) {
1509
+ const carrier = {};
1510
+ for (const [key, value] of event.headers.entries()) {
1511
+ carrier[key] = value;
1512
+ }
1513
+ const serviceName = this.serviceIdentifier.qualifiedName();
1514
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1515
+ kind: SpanKind.SERVER,
1516
+ attributes: {
1517
+ "rpc.system": "kinotic",
1518
+ "rpc.service": serviceName,
1519
+ "rpc.method": methodName
1127
1520
  }
1521
+ }, propagation2.extract(context2.active(), carrier));
1522
+ }
1523
+ failSpan(span, error) {
1524
+ span.recordException(error);
1525
+ span.setStatus({ code: SpanStatusCode.ERROR });
1526
+ span.end();
1527
+ }
1528
+ replyOwed(generation) {
1529
+ return generation === this.connectionGeneration;
1530
+ }
1531
+ failInvocation(event, error, span, generation) {
1532
+ if (this.replyOwed(generation)) {
1533
+ this.handleException(event, error);
1534
+ }
1535
+ this.failSpan(span, error);
1536
+ }
1537
+ processMethodInvocationResult(event, result, span, generation) {
1538
+ if (!this.replyOwed(generation)) {
1539
+ span.end();
1540
+ } else if (isObservable(result)) {
1541
+ this.streamResult(event, result, span);
1542
+ } else {
1543
+ const reply = this.returnValueConverter.convert(event.headers, result);
1544
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1545
+ this.sendReply(reply);
1546
+ span.end();
1128
1547
  }
1129
- if (injectContext) {
1130
- args.push(context2);
1548
+ }
1549
+ streamResult(event, stream, span) {
1550
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1551
+ if (!correlationId) {
1552
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1131
1553
  }
1132
- const expectedArgsCount = handlerMethod.length;
1133
- if (args.length !== expectedArgsCount) {
1134
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1554
+ if (this.activeStreams.has(correlationId)) {
1555
+ const error = new Error(`stream ${correlationId} already active`);
1556
+ this.handleException(event, error);
1557
+ this.failSpan(span, error);
1558
+ return;
1135
1559
  }
1136
- let result;
1137
- try {
1138
- result = handlerMethod(...args);
1139
- if (result instanceof Promise) {
1140
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1141
- } else {
1142
- this.processMethodInvocationResult(event, result);
1560
+ let subscription = null;
1561
+ let failed = false;
1562
+ subscription = stream.pipe(finalize(() => {
1563
+ if (this.activeStreams.get(correlationId)?.subscription === subscription) {
1564
+ this.activeStreams.delete(correlationId);
1143
1565
  }
1144
- } catch (e) {
1145
- this.handleException(event, e);
1566
+ span.end();
1567
+ })).subscribe({
1568
+ next: (value) => {
1569
+ if (failed) {
1570
+ return;
1571
+ }
1572
+ try {
1573
+ const reply = this.returnValueConverter.convert(event.headers, value);
1574
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1575
+ this.sendReply(reply);
1576
+ } catch (e) {
1577
+ failed = true;
1578
+ this.handleException(event, e);
1579
+ span.recordException(e);
1580
+ span.setStatus({ code: SpanStatusCode.ERROR });
1581
+ subscription?.unsubscribe();
1582
+ }
1583
+ },
1584
+ error: (error) => {
1585
+ if (failed) {
1586
+ return;
1587
+ }
1588
+ this.handleException(event, error);
1589
+ span.recordException(error);
1590
+ span.setStatus({ code: SpanStatusCode.ERROR });
1591
+ },
1592
+ complete: () => {
1593
+ if (failed) {
1594
+ return;
1595
+ }
1596
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1597
+ }
1598
+ });
1599
+ if (failed) {
1600
+ subscription.unsubscribe();
1601
+ }
1602
+ if (!subscription.closed) {
1603
+ this.activeStreams.set(correlationId, { request: event, subscription });
1146
1604
  }
1147
1605
  }
1148
- processMethodInvocationResult(event, result) {
1149
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1150
- this._eventBus.send(outgoingEvent);
1606
+ sendReply(event) {
1607
+ try {
1608
+ this._eventBus.send(event);
1609
+ } catch (e) {
1610
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1611
+ }
1151
1612
  }
1152
1613
  handleException(event, error) {
1153
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1154
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1155
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1156
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1157
- this._eventBus.send(errorEvent);
1614
+ try {
1615
+ const errorMessage = error?.message || "Unknown error";
1616
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1617
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1618
+ ["error" /* ERROR_HEADER */, errorMessage],
1619
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1620
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1621
+ this.sendReply(errorEvent);
1622
+ } catch (e) {
1623
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1624
+ }
1158
1625
  }
1159
1626
  validateReplyTo(event) {
1160
1627
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1175,100 +1642,12 @@ class ServiceInvocationSupervisor {
1175
1642
  }
1176
1643
 
1177
1644
  // packages/core/src/api/ServiceRegistry.ts
1178
- import opentelemetry, { SpanKind, SpanStatusCode } from "@opentelemetry/api";
1645
+ import opentelemetry2, { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
1179
1646
  import {
1180
1647
  ATTR_SERVER_ADDRESS,
1181
1648
  ATTR_SERVER_PORT
1182
1649
  } from "@opentelemetry/semantic-conventions";
1183
1650
  import { first, map as map2 } from "rxjs/operators";
1184
- // packages/core/package.json
1185
- var package_default = {
1186
- name: "@kinotic-ai/core",
1187
- version: "5.0.0-beta.3",
1188
- type: "module",
1189
- files: [
1190
- "dist"
1191
- ],
1192
- module: "./dist/index.js",
1193
- main: "./dist/index.cjs",
1194
- types: "./dist/index.d.ts",
1195
- exports: {
1196
- ".": {
1197
- import: {
1198
- types: "./dist/index.d.ts",
1199
- default: "./dist/index.js"
1200
- },
1201
- require: {
1202
- types: "./dist/index.d.cts",
1203
- default: "./dist/index.cjs"
1204
- }
1205
- },
1206
- "./node": {
1207
- import: {
1208
- types: "./dist/node/index.d.ts",
1209
- default: "./dist/node/index.js"
1210
- },
1211
- require: {
1212
- types: "./dist/node/index.d.cts",
1213
- default: "./dist/node/index.cjs"
1214
- }
1215
- },
1216
- "./package.json": "./package.json"
1217
- },
1218
- homepage: "https://github.com/kinotic-ai/kinotic",
1219
- license: "Elastic License 2.0",
1220
- publishConfig: {
1221
- access: "public"
1222
- },
1223
- scripts: {
1224
- "type-check": "tsc --noEmit",
1225
- test: "vitest run",
1226
- coverage: "vitest run --coverage",
1227
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1228
- },
1229
- devDependencies: {
1230
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1231
- "@opentelemetry/resources": "^2.6.1",
1232
- "@opentelemetry/sdk-metrics": "^2.6.1",
1233
- "@opentelemetry/sdk-node": "^0.214.0",
1234
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1235
- "@types/node": "^25.6.0",
1236
- "@types/uuid": "^11.0.0",
1237
- "@types/ws": "^8.18.0",
1238
- "@vitest/coverage-v8": "^4.1.4",
1239
- "@vitest/runner": "^4.1.4",
1240
- "@vitest/ui": "^4.1.4",
1241
- allure: "^3.4.1",
1242
- "allure-vitest": "^3.7.1",
1243
- dotenv: "^17.4.1",
1244
- "properties-file": "^4.0.0",
1245
- testcontainers: "^11.14.0",
1246
- tslib: "^2.8.1",
1247
- typescript: "^6.0.2",
1248
- vitest: "^4.1.4",
1249
- ws: "^8.20.0"
1250
- },
1251
- dependencies: {
1252
- "@opentelemetry/api": "^1.9.1",
1253
- "@opentelemetry/semantic-conventions": "^1.40.0",
1254
- "@stomp/rx-stomp": "^2.4.0",
1255
- "@stomp/stompjs": "^7.3.0",
1256
- "@types/debug": "^4.1.13",
1257
- debug: "^4.4.3",
1258
- "p-tap": "^4.0.0",
1259
- rxjs: "^7.8.2",
1260
- "typescript-optional": "3.0.0-alpha.3",
1261
- uuid: "^13.0.0",
1262
- ws: "^8.18.0"
1263
- },
1264
- peerDependenciesMeta: {
1265
- typescript: {
1266
- optional: true
1267
- }
1268
- }
1269
- };
1270
-
1271
- // packages/core/src/api/ServiceRegistry.ts
1272
1651
  class JsonEventFactory {
1273
1652
  create(cri, args) {
1274
1653
  const event = new Event(cri);
@@ -1302,12 +1681,61 @@ class TextEventFactory {
1302
1681
  return event;
1303
1682
  }
1304
1683
  }
1684
+ var APPLICATION_SERVICE_DIRECTORY = "app-api~org.kinotic.app.api.services.ApplicationServiceDirectory";
1685
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1686
+ var declaredDefinitions = new Map;
1687
+ function declareServiceDefinitions(definitions) {
1688
+ for (const definition of definitions) {
1689
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1690
+ }
1691
+ }
1692
+ function qualifiedNameOf(namespace, name) {
1693
+ return namespace ? `${namespace}.${name}` : name;
1694
+ }
1695
+ function servedFunctions(serviceInstance) {
1696
+ const ret = new Set;
1697
+ let proto = Object.getPrototypeOf(serviceInstance);
1698
+ while (proto && proto !== Object.prototype) {
1699
+ for (const key of Object.getOwnPropertyNames(proto)) {
1700
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1701
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1702
+ ret.add(key);
1703
+ }
1704
+ }
1705
+ proto = Object.getPrototypeOf(proto);
1706
+ }
1707
+ return [...ret].sort();
1708
+ }
1709
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1710
+ let ret = null;
1711
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1712
+ if (application) {
1713
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1714
+ const definition = declaredDefinitions.get(qualifiedName);
1715
+ if (definition) {
1716
+ const declared = definition.functions.map((f) => f.name).sort();
1717
+ const served = servedFunctions(serviceInstance);
1718
+ if (declared.join() !== served.join()) {
1719
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1720
+ }
1721
+ ret = {
1722
+ applicationId: application[1],
1723
+ zone: serviceIdentifier.zone,
1724
+ version: serviceIdentifier.version ?? null,
1725
+ advertised: isAdvertised(serviceInstance),
1726
+ serviceDefinition: definition
1727
+ };
1728
+ }
1729
+ }
1730
+ return ret;
1731
+ }
1305
1732
 
1306
1733
  class ServiceRegistry {
1307
1734
  _eventBus;
1308
1735
  supervisors = new Map;
1736
+ entries = new Map;
1309
1737
  contextInterceptor = null;
1310
- debugLogger = debug3("kinoitc:serviceRegistry");
1738
+ debugLogger = debug3("kinotic:serviceRegistry");
1311
1739
  constructor(eventBus) {
1312
1740
  this._eventBus = eventBus;
1313
1741
  }
@@ -1327,9 +1755,16 @@ class ServiceRegistry {
1327
1755
  const criString = serviceIdentifier.cri().raw();
1328
1756
  if (!this.supervisors.has(criString)) {
1329
1757
  this.debugLogger(`Registering service for CRI: ${criString}`);
1758
+ const entry = directoryEntryOf(service, serviceIdentifier);
1330
1759
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1331
1760
  this.supervisors.set(criString, supervisor);
1332
1761
  supervisor.start();
1762
+ if (entry) {
1763
+ this.entries.set(criString, entry);
1764
+ if (this.eventBus.isConnected()) {
1765
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1766
+ }
1767
+ }
1333
1768
  }
1334
1769
  }
1335
1770
  unRegister(serviceIdentifier) {
@@ -1339,8 +1774,18 @@ class ServiceRegistry {
1339
1774
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1340
1775
  supervisor.stop();
1341
1776
  this.supervisors.delete(criString);
1777
+ this.entries.delete(criString);
1778
+ }
1779
+ }
1780
+ async registerEntries() {
1781
+ for (const entry of this.entries.values()) {
1782
+ await this.registerEntry(entry);
1342
1783
  }
1343
1784
  }
1785
+ async registerEntry(entry) {
1786
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
1787
+ await this.serviceProxy(APPLICATION_SERVICE_DIRECTORY).invoke("register", [entry]);
1788
+ }
1344
1789
  registerContextInterceptor(interceptor) {
1345
1790
  this.contextInterceptor = interceptor;
1346
1791
  }
@@ -1357,16 +1802,16 @@ class ServiceProxy {
1357
1802
  }
1358
1803
  this.serviceIdentifier = serviceIdentifier;
1359
1804
  this.serviceRegistry = serviceRegistry;
1360
- this.tracer = opentelemetry.trace.getTracer("kinoitc.client", package_default.version);
1805
+ this.tracer = opentelemetry2.trace.getTracer(package_default.name, package_default.version);
1361
1806
  }
1362
1807
  invoke(methodIdentifier, args, scope, eventFactory) {
1363
1808
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1364
- kind: SpanKind.CLIENT
1809
+ kind: SpanKind2.CLIENT
1365
1810
  }, async (span) => {
1366
1811
  if (scope) {
1367
- span.setAttribute("kinoitc.scope", scope);
1812
+ span.setAttribute("kinotic.scope", scope);
1368
1813
  }
1369
- span.setAttribute("rpc.system", "kinoitc");
1814
+ span.setAttribute("rpc.system", "kinotic");
1370
1815
  span.setAttribute("rpc.service", this.serviceIdentifier);
1371
1816
  span.setAttribute("rpc.method", methodIdentifier);
1372
1817
  return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(first()).toPromise().then(async (value) => {
@@ -1374,7 +1819,7 @@ class ServiceProxy {
1374
1819
  return value;
1375
1820
  }, async (ex) => {
1376
1821
  span.recordException(ex);
1377
- span.setStatus({ code: SpanStatusCode.ERROR });
1822
+ span.setStatus({ code: SpanStatusCode2.ERROR });
1378
1823
  span.end();
1379
1824
  throw ex;
1380
1825
  });
@@ -1390,7 +1835,7 @@ class ServiceProxy {
1390
1835
  eventFactoryToUse = eventFactory;
1391
1836
  }
1392
1837
  let eventBusToUse = this.serviceRegistry.eventBus;
1393
- const span = opentelemetry.trace.getActiveSpan();
1838
+ const span = opentelemetry2.trace.getActiveSpan();
1394
1839
  if (span) {
1395
1840
  span.setAttribute(ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1396
1841
  span.setAttribute(ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
@@ -1432,8 +1877,10 @@ class KinoticSingleton {
1432
1877
  this._eventBus = eventBus;
1433
1878
  this.serviceRegistry.eventBus = eventBus;
1434
1879
  }
1435
- connect(options) {
1436
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1880
+ async connect(options) {
1881
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1882
+ await this.serviceRegistry.registerEntries();
1883
+ return ret;
1437
1884
  }
1438
1885
  disconnect(force) {
1439
1886
  return this._eventBus.disconnect(force);
@@ -1554,6 +2001,9 @@ class CrudServiceProxy {
1554
2001
  deleteById(id) {
1555
2002
  return this.serviceProxy.invoke("deleteById", [id]);
1556
2003
  }
2004
+ deleteByIdSync(id) {
2005
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
2006
+ }
1557
2007
  async findAll(pageable) {
1558
2008
  const page = await this.findAllSinglePage(pageable);
1559
2009
  return new FindAllIterablePage(pageable, page, this);
@@ -1644,15 +2094,15 @@ class CursorPageable extends Pageable {
1644
2094
  }
1645
2095
  // packages/core/src/api/crud/Sort.ts
1646
2096
  var Direction;
1647
- ((Direction2) => {
1648
- Direction2["ASC"] = "ASC";
1649
- Direction2["DESC"] = "DESC";
2097
+ ((Direction) => {
2098
+ Direction["ASC"] = "ASC";
2099
+ Direction["DESC"] = "DESC";
1650
2100
  })(Direction ||= {});
1651
2101
  var NullHandling;
1652
- ((NullHandling2) => {
1653
- NullHandling2["NATIVE"] = "NATIVE";
1654
- NullHandling2["NULLS_FIRST"] = "NULLS_FIRST";
1655
- NullHandling2["NULLS_LAST"] = "NULLS_LAST";
2102
+ ((NullHandling) => {
2103
+ NullHandling["NATIVE"] = "NATIVE";
2104
+ NullHandling["NULLS_FIRST"] = "NULLS_FIRST";
2105
+ NullHandling["NULLS_LAST"] = "NULLS_LAST";
1656
2106
  })(NullHandling ||= {});
1657
2107
 
1658
2108
  class Order {
@@ -1676,6 +2126,13 @@ class Order {
1676
2126
  class Sort {
1677
2127
  orders = [];
1678
2128
  }
2129
+ // packages/core/src/api/security/AuthorizationException.ts
2130
+ class AuthorizationException extends Error {
2131
+ constructor(message = "Access denied") {
2132
+ super(message);
2133
+ this.name = "AuthorizationException";
2134
+ }
2135
+ }
1679
2136
  // packages/core/src/api/security/ConnectedInfo.ts
1680
2137
  class ConnectedInfo {
1681
2138
  replyToId;
@@ -1690,46 +2147,52 @@ class ParticipantConstants {
1690
2147
  static CLI_PARTICIPANT_ID = "-42-Kinotic-CLI-42-";
1691
2148
  }
1692
2149
  export {
1693
- validateZone,
1694
- validateLabel,
1695
- receivesContext,
1696
- isAdvertised,
1697
- createCRI,
1698
- buildServerUrl,
1699
- buildBrokerUrl,
1700
- Zone,
1701
- Version,
1702
- TextEventFactory,
1703
- Sort,
1704
- SessionKeepAliveMode,
1705
- SessionCredentialsResolver,
1706
- ServiceRegistry,
1707
- ServerInfo,
1708
- Scope,
1709
- Publish,
1710
- ParticipantConstants,
1711
- Pageable,
1712
- Order,
1713
- OffsetPageable,
1714
- NullHandling,
1715
- KinoticSingleton,
1716
- Kinotic,
1717
- JsonEventFactory,
1718
- FunctionalIterablePage,
1719
- EventConstants,
1720
- EventBus,
1721
- Event,
1722
- EnvCredentialsResolver,
1723
- Direction,
1724
- DefaultCRI,
1725
- DataSourceUtils,
1726
- CursorPageable,
1727
- CrudServiceProxyFactory,
1728
- CrudServiceProxy,
1729
- Context,
1730
- ConnectedInfo,
1731
- ChainedCredentialsResolver,
1732
- BearerCredentialsResolver,
2150
+ AbstractIterablePage,
2151
+ AuthorizationException,
1733
2152
  BasicCredentialsResolver,
1734
- AbstractIterablePage
2153
+ BearerCredentialsResolver,
2154
+ ChainedCredentialsResolver,
2155
+ ConnectedInfo,
2156
+ Context,
2157
+ CrudServiceProxy,
2158
+ CrudServiceProxyFactory,
2159
+ CursorPageable,
2160
+ DataSourceUtils,
2161
+ DefaultCRI,
2162
+ Direction,
2163
+ EnvCredentialsResolver,
2164
+ Event,
2165
+ EventBus,
2166
+ EventConstants,
2167
+ FunctionalIterablePage,
2168
+ JsonEventFactory,
2169
+ Kinotic,
2170
+ KinoticSingleton,
2171
+ NullHandling,
2172
+ OffsetPageable,
2173
+ Order,
2174
+ Pageable,
2175
+ ParticipantConstants,
2176
+ Publish,
2177
+ RpcError,
2178
+ Scope,
2179
+ ScopeOptional,
2180
+ ServerInfo,
2181
+ ServiceIdentifier,
2182
+ ServiceRegistry,
2183
+ SessionCredentialsResolver,
2184
+ SessionKeepAliveMode,
2185
+ Sort,
2186
+ TextEventFactory,
2187
+ Version,
2188
+ Zone,
2189
+ buildBrokerUrl,
2190
+ buildServerUrl,
2191
+ createCRI,
2192
+ declareServiceDefinitions,
2193
+ isAdvertised,
2194
+ receivesContext,
2195
+ scopeOptionalMethodNames,
2196
+ validateLabel,
2197
+ validateZone
1735
2198
  };