@kinotic-ai/core 5.0.0-beta.2 → 5.0.0-beta.20

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
@@ -4,6 +4,12 @@ class ServerInfo {
4
4
  port;
5
5
  useSSL;
6
6
  }
7
+ function buildServerUrl(server, scheme) {
8
+ return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
9
+ }
10
+ function buildBrokerUrl(server) {
11
+ return buildServerUrl(server, "ws") + "/v1";
12
+ }
7
13
  var SessionKeepAliveMode;
8
14
  ((SessionKeepAliveMode2) => {
9
15
  SessionKeepAliveMode2["NONE"] = "NONE";
@@ -16,6 +22,7 @@ var EventConstants;
16
22
  EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
17
23
  EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
18
24
  EventConstants2["REPLY_TO_HEADER"] = "reply-to";
25
+ EventConstants2["SENDER_HEADER"] = "sender";
19
26
  EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
20
27
  EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
21
28
  EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
@@ -40,126 +47,172 @@ var EventConstants;
40
47
  EventConstants2["TRACESTATE_HEADER"] = "tracestate";
41
48
  })(EventConstants ||= {});
42
49
 
50
+ // packages/core/src/internal/api/Logger.ts
51
+ import debug from "debug";
52
+ function createDebugLogger(namespace) {
53
+ const debugLogger = debug(namespace);
54
+ return {
55
+ trace: (...args) => debugLogger("TRACE", ...args),
56
+ debug: (...args) => debugLogger("DEBUG", ...args),
57
+ info: (...args) => debugLogger("INFO", ...args),
58
+ warn: (...args) => debugLogger("WARN", ...args),
59
+ error: (...args) => debugLogger("ERROR", ...args)
60
+ };
61
+ }
62
+
43
63
  // packages/core/src/internal/api/StompConnectionManager.ts
44
- import { RxStomp } from "@stomp/rx-stomp";
64
+ import { RxStomp, RxStompState } from "@stomp/rx-stomp";
45
65
  import { ReconnectionTimeMode } from "@stomp/stompjs";
46
- import debug from "debug";
66
+ import debug2 from "debug";
47
67
  import { Subject } from "rxjs";
68
+ import { skip } from "rxjs/operators";
48
69
  import { v4 as uuidv4 } from "uuid";
70
+
71
+ // packages/core/src/internal/api/StompActivation.ts
72
+ class StompActivation {
73
+ _ended = false;
74
+ wake = null;
75
+ preparedSocket = null;
76
+ attempt = null;
77
+ failPending = null;
78
+ subscriptions = [];
79
+ get ended() {
80
+ return this._ended;
81
+ }
82
+ end() {
83
+ this._ended = true;
84
+ this.wake?.();
85
+ this.wake = null;
86
+ }
87
+ delay(ms) {
88
+ return new Promise((resolve) => {
89
+ const timer = setTimeout(() => {
90
+ this.wake = null;
91
+ resolve();
92
+ }, ms);
93
+ this.wake = () => {
94
+ clearTimeout(timer);
95
+ resolve();
96
+ };
97
+ });
98
+ }
99
+ own(subscription) {
100
+ this.subscriptions.push(subscription);
101
+ }
102
+ pending(fail) {
103
+ this.failPending = fail;
104
+ }
105
+ established() {
106
+ this.failPending = null;
107
+ }
108
+ failIfPending(reason) {
109
+ const fail = this.failPending;
110
+ this.failPending = null;
111
+ fail?.(reason);
112
+ }
113
+ unsubscribeAll() {
114
+ for (const subscription of this.subscriptions) {
115
+ subscription.unsubscribe();
116
+ }
117
+ this.subscriptions.length = 0;
118
+ }
119
+ }
120
+
121
+ // packages/core/src/internal/api/StompConnectionManager.ts
49
122
  var SESSION_CHECK_PATH = "/api/auth/me";
50
123
 
