@kinotic-ai/core 5.0.0-beta.10 → 5.0.0-beta.12

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.cjs CHANGED
@@ -70,7 +70,6 @@ __export(exports_src, {
70
70
  receivesContext: () => receivesContext,
71
71
  isAdvertised: () => isAdvertised,
72
72
  createCRI: () => createCRI,
73
- checkUiVersion: () => checkUiVersion,
74
73
  buildServerUrl: () => buildServerUrl,
75
74
  buildBrokerUrl: () => buildBrokerUrl,
76
75
  Zone: () => Zone,
@@ -80,9 +79,11 @@ __export(exports_src, {
80
79
  SessionKeepAliveMode: () => SessionKeepAliveMode,
81
80
  SessionCredentialsResolver: () => SessionCredentialsResolver,
82
81
  ServiceRegistry: () => ServiceRegistry,
82
+ ServiceIdentifier: () => ServiceIdentifier,
83
83
  ServerInfo: () => ServerInfo,
84
84
  ScopeOptional: () => ScopeOptional,
85
85
  Scope: () => Scope,
86
+ RpcError: () => RpcError,
86
87
  Publish: () => Publish,
87
88
  ParticipantConstants: () => ParticipantConstants,
88
89
  Pageable: () => Pageable,
@@ -180,17 +181,67 @@ var import_debug2 = __toESM(require("debug"));
180
181
  var import_rxjs = require("rxjs");
181
182
  var import_operators = require("rxjs/operators");
182
183
  var import_uuid = require("uuid");
184
+
185
+ // packages/core/src/internal/api/StompActivation.ts
186
+ class StompActivation {
187
+ _ended = false;
188
+ wake = null;
189
+ preparedSocket = null;
190
+ attempt = null;
191
+ failPending = null;
192
+ subscriptions = [];
193
+ get ended() {
194
+ return this._ended;
195
+ }
196
+ end() {
197
+ this._ended = true;
198
+ this.wake?.();
199
+ this.wake = null;
200
+ }
201
+ delay(ms) {
202
+ return new Promise((resolve) => {
203
+ const timer = setTimeout(() => {
204
+ this.wake = null;
205
+ resolve();
206
+ }, ms);
207
+ this.wake = () => {
208
+ clearTimeout(timer);
209
+ resolve();
210
+ };
211
+ });
212
+ }
213
+ own(subscription) {
214
+ this.subscriptions.push(subscription);
215
+ }
216
+ pending(fail) {
217
+ this.failPending = fail;
218
+ }
219
+ established() {
220
+ this.failPending = null;
221
+ }
222
+ failIfPending(reason) {
223
+ const fail = this.failPending;
224
+ this.failPending = null;
225
+ fail?.(reason);
226
+ }
227
+ unsubscribeAll() {
228
+ for (const subscription of this.subscriptions) {
229
+ subscription.unsubscribe();
230
+ }
231
+ this.subscriptions.length = 0;
232
+ }
233
+ }
234
+
235
+ // packages/core/src/internal/api/StompConnectionManager.ts
183
236
  var SESSION_CHECK_PATH = "/api/auth/me";
184
237
 
185
238
  class StompConnectionManager {
186
239
  lastWebsocketError = null;
187
240
  maxConnectionAttemptsReached = false;
188
- replyToCriChangedHandler = null;
241
+ connectionLostHandler = null;
189
242
  rxStomp = new import_rx_stomp.RxStomp;
190
- isActive = false;
191
- initialConnectedSubscription = null;
192
- initialFailureSubscription = null;
193
- webSocketErrorsSubscription = null;
243
+ activation = null;
244
+ teardown = null;
194
245
  INITIAL_RECONNECT_DELAY = 2000;
195
246
  JITTER_MAX = 5000;
196
247
  MAX_RECONNECT_DELAY = 120000;
@@ -200,18 +251,15 @@ class StompConnectionManager {
200
251
  _fatalErrors = this.fatalErrorsSubject.asObservable();
201
252
  initialConnectionSuccessful = false;
202
253
  rxStompHasConnected = false;
203
- serverHeadersSubscription = null;
204
- stompErrorsSubscription = null;
205
- uuidv4 = import_uuid.v4();
206
254
  _replyToCri = null;
207
255
  get replyToCri() {
208
256
  return this._replyToCri;
209
257
  }
210
258
  get active() {
211
- return this.isActive;
259
+ return this.activation !== null;
212
260
  }
213
261
  get connected() {
214
- return this.isActive && this.rxStomp.connected();
262
+ return this.activation !== null && this.rxStomp.connected();
215
263
  }
216
264
  get fatalErrors() {
217
265
  return this._fatalErrors;
@@ -220,21 +268,37 @@ class StompConnectionManager {
220
268
  if (!options?.server?.host) {
221
269
  throw new Error("No host provided");
222
270
  }
223
- if (this.isActive) {
271
+ if (this.activation) {
272
+ throw new Error("Stomp connection already active");
273
+ }
274
+ await this.teardown;
275
+ if (this.activation) {
224
276
  throw new Error("Stomp connection already active");
225
277
  }
226
278
  const server = options.server;
227
279
  const credentialsResolver = options.credentials;
280
+ const activation = new StompActivation;
281
+ this.activation = activation;
228
282
  let headerAuth = false;
229
- if (!options.webSocketFactory) {
230
- if (!credentialsResolver) {
231
- throw new Error("No credentials supplied and no default resolution applied");
283
+ try {
284
+ if (!options.webSocketFactory) {
285
+ if (!credentialsResolver) {
286
+ throw new Error("No credentials supplied and no default resolution applied");
287
+ }
288
+ const resolved = await credentialsResolver.resolve(server);
289
+ if (resolved === null) {
290
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
291
+ }
292
+ headerAuth = resolved.authHeaders != null;
232
293
  }
233
- const resolved = await credentialsResolver.resolve(server);
234
- if (resolved === null) {
235
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
294
+ if (activation.ended) {
295
+ throw new Error("Deactivated before the connection was established");
236
296
  }
237
- headerAuth = resolved.authHeaders != null;
297
+ } catch (e) {
298
+ if (this.activation === activation) {
299
+ this.activation = null;
300
+ }
301
+ throw e;
238
302
  }
239
303
  return new Promise((resolve, reject) => {
240
304
  this.connectionAttempts = 0;
@@ -242,64 +306,28 @@ class StompConnectionManager {
242
306
  this.lastWebsocketError = null;
243
307
  this.maxConnectionAttemptsReached = false;
244
308
  const url = buildBrokerUrl(server);
245
- let preparedSocket = null;
246
- const userWebSocketFactory = options.webSocketFactory;
247
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
309
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
310
+ const takePreparedSocket = () => {
311
+ const socket = activation.preparedSocket;
312
+ activation.preparedSocket = null;
313
+ return socket;
314
+ };
248
315
  const stompConfig = {
249
316
  brokerURL: url,
250
317
  connectHeaders: {
251
318
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
252
319
  },
253
- heartbeatIncoming: 120000,
320
+ heartbeatIncoming: 30000,
254
321
  heartbeatOutgoing: 30000,
255
322
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
256
323
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
257
324
  reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
258
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
259
- beforeConnect: async () => {
260
- if (!usesPreparedSocket) {
261
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
262
- try {
263
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
264
- if (res.status === 401) {
265
- await this.signalFatal(new Error("Authentication required"));
266
- return;
267
- }
268
- } catch (e) {
269
- this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
270
- }
271
- }
272
- if (options?.maxConnectionAttempts) {
273
- this.connectionAttempts++;
274
- if (this.connectionAttempts > options.maxConnectionAttempts) {
275
- this.maxConnectionAttemptsReached = true;
276
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
277
- return;
278
- } else {
279
- await this.connectionJitterDelay();
280
- }
281
- } else {
282
- await this.connectionJitterDelay();
283
- }
284
- if (userWebSocketFactory) {
285
- try {
286
- preparedSocket = await userWebSocketFactory();
287
- } catch (e) {
288
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
289
- }
290
- } else if (headerAuth) {
291
- try {
292
- const resolved = await credentialsResolver.resolve(server);
293
- if (resolved?.authHeaders == null) {
294
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
295
- } else {
296
- const WS = WebSocket;
297
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
298
- }
299
- } catch (e) {
300
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
301
- }
302
- }
325
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
326
+ beforeConnect: () => {
327
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
328
+ const settled = () => new Promise((resolve2) => setTimeout(resolve2, 0));
329
+ activation.attempt = attempt.then(settled, settled);
330
+ return attempt;
303
331
  }
304
332
  };
305
333
  if (this.debugLogger.enabled) {
@@ -308,87 +336,152 @@ class StompConnectionManager {
308
336
  };
309
337
  }
310
338
  this.rxStomp.configure(stompConfig);
311
- this.webSocketErrorsSubscription = this.rxStomp.webSocketErrors$.subscribe(async (value) => {
339
+ activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
312
340
  this.lastWebsocketError = value;
313
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
341
+ if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
314
342
  this.maxConnectionAttemptsReached = true;
315
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
343
+ await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
316
344
  }
317
- });
318
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
345
+ }));
346
+ activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
319
347
  const stompError = new Error(frame.headers["message"], { cause: frame });
320
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
321
- });
322
- this.initialConnectedSubscription = this.rxStomp.connected$.subscribe(() => {
323
- this.initialConnectedSubscription?.unsubscribe();
324
- this.initialFailureSubscription?.unsubscribe();
325
- if (!this.initialConnectionSuccessful) {
326
- this.initialConnectionSuccessful = true;
327
- }
328
- });
329
- this.initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
330
- this.initialConnectedSubscription?.unsubscribe();
331
- this.initialFailureSubscription?.unsubscribe();
332
- reject(err.message);
333
- });
334
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
348
+ await this.signalFatal(activation, new Error("STOMP connection error", { cause: stompError }));
349
+ }));
350
+ activation.own(this.rxStomp.connected$.subscribe(() => {
351
+ activation.established();
352
+ this.initialConnectionSuccessful = true;
353
+ this.connectionAttempts = 0;
354
+ }));
355
+ activation.pending(reject);
356
+ activation.own(this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
335
357
  this.rxStompHasConnected = true;
336
358
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
337
359
  if (connectedInfoJson == null) {
338
360
  if (!this.initialConnectionSuccessful) {
361
+ activation.failIfPending(new Error("Server did not return proper data for successful login"));
339
362
  await this.deactivate();
340
- reject("Server did not return proper data for successful login");
341
363
  }
342
364
  return;
343
365
  }
344
366
  const connectedInfo = JSON.parse(connectedInfoJson);
345
367
  if (connectedInfo.replyToId == null) {
346
368
  if (!this.initialConnectionSuccessful) {
369
+ activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
347
370
  await this.deactivate();
348
- reject("Server did not return a replyToId for successful login");
349
371
  }
350
372
  return;
351
373
  }
352
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinotic.js.EventBus/replyHandler";
374
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + import_uuid.v4() + "@kinotic.js.EventBus/replyHandler";
375
+ this._replyToCri = newReplyToCri;
353
376
  if (!this.initialConnectionSuccessful) {
354
- this._replyToCri = newReplyToCri;
355
377
  resolve(connectedInfo);
356
- } else if (this._replyToCri !== newReplyToCri) {
357
- this._replyToCri = newReplyToCri;
358
- this.replyToCriChangedHandler?.(newReplyToCri);
359
378
  }
360
- });
361
- this.isActive = true;
379
+ }));
380
+ let previousState = this.rxStomp.connectionState$.getValue();
381
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
382
+ if (state === import_rx_stomp.RxStompState.CLOSED && previousState === import_rx_stomp.RxStompState.OPEN && this.activation === activation) {
383
+ this.connectionLostHandler?.();
384
+ }
385
+ previousState = state;
386
+ }));
362
387
  this.rxStomp.activate();
