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

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