51
124
  class StompConnectionManager {
52
125
  lastWebsocketError = null;
53
126
  maxConnectionAttemptsReached = false;
54
- replyToCriChangedHandler = null;
55
- rxStomp = null;
127
+ connectionEndedHandler = null;
128
+ rxStomp = new RxStomp;
129
+ activation = null;
130
+ teardown = null;
56
131
  INITIAL_RECONNECT_DELAY = 2000;
57
132
  JITTER_MAX = 5000;
58
133
  MAX_RECONNECT_DELAY = 120000;
59
134
  connectionAttempts = 0;
60
- debugLogger = debug("kinoitc:stomp");
61
- fatalErrorsSubject = new Subject;
62
- _fatalErrors = this.fatalErrorsSubject.asObservable();
135
+ debugLogger = debug2("kinotic:stomp");
136
+ connectionEstablishedSubject = new Subject;
63
137
  initialConnectionSuccessful = false;
64
- serverHeadersSubscription = null;
65
- stompErrorsSubscription = null;
66
- uuidv4 = uuidv4();
138
+ rxStompHasConnected = false;
67
139
  _replyToCri = null;
68
140
  get replyToCri() {
69
141
  return this._replyToCri;
70
142
  }
71
143
  get active() {
72
- return !!this.rxStomp;
144
+ return this.activation !== null;
73
145
  }
74
146
  get connected() {
75
- return this.rxStomp != null && this.rxStomp.connected();
147
+ return this.activation !== null && this.rxStomp.connected();
76
148
  }
77
- get fatalErrors() {
78
- return this._fatalErrors;
149
+ get connectionEstablished() {
150
+ return this.connectionEstablishedSubject.asObservable();
79
151
  }
80
152
  async activate(options) {
81
- if (!options?.host) {
153
+ if (!options?.server?.host) {
82
154
  throw new Error("No host provided");
83
155
  }
84
- if (this.rxStomp) {
156
+ if (this.activation) {
85
157
  throw new Error("Stomp connection already active");
86
158
  }
87
- const server = { host: options.host, port: options.port, useSSL: options.useSSL };
159
+ await this.teardown;
160
+ if (this.activation) {
161
+ throw new Error("Stomp connection already active");
162
+ }
163
+ const server = options.server;
88
164
  const credentialsResolver = options.credentials;
165
+ const activation = new StompActivation;
166
+ this.activation = activation;
89
167
  let headerAuth = false;
90
- if (!options.webSocketFactory) {
91
- if (!credentialsResolver) {
92
- throw new Error("No credentials supplied and no default resolution applied");
168
+ try {
169
+ if (!options.webSocketFactory) {
170
+ if (!credentialsResolver) {
171
+ throw new Error("No credentials supplied and no default resolution applied");
172
+ }
173
+ const resolved = await credentialsResolver.resolve(server);
174
+ if (resolved === null) {
175
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
176
+ }
177
+ headerAuth = resolved.authHeaders != null;
178
+ }
179
+ if (activation.ended) {
180
+ throw new Error("Deactivated before the connection was established");
93
181
  }
94
- const resolved = await credentialsResolver.resolve(server);
95
- if (resolved === null) {
96
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
182
+ } catch (e) {
183
+ if (this.activation === activation) {
184
+ this.activation = null;
97
185
  }
98
- headerAuth = resolved.authHeaders != null;
186
+ throw e;
99
187
  }
100
188
  return new Promise((resolve, reject) => {
101
189
  this.connectionAttempts = 0;
102
190
  this.initialConnectionSuccessful = false;
103
191
  this.lastWebsocketError = null;
104
192
  this.maxConnectionAttemptsReached = false;
105
- const url = Util.buildBrokerUrl(server);
106
- this.rxStomp = new RxStomp;
107
- let preparedSocket = null;
108
- const userWebSocketFactory = options.webSocketFactory;
109
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
193
+ const url = buildBrokerUrl(server);
194
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
195
+ const takePreparedSocket = () => {
196
+ const socket = activation.preparedSocket;
197
+ activation.preparedSocket = null;
198
+ return socket;
199
+ };
110
200
  const stompConfig = {
111
201
  brokerURL: url,
112
202
  connectHeaders: {
113
203
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
114
204
  },
115
- heartbeatIncoming: 120000,
205
+ heartbeatIncoming: 30000,
116
206
  heartbeatOutgoing: 30000,
117
207
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
118
208
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
119
209
  reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
120
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
121
- beforeConnect: async () => {
122
- if (!usesPreparedSocket) {
123
- const sessionCheckUrl = "http" + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "") + SESSION_CHECK_PATH;
124
- try {
125
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
126
- if (res.status === 401) {
127
- await this.signalFatal(new Error("Authentication required"));
128
- return;
129
- }
130
- } catch {}
131
- }
132
- if (options?.maxConnectionAttempts) {
133
- this.connectionAttempts++;
134
- if (this.connectionAttempts > options.maxConnectionAttempts) {
135
- this.maxConnectionAttemptsReached = true;
136
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
137
- return;
138
- } else {
139
- await this.connectionJitterDelay();
140
- }
141
- } else {
142
- await this.connectionJitterDelay();
143
- }
144
- if (userWebSocketFactory) {
145
- try {
146
- preparedSocket = await userWebSocketFactory();
147
- } catch (e) {
148
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
149
- }
150
- } else if (headerAuth) {
151
- try {
152
- const resolved = await credentialsResolver.resolve(server);
153
- if (resolved?.authHeaders == null) {
154
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
155
- } else {
156
- const WS = WebSocket;
157
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
158
- }
159
- } catch (e) {
160
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
161
- }
162
- }
210
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
211
+ beforeConnect: () => {
212
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
213
+ const settled = () => new Promise((resolve2) => setTimeout(resolve2, 0));
214
+ activation.attempt = attempt.then(settled, settled);
215
+ return attempt;
163
216
  }
164
217
  };
165
218
  if (this.debugLogger.enabled) {
@@ -168,93 +221,195 @@ class StompConnectionManager {
168
221
  };
169
222
  }
170
223
  this.rxStomp.configure(stompConfig);
171
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
224
+ activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
172
225
  this.lastWebsocketError = value;
173
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
226
+ if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
174
227
  this.maxConnectionAttemptsReached = true;
175
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
228
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
176
229
  }
177
- });
178
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
230
+ }));
231
+ activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
179
232
  const stompError = new Error(frame.headers["message"], { cause: frame });
180
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
181
- });
182
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
183
- connectedSubscription.unsubscribe();
184
- initialFailureSubscription.unsubscribe();
185
- if (!this.initialConnectionSuccessful) {
186
- this.initialConnectionSuccessful = true;
187
- }
188
- });
189
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
190
- connectedSubscription.unsubscribe();
191
- initialFailureSubscription.unsubscribe();
192
- reject(err.message);
193
- });
194
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
233
+ await this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
234
+ }));
235
+ activation.own(this.rxStomp.connected$.subscribe(() => {
236
+ activation.established();
237
+ this.initialConnectionSuccessful = true;
238
+ this.connectionAttempts = 0;
239
+ }));
240
+ activation.pending(reject);
241
+ activation.own(this.rxStomp.serverHeaders$.pipe(skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
242
+ this.rxStompHasConnected = true;
195
243
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
196
244
  if (connectedInfoJson == null) {
197
245
  if (!this.initialConnectionSuccessful) {
198
- await this.deactivate();
199
- reject("Server did not return proper data for successful login");
246
+ await this.deactivate(undefined, new Error("Server did not return proper data for successful login"));
200
247
  }
201
248
  return;
202
249
  }
203
250
  const connectedInfo = JSON.parse(connectedInfoJson);
204
251
  if (connectedInfo.replyToId == null) {
205
252
  if (!this.initialConnectionSuccessful) {
206
- await this.deactivate();
207
- reject("Server did not return a replyToId for successful login");
253
+ await this.deactivate(undefined, new Error("Server did not return a replyToId for successful login"));
208
254
  }
209
255
  return;
210
256
  }
211
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
257
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + uuidv4() + "@kinotic.js.EventBus/replyHandler";
258
+ this._replyToCri = newReplyToCri;
212
259
  if (!this.initialConnectionSuccessful) {
213
- this._replyToCri = newReplyToCri;
214
260
  resolve(connectedInfo);
215
- } else if (this._replyToCri !== newReplyToCri) {
216
- this._replyToCri = newReplyToCri;
217
- this.replyToCriChangedHandler?.(newReplyToCri);
218
261
  }
219
- });
262
+ this.connectionEstablishedSubject.next(connectedInfo);
263
+ }));
264
+ let previousState = this.rxStomp.connectionState$.getValue();
265
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
266
+ if (state === RxStompState.CLOSED && previousState === RxStompState.OPEN && this.activation === activation) {
267
+ this.connectionEndedHandler?.(null);
268
+ }
269
+ previousState = state;
270
+ }));
220
271
  this.rxStomp.activate();
221
272
  });
222
273
  }