363
388
  });
364
389
  }
365
- async deactivate(force) {
366
- if (this.isActive) {
367
- this.isActive = false;
368
- await this.rxStomp.deactivate({ force });
369
- this.initialConnectedSubscription?.unsubscribe();
370
- this.initialConnectedSubscription = null;
371
- this.webSocketErrorsSubscription?.unsubscribe();
372
- this.webSocketErrorsSubscription = null;
373
- this.serverHeadersSubscription?.unsubscribe();
374
- this.serverHeadersSubscription = null;
375
- this.stompErrorsSubscription?.unsubscribe();
376
- this.stompErrorsSubscription = null;
390
+ async prepareAttempt(activation, options, server, headerAuth) {
391
+ const credentialsResolver = options.credentials;
392
+ const userWebSocketFactory = options.webSocketFactory;
393
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
394
+ const url = buildBrokerUrl(server);
395
+ if (!usesPreparedSocket) {
396
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
397
+ try {
398
+ const res = await fetch(sessionCheckUrl, { credentials: "include" });
399
+ if (res.status === 401) {
400
+ await this.signalFatal(activation, new Error("Authentication required"));
401
+ return;
402
+ }
403
+ } catch (e) {
404
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
405
+ }
406
+ }
407
+ if (options?.maxConnectionAttempts) {
408
+ this.connectionAttempts++;
409
+ if (this.connectionAttempts > options.maxConnectionAttempts) {
410
+ this.maxConnectionAttemptsReached = true;
411
+ await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
412
+ return;
413
+ } else {
414
+ await this.connectionJitterDelay(activation);
415
+ }
416
+ } else {
417
+ await this.connectionJitterDelay(activation);
418
+ }
419
+ if (activation.ended) {
420
+ return;
421
+ }
422
+ if (userWebSocketFactory) {
423
+ try {
424
+ activation.preparedSocket = await userWebSocketFactory();
425
+ } catch (e) {
426
+ await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
427
+ }
428
+ } else if (headerAuth) {
429
+ try {
430
+ const resolved = await credentialsResolver.resolve(server);
431
+ if (resolved?.authHeaders == null) {
432
+ await this.signalFatal(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
433
+ } else {
434
+ const WS = WebSocket;
435
+ activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
436
+ }
437
+ } catch (e) {
438
+ await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
439
+ }
440
+ }
441
+ if (activation.ended && activation.preparedSocket) {
442
+ activation.preparedSocket.close();
443
+ activation.preparedSocket = null;
444
+ }
445
+ }
446
+ deactivate(force) {
447
+ const activation = this.activation;
448
+ let ret;
449
+ if (activation) {
450
+ this.activation = null;
451
+ activation.end();
452
+ const wasOpen = this.rxStomp.connected();
377
453
  this._replyToCri = null;
454
+ activation.failIfPending(new Error("Deactivated before the connection was established"));
455
+ activation.preparedSocket?.close();
456
+ activation.preparedSocket = null;
457
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
458
+ activation.unsubscribeAll();
459
+ this.teardown = null;
460
+ if (wasOpen) {
461
+ this.connectionLostHandler?.();
462
+ }
463
+ });
464
+ this.teardown = teardown;
465
+ ret = teardown;
466
+ } else {
467
+ ret = this.teardown ?? Promise.resolve();
378
468
  }
379
- return;
469
+ return ret;
380
470
  }
381
- async connectionJitterDelay() {
471
+ async connectionJitterDelay(activation) {
382
472
  if (this.initialConnectionSuccessful) {
383
473
  const randomJitter = Math.random() * this.JITTER_MAX;
384
474
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
385
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
475
+ await activation.delay(randomJitter);
386
476
  }
387
477
  }
388
- async signalFatal(err) {
389
- this.debugLogger("Fatal error, deactivating connection: %O", err);
390
- await this.deactivate();
391
- this.fatalErrorsSubject.next(err);
478
+ async signalFatal(activation, err) {
479
+ if (!activation.ended) {
480
+ this.debugLogger("Fatal error, deactivating connection: %O", err);
481
+ activation.failIfPending(err);
482
+ await this.deactivate();
483
+ this.fatalErrorsSubject.next(err);
484
+ }
392
485
  }
393
486
  }
394
487
 
@@ -398,6 +491,43 @@ var import_rxjs2 = require("rxjs");
398
491
  var import_operators2 = require("rxjs/operators");
399
492
  var import_typescript_optional = require("typescript-optional");
400
493
  var import_uuid2 = require("uuid");
494
+
495
+ // packages/core/src/api/event/RpcError.ts
496
+ class RpcError extends Error {
497
+ exceptionName;
498
+ exceptionClass;
499
+ constructor(message, exceptionName, exceptionClass) {
500
+ super(message);
501
+ this.name = "RpcError";
502
+ this.exceptionName = exceptionName;
503
+ this.exceptionClass = exceptionClass;
504
+ }
505
+ static fromEvent(reply) {
506
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
507
+ let ret;
508
+ const detail = describedException(reply);
509
+ if (detail !== undefined) {
510
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
511
+ } else {
512
+ ret = new RpcError(message, "", "");
513
+ }
514
+ return ret;
515
+ }
516
+ }
517
+ function describedException(reply) {
518
+ let ret = undefined;
519
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
520
+ try {
521
+ const parsed = JSON.parse(reply.getDataString());
522
+ if (parsed !== null && typeof parsed === "object") {
523
+ ret = parsed;
524
+ }
525
+ } catch {}
526
+ }
527
+ return ret;
528
+ }
529
+
530
+ // packages/core/src/api/event/EventBus.ts
401
531
  class Event {
402
532
  cri;
403
533
  headers;
@@ -439,23 +569,27 @@ class EventBus {
439
569
  log = createDebugLogger("kinotic:EventBus");
440
570
  stompConnectionManager = new StompConnectionManager;
441
571
  connectionLifecycle = Promise.resolve();
442
- replyToCri = null;
572
+ disconnectRequests = 0;
443
573
  requestRepliesObservable = null;
444
574
  requestRepliesSubject = null;
445
575
  requestRepliesSubscription = null;
446
576
  activeCorrelationIds = new Set;
447
577
  recentlyReaped = new Set;
578
+ connectionLostSubject = new import_rxjs2.Subject;
448
579
  static REAP_DEBOUNCE_MS = 5000;
449
580
  constructor() {
450
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
451
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
452
- this.replyToCri = replyToCri;
453
- this.resetRequestReplies("Reply destination changed");
581
+ this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
582
+ this.stompConnectionManager.connectionLostHandler = () => {
583
+ this.resetRequestReplies("Connection lost");
584
+ this.connectionLostSubject.next();
454
585
  };
455
586
  }
456
587
  get fatalErrors() {
457
588
  return this.stompConnectionManager.fatalErrors;
458
589
  }
590
+ get connectionLost() {
591
+ return this.connectionLostSubject.asObservable();
592
+ }
459
593
  isConnectionActive() {
460
594
  return this.stompConnectionManager.active;
461
595
  }
@@ -463,12 +597,14 @@ class EventBus {
463
597
  return this.stompConnectionManager.connected;
464
598
  }
465
599
  connect(options) {
600
+ const disconnectsWhenQueued = this.disconnectRequests;
466
601
  return this.serializeLifecycle(async () => {
602
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
603
+ throw new Error("Disconnected before the connection was started");
604
+ }
467
605
  if (!this.stompConnectionManager.active) {
468
- this.cleanup();
469
606
  const connectedInfo = await this.stompConnectionManager.activate(options);
470
607
  this.serverInfo = { ...options.server };
471
- this.replyToCri = this.stompConnectionManager.replyToCri;
472
608
  return connectedInfo;
473
609
  } else {
474
610
  throw new Error("Event Bus connection already active");
@@ -476,9 +612,12 @@ class EventBus {
476
612
  });
477
613
  }
478
614
  disconnect(force) {
615
+ this.disconnectRequests++;
616
+ const deactivated = this.stompConnectionManager.deactivate(force);
479
617
  return this.serializeLifecycle(async () => {
618
+ await deactivated;
480
619
  await this.stompConnectionManager.deactivate(force);
481
- this.cleanup();
620
+ this.serverInfo = null;
482
621
  });
483
622
  }
484
623
  serializeLifecycle(operation) {
@@ -514,59 +653,65 @@ class EventBus {
514
653
  return import_rxjs2.firstValueFrom(this.requestStream(event, false));
515
654
  }
516
655
  requestStream(event, sendControlEvents = true) {
517
- if (this.stompConnectionManager.active) {
518
- return new import_rxjs2.Observable((subscriber) => {
519
- if (this.requestRepliesObservable == null) {
520
- this.requestRepliesSubject = new import_rxjs2.Subject;
521
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
522
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
523
- }
524
- let serverSignaledCompletion = false;
525
- const correlationId = import_uuid2.v4();
526
- this.activeCorrelationIds.add(correlationId);
527
- subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
528
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
529
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
530
- })).subscribe({
531
- next(value) {
532
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
533
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
534
- serverSignaledCompletion = true;
535
- subscriber.complete();
536
- } else {
537
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
538
- }
539
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
656
+ return new import_rxjs2.Observable((subscriber) => {
657
+ const replyToCri = this.stompConnectionManager.replyToCri;
658
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
659
+ subscriber.error(this.createSendUnavailableError());
660
+ return;
661
+ }
662
+ if (this.requestRepliesObservable == null) {
663
+ this.requestRepliesSubject = new import_rxjs2.Subject;
664
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
665
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
666
+ }
667
+ let serverSignaledCompletion = false;
668
+ let replyDestinationReset = false;
669
+ const correlationId = import_uuid2.v4();
670
+ this.activeCorrelationIds.add(correlationId);
671
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
672
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
673
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
674
+ })).subscribe({
675
+ next(value) {
676
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
677
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
540
678
  serverSignaledCompletion = true;
541
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
679
+ if (value.data.isPresent() || !sendControlEvents) {
680
+ subscriber.next(value);
681
+ }
682
+ subscriber.complete();
542
683
  } else {
543
- subscriber.next(value);
684
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
544
685
  }
545
- },
546
- error(err) {
547
- subscriber.error(err);
548
- },
549
- complete() {
550
- subscriber.complete();
686
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
687
+ serverSignaledCompletion = true;
688
+ subscriber.error(RpcError.fromEvent(value));
689
+ } else {
690
+ subscriber.next(value);
551
691
  }
552
- });
553
- subscriber.add(defaultMessagesSubscription);
554
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
555
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
556
- this.send(event);
557
- subscriber.add(() => {
558
- if (sendControlEvents && !serverSignaledCompletion) {
559
- try {
560
- this.sendCancel(event.cri, correlationId);
561
- } catch (e) {
562
- this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
563
- }
692
+ },
693
+ error(err) {
694
+ replyDestinationReset = true;
695
+ subscriber.error(err);
696
+ },
697
+ complete() {
698
+ subscriber.complete();
699
+ }
700
+ });
701
+ subscriber.add(defaultMessagesSubscription);
702
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
703
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
704
+ this.send(event);
705
+ subscriber.add(() => {
706
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
707
+ try {
708
+ this.sendCancel(event.cri, correlationId);
709
+ } catch (e) {
710
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
564
711
  }
565
- });
712
+ }
566
713
  });
567
- } else {
568
- return import_rxjs2.throwError(() => this.createSendUnavailableError());
569
- }
714
+ });
570
715
  }
