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

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,24 @@ 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 AuthzUnchecked(_value, _context) {}
1167
+ function declaresAuthzResource(serviceInstance) {
1168
+ let ret = false;
1169
+ let current = serviceInstance.constructor;
1170
+ while (current && !ret) {
1171
+ ret = authzResourceClasses.has(current);
1172
+ current = Object.getPrototypeOf(current);
1173
+ }
1174
+ return ret;
1175
+ }
956
1176
  function Publish(namespace, name, advertise = false) {
957
1177
  return function(value, _context) {
958
1178
  advertisedRegistry.set(value, advertise);
@@ -975,6 +1195,94 @@ function Publish(namespace, name, advertise = false) {
975
1195
  };
976
1196
  }
977
1197
 
1198
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1199
+ import opentelemetry, { context as context2, propagation as propagation2, trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
1200
+ // packages/core/package.json
1201
+ var package_default = {
1202
+ name: "@kinotic-ai/core",
1203
+ version: "5.0.0-beta.21",
1204
+ type: "module",
1205
+ files: [
1206
+ "dist"
1207
+ ],
1208
+ module: "./dist/index.js",
1209
+ main: "./dist/index.cjs",
1210
+ types: "./dist/index.d.ts",
1211
+ exports: {
1212
+ ".": {
1213
+ import: {
1214
+ types: "./dist/index.d.ts",
1215
+ default: "./dist/index.js"
1216
+ },
1217
+ require: {
1218
+ types: "./dist/index.d.cts",
1219
+ default: "./dist/index.cjs"
1220
+ }
1221
+ },
1222
+ "./node": {
1223
+ import: {
1224
+ types: "./dist/node/index.d.ts",
1225
+ default: "./dist/node/index.js"
1226
+ },
1227
+ require: {
1228
+ types: "./dist/node/index.d.cts",
1229
+ default: "./dist/node/index.cjs"
1230
+ }
1231
+ },
1232
+ "./package.json": "./package.json"
1233
+ },
1234
+ homepage: "https://github.com/kinotic-ai/kinotic",
1235
+ repository: {
1236
+ type: "git",
1237
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1238
+ directory: "kinotic-js/workspace/packages/core"
1239
+ },
1240
+ license: "Elastic License 2.0",
1241
+ publishConfig: {
1242
+ access: "public"
1243
+ },
1244
+ scripts: {
1245
+ "type-check": "tsc --noEmit",
1246
+ test: "vitest run",
1247
+ coverage: "vitest run --coverage",
1248
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1249
+ },
1250
+ devDependencies: {
1251
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1252
+ "@opentelemetry/resources": "^2.10.0",
1253
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1254
+ "@opentelemetry/sdk-node": "^0.221.0",
1255
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1256
+ "@types/debug": "^4.1.13",
1257
+ "@types/node": "^25.6.0",
1258
+ "@types/ws": "^8.18.0",
1259
+ "@vitest/coverage-v8": "^4.1.4",
1260
+ "@vitest/runner": "^4.1.4",
1261
+ "@vitest/ui": "^4.1.4",
1262
+ allure: "^3.19.1",
1263
+ "allure-vitest": "^3.13.0",
1264
+ dotenv: "^17.4.1",
1265
+ "properties-file": "^4.0.0",
1266
+ testcontainers: "^11.14.0",
1267
+ tslib: "^2.8.1",
1268
+ typescript: "^6.0.2",
1269
+ vitest: "^4.1.4"
1270
+ },
1271
+ dependencies: {
1272
+ "@kinotic-ai/idl": "workspace:*",
1273
+ "@opentelemetry/api": "^1.9.1",
1274
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1275
+ "@stomp/rx-stomp": "^2.4.0",
1276
+ "@stomp/stompjs": "^7.3.0",
1277
+ debug: "^4.4.3",
1278
+ "p-tap": "^4.0.0",
1279
+ rxjs: "^7.8.2",
1280
+ "typescript-optional": "3.0.0-alpha.3",
1281
+ uuid: "^13.0.0",
1282
+ ws: "^8.21.0"
1283
+ }
1284
+ };
1285
+
978
1286
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
979
1287
  class ServiceInvocationSupervisor {
980
1288
  log;
@@ -986,7 +1294,13 @@ class ServiceInvocationSupervisor {
986
1294
  serviceIdentifier;
987
1295
  serviceInstance;
988
1296
  methodSubscription = null;
1297
+ unscopedSubscription = null;
1298
+ activeStreams = new Map;
1299
+ connectionEndedSubscription = null;
1300
+ connectionGeneration = 0;
989
1301
  methodMap;
1302
+ scopeOptionalMethods;
1303
+ tracer;
990
1304
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
991
1305
  if (!serviceIdentifier)
992
1306
  throw new Error("ServiceIdentifier must not be null");
@@ -1000,10 +1314,12 @@ class ServiceInvocationSupervisor {
1000
1314
  this.serviceInstance = serviceInstance;
1001
1315
  this._eventBus = eventBusService;
1002
1316
  this.interceptorProvider = interceptorProvider;
1003
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1317
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1004
1318
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1005
1319
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1006
1320
  this.methodMap = this.buildMethodMap(serviceInstance);
1321
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1322
+ this.tracer = opentelemetry.trace.getTracer(package_default.name, package_default.version);
1007
1323
  }
1008
1324
  isActive() {
1009
1325
  return this.active;
@@ -1023,7 +1339,22 @@ class ServiceInvocationSupervisor {
1023
1339
  }
1024
1340
  this.active = true;
1025
1341
  const criBase = this.serviceIdentifier.cri().baseResource();
1026
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1342
+ this.methodSubscription = this.subscribeAt(criBase);
1343
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1344
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1345
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1346
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1347
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1348
+ }
1349
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1350
+ this.connectionGeneration++;
1351
+ for (const stream of this.activeStreams.values()) {
1352
+ stream.subscription.unsubscribe();
1353
+ }
1354
+ });
1355
+ }
1356
+ subscribeAt(criBase) {
1357
+ return this._eventBus.observe(criBase).subscribe({
1027
1358
  next: async (event) => {
1028
1359
  await this.processEvent(event);
1029
1360
  },
@@ -1036,7 +1367,6 @@ class ServiceInvocationSupervisor {
1036
1367
  this.active = false;
1037
1368
  }
1038
1369
  });
1039
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1040
1370
  }
1041
1371
  stop() {
1042
1372
  if (!this.active) {
@@ -1045,6 +1375,15 @@ class ServiceInvocationSupervisor {
1045
1375
  this.active = false;
1046
1376
  this.methodSubscription?.unsubscribe();
1047
1377
  this.methodSubscription = null;
1378
+ this.unscopedSubscription?.unsubscribe();
1379
+ this.unscopedSubscription = null;
1380
+ this.connectionEndedSubscription?.unsubscribe();
1381
+ this.connectionEndedSubscription = null;
1382
+ const serviceName = this.serviceIdentifier.qualifiedName();
1383
+ for (const stream of this.activeStreams.values()) {
1384
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1385
+ stream.subscription.unsubscribe();
1386
+ }
1048
1387
  this.log.info("ServiceInvocationSupervisor stopped");
1049
1388
  }
1050
1389
  buildMethodMap(serviceInstance) {
@@ -1084,10 +1423,19 @@ class ServiceInvocationSupervisor {
1084
1423
  if (!correlationId) {
1085
1424
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1086
1425
  }
1087
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1426
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1427
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1428
+ const stream = this.activeStreams.get(correlationId);
1429
+ if (stream) {
1430
+ stream.subscription.unsubscribe();
1431
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1432
+ throw new Error(`Unknown control header value ${control}`);
1433
+ }
1434
+ }
1088
1435
  }
1089
1436
  async processInvocationRequest(event) {
1090
- const path = createCRI(event.cri).path();
1437
+ const incomingCri = createCRI(event.cri);
1438
+ const path = incomingCri.path();
1091
1439
  if (!path) {
1092
1440
  throw new Error("The methodId must not be blank");
1093
1441
  }
@@ -1095,49 +1443,167 @@ class ServiceInvocationSupervisor {
1095
1443
  if (!handlerMethod) {
1096
1444
  throw new Error(`No method resolved for methodId ${path}`);
1097
1445
  }
1446
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1447
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1448
+ }
1098
1449
  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) {
1450
+ const span = this.startInvocationSpan(event, methodName);
1451
+ const generation = this.connectionGeneration;
1452
+ try {
1453
+ const args = this.argumentResolver.resolveArguments(event);
1454
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1455
+ let serviceContext = {};
1456
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1457
+ if (sender) {
1458
+ serviceContext.participant = JSON.parse(sender);
1459
+ }
1460
+ const interceptor = this.interceptorProvider();
1461
+ if (interceptor) {
1462
+ try {
1463
+ serviceContext = await interceptor.intercept(event, serviceContext);
1464
+ } catch (e) {
1465
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1466
+ if (this.replyOwed(generation)) {
1467
+ this.handleException(event, new Error("Internal server error"));
1468
+ }
1469
+ this.failSpan(span, e);
1470
+ return;
1471
+ }
1472
+ }
1473
+ if (injectContext) {
1474
+ args.push(serviceContext);
1475
+ }
1476
+ const expectedArgsCount = handlerMethod.length;
1477
+ if (args.length !== expectedArgsCount) {
1478
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1479
+ }
1480
+ let result;
1104
1481
  try {
1105
- context2 = await interceptor.intercept(event, context2);
1482
+ result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
1483
+ if (result instanceof Promise) {
1484
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1485
+ this.failInvocation(event, e, span, generation);
1486
+ });
1487
+ } else {
1488
+ this.processMethodInvocationResult(event, result, span, generation);
1489
+ }
1106
1490
  } 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;
1491
+ this.failInvocation(event, e, span, generation);
1492
+ }
1493
+ } catch (e) {
1494
+ this.failSpan(span, e);
1495
+ throw e;
1496
+ }
1497
+ }
1498
+ startInvocationSpan(event, methodName) {
1499
+ const carrier = {};
1500
+ for (const [key, value] of event.headers.entries()) {
1501
+ carrier[key] = value;
1502
+ }
1503
+ const serviceName = this.serviceIdentifier.qualifiedName();
1504
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1505
+ kind: SpanKind.SERVER,
1506
+ attributes: {
1507
+ "rpc.system": "kinotic",
1508
+ "rpc.service": serviceName,
1509
+ "rpc.method": methodName
1110
1510
  }
1511
+ }, propagation2.extract(context2.active(), carrier));
1512
+ }
1513
+ failSpan(span, error) {
1514
+ span.recordException(error);
1515
+ span.setStatus({ code: SpanStatusCode.ERROR });
1516
+ span.end();
1517
+ }
1518
+ replyOwed(generation) {
1519
+ return generation === this.connectionGeneration;
1520
+ }
1521
+ failInvocation(event, error, span, generation) {
1522
+ if (this.replyOwed(generation)) {
1523
+ this.handleException(event, error);
1111
1524
  }
1112
- if (injectContext) {
1113
- args.push(context2);
1525
+ this.failSpan(span, error);
1526
+ }
1527
+ processMethodInvocationResult(event, result, span, generation) {
1528
+ if (!this.replyOwed(generation)) {
1529
+ span.end();
1530
+ } else if (isObservable(result)) {
1531
+ this.streamResult(event, result, span);
1532
+ } else {
1533
+ const reply = this.returnValueConverter.convert(event.headers, result);
1534
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1535
+ this.sendReply(reply);
1536
+ span.end();
1114
1537
  }
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}`);
1538
+ }
1539
+ streamResult(event, stream, span) {
1540
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1541
+ if (!correlationId) {
1542
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1543
+ }
1544
+ let subscription = null;
1545
+ let failed = false;
1546
+ subscription = stream.pipe(finalize(() => {
1547
+ this.activeStreams.delete(correlationId);
1548
+ span.end();
1549
+ })).subscribe({
1550
+ next: (value) => {
1551
+ if (failed) {
1552
+ return;
1553
+ }
1554
+ try {
1555
+ const reply = this.returnValueConverter.convert(event.headers, value);
1556
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1557
+ this.sendReply(reply);
1558
+ } catch (e) {
1559
+ failed = true;
1560
+ this.handleException(event, e);
1561
+ span.recordException(e);
1562
+ span.setStatus({ code: SpanStatusCode.ERROR });
1563
+ subscription?.unsubscribe();
1564
+ }
1565
+ },
1566
+ error: (error) => {
1567
+ if (failed) {
1568
+ return;
1569
+ }
1570
+ this.handleException(event, error);
1571
+ span.recordException(error);
1572
+ span.setStatus({ code: SpanStatusCode.ERROR });
1573
+ },
1574
+ complete: () => {
1575
+ if (failed) {
1576
+ return;
1577
+ }
1578
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1579
+ }
1580
+ });
1581
+ if (failed) {
1582
+ subscription.unsubscribe();
1583
+ }
1584
+ if (!subscription.closed) {
1585
+ this.activeStreams.set(correlationId, { request: event, subscription });
1118
1586
  }
1119
- let result;
1587
+ }
1588
+ sendReply(event) {
1120
1589
  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
- }
1590
+ this._eventBus.send(event);
1127
1591
  } catch (e) {
1128
- this.handleException(event, e);
1592
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1129
1593
  }
1130
1594
  }
1131
- processMethodInvocationResult(event, result) {
1132
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1133
- this._eventBus.send(outgoingEvent);
1134
- }
1135
1595
  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);
1596
+ try {
1597
+ const errorMessage = error?.message || "Unknown error";
1598
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1599
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1600
+ ["error" /* ERROR_HEADER */, errorMessage],
1601
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1602
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1603
+ this.sendReply(errorEvent);
1604
+ } catch (e) {
1605
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1606
+ }
1141
1607
  }
1142
1608
  validateReplyTo(event) {
1143
1609
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1158,100 +1624,12 @@ class ServiceInvocationSupervisor {
1158
1624
  }
1159
1625
 
1160
1626
  // packages/core/src/api/ServiceRegistry.ts
1161
- import opentelemetry, { SpanKind, SpanStatusCode } from "@opentelemetry/api";
1627
+ import opentelemetry2, { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
1162
1628
  import {
1163
1629
  ATTR_SERVER_ADDRESS,
1164
1630
  ATTR_SERVER_PORT
1165
1631
  } from "@opentelemetry/semantic-conventions";
1166
1632
  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
1633
  class JsonEventFactory {
1256
1634
  create(cri, args) {
1257
1635
  const event = new Event(cri);
@@ -1285,12 +1663,63 @@ class TextEventFactory {
1285
1663
  return event;
1286
1664
  }
1287
1665
  }
1666
+ var SERVICE_DIRECTORY_SERVICE = "app-api~org.kinotic.app.api.services.ServiceDirectoryService";
1667
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1668
+ var declaredDefinitions = new Map;
1669
+ function declareServiceDefinitions(definitions) {
1670
+ for (const definition of definitions) {
1671
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1672
+ }
1673
+ }
1674
+ function qualifiedNameOf(namespace, name) {
1675
+ return namespace ? `${namespace}.${name}` : name;
1676
+ }
1677
+ function servedFunctions(serviceInstance) {
1678
+ const ret = new Set;
1679
+ let proto = Object.getPrototypeOf(serviceInstance);
1680
+ while (proto && proto !== Object.prototype) {
1681
+ for (const key of Object.getOwnPropertyNames(proto)) {
1682
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1683
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1684
+ ret.add(key);
1685
+ }
1686
+ }
1687
+ proto = Object.getPrototypeOf(proto);
1688
+ }
1689
+ return [...ret].sort();
1690
+ }
1691
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1692
+ let ret = null;
1693
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1694
+ if (application) {
1695
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1696
+ const definition = declaredDefinitions.get(qualifiedName);
1697
+ if (definition) {
1698
+ const declared = definition.functions.map((f) => f.name).sort();
1699
+ const served = servedFunctions(serviceInstance);
1700
+ if (declared.join() !== served.join()) {
1701
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1702
+ }
1703
+ ret = {
1704
+ applicationId: application[1],
1705
+ zone: serviceIdentifier.zone,
1706
+ version: serviceIdentifier.version ?? null,
1707
+ advertised: isAdvertised(serviceInstance),
1708
+ serviceDefinition: definition
1709
+ };
1710
+ } else if (declaresAuthzResource(serviceInstance)) {
1711
+ throw new Error(`${qualifiedName} declares a resource but the project declares no definition for it;` + " run kinotic sync and import the generated ServiceDefinitions module");
1712
+ }
1713
+ }
1714
+ return ret;
1715
+ }
1288
1716
 
1289
1717
  class ServiceRegistry {
1290
1718
  _eventBus;
1291
1719
  supervisors = new Map;
1720
+ entries = new Map;
1292
1721
  contextInterceptor = null;
1293
- debugLogger = debug3("kinoitc:serviceRegistry");
1722
+ debugLogger = debug3("kinotic:serviceRegistry");
1294
1723
  constructor(eventBus) {
1295
1724
  this._eventBus = eventBus;
1296
1725
  }
@@ -1310,9 +1739,16 @@ class ServiceRegistry {
1310
1739
  const criString = serviceIdentifier.cri().raw();
1311
1740
  if (!this.supervisors.has(criString)) {
1312
1741
  this.debugLogger(`Registering service for CRI: ${criString}`);
1742
+ const entry = directoryEntryOf(service, serviceIdentifier);
1313
1743
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1314
1744
  this.supervisors.set(criString, supervisor);
1315
1745
  supervisor.start();
1746
+ if (entry) {
1747
+ this.entries.set(criString, entry);
1748
+ if (this.eventBus.isConnected()) {
1749
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1750
+ }
1751
+ }
1316
1752
  }
1317
1753
  }
1318
1754
  unRegister(serviceIdentifier) {
@@ -1322,8 +1758,18 @@ class ServiceRegistry {
1322
1758
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1323
1759
  supervisor.stop();
1324
1760
  this.supervisors.delete(criString);
1761
+ this.entries.delete(criString);
1762
+ }
1763
+ }
1764
+ async registerEntries() {
1765
+ for (const entry of this.entries.values()) {
1766
+ await this.registerEntry(entry);
1325
1767
  }
1326
1768
  }
1769
+ async registerEntry(entry) {
1770
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
1771
+ await this.serviceProxy(SERVICE_DIRECTORY_SERVICE).invoke("register", [entry]);
1772
+ }
1327
1773
  registerContextInterceptor(interceptor) {
1328
1774
  this.contextInterceptor = interceptor;
1329
1775
  }
@@ -1340,16 +1786,16 @@ class ServiceProxy {
1340
1786
  }
1341
1787
  this.serviceIdentifier = serviceIdentifier;
1342
1788
  this.serviceRegistry = serviceRegistry;
1343
- this.tracer = opentelemetry.trace.getTracer("kinoitc.client", package_default.version);
1789
+ this.tracer = opentelemetry2.trace.getTracer(package_default.name, package_default.version);
1344
1790
  }
1345
1791
  invoke(methodIdentifier, args, scope, eventFactory) {
1346
1792
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1347
- kind: SpanKind.CLIENT
1793
+ kind: SpanKind2.CLIENT
1348
1794
  }, async (span) => {
1349
1795
  if (scope) {
1350
- span.setAttribute("kinoitc.scope", scope);
1796
+ span.setAttribute("kinotic.scope", scope);
1351
1797
  }
1352
- span.setAttribute("rpc.system", "kinoitc");
1798
+ span.setAttribute("rpc.system", "kinotic");
1353
1799
  span.setAttribute("rpc.service", this.serviceIdentifier);
1354
1800
  span.setAttribute("rpc.method", methodIdentifier);
1355
1801
  return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(first()).toPromise().then(async (value) => {
@@ -1357,7 +1803,7 @@ class ServiceProxy {
1357
1803
  return value;
1358
1804
  }, async (ex) => {
1359
1805
  span.recordException(ex);
1360
- span.setStatus({ code: SpanStatusCode.ERROR });
1806
+ span.setStatus({ code: SpanStatusCode2.ERROR });
1361
1807
  span.end();
1362
1808
  throw ex;
1363
1809
  });
@@ -1373,7 +1819,7 @@ class ServiceProxy {
1373
1819
  eventFactoryToUse = eventFactory;
1374
1820
  }
1375
1821
  let eventBusToUse = this.serviceRegistry.eventBus;
1376
- const span = opentelemetry.trace.getActiveSpan();
1822
+ const span = opentelemetry2.trace.getActiveSpan();
1377
1823
  if (span) {
1378
1824
  span.setAttribute(ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1379
1825
  span.setAttribute(ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
@@ -1415,8 +1861,10 @@ class KinoticSingleton {
1415
1861
  this._eventBus = eventBus;
1416
1862
  this.serviceRegistry.eventBus = eventBus;
1417
1863
  }
1418
- connect(options) {
1419
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1864
+ async connect(options) {
1865
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1866
+ await this.serviceRegistry.registerEntries();
1867
+ return ret;
1420
1868
  }
1421
1869
  disconnect(force) {
1422
1870
  return this._eventBus.disconnect(force);
@@ -1537,6 +1985,9 @@ class CrudServiceProxy {
1537
1985
  deleteById(id) {
1538
1986
  return this.serviceProxy.invoke("deleteById", [id]);
1539
1987
  }
1988
+ deleteByIdSync(id) {
1989
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
1990
+ }
1540
1991
  async findAll(pageable) {
1541
1992
  const page = await this.findAllSinglePage(pageable);
1542
1993
  return new FindAllIterablePage(pageable, page, this);
@@ -1659,32 +2110,11 @@ class Order {
1659
2110
  class Sort {
1660
2111
  orders = [];
1661
2112
  }
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}` } };
2113
+ // packages/core/src/api/security/AuthorizationException.ts
2114
+ class AuthorizationException extends Error {
2115
+ constructor(message = "Access denied") {
2116
+ super(message);
2117
+ this.name = "AuthorizationException";
1688
2118
  }
1689
2119
  }