223
- async deactivate(force) {
224
- const rxStomp = this.rxStomp;
225
- if (rxStomp) {
226
- await rxStomp.deactivate({ force });
227
- if (this.rxStomp === rxStomp) {
228
- this.serverHeadersSubscription?.unsubscribe();
229
- this.serverHeadersSubscription = null;
230
- this.stompErrorsSubscription?.unsubscribe();
231
- this.stompErrorsSubscription = null;
232
- this.rxStomp = null;
233
- this._replyToCri = null;
274
+ async prepareAttempt(activation, options, server, headerAuth) {
275
+ const credentialsResolver = options.credentials;
276
+ const userWebSocketFactory = options.webSocketFactory;
277
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
278
+ const url = buildBrokerUrl(server);
279
+ if (!usesPreparedSocket) {
280
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
281
+ try {
282
+ const res = await fetch(sessionCheckUrl, { credentials: "include" });
283
+ if (res.status === 401) {
284
+ await this.failConnection(activation, new Error("Authentication required"));
285
+ return;
286
+ }
287
+ } catch (e) {
288
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
234
289
  }
235
290
  }
236
- return;
291
+ if (options?.maxConnectionAttempts) {
292
+ this.connectionAttempts++;
293
+ if (this.connectionAttempts > options.maxConnectionAttempts) {
294
+ this.maxConnectionAttemptsReached = true;
295
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
296
+ return;
297
+ } else {
298
+ await this.connectionJitterDelay(activation);
299
+ }
300
+ } else {
301
+ await this.connectionJitterDelay(activation);
302
+ }
303
+ if (activation.ended) {
304
+ return;
305
+ }
306
+ if (userWebSocketFactory) {
307
+ try {
308
+ activation.preparedSocket = await userWebSocketFactory();
309
+ } catch (e) {
310
+ await this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
311
+ }
312
+ } else if (headerAuth) {
313
+ try {
314
+ const resolved = await credentialsResolver.resolve(server);
315
+ if (resolved?.authHeaders == null) {
316
+ await this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
317
+ } else {
318
+ const WS = WebSocket;
319
+ activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
320
+ }
321
+ } catch (e) {
322
+ await this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
323
+ }
324
+ }
325
+ if (activation.ended && activation.preparedSocket) {
326
+ activation.preparedSocket.close();
327
+ activation.preparedSocket = null;
328
+ }
237
329
  }
238
- async connectionJitterDelay() {
330
+ deactivate(force, reason = null) {
331
+ const activation = this.activation;
332
+ let ret;
333
+ if (activation) {
334
+ this.activation = null;
335
+ activation.end();
336
+ const wasOpen = this.rxStomp.connected();
337
+ this._replyToCri = null;
338
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
339
+ activation.preparedSocket?.close();
340
+ activation.preparedSocket = null;
341
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
342
+ activation.unsubscribeAll();
343
+ this.teardown = null;
344
+ });
345
+ this.teardown = teardown;
346
+ if (wasOpen || reason !== null) {
347
+ this.connectionEndedHandler?.(reason);
348
+ }
349
+ ret = teardown;
350
+ } else {
351
+ ret = this.teardown ?? Promise.resolve();
352
+ }
353
+ return ret;
354
+ }
355
+ async connectionJitterDelay(activation) {
239
356
  if (this.initialConnectionSuccessful) {
240
357
  const randomJitter = Math.random() * this.JITTER_MAX;
241
358
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
242
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
359
+ await activation.delay(randomJitter);
243
360
  }
244
361
  }
245
- async signalFatal(err) {
246
- this.debugLogger("Fatal error, deactivating connection: %O", err);
247
- await this.deactivate();
248
- this.fatalErrorsSubject.next(err);
362
+ async failConnection(activation, err) {
363
+ if (!activation.ended) {
364
+ this.debugLogger("Connection failed, ending it: %O", err);
365
+ await this.deactivate(undefined, err);
366
+ }
249
367
  }
250
368
  }
251
369
 
252
370
  // packages/core/src/api/event/EventBus.ts
253
371
  import { context, propagation } from "@opentelemetry/api";
254
- import { firstValueFrom, Observable as Observable2, Subject as Subject2, throwError } from "rxjs";
372
+ import { firstValueFrom, Observable as Observable2, Subject as Subject2 } from "rxjs";
255
373
  import { filter, map, multicast, tap } from "rxjs/operators";
256
374
  import { Optional } from "typescript-optional";
257
375
  import { v4 as uuidv42 } from "uuid";
376
+
377
+ // packages/core/src/api/event/RpcError.ts
378
+ class RpcError extends Error {
379
+ exceptionName;
380
+ exceptionClass;
381
+ constructor(message, exceptionName, exceptionClass) {
382
+ super(message);
383
+ this.name = "RpcError";
384
+ this.exceptionName = exceptionName;
385
+ this.exceptionClass = exceptionClass;
386
+ }
387
+ static fromEvent(reply) {
388
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
389
+ let ret;
390
+ const detail = describedException(reply);
391
+ if (detail !== undefined) {
392
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
393
+ } else {
394
+ ret = new RpcError(message, "", "");
395
+ }
396
+ return ret;
397
+ }
398
+ }
399
+ function describedException(reply) {
400
+ let ret = undefined;
401
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
402
+ try {
403
+ const parsed = JSON.parse(reply.getDataString());
404
+ if (parsed !== null && typeof parsed === "object") {
405
+ ret = parsed;
406
+ }
407
+ } catch {}
408
+ }
409
+ return ret;
410
+ }
411
+
412
+ // packages/core/src/api/event/EventBus.ts
258
413
  class Event {
259
414
  cri;
260
415
  headers;
@@ -293,24 +448,31 @@ class Event {
293
448
 
294
449
  class EventBus {
295
450
  serverInfo = null;
451
+ log = createDebugLogger("kinotic:EventBus");
296
452
  stompConnectionManager = new StompConnectionManager;
297
453
  connectionLifecycle = Promise.resolve();
298
- replyToCri = null;
454
+ disconnectRequests = 0;
299
455
  requestRepliesObservable = null;
300
456
  requestRepliesSubject = null;
301
457
  requestRepliesSubscription = null;
302
458
  activeCorrelationIds = new Set;
303
459
  recentlyReaped = new Set;
460
+ connectionEndedSubject = new Subject2;
304
461
  static REAP_DEBOUNCE_MS = 5000;
305
462
  constructor() {
306
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
307
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
308
- this.replyToCri = replyToCri;
309
- this.resetRequestReplies("Reply destination changed");
463
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
464
+ this.resetRequestReplies("Connection lost");
465
+ if (!this.stompConnectionManager.active) {
466
+ this.serverInfo = null;
467
+ }
468
+ this.connectionEndedSubject.next(reason);
310
469
  };
311
470
  }
312
- get fatalErrors() {
313
- return this.stompConnectionManager.fatalErrors;
471
+ get connectionEnded() {
472
+ return this.connectionEndedSubject.asObservable();
473
+ }
474
+ get connectionEstablished() {
475
+ return this.stompConnectionManager.connectionEstablished;
314
476
  }
315
477
  isConnectionActive() {
316
478
  return this.stompConnectionManager.active;
@@ -319,15 +481,14 @@ class EventBus {
319
481
  return this.stompConnectionManager.connected;
320
482
  }
321
483
  connect(options) {
484
+ const disconnectsWhenQueued = this.disconnectRequests;
322
485
  return this.serializeLifecycle(async () => {
486
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
487
+ throw new Error("Disconnected before the connection was started");
488
+ }
323
489
  if (!this.stompConnectionManager.active) {
324
- this.cleanup();
325
490
  const connectedInfo = await this.stompConnectionManager.activate(options);
326
- this.serverInfo = new ServerInfo;
327
- this.serverInfo.host = options.host;
328
- this.serverInfo.port = options.port;
329
- this.serverInfo.useSSL = options.useSSL;
330
- this.replyToCri = this.stompConnectionManager.replyToCri;
491
+ this.serverInfo = { ...options.server };
331
492
  return connectedInfo;
332
493
  } else {
333
494
  throw new Error("Event Bus connection already active");
@@ -335,9 +496,12 @@ class EventBus {
335
496
  });
336
497
  }
337
498
  disconnect(force) {
499
+ this.disconnectRequests++;
500
+ const deactivated = this.stompConnectionManager.deactivate(force);
338
501
  return this.serializeLifecycle(async () => {
502
+ await deactivated;
339
503
  await this.stompConnectionManager.deactivate(force);
340
- this.cleanup();
504
+ this.serverInfo = null;
341
505
  });
342
506
  }
343
507
  serializeLifecycle(operation) {
@@ -346,7 +510,7 @@ class EventBus {
346
510
  return result;
347
511
  }
348
512
  send(event) {
349
- if (this.stompConnectionManager.rxStomp) {
513
+ if (this.stompConnectionManager.connected) {
350
514
  const headers = {};
351
515
  for (const [key, value] of event.headers.entries()) {
352
516
  headers[key] = value;
@@ -362,7 +526,8 @@ class EventBus {
362
526
  this.stompConnectionManager.rxStomp.publish({
363
527
  destination: event.cri,
364
528
  headers,
365
- binaryBody: event.data.orUndefined()
529
+ binaryBody: event.data.orUndefined(),
530
+ retryIfDisconnected: false
366
531
  });
367
532
  } else {
368
533
  throw this.createSendUnavailableError();
@@ -372,58 +537,65 @@ class EventBus {
372
537
  return firstValueFrom(this.requestStream(event, false));
373
538
  }
374
539
  requestStream(event, sendControlEvents = true) {
375
- if (this.stompConnectionManager?.rxStomp) {
376
- return new Observable2((subscriber) => {
377
- if (this.requestRepliesObservable == null) {
378
- this.requestRepliesSubject = new Subject2;
379
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
380
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
381
- }
382
- let serverSignaledCompletion = false;
383
- const correlationId = uuidv42();
384
- this.activeCorrelationIds.add(correlationId);
385
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
386
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
387
- })).subscribe({
388
- next(value) {
389
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
390
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
391
- serverSignaledCompletion = true;
392
- subscriber.complete();
393
- } else {
394
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
395
- }
396
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
540
+ return new Observable2((subscriber) => {
541
+ const replyToCri = this.stompConnectionManager.replyToCri;
542
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
543
+ subscriber.error(this.createSendUnavailableError());
544
+ return;
545
+ }
546
+ if (this.requestRepliesObservable == null) {
547
+ this.requestRepliesSubject = new Subject2;
548
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
549
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
550
+ }
551
+ let serverSignaledCompletion = false;
552
+ let replyDestinationReset = false;
553
+ const correlationId = uuidv42();
554
+ this.activeCorrelationIds.add(correlationId);
555
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
556
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
557
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
558
+ })).subscribe({
559
+ next(value) {
560
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
561
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
397
562
  serverSignaledCompletion = true;
398
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
563
+ if (value.data.isPresent() || !sendControlEvents) {
564
+ subscriber.next(value);
565
+ }
566
+ subscriber.complete();
399
567
  } else {
400
- subscriber.next(value);
568
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
401
569
  }
402
- },
403
- error(err) {
404
- subscriber.error(err);
405
- },
406
- complete() {
407
- subscriber.complete();
570
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
571
+ serverSignaledCompletion = true;
572
+ subscriber.error(RpcError.fromEvent(value));
573
+ } else {
574
+ subscriber.next(value);
408
575
  }
409
- });
410
- subscriber.add(defaultMessagesSubscription);
411
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
412
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
413
- this.send(event);
414
- return () => {
415
- this.activeCorrelationIds.delete(correlationId);
416
- if (sendControlEvents && !serverSignaledCompletion) {
417
- const controlEvent = new Event(event.cri);
418
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
419
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
420
- this.send(controlEvent);
576
+ },
577
+ error(err) {
578
+ replyDestinationReset = true;
579
+ subscriber.error(err);
580
+ },
581
+ complete() {
582
+ subscriber.complete();
583
+ }
584
+ });
585
+ subscriber.add(defaultMessagesSubscription);
586
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
587
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
588
+ this.send(event);
589
+ subscriber.add(() => {
590
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
591
+ try {
592
+ this.sendCancel(event.cri, correlationId);
593
+ } catch (e) {
594
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
421
595
  }
422
- };
596
+ }
423
597
  });
424
- } else {
425
- return throwError(() => this.createSendUnavailableError());
426
- }
598
+ });
427
599
  }
428
600
  listen(_serverInfo) {
429
601
  return Promise.reject("Not implemented");
@@ -431,10 +603,6 @@ class EventBus {
431
603
  observe(cri) {
432
604
  return this._observe(cri);
433
605
  }
434
- cleanup() {
435
- this.resetRequestReplies("Connection disconnected");
436
- this.serverInfo = null;
437
- }
438
606
  cancelIfUnexpected(value) {
439
607
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
440
608
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -445,13 +613,19 @@ class EventBus {
445
613
  return;
446
614
  }
447
615
  try {
448
- const cancelEvent = new Event(originCri);
449
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
450
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
451
- this.send(cancelEvent);
616
+ this.sendCancel(originCri, correlationId);
452
617
  this.recentlyReaped.add(correlationId);
453
618
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
454
- } catch {}
619
+ } catch (e) {
620
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
621
+ }
622
+ }
623
+ sendCancel(cri, correlationId) {
624
+ const cancelEvent = new Event(cri);
625
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
626
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
627
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
628
+ this.send(cancelEvent);
455
629
  }
456
630
  resetRequestReplies(reason) {
457
631
  if (this.requestRepliesSubject != null) {
@@ -466,29 +640,29 @@ class EventBus {
466
640
  }
467
641
  }
468
642
  createSendUnavailableError() {
469
- let ret = "You must call connect on the event bus before sending any request";
643
+ let ret;
470
644
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
471
645
  ret = "Max connection attempts reached event bus is not available";
646
+ } else if (this.stompConnectionManager.active) {
647
+ ret = "The event bus is not connected to the server";
648
+ } else {
649
+ ret = "You must call connect on the event bus before sending any request";
472
650
  }
473
651
  return new Error(ret);
474
652
  }
475
653
  _observe(cri) {
476
- if (this.stompConnectionManager?.rxStomp) {
477
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
478
- const headers = new Map;
479
- let destination = "";
480
- for (const prop of Object.keys(message.headers)) {
481
- if (prop === "destination") {
482
- destination = message.headers[prop];
483
- } else {
484
- headers.set(prop, message.headers[prop]);
485
- }
654
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
655
+ const headers = new Map;
656
+ let destination = "";
657
+ for (const prop of Object.keys(message.headers)) {
658
+ if (prop === "destination") {
659
+ destination = message.headers[prop];
660
+ } else {
661
+ headers.set(prop, message.headers[prop]);
486
662
  }
487
- return new Event(destination, headers, message.binaryBody);
488
- }));
489
- } else {
490
- throw this.createSendUnavailableError();
491
- }
663
+ }
664
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
665
+ }));
492
666
  }
493
667
  }