571
716
  listen(_serverInfo) {
572
717
  return Promise.reject("Not implemented");
@@ -574,10 +719,6 @@ class EventBus {
574
719
  observe(cri) {
575
720
  return this._observe(cri);
576
721
  }
577
- cleanup() {
578
- this.resetRequestReplies("Connection disconnected");
579
- this.serverInfo = null;
580
- }
581
722
  cancelIfUnexpected(value) {
582
723
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
583
724
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -599,7 +740,7 @@ class EventBus {
599
740
  const cancelEvent = new Event(cri);
600
741
  cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
601
742
  cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
602
- cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
743
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
603
744
  this.send(cancelEvent);
604
745
  }
605
746
  resetRequestReplies(reason) {
@@ -636,7 +777,7 @@ class EventBus {
636
777
  headers.set(prop, message.headers[prop]);
637
778
  }
638
779
  }
639
- return new Event(destination, headers, message.binaryBody);
780
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
640
781
  }));
641
782
  }
642
783
  }
@@ -973,6 +1114,10 @@ class BasicReturnValueConverter {
973
1114
  }
974
1115
  }
975
1116
 
1117
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1118
+ var import_rxjs3 = require("rxjs");
1119
+ var import_operators3 = require("rxjs/operators");
1120
+
976
1121
  // packages/core/src/api/ServiceIdentifier.ts