1690
2120
  // packages/core/src/api/security/ConnectedInfo.ts
@@ -1703,9 +2133,14 @@ class ParticipantConstants {
1703
2133
  export {
1704
2134
  validateZone,
1705
2135
  validateLabel,
2136
+ scopeOptionalMethodNames,
1706
2137
  receivesContext,
1707
2138
  isAdvertised,
2139
+ declaresAuthzResource,
2140
+ declareServiceDefinitions,
1708
2141
  createCRI,
2142
+ buildServerUrl,
2143
+ buildBrokerUrl,
1709
2144
  Zone,
1710
2145
  Version,
1711
2146
  TextEventFactory,
@@ -1713,8 +2148,11 @@ export {
1713
2148
  SessionKeepAliveMode,
1714
2149
  SessionCredentialsResolver,
1715
2150
  ServiceRegistry,
2151
+ ServiceIdentifier,
1716
2152
  ServerInfo,
2153
+ ScopeOptional,
1717
2154
  Scope,
2155
+ RpcError,
1718
2156
  Publish,
1719
2157
  ParticipantConstants,
1720
2158
  Pageable,
@@ -1740,5 +2178,9 @@ export {
1740
2178
  ChainedCredentialsResolver,
1741
2179
  BearerCredentialsResolver,
1742
2180
  BasicCredentialsResolver,
2181
+ AuthzUnchecked,
2182
+ AuthzResource,
2183
+ AuthzCheck,
2184
+ AuthorizationException,
1743
2185
  AbstractIterablePage
1744
2186
  };