494
668
 
@@ -511,28 +685,46 @@ class ChainedCredentialsResolver {
511
685
  }
512
686
  }
513
687
 
688
+ // packages/core/src/api/security/BasicCredentialsResolver.ts
689
+ class BasicCredentialsResolver {
690
+ name = "BasicCredentialsResolver";
691
+ credentials;
692
+ constructor(clientId, clientSecret, organizationId, applicationId) {
693
+ const authHeaders = { clientId, clientSecret };
694
+ if (organizationId != null)
695
+ authHeaders.organizationId = organizationId;
696
+ if (applicationId != null)
697
+ authHeaders.applicationId = applicationId;
698
+ this.credentials = { authHeaders, organizationId, applicationId };
699
+ }
700
+ async resolve(_server) {
701
+ return this.credentials;
702
+ }
703
+ }
704
+
705
+ // packages/core/src/api/security/BearerCredentialsResolver.ts
706
+ class BearerCredentialsResolver {
707
+ name = "BearerCredentialsResolver";
708
+ token;
709
+ constructor(token) {
710
+ this.token = token;
711
+ }
712
+ async resolve(_server) {
713
+ const token = typeof this.token === "function" ? await this.token() : this.token;
714
+ return { authHeaders: { Authorization: `Bearer ${token}` } };
715
+ }
716
+ }
717
+
514
718
  // packages/core/src/api/security/EnvCredentialsResolver.ts