977
1122
  class ServiceIdentifier {
978
1123
  namespace;
@@ -1152,7 +1297,7 @@ var import_api2 = __toESM(require("@opentelemetry/api"));
1152
1297
  // packages/core/package.json
1153
1298
  var package_default = {
1154
1299
  name: "@kinotic-ai/core",
1155
- version: "5.0.0-beta.10",
1300
+ version: "5.0.0-beta.12",
1156
1301
  type: "module",
1157
1302
  files: [
1158
1303
  "dist"
@@ -1246,6 +1391,9 @@ class ServiceInvocationSupervisor {
1246
1391
  serviceInstance;
1247
1392
  methodSubscription = null;
1248
1393
  unscopedSubscription = null;
1394
+ activeStreams = new Map;
1395
+ connectionLostSubscription = null;
1396
+ connectionGeneration = 0;
1249
1397
  methodMap;
1250
1398
  scopeOptionalMethods;
1251
1399
  tracer;
@@ -1294,6 +1442,12 @@ class ServiceInvocationSupervisor {
1294
1442
  this.unscopedSubscription = this.subscribeAt(unscopedBase);
1295
1443
  this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1296
1444
  }
1445
+ this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
1446
+ this.connectionGeneration++;
1447
+ for (const stream of this.activeStreams.values()) {
1448
+ stream.subscription.unsubscribe();
1449
+ }
1450
+ });
1297
1451
  }
1298
1452
  subscribeAt(criBase) {
1299
1453
  return this._eventBus.observe(criBase).subscribe({
@@ -1319,6 +1473,13 @@ class ServiceInvocationSupervisor {
1319
1473
  this.methodSubscription = null;
1320
1474
  this.unscopedSubscription?.unsubscribe();
1321
1475
  this.unscopedSubscription = null;
1476
+ this.connectionLostSubscription?.unsubscribe();
1477
+ this.connectionLostSubscription = null;
1478
+ const serviceName = this.serviceIdentifier.qualifiedName();
1479
+ for (const stream of this.activeStreams.values()) {
1480
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1481
+ stream.subscription.unsubscribe();
1482
+ }
1322
1483
  this.log.info("ServiceInvocationSupervisor stopped");
1323
1484
  }
1324
1485
  buildMethodMap(serviceInstance) {
@@ -1358,7 +1519,15 @@ class ServiceInvocationSupervisor {
1358
1519
  if (!correlationId) {
1359
1520
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1360
1521
  }
1361
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1522
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1523
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1524
+ const stream = this.activeStreams.get(correlationId);
1525
+ if (stream) {
1526
+ stream.subscription.unsubscribe();
1527
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1528
+ throw new Error(`Unknown control header value ${control}`);
1529
+ }
1530
+ }
1362
1531
  }
1363
1532
  async processInvocationRequest(event) {
1364
1533
  const incomingCri = createCRI(event.cri);
@@ -1375,6 +1544,7 @@ class ServiceInvocationSupervisor {
1375
1544
  }
1376
1545
  const methodName = path;
1377
1546
  const span = this.startInvocationSpan(event, methodName);
1547
+ const generation = this.connectionGeneration;
1378
1548
  try {
1379
1549
  const args = this.argumentResolver.resolveArguments(event);
1380
1550
  const injectContext = receivesContext(this.serviceInstance, methodName);
@@ -1385,7 +1555,9 @@ class ServiceInvocationSupervisor {
1385
1555
  serviceContext = await interceptor.intercept(event, serviceContext);
1386
1556
  } catch (e) {
1387
1557
  this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1388
- this.handleException(event, new Error("Internal server error"));
1558
+ if (this.replyOwed(generation)) {
1559
+ this.handleException(event, new Error("Internal server error"));
1560
+ }
1389
1561
  this.failSpan(span, e);
1390
1562
  return;
1391
1563
  }
@@ -1401,20 +1573,14 @@ class ServiceInvocationSupervisor {
1401
1573
  try {
1402
1574
  result = import_api2.context.with(import_api2.trace.setSpan(import_api2.context.active(), span), () => handlerMethod(...args));
1403
1575
  if (result instanceof Promise) {
1404
- result.then((resolved) => {
1405
- this.processMethodInvocationResult(event, resolved);
1406
- span.end();
1407
- }, (error) => {
1408
- this.handleException(event, error);
1409
- this.failSpan(span, error);
1576
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1577
+ this.failInvocation(event, e, span, generation);
1410
1578
  });
1411
1579
  } else {
1412
- this.processMethodInvocationResult(event, result);
1413
- span.end();
1580
+ this.processMethodInvocationResult(event, result, span, generation);
1414
1581
  }
1415
1582
  } catch (e) {
1416
- this.handleException(event, e);
1417
- this.failSpan(span, e);
1583
+ this.failInvocation(event, e, span, generation);
1418
1584
  }
1419
1585
  } catch (e) {
1420
1586
  this.failSpan(span, e);
@@ -1441,9 +1607,75 @@ class ServiceInvocationSupervisor {
1441
1607
  span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1442
1608
  span.end();
1443
1609
  }
1444
- processMethodInvocationResult(event, result) {
1445
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1446
- this.sendReply(outgoingEvent);
1610
+ replyOwed(generation) {
1611
+ return generation === this.connectionGeneration;
1612
+ }
1613
+ failInvocation(event, error, span, generation) {
1614
+ if (this.replyOwed(generation)) {
1615
+ this.handleException(event, error);
1616
+ }
1617
+ this.failSpan(span, error);
1618
+ }
1619
+ processMethodInvocationResult(event, result, span, generation) {
1620
+ if (!this.replyOwed(generation)) {
1621
+ span.end();
1622
+ } else if (import_rxjs3.isObservable(result)) {
1623
+ this.streamResult(event, result, span);
1624
+ } else {
1625
+ const reply = this.returnValueConverter.convert(event.headers, result);
1626
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1627
+ this.sendReply(reply);
1628
+ span.end();
1629
+ }
1630
+ }
1631
+ streamResult(event, stream, span) {
1632
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1633
+ if (!correlationId) {
1634
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1635
+ }
1636
+ let subscription = null;
1637
+ let failed = false;
1638
+ subscription = stream.pipe(import_operators3.finalize(() => {
1639
+ this.activeStreams.delete(correlationId);
1640
+ span.end();
1641
+ })).subscribe({
1642
+ next: (value) => {
1643
+ if (failed) {
1644
+ return;
1645
+ }
1646
+ try {
1647
+ const reply = this.returnValueConverter.convert(event.headers, value);
1648
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1649
+ this.sendReply(reply);
1650
+ } catch (e) {
1651
+ failed = true;
1652
+ this.handleException(event, e);
1653
+ span.recordException(e);
1654
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1655
+ subscription?.unsubscribe();
1656
+ }
1657
+ },
1658
+ error: (error) => {
1659
+ if (failed) {
1660
+ return;
1661
+ }
1662
+ this.handleException(event, error);
1663
+ span.recordException(error);
1664
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1665
+ },
1666
+ complete: () => {
1667
+ if (failed) {
1668
+ return;
1669
+ }
1670
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1671
+ }
1672
+ });
1673
+ if (failed) {
1674
+ subscription.unsubscribe();
1675
+ }
1676
+ if (!subscription.closed) {
1677
+ this.activeStreams.set(correlationId, { request: event, subscription });
1678
+ }
1447
1679
  }
1448
1680
  sendReply(event) {
1449
1681
  try {
@@ -1453,11 +1685,17 @@ class ServiceInvocationSupervisor {
1453
1685
  }
1454
1686
  }
1455
1687
  handleException(event, error) {
1456
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1457
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1458
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1459
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1460
- this.sendReply(errorEvent);
1688
+ try {
1689
+ const errorMessage = error?.message || "Unknown error";
1690
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1691
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1692
+ ["error" /* ERROR_HEADER */, errorMessage],
1693
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1694
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1695
+ this.sendReply(errorEvent);
1696
+ } catch (e) {
1697
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1698
+ }
1461
1699
  }
1462
1700
  validateReplyTo(event) {
1463
1701
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1480,7 +1718,7 @@ class ServiceInvocationSupervisor {
1480
1718
  // packages/core/src/api/ServiceRegistry.ts
1481
1719
  var import_api3 = __toESM(require("@opentelemetry/api"));
1482
1720
  var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
1483
- var import_operators3 = require("rxjs/operators");
1721
+ var import_operators4 = require("rxjs/operators");
1484
1722
  class JsonEventFactory {
1485
1723
  create(cri, args) {
1486
1724
  const event = new Event(cri);
@@ -1581,7 +1819,7 @@ class ServiceProxy {
1581
1819
  span.setAttribute("rpc.system", "kinotic");
1582
1820
  span.setAttribute("rpc.service", this.serviceIdentifier);
1583
1821
  span.setAttribute("rpc.method", methodIdentifier);
1584
- return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators3.first()).toPromise().then(async (value) => {
1822
+ return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators4.first()).toPromise().then(async (value) => {
1585
1823
  span.end();
1586
1824
  return value;
1587
1825
  }, async (ex) => {
@@ -1608,7 +1846,7 @@ class ServiceProxy {
1608
1846
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
1609
1847
  }
1610
1848
  let event = eventFactoryToUse.create(cri, args);
1611
- return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators3.map((value) => {
1849
+ return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators4.map((value) => {
1612
1850
  const contentType = value.getHeader("content-type" /* CONTENT_TYPE_HEADER */);
1613
1851
  if (contentType !== undefined) {
1614
1852
  if (contentType === "application/json" /* CONTENT_JSON */) {
@@ -1659,21 +1897,6 @@ class KinoticSingleton {
1659
1897
  }
1660
1898
  }
1661
1899
  var Kinotic = new KinoticSingleton;
1662
- // packages/core/src/api/UiVersionUtil.ts
1663
- async function checkUiVersion(builtCommit, versionUrl = "/version.json") {
1664
- if (!builtCommit) {
1665
- throw new Error("builtCommit is required");
1666
- }
1667
- let servedCommit = null;
1668
- try {
1669
- const response = await fetch(versionUrl, { cache: "no-store" });
1670
- if (response.ok) {
1671
- const body = await response.json();
1672
- servedCommit = typeof body.commitSha === "string" && body.commitSha.length > 0 ? body.commitSha : null;
1673
- }
1674
- } catch {}
1675
- return { stale: servedCommit !== null && servedCommit !== builtCommit, servedCommit };
1676
- }
1677
1900
  // packages/core/src/api/crud/AbstractIterablePage.ts
1678
1901
  class AbstractIterablePage {
1679
1902
  pageable;