515
719
  class EnvCredentialsResolver {
516
720
  name = "EnvCredentialsResolver";
517
- async resolve(_server) {
721
+ async resolve(server) {
518
722
  const env = typeof process !== "undefined" ? process.env : undefined;
519
723
  let ret = null;
520
724
  if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
521
- const authHeaders = {
522
- clientId: env.KINOTIC_CLIENT_ID,
523
- clientSecret: env.KINOTIC_CLIENT_SECRET
524
- };
525
- if (env.KINOTIC_ORGANIZATION_ID)
526
- authHeaders.organizationId = env.KINOTIC_ORGANIZATION_ID;
527
- if (env.KINOTIC_APPLICATION_ID)
528
- authHeaders.applicationId = env.KINOTIC_APPLICATION_ID;
529
- ret = {
530
- authHeaders,
531
- organizationId: env.KINOTIC_ORGANIZATION_ID,
532
- applicationId: env.KINOTIC_APPLICATION_ID
533
- };
725
+ ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
534
726
  } else if (env?.KINOTIC_TOKEN) {
535
- ret = { authHeaders: { Authorization: `Bearer ${env.KINOTIC_TOKEN}` } };
727
+ ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
536
728
  }
537
729
  return ret;
538
730
  }
@@ -548,7 +740,7 @@ class SessionCredentialsResolver {
548
740
 
549
741
  // packages/core/src/internal/api/Util.ts
550
742
  var DEFAULT_PORT = 58503;
551
- var DEFAULT_HOST = "api.kinotic.com";
743
+ var DEFAULT_HOST = "api.kinotic.ai";
552
744
 
553
745
  class Util {
554
746
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -572,20 +764,18 @@ class Util {
572
764
  }
573
765
  return new Event(replyCRI, newHeaders, body || undefined);
574
766
  }
575
- static buildBrokerUrl(serverInfo) {
576
- return "ws" + (serverInfo.useSSL ? "s" : "") + "://" + serverInfo.host + (serverInfo.port ? ":" + serverInfo.port : "") + "/v1";
577
- }
578
767
  static resolveConnectOptions(options) {
579
768
  const opts = options ?? {};
769
+ const server = opts.server ?? {};
580
770
  const env = typeof process !== "undefined" ? process.env : undefined;
581
771
  const location = typeof window !== "undefined" ? window.location : undefined;
582
- let host = opts.host ?? env?.KINOTIC_SERVER_HOST;
772
+ let host = server.host ?? env?.KINOTIC_SERVER_HOST;
583
773
  const hostFromLocation = host == null && location != null;
584
774
  const hostDefaulted = host == null && location == null;
585
775
  if (host == null) {
586
776
  host = location?.hostname ?? DEFAULT_HOST;
587
777
  }
588
- let useSSL = opts.useSSL;
778
+ let useSSL = server.useSSL;
589
779
  if (useSSL == null) {
590
780
  if (env?.KINOTIC_SERVER_USE_SSL != null) {
591
781
  useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
@@ -595,7 +785,7 @@ class Util {
595
785
  useSSL = hostDefaulted;
596
786
  }
597
787
  }
598
- let port = opts.port;
788
+ let port = server.port;
599
789
  if (port === undefined) {
600
790
  if (env?.KINOTIC_SERVER_PORT != null) {
601
791
  port = Number(env.KINOTIC_SERVER_PORT);
@@ -607,9 +797,7 @@ class Util {
607
797
  }
608
798
  return {
609
799
  ...opts,
610
- host,
611
- port,
612
- useSSL,
800
+ server: { host, port, useSSL },
613
801
  sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
614
802
  credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
615
803
  };
@@ -805,22 +993,14 @@ class JsonArgumentResolver {
805
993
  // packages/core/src/internal/api/ReturnValueConverter.ts
806
994
  class BasicReturnValueConverter {
807
995
  convert(incomingMetadata, returnValue) {
808
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
996
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
997
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
809
998
  }
810
999
  }
811
1000
 
812
- // packages/core/src/internal/api/Logger.ts
813
- import debug2 from "debug";
814
- function createDebugLogger(namespace) {
815
- const debugLogger = debug2(namespace);
816
- return {
817
- trace: (...args) => debugLogger("TRACE", ...args),
818
- debug: (...args) => debugLogger("DEBUG", ...args),
819
- info: (...args) => debugLogger("INFO", ...args),
820
- warn: (...args) => debugLogger("WARN", ...args),
821
- error: (...args) => debugLogger("ERROR", ...args)
822
- };
823
- }
1001
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1002
+ import { isObservable } from "rxjs";
1003
+ import { finalize } from "rxjs/operators";
824
1004
 
825
1005
  // packages/core/src/api/ServiceIdentifier.ts
826
1006
  class ServiceIdentifier {
@@ -857,6 +1037,9 @@ class ServiceIdentifier {
857
1037
  }
858
1038
  return this._cri;
859
1039
  }
1040
+ unscopedCri() {
1041
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1042
+ }
860
1043
  }
861
1044
 
862
1045
  // packages/core/src/api/ZoneUtil.ts
@@ -876,10 +1059,12 @@ function validateLabel(label) {
876
1059
 
877
1060
  // packages/core/src/api/KinoticDecorators.ts
878
1061
  var scopeFunctions = new WeakSet;
1062
+ var scopeOptionalFunctions = new WeakSet;
879
1063
  var versionRegistry = new WeakMap;
880
1064
  var zonesRegistry = new WeakMap;
881
1065
  var advertisedRegistry = new WeakMap;
882
1066
  var contextMarkedFunctions = new WeakSet;
1067
+ var authzResourceClasses = new WeakSet;
883
1068
  function findInConstructorChain(registry, constructor) {
884
1069
  let current = constructor;
885
1070
  while (current) {
@@ -913,6 +1098,23 @@ function resolveScope(instance) {
913
1098
  function Scope(value, _context) {
914
1099
  scopeFunctions.add(value);
915
1100
  }
1101
+ function ScopeOptional(value, _context) {
1102
+ scopeOptionalFunctions.add(value);
1103
+ }
1104
+ function scopeOptionalMethodNames(instance) {
1105
+ const ret = new Set;
1106
+ let proto = Object.getPrototypeOf(instance);
1107
+ while (proto && proto !== Object.prototype) {
1108
+ for (const key of Object.getOwnPropertyNames(proto)) {
1109
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1110
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1111
+ ret.add(key);
1112
+ }
1113
+ }
1114
+ proto = Object.getPrototypeOf(proto);
1115
+ }
1116
+ return ret;
1117
+ }
916
1118
  function Version(version) {
917
1119
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
918
1120
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -953,6 +1155,23 @@ function resolveEffectiveZone(constructor) {
953
1155
  }
954
1156
  return effectiveZone;
955
1157
  }
1158
+ function AuthzResource(declaration) {
1159
+ return function(value, _context) {
1160
+ authzResourceClasses.add(value);
1161
+ };
1162
+ }
1163
+ function AuthzCheck(declaration) {
1164
+ return function(_value, _context) {};
1165
+ }
1166
+ function declaresAuthzResource(serviceInstance) {
1167
+ let ret = false;
1168
+ let current = serviceInstance.constructor;
1169
+ while (current && !ret) {
1170
+ ret = authzResourceClasses.has(current);
1171
+ current = Object.getPrototypeOf(current);
1172
+ }
1173
+ return ret;
1174
+ }
956
1175
  function Publish(namespace, name, advertise = false) {
957
1176
  return function(value, _context) {
958
1177
  advertisedRegistry.set(value, advertise);
@@ -975,6 +1194,94 @@ function Publish(namespace, name, advertise = false) {
975
1194
  };
976
1195
  }
977
1196
 
1197
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1198
+ import opentelemetry, { context as context2, propagation as propagation2, trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
1199
+ // packages/core/package.json
1200
+ var package_default = {
1201
+ name: "@kinotic-ai/core",
1202
+ version: "5.0.0-beta.20",
1203
+ type: "module",
1204
+ files: [
1205
+ "dist"
1206
+ ],
1207
+ module: "./dist/index.js",
1208
+ main: "./dist/index.cjs",
1209
+ types: "./dist/index.d.ts",
1210
+ exports: {
1211
+ ".": {
1212
+ import: {
1213
+ types: "./dist/index.d.ts",
1214
+ default: "./dist/index.js"
1215
+ },
1216
+ require: {
1217
+ types: "./dist/index.d.cts",
1218
+ default: "./dist/index.cjs"
1219
+ }
1220
+ },
1221
+ "./node": {
1222
+ import: {
1223
+ types: "./dist/node/index.d.ts",
1224
+ default: "./dist/node/index.js"
1225
+ },
1226
+ require: {
1227
+ types: "./dist/node/index.d.cts",
1228
+ default: "./dist/node/index.cjs"
1229
+ }
1230
+ },
1231
+ "./package.json": "./package.json"
1232
+ },
1233
+ homepage: "https://github.com/kinotic-ai/kinotic",
1234
+ repository: {
1235
+ type: "git",
1236
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1237
+ directory: "kinotic-js/workspace/packages/core"
1238
+ },
1239
+ license: "Elastic License 2.0",
1240
+ publishConfig: {
1241
+ access: "public"
1242
+ },
1243
+ scripts: {
1244
+ "type-check": "tsc --noEmit",
1245
+ test: "vitest run",
1246
+ coverage: "vitest run --coverage",
1247
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1248
+ },
1249
+ devDependencies: {
1250
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1251
+ "@opentelemetry/resources": "^2.10.0",
1252
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1253
+ "@opentelemetry/sdk-node": "^0.221.0",
1254
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1255
+ "@types/debug": "^4.1.13",
1256
+ "@types/node": "^25.6.0",
1257
+ "@types/ws": "^8.18.0",
1258
+ "@vitest/coverage-v8": "^4.1.4",
1259
+ "@vitest/runner": "^4.1.4",
1260
+ "@vitest/ui": "^4.1.4",
1261
+ allure: "^3.19.1",
1262
+ "allure-vitest": "^3.13.0",
1263
+ dotenv: "^17.4.1",
1264
+ "properties-file": "^4.0.0",
1265
+ testcontainers: "^11.14.0",
1266
+ tslib: "^2.8.1",
1267
+ typescript: "^6.0.2",
1268
+ vitest: "^4.1.4"
1269
+ },
1270
+ dependencies: {
1271
+ "@kinotic-ai/idl": "workspace:*",
1272
+ "@opentelemetry/api": "^1.9.1",
1273
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1274
+ "@stomp/rx-stomp": "^2.4.0",
1275
+ "@stomp/stompjs": "^7.3.0",
1276
+ debug: "^4.4.3",
1277
+ "p-tap": "^4.0.0",
1278
+ rxjs: "^7.8.2",
1279
+ "typescript-optional": "3.0.0-alpha.3",
1280
+ uuid: "^13.0.0",
1281
+ ws: "^8.21.0"
1282
+ }
1283
+ };
1284
+
978
1285
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
979
1286
  class ServiceInvocationSupervisor {
980
1287
  log;
@@ -986,7 +1293,13 @@ class ServiceInvocationSupervisor {
986
1293
  serviceIdentifier;
987
1294
  serviceInstance;
988
1295
  methodSubscription = null;
1296
+ unscopedSubscription = null;
1297
+ activeStreams = new Map;
1298
+ connectionEndedSubscription = null;
1299
+ connectionGeneration = 0;
989
1300
  methodMap;
1301
+ scopeOptionalMethods;
1302
+ tracer;
990
1303
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
991
1304
  if (!serviceIdentifier)
992
1305
  throw new Error("ServiceIdentifier must not be null");
@@ -1000,10 +1313,12 @@ class ServiceInvocationSupervisor {
1000
1313
  this.serviceInstance = serviceInstance;
1001
1314
  this._eventBus = eventBusService;
1002
1315
  this.interceptorProvider = interceptorProvider;
1003
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1316
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1004
1317
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1005
1318
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1006
1319
  this.methodMap = this.buildMethodMap(serviceInstance);
1320
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1321
+ this.tracer = opentelemetry.trace.getTracer(package_default.name, package_default.version);
1007
1322
  }
1008
1323
  isActive() {
1009
1324
  return this.active;
@@ -1023,7 +1338,22 @@ class ServiceInvocationSupervisor {
1023
1338
  }
1024
1339
  this.active = true;
1025
1340
  const criBase = this.serviceIdentifier.cri().baseResource();
1026
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1341
+ this.methodSubscription = this.subscribeAt(criBase);
1342
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1343
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1344
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1345
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1346
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1347
+ }
1348
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1349
+ this.connectionGeneration++;
1350
+ for (const stream of this.activeStreams.values()) {
1351
+ stream.subscription.unsubscribe();
1352
+ }
1353
+ });
1354
+ }
1355
+ subscribeAt(criBase) {
1356
+ return this._eventBus.observe(criBase).subscribe({
1027
1357
  next: async (event) => {
1028
1358
  await this.processEvent(event);
1029
1359
  },
@@ -1036,7 +1366,6 @@ class ServiceInvocationSupervisor {
1036
1366
  this.active = false;
1037
1367
  }
1038
1368
  });
1039
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1040
1369
  }
1041
1370
  stop() {
1042
1371
  if (!this.active) {
@@ -1045,6 +1374,15 @@ class ServiceInvocationSupervisor {
1045
1374
  this.active = false;
1046
1375
  this.methodSubscription?.unsubscribe();
1047
1376
  this.methodSubscription = null;
1377
+ this.unscopedSubscription?.unsubscribe();
1378
+ this.unscopedSubscription = null;
1379
+ this.connectionEndedSubscription?.unsubscribe();
1380
+ this.connectionEndedSubscription = null;
1381
+ const serviceName = this.serviceIdentifier.qualifiedName();
1382
+ for (const stream of this.activeStreams.values()) {
1383
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1384
+ stream.subscription.unsubscribe();
1385
+ }
1048
1386
  this.log.info("ServiceInvocationSupervisor stopped");
1049
1387
  }
1050
1388
  buildMethodMap(serviceInstance) {
@@ -1084,10 +1422,19 @@ class ServiceInvocationSupervisor {
1084
1422
  if (!correlationId) {
1085
1423
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1086
1424
  }
1087
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1425
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1426
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1427
+ const stream = this.activeStreams.get(correlationId);
1428
+ if (stream) {
1429
+ stream.subscription.unsubscribe();
1430
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1431
+ throw new Error(`Unknown control header value ${control}`);
1432
+ }
1433
+ }
1088
1434
  }
1089
1435
  async processInvocationRequest(event) {
1090
- const path = createCRI(event.cri).path();
1436
+ const incomingCri = createCRI(event.cri);
1437
+ const path = incomingCri.path();
1091
1438
  if (!path) {
1092
1439
  throw new Error("The methodId must not be blank");
1093
1440
  }
@@ -1095,49 +1442,167 @@ class ServiceInvocationSupervisor {
1095
1442
  if (!handlerMethod) {
1096
1443
  throw new Error(`No method resolved for methodId ${path}`);
1097
1444
  }
1445
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1446
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1447
+ }
1098
1448
  const methodName = path;
1099
- const args = this.argumentResolver.resolveArguments(event);
1100
- const injectContext = receivesContext(this.serviceInstance, methodName);
1101
- let context2 = {};
1102
- const interceptor = this.interceptorProvider();
1103
- if (interceptor) {
1449
+ const span = this.startInvocationSpan(event, methodName);
1450
+ const generation = this.connectionGeneration;
1451
+ try {
1452
+ const args = this.argumentResolver.resolveArguments(event);
1453
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1454
+ let serviceContext = {};
1455
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1456
+ if (sender) {
1457
+ serviceContext.participant = JSON.parse(sender);
1458
+ }
1459
+ const interceptor = this.interceptorProvider();
1460
+ if (interceptor) {
1461
+ try {
1462
+ serviceContext = await interceptor.intercept(event, serviceContext);
1463
+ } catch (e) {
1464
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1465
+ if (this.replyOwed(generation)) {
1466
+ this.handleException(event, new Error("Internal server error"));
1467
+ }
1468
+ this.failSpan(span, e);
1469
+ return;
1470
+ }
1471
+ }
1472
+ if (injectContext) {
1473
+ args.push(serviceContext);
1474
+ }
1475
+ const expectedArgsCount = handlerMethod.length;
1476
+ if (args.length !== expectedArgsCount) {
1477
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1478
+ }
1479
+ let result;
1104
1480
  try {
1105
- context2 = await interceptor.intercept(event, context2);
1481
+ result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
1482
+ if (result instanceof Promise) {
1483
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1484
+ this.failInvocation(event, e, span, generation);
1485
+ });
1486
+ } else {
1487
+ this.processMethodInvocationResult(event, result, span, generation);
1488
+ }
1106
1489
  } catch (e) {
1107
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1108
- this.handleException(event, new Error("Internal server error"));
1109
- return;
1490
+ this.failInvocation(event, e, span, generation);
1491
+ }
1492
+ } catch (e) {
1493
+ this.failSpan(span, e);
1494
+ throw e;
1495
+ }
1496
+ }
1497
+ startInvocationSpan(event, methodName) {
1498
+ const carrier = {};
1499
+ for (const [key, value] of event.headers.entries()) {
1500
+ carrier[key] = value;
1501
+ }
1502
+ const serviceName = this.serviceIdentifier.qualifiedName();
1503
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1504
+ kind: SpanKind.SERVER,
1505
+ attributes: {
1506
+ "rpc.system": "kinotic",
1507
+ "rpc.service": serviceName,
1508
+ "rpc.method": methodName
1110
1509
  }
1510
+ }, propagation2.extract(context2.active(), carrier));
1511
+ }
1512
+ failSpan(span, error) {
1513
+ span.recordException(error);
1514
+ span.setStatus({ code: SpanStatusCode.ERROR });
1515
+ span.end();
1516
+ }
1517
+ replyOwed(generation) {
1518
+ return generation === this.connectionGeneration;
1519
+ }
1520
+ failInvocation(event, error, span, generation) {
1521
+ if (this.replyOwed(generation)) {
1522
+ this.handleException(event, error);
1111
1523
  }
1112
- if (injectContext) {
1113
- args.push(context2);
1524
+ this.failSpan(span, error);
1525
+ }
1526
+ processMethodInvocationResult(event, result, span, generation) {
1527
+ if (!this.replyOwed(generation)) {
1528
+ span.end();
1529
+ } else if (isObservable(result)) {
1530
+ this.streamResult(event, result, span);
1531
+ } else {
1532
+ const reply = this.returnValueConverter.convert(event.headers, result);
1533
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1534
+ this.sendReply(reply);
1535
+ span.end();
1114
1536
  }
1115
- const expectedArgsCount = handlerMethod.length;
1116
- if (args.length !== expectedArgsCount) {
1117
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1537
+ }
1538
+ streamResult(event, stream, span) {
1539
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1540
+ if (!correlationId) {
1541
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1542
+ }
1543
+ let subscription = null;
1544
+ let failed = false;
1545
+ subscription = stream.pipe(finalize(() => {
1546
+ this.activeStreams.delete(correlationId);
1547
+ span.end();
1548
+ })).subscribe({
1549
+ next: (value) => {
1550
+ if (failed) {
1551
+ return;
1552
+ }
1553
+ try {
1554
+ const reply = this.returnValueConverter.convert(event.headers, value);
1555
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1556
+ this.sendReply(reply);
1557
+ } catch (e) {
1558
+ failed = true;
1559
+ this.handleException(event, e);
1560
+ span.recordException(e);
1561
+ span.setStatus({ code: SpanStatusCode.ERROR });
1562
+ subscription?.unsubscribe();
1563
+ }
1564
+ },
1565
+ error: (error) => {
1566
+ if (failed) {
1567
+ return;
1568
+ }
1569
+ this.handleException(event, error);
1570
+ span.recordException(error);
1571
+ span.setStatus({ code: SpanStatusCode.ERROR });
1572
+ },
1573
+ complete: () => {
1574
+ if (failed) {
1575
+ return;
1576
+ }
1577
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1578
+ }
1579
+ });
1580
+ if (failed) {
1581
+ subscription.unsubscribe();
1582
+ }
1583
+ if (!subscription.closed) {
1584
+ this.activeStreams.set(correlationId, { request: event, subscription });
1118
1585
  }
1119
- let result;
1586
+ }
1587
+ sendReply(event) {
1120
1588
  try {
1121
- result = handlerMethod(...args);
1122
- if (result instanceof Promise) {
1123
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1124
- } else {
1125
- this.processMethodInvocationResult(event, result);
1126
- }
1589
+ this._eventBus.send(event);
1127
1590
  } catch (e) {
1128
- this.handleException(event, e);
1591
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1129
1592
  }
1130
1593
  }
1131
- processMethodInvocationResult(event, result) {
1132
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1133
- this._eventBus.send(outgoingEvent);
1134
- }
1135
1594
  handleException(event, error) {
1136
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1137
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1138
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1139
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1140
- this._eventBus.send(errorEvent);
1595
+ try {
1596
+ const errorMessage = error?.message || "Unknown error";
1597
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1598
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1599
+ ["error" /* ERROR_HEADER */, errorMessage],
1600
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1601
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1602
+ this.sendReply(errorEvent);
1603
+ } catch (e) {
1604
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1605
+ }
1141
1606
  }
1142
1607
  validateReplyTo(event) {
1143
1608
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1158,100 +1623,12 @@ class ServiceInvocationSupervisor {
1158
1623
  }
1159
1624
 
1160
1625
  // packages/core/src/api/ServiceRegistry.ts
1161
- import opentelemetry, { SpanKind, SpanStatusCode } from "@opentelemetry/api";
1626
+ import opentelemetry2, { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
1162
1627
  import {
1163
1628
  ATTR_SERVER_ADDRESS,
1164
1629
  ATTR_SERVER_PORT
1165
1630
  } from "@opentelemetry/semantic-conventions";
1166
1631
  import { first, map as map2 } from "rxjs/operators";
1167
- // packages/core/package.json
1168
- var package_default = {
1169
- name: "@kinotic-ai/core",
1170
- version: "5.0.0-beta.2",
1171
- type: "module",
1172
- files: [
1173
- "dist"
1174
- ],
1175
- module: "./dist/index.js",
1176
- main: "./dist/index.cjs",
1177
- types: "./dist/index.d.ts",
1178
- exports: {
1179
- ".": {
1180
- import: {
1181
- types: "./dist/index.d.ts",
1182
- default: "./dist/index.js"
1183
- },
1184
- require: {
1185
- types: "./dist/index.d.cts",
1186
- default: "./dist/index.cjs"
1187
- }
1188
- },
1189
- "./node": {
1190
- import: {
1191
- types: "./dist/node/index.d.ts",
1192
- default: "./dist/node/index.js"
1193
- },
1194
- require: {
1195
- types: "./dist/node/index.d.cts",
1196
- default: "./dist/node/index.cjs"
1197
- }
1198
- },
1199
- "./package.json": "./package.json"
1200
- },
1201
- homepage: "https://github.com/kinotic-ai/kinotic",
1202
- license: "Elastic License 2.0",
1203
- publishConfig: {
1204
- access: "public"
1205
- },
1206
- scripts: {
1207
- "type-check": "tsc --noEmit",
1208
- test: "vitest run",
1209
- coverage: "vitest run --coverage",
1210
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1211
- },
1212
- devDependencies: {
1213
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1214
- "@opentelemetry/resources": "^2.6.1",
1215
- "@opentelemetry/sdk-metrics": "^2.6.1",
1216
- "@opentelemetry/sdk-node": "^0.214.0",
1217
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1218
- "@types/node": "^25.6.0",
1219
- "@types/uuid": "^11.0.0",
1220
- "@types/ws": "^8.18.0",
1221
- "@vitest/coverage-v8": "^4.1.4",
1222
- "@vitest/runner": "^4.1.4",
1223
- "@vitest/ui": "^4.1.4",
1224
- allure: "^3.4.1",
1225
- "allure-vitest": "^3.7.1",
1226
- dotenv: "^17.4.1",
1227
- "properties-file": "^4.0.0",
1228
- testcontainers: "^11.14.0",
1229
- tslib: "^2.8.1",
1230
- typescript: "^6.0.2",
1231
- vitest: "^4.1.4",
1232
- ws: "^8.20.0"
1233
- },
1234
- dependencies: {
1235
- "@opentelemetry/api": "^1.9.1",
1236
- "@opentelemetry/semantic-conventions": "^1.40.0",
1237
- "@stomp/rx-stomp": "^2.4.0",
1238
- "@stomp/stompjs": "^7.3.0",
1239
- "@types/debug": "^4.1.13",
1240
- debug: "^4.4.3",
1241
- "p-tap": "^4.0.0",
1242
- rxjs: "^7.8.2",
1243
- "typescript-optional": "3.0.0-alpha.3",
1244
- uuid: "^13.0.0",
1245
- ws: "^8.18.0"
1246
- },
1247
- peerDependenciesMeta: {
1248
- typescript: {
1249
- optional: true
1250
- }
1251
- }
1252
- };
1253
-
1254
- // packages/core/src/api/ServiceRegistry.ts
1255
1632
  class JsonEventFactory {
1256
1633
  create(cri, args) {
1257
1634
  const event = new Event(cri);
@@ -1285,12 +1662,63 @@ class TextEventFactory {
1285
1662
  return event;
1286
1663
  }
1287
1664
  }
1665
+ var SERVICE_DIRECTORY_SERVICE = "app-api~org.kinotic.app.api.services.ServiceDirectoryService";
1666
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1667
+ var declaredDefinitions = new Map;
1668
+ function declareServiceDefinitions(definitions) {
1669
+ for (const definition of definitions) {
1670
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1671
+ }
1672
+ }
1673
+ function qualifiedNameOf(namespace, name) {
1674
+ return namespace ? `${namespace}.${name}` : name;
1675
+ }
1676
+ function servedFunctions(serviceInstance) {
1677
+ const ret = new Set;
1678
+ let proto = Object.getPrototypeOf(serviceInstance);
1679
+ while (proto && proto !== Object.prototype) {
1680
+ for (const key of Object.getOwnPropertyNames(proto)) {
1681
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1682
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1683
+ ret.add(key);
1684
+ }
1685
+ }
1686
+ proto = Object.getPrototypeOf(proto);
1687
+ }
1688
+ return [...ret].sort();
1689
+ }
1690
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1691
+ let ret = null;
1692
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1693
+ if (application) {
1694
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1695
+ const definition = declaredDefinitions.get(qualifiedName);
1696
+ if (definition) {
1697
+ const declared = definition.functions.map((f) => f.name).sort();
1698
+ const served = servedFunctions(serviceInstance);
1699
+ if (declared.join() !== served.join()) {
1700
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1701
+ }
1702
+ ret = {
1703
+ applicationId: application[1],
1704
+ zone: serviceIdentifier.zone,
1705
+ version: serviceIdentifier.version ?? null,
1706
+ advertised: isAdvertised(serviceInstance),
1707
+ serviceDefinition: definition
1708
+ };
1709
+ } else if (declaresAuthzResource(serviceInstance)) {
1710
+ throw new Error(`${qualifiedName} declares a resource but the project declares no definition for it;` + " run kinotic sync and import the generated ServiceDefinitions module");
1711
+ }
1712
+ }
1713
+ return ret;
1714
+ }
1288
1715
 
1289
1716
  class ServiceRegistry {
1290
1717
  _eventBus;
1291
1718
  supervisors = new Map;
1719
+ entries = new Map;
1292
1720
  contextInterceptor = null;
1293
- debugLogger = debug3("kinoitc:serviceRegistry");
1721
+ debugLogger = debug3("kinotic:serviceRegistry");
1294
1722
  constructor(eventBus) {
1295
1723
  this._eventBus = eventBus;
1296
1724
  }
@@ -1310,9 +1738,16 @@ class ServiceRegistry {
1310
1738
  const criString = serviceIdentifier.cri().raw();
1311
1739
  if (!this.supervisors.has(criString)) {
1312
1740
  this.debugLogger(`Registering service for CRI: ${criString}`);
1741
+ const entry = directoryEntryOf(service, serviceIdentifier);
1313
1742
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1314
1743
  this.supervisors.set(criString, supervisor);
1315
1744
  supervisor.start();
1745
+ if (entry) {
1746
+ this.entries.set(criString, entry);
1747
+ if (this.eventBus.isConnected()) {
1748
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1749
+ }
1750
+ }
1316
1751
  }
1317
1752
  }
1318
1753
  unRegister(serviceIdentifier) {
@@ -1322,8 +1757,18 @@ class ServiceRegistry {
1322
1757
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1323
1758
  supervisor.stop();
1324
1759
  this.supervisors.delete(criString);
1760
+ this.entries.delete(criString);
1761
+ }
1762
+ }
1763
+ async registerEntries() {
1764
+ for (const entry of this.entries.values()) {
1765
+ await this.registerEntry(entry);
1325
1766
  }
1326
1767
  }
1768
+ async registerEntry(entry) {
1769
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
1770
+ await this.serviceProxy(SERVICE_DIRECTORY_SERVICE).invoke("register", [entry]);
1771
+ }
1327
1772
  registerContextInterceptor(interceptor) {
1328
1773
  this.contextInterceptor = interceptor;
1329
1774
  }
@@ -1340,16 +1785,16 @@ class ServiceProxy {
1340
1785
  }
1341
1786
  this.serviceIdentifier = serviceIdentifier;
1342
1787
  this.serviceRegistry = serviceRegistry;
1343
- this.tracer = opentelemetry.trace.getTracer("kinoitc.client", package_default.version);
1788
+ this.tracer = opentelemetry2.trace.getTracer(package_default.name, package_default.version);
1344
1789
  }
1345
1790
  invoke(methodIdentifier, args, scope, eventFactory) {
1346
1791
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1347
- kind: SpanKind.CLIENT
1792
+ kind: SpanKind2.CLIENT
1348
1793
  }, async (span) => {
1349
1794
  if (scope) {
1350
- span.setAttribute("kinoitc.scope", scope);
1795
+ span.setAttribute("kinotic.scope", scope);
1351
1796
  }
1352
- span.setAttribute("rpc.system", "kinoitc");
1797
+ span.setAttribute("rpc.system", "kinotic");
1353
1798
  span.setAttribute("rpc.service", this.serviceIdentifier);
1354
1799
  span.setAttribute("rpc.method", methodIdentifier);
1355
1800
  return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(first()).toPromise().then(async (value) => {
@@ -1357,7 +1802,7 @@ class ServiceProxy {
1357
1802
  return value;
1358
1803
  }, async (ex) => {
1359
1804
  span.recordException(ex);
1360
- span.setStatus({ code: SpanStatusCode.ERROR });
1805
+ span.setStatus({ code: SpanStatusCode2.ERROR });
1361
1806
  span.end();
1362
1807
  throw ex;
1363
1808
  });
@@ -1373,7 +1818,7 @@ class ServiceProxy {
1373
1818
  eventFactoryToUse = eventFactory;
1374
1819
  }
1375
1820
  let eventBusToUse = this.serviceRegistry.eventBus;
1376
- const span = opentelemetry.trace.getActiveSpan();
1821
+ const span = opentelemetry2.trace.getActiveSpan();
1377
1822
  if (span) {
1378
1823
  span.setAttribute(ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1379
1824
  span.setAttribute(ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
@@ -1415,8 +1860,10 @@ class KinoticSingleton {
1415
1860
  this._eventBus = eventBus;
1416
1861
  this.serviceRegistry.eventBus = eventBus;
1417
1862
  }
1418
- connect(options) {
1419
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1863
+ async connect(options) {
1864
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1865
+ await this.serviceRegistry.registerEntries();
1866
+ return ret;
1420
1867
  }
1421
1868
  disconnect(force) {
1422
1869
  return this._eventBus.disconnect(force);
@@ -1537,6 +1984,9 @@ class CrudServiceProxy {
1537
1984
  deleteById(id) {
1538
1985
  return this.serviceProxy.invoke("deleteById", [id]);
1539
1986
  }
1987
+ deleteByIdSync(id) {
1988
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
1989
+ }
1540
1990
  async findAll(pageable) {
1541
1991
  const page = await this.findAllSinglePage(pageable);
1542
1992
  return new FindAllIterablePage(pageable, page, this);
@@ -1659,32 +2109,11 @@ class Order {
1659
2109
  class Sort {
1660
2110
  orders = [];
1661
2111
  }
1662
- // packages/core/src/api/security/BasicCredentialsResolver.ts
1663
- class BasicCredentialsResolver {
1664
- name = "BasicCredentialsResolver";
1665
- credentials;
1666
- constructor(clientId, clientSecret, organizationId, applicationId) {
1667
- const authHeaders = { clientId, clientSecret };
1668
- if (organizationId != null)
1669
- authHeaders.organizationId = organizationId;
1670
- if (applicationId != null)
1671
- authHeaders.applicationId = applicationId;
1672
- this.credentials = { authHeaders, organizationId, applicationId };
1673
- }
1674
- async resolve(_server) {
1675
- return this.credentials;
1676
- }
1677
- }
1678
- // packages/core/src/api/security/BearerCredentialsResolver.ts
1679
- class BearerCredentialsResolver {
1680
- name = "BearerCredentialsResolver";
1681
- token;
1682
- constructor(token) {
1683
- this.token = token;
1684
- }
1685
- async resolve(_server) {
1686
- const token = typeof this.token === "function" ? await this.token() : this.token;
1687
- return { authHeaders: { Authorization: `Bearer ${token}` } };
2112
+ // packages/core/src/api/security/AuthorizationException.ts
2113
+ class AuthorizationException extends Error {
2114
+ constructor(message = "Access denied") {
2115
+ super(message);
2116
+ this.name = "AuthorizationException";
1688
2117
  }
1689
2118
  }
1690
2119
  // packages/core/src/api/security/ConnectedInfo.ts
@@ -1703,9 +2132,14 @@ class ParticipantConstants {
1703
2132
  export {
1704
2133
  validateZone,
1705
2134
  validateLabel,
2135
+ scopeOptionalMethodNames,
1706
2136
  receivesContext,
1707
2137
  isAdvertised,
2138
+ declaresAuthzResource,
2139
+ declareServiceDefinitions,
1708
2140
  createCRI,
2141
+ buildServerUrl,
2142
+ buildBrokerUrl,
1709
2143
  Zone,
1710
2144
  Version,
1711
2145
  TextEventFactory,
@@ -1713,8 +2147,11 @@ export {
1713
2147
  SessionKeepAliveMode,
1714
2148
  SessionCredentialsResolver,
1715
2149
  ServiceRegistry,
2150
+ ServiceIdentifier,
1716
2151
  ServerInfo,
2152
+ ScopeOptional,
1717
2153
  Scope,
2154
+ RpcError,
1718
2155
  Publish,
1719
2156
  ParticipantConstants,
1720
2157
  Pageable,
@@ -1740,5 +2177,8 @@ export {
1740
2177
  ChainedCredentialsResolver,
1741
2178
  BearerCredentialsResolver,
1742
2179
  BasicCredentialsResolver,
2180
+ AuthzResource,
2181
+ AuthzCheck,
2182
+ AuthorizationException,
1743
2183
  AbstractIterablePage
1744
2184
  };