@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.js CHANGED
@@ -60,23 +60,73 @@ function createDebugLogger(namespace) {
60
60
  }
61
61
 
62
62
  // packages/core/src/internal/api/StompConnectionManager.ts
63
- import { RxStomp } from "@stomp/rx-stomp";
63
+ import { RxStomp, RxStompState } from "@stomp/rx-stomp";
64
64
  import { ReconnectionTimeMode } from "@stomp/stompjs";
65
65
  import debug2 from "debug";
66
66
  import { Subject } from "rxjs";
67
67
  import { skip } from "rxjs/operators";
68
68
  import { v4 as uuidv4 } from "uuid";
69
+
70
+ // packages/core/src/internal/api/StompActivation.ts
71
+ class StompActivation {
72
+ _ended = false;
73
+ wake = null;
74
+ preparedSocket = null;
75
+ attempt = null;
76
+ failPending = null;
77
+ subscriptions = [];
78
+ get ended() {
79
+ return this._ended;
80
+ }
81
+ end() {
82
+ this._ended = true;
83
+ this.wake?.();
84
+ this.wake = null;
85
+ }
86
+ delay(ms) {
87
+ return new Promise((resolve) => {
88
+ const timer = setTimeout(() => {
89
+ this.wake = null;
90
+ resolve();
91
+ }, ms);
92
+ this.wake = () => {
93
+ clearTimeout(timer);
94
+ resolve();
95
+ };
96
+ });
97
+ }
98
+ own(subscription) {
99
+ this.subscriptions.push(subscription);
100
+ }
101
+ pending(fail) {
102
+ this.failPending = fail;
103
+ }
104
+ established() {
105
+ this.failPending = null;
106
+ }
107
+ failIfPending(reason) {
108
+ const fail = this.failPending;
109
+ this.failPending = null;
110
+ fail?.(reason);
111
+ }
112
+ unsubscribeAll() {
113
+ for (const subscription of this.subscriptions) {
114
+ subscription.unsubscribe();
115
+ }
116
+ this.subscriptions.length = 0;
117
+ }
118
+ }
119
+
120
+ // packages/core/src/internal/api/StompConnectionManager.ts
69
121
  var SESSION_CHECK_PATH = "/api/auth/me";
70
122
 
71
123
  class StompConnectionManager {
72
124
  lastWebsocketError = null;
73
125
  maxConnectionAttemptsReached = false;
74
- replyToCriChangedHandler = null;
126
+ connectionLostHandler = null;
75
127
  rxStomp = new RxStomp;
76
- isActive = false;
77
- initialConnectedSubscription = null;
78
- initialFailureSubscription = null;
79
- webSocketErrorsSubscription = null;
128
+ activation = null;
129
+ teardown = null;
80
130
  INITIAL_RECONNECT_DELAY = 2000;
81
131
  JITTER_MAX = 5000;
82
132
  MAX_RECONNECT_DELAY = 120000;
@@ -86,18 +136,15 @@ class StompConnectionManager {
86
136
  _fatalErrors = this.fatalErrorsSubject.asObservable();
87
137
  initialConnectionSuccessful = false;
88
138
  rxStompHasConnected = false;
89
- serverHeadersSubscription = null;
90
- stompErrorsSubscription = null;
91
- uuidv4 = uuidv4();
92
139
  _replyToCri = null;
93
140
  get replyToCri() {
94
141
  return this._replyToCri;
95
142
  }
96
143
  get active() {
97
- return this.isActive;
144
+ return this.activation !== null;
98
145
  }
99
146
  get connected() {
100
- return this.isActive && this.rxStomp.connected();
147
+ return this.activation !== null && this.rxStomp.connected();
101
148
  }
102
149
  get fatalErrors() {
103
150
  return this._fatalErrors;
@@ -106,21 +153,37 @@ class StompConnectionManager {
106
153
  if (!options?.server?.host) {
107
154
  throw new Error("No host provided");
108
155
  }
109
- if (this.isActive) {
156
+ if (this.activation) {
157
+ throw new Error("Stomp connection already active");
158
+ }
159
+ await this.teardown;
160
+ if (this.activation) {
110
161
  throw new Error("Stomp connection already active");
111
162
  }
112
163
  const server = options.server;
113
164
  const credentialsResolver = options.credentials;
165
+ const activation = new StompActivation;
166
+ this.activation = activation;
114
167
  let headerAuth = false;
115
- if (!options.webSocketFactory) {
116
- if (!credentialsResolver) {
117
- 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;
118
178
  }
119
- const resolved = await credentialsResolver.resolve(server);
120
- if (resolved === null) {
121
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
179
+ if (activation.ended) {
180
+ throw new Error("Deactivated before the connection was established");
122
181
  }
123
- headerAuth = resolved.authHeaders != null;
182
+ } catch (e) {
183
+ if (this.activation === activation) {
184
+ this.activation = null;
185
+ }
186
+ throw e;
124
187
  }
125
188
  return new Promise((resolve, reject) => {
126
189
  this.connectionAttempts = 0;
@@ -128,64 +191,28 @@ class StompConnectionManager {
128
191
  this.lastWebsocketError = null;
129
192
  this.maxConnectionAttemptsReached = false;
130
193
  const url = buildBrokerUrl(server);
131
- let preparedSocket = null;
132
- const userWebSocketFactory = options.webSocketFactory;
133
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
194
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
195
+ const takePreparedSocket = () => {
196
+ const socket = activation.preparedSocket;
197
+ activation.preparedSocket = null;
198
+ return socket;
199
+ };
134
200
  const stompConfig = {
135
201
  brokerURL: url,
136
202
  connectHeaders: {
137
203
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
138
204
  },
139
- heartbeatIncoming: 120000,
205
+ heartbeatIncoming: 30000,
140
206
  heartbeatOutgoing: 30000,
141
207
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
142
208
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
143
209
  reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
144
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
145
- beforeConnect: async () => {
146
- if (!usesPreparedSocket) {
147
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
148
- try {
149
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
150
- if (res.status === 401) {
151
- await this.signalFatal(new Error("Authentication required"));
152
- return;
153
- }
154
- } catch (e) {
155
- this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
156
- }
157
- }
158
- if (options?.maxConnectionAttempts) {
159
- this.connectionAttempts++;
160
- if (this.connectionAttempts > options.maxConnectionAttempts) {
161
- this.maxConnectionAttemptsReached = true;
162
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
163
- return;
164
- } else {
165
- await this.connectionJitterDelay();
166
- }
167
- } else {
168
- await this.connectionJitterDelay();
169
- }
170
- if (userWebSocketFactory) {
171
- try {
172
- preparedSocket = await userWebSocketFactory();
173
- } catch (e) {
174
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
175
- }
176
- } else if (headerAuth) {
177
- try {
178
- const resolved = await credentialsResolver.resolve(server);
179
- if (resolved?.authHeaders == null) {
180
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
181
- } else {
182
- const WS = WebSocket;
183
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
184
- }
185
- } catch (e) {
186
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
187
- }
188
- }
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;
189
216
  }
190
217
  };
191
218
  if (this.debugLogger.enabled) {
@@ -194,96 +221,198 @@ class StompConnectionManager {
194
221
  };
195
222
  }
196
223
  this.rxStomp.configure(stompConfig);
197
- this.webSocketErrorsSubscription = this.rxStomp.webSocketErrors$.subscribe(async (value) => {
224
+ activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
198
225
  this.lastWebsocketError = value;
199
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
226
+ if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
200
227
  this.maxConnectionAttemptsReached = true;
201
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
228
+ await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
202
229
  }
203
- });
204
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
230
+ }));
231
+ activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
205
232
  const stompError = new Error(frame.headers["message"], { cause: frame });
206
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
207
- });
208
- this.initialConnectedSubscription = this.rxStomp.connected$.subscribe(() => {
209
- this.initialConnectedSubscription?.unsubscribe();
210
- this.initialFailureSubscription?.unsubscribe();
211
- if (!this.initialConnectionSuccessful) {
212
- this.initialConnectionSuccessful = true;
213
- }
214
- });
215
- this.initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
216
- this.initialConnectedSubscription?.unsubscribe();
217
- this.initialFailureSubscription?.unsubscribe();
218
- reject(err.message);
219
- });
220
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.pipe(skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
233
+ await this.signalFatal(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) => {
221
242
  this.rxStompHasConnected = true;
222
243
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
223
244
  if (connectedInfoJson == null) {
224
245
  if (!this.initialConnectionSuccessful) {
246
+ activation.failIfPending(new Error("Server did not return proper data for successful login"));
225
247
  await this.deactivate();
226
- reject("Server did not return proper data for successful login");
227
248
  }
228
249
  return;
229
250
  }
230
251
  const connectedInfo = JSON.parse(connectedInfoJson);
231
252
  if (connectedInfo.replyToId == null) {
232
253
  if (!this.initialConnectionSuccessful) {
254
+ activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
233
255
  await this.deactivate();
234
- reject("Server did not return a replyToId for successful login");
235
256
  }
236
257
  return;
237
258
  }
238
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinotic.js.EventBus/replyHandler";
259
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + uuidv4() + "@kinotic.js.EventBus/replyHandler";
260
+ this._replyToCri = newReplyToCri;
239
261
  if (!this.initialConnectionSuccessful) {
240
- this._replyToCri = newReplyToCri;
241
262
  resolve(connectedInfo);
242
- } else if (this._replyToCri !== newReplyToCri) {
243
- this._replyToCri = newReplyToCri;
244
- this.replyToCriChangedHandler?.(newReplyToCri);
245
263
  }
246
- });
247
- this.isActive = true;
264
+ }));
265
+ let previousState = this.rxStomp.connectionState$.getValue();
266
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
267
+ if (state === RxStompState.CLOSED && previousState === RxStompState.OPEN && this.activation === activation) {
268
+ this.connectionLostHandler?.();
269
+ }
270
+ previousState = state;
271
+ }));
248
272
  this.rxStomp.activate();
249
273
  });
250
274
  }
251
- async deactivate(force) {
252
- if (this.isActive) {
253
- this.isActive = false;
254
- await this.rxStomp.deactivate({ force });
255
- this.initialConnectedSubscription?.unsubscribe();
256
- this.initialConnectedSubscription = null;
257
- this.webSocketErrorsSubscription?.unsubscribe();
258
- this.webSocketErrorsSubscription = null;
259
- this.serverHeadersSubscription?.unsubscribe();
260
- this.serverHeadersSubscription = null;
261
- this.stompErrorsSubscription?.unsubscribe();
262
- this.stompErrorsSubscription = null;
275
+ async prepareAttempt(activation, options, server, headerAuth) {
276
+ const credentialsResolver = options.credentials;
277
+ const userWebSocketFactory = options.webSocketFactory;
278
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
279
+ const url = buildBrokerUrl(server);
280
+ if (!usesPreparedSocket) {
281
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
282
+ try {
283
+ const res = await fetch(sessionCheckUrl, { credentials: "include" });
284
+ if (res.status === 401) {
285
+ await this.signalFatal(activation, new Error("Authentication required"));
286
+ return;
287
+ }
288
+ } catch (e) {
289
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
290
+ }
291
+ }
292
+ if (options?.maxConnectionAttempts) {
293
+ this.connectionAttempts++;
294
+ if (this.connectionAttempts > options.maxConnectionAttempts) {
295
+ this.maxConnectionAttemptsReached = true;
296
+ await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
297
+ return;
298
+ } else {
299
+ await this.connectionJitterDelay(activation);
300
+ }
301
+ } else {
302
+ await this.connectionJitterDelay(activation);
303
+ }
304
+ if (activation.ended) {
305
+ return;
306
+ }
307
+ if (userWebSocketFactory) {
308
+ try {
309
+ activation.preparedSocket = await userWebSocketFactory();
310
+ } catch (e) {
311
+ await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
312
+ }
313
+ } else if (headerAuth) {
314
+ try {
315
+ const resolved = await credentialsResolver.resolve(server);
316
+ if (resolved?.authHeaders == null) {
317
+ await this.signalFatal(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
318
+ } else {
319
+ const WS = WebSocket;
320
+ activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
321
+ }
322
+ } catch (e) {
323
+ await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
324
+ }
325
+ }
326
+ if (activation.ended && activation.preparedSocket) {
327
+ activation.preparedSocket.close();
328
+ activation.preparedSocket = null;
329
+ }
330
+ }
331
+ deactivate(force) {
332
+ const activation = this.activation;
333
+ let ret;
334
+ if (activation) {
335
+ this.activation = null;
336
+ activation.end();
337
+ const wasOpen = this.rxStomp.connected();
263
338
  this._replyToCri = null;
339
+ activation.failIfPending(new Error("Deactivated before the connection was established"));
340
+ activation.preparedSocket?.close();
341
+ activation.preparedSocket = null;
342
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
343
+ activation.unsubscribeAll();
344
+ this.teardown = null;
345
+ if (wasOpen) {
346
+ this.connectionLostHandler?.();
347
+ }
348
+ });
349
+ this.teardown = teardown;
350
+ ret = teardown;
351
+ } else {
352
+ ret = this.teardown ?? Promise.resolve();
264
353
  }
265
- return;
354
+ return ret;
266
355
  }
267
- async connectionJitterDelay() {
356
+ async connectionJitterDelay(activation) {
268
357
  if (this.initialConnectionSuccessful) {
269
358
  const randomJitter = Math.random() * this.JITTER_MAX;
270
359
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
271
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
360
+ await activation.delay(randomJitter);
272
361
  }
273
362
  }
274
- async signalFatal(err) {
275
- this.debugLogger("Fatal error, deactivating connection: %O", err);
276
- await this.deactivate();
277
- this.fatalErrorsSubject.next(err);
363
+ async signalFatal(activation, err) {
364
+ if (!activation.ended) {
365
+ this.debugLogger("Fatal error, deactivating connection: %O", err);
366
+ activation.failIfPending(err);
367
+ await this.deactivate();
368
+ this.fatalErrorsSubject.next(err);
369
+ }
278
370
  }
279
371
  }
280
372
 
281
373
  // packages/core/src/api/event/EventBus.ts
282
374
  import { context, propagation } from "@opentelemetry/api";
283
- import { firstValueFrom, Observable as Observable2, Subject as Subject2, throwError } from "rxjs";
375
+ import { firstValueFrom, Observable as Observable2, Subject as Subject2 } from "rxjs";
284
376
  import { filter, map, multicast, tap } from "rxjs/operators";
285
377
  import { Optional } from "typescript-optional";
286
378
  import { v4 as uuidv42 } from "uuid";
379
+
380
+ // packages/core/src/api/event/RpcError.ts
381
+ class RpcError extends Error {
382
+ exceptionName;
383
+ exceptionClass;
384
+ constructor(message, exceptionName, exceptionClass) {
385
+ super(message);
386
+ this.name = "RpcError";
387
+ this.exceptionName = exceptionName;
388
+ this.exceptionClass = exceptionClass;
389
+ }
390
+ static fromEvent(reply) {
391
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
392
+ let ret;
393
+ const detail = describedException(reply);
394
+ if (detail !== undefined) {
395
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
396
+ } else {
397
+ ret = new RpcError(message, "", "");
398
+ }
399
+ return ret;
400
+ }
401
+ }
402
+ function describedException(reply) {
403
+ let ret = undefined;
404
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
405
+ try {
406
+ const parsed = JSON.parse(reply.getDataString());
407
+ if (parsed !== null && typeof parsed === "object") {
408
+ ret = parsed;
409
+ }
410
+ } catch {}
411
+ }
412
+ return ret;
413
+ }
414
+
415
+ // packages/core/src/api/event/EventBus.ts
287
416
  class Event {
288
417
  cri;
289
418
  headers;
@@ -325,23 +454,27 @@ class EventBus {
325
454
  log = createDebugLogger("kinotic:EventBus");
326
455
  stompConnectionManager = new StompConnectionManager;
327
456
  connectionLifecycle = Promise.resolve();
328
- replyToCri = null;
457
+ disconnectRequests = 0;
329
458
  requestRepliesObservable = null;
330
459
  requestRepliesSubject = null;
331
460
  requestRepliesSubscription = null;
332
461
  activeCorrelationIds = new Set;
333
462
  recentlyReaped = new Set;
463
+ connectionLostSubject = new Subject2;
334
464
  static REAP_DEBOUNCE_MS = 5000;
335
465
  constructor() {
336
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
337
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
338
- this.replyToCri = replyToCri;
339
- this.resetRequestReplies("Reply destination changed");
466
+ this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
467
+ this.stompConnectionManager.connectionLostHandler = () => {
468
+ this.resetRequestReplies("Connection lost");
469
+ this.connectionLostSubject.next();
340
470
  };
341
471
  }
342
472
  get fatalErrors() {
343
473
  return this.stompConnectionManager.fatalErrors;
344
474
  }
475
+ get connectionLost() {
476
+ return this.connectionLostSubject.asObservable();
477
+ }
345
478
  isConnectionActive() {
346
479
  return this.stompConnectionManager.active;
347
480
  }
@@ -349,12 +482,14 @@ class EventBus {
349
482
  return this.stompConnectionManager.connected;
350
483
  }
351
484
  connect(options) {
485
+ const disconnectsWhenQueued = this.disconnectRequests;
352
486
  return this.serializeLifecycle(async () => {
487
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
488
+ throw new Error("Disconnected before the connection was started");
489
+ }
353
490
  if (!this.stompConnectionManager.active) {
354
- this.cleanup();
355
491
  const connectedInfo = await this.stompConnectionManager.activate(options);
356
492
  this.serverInfo = { ...options.server };
357
- this.replyToCri = this.stompConnectionManager.replyToCri;
358
493
  return connectedInfo;
359
494
  } else {
360
495
  throw new Error("Event Bus connection already active");
@@ -362,9 +497,12 @@ class EventBus {
362
497
  });
363
498
  }
364
499
  disconnect(force) {
500
+ this.disconnectRequests++;
501
+ const deactivated = this.stompConnectionManager.deactivate(force);
365
502
  return this.serializeLifecycle(async () => {
503
+ await deactivated;
366
504
  await this.stompConnectionManager.deactivate(force);
367
- this.cleanup();
505
+ this.serverInfo = null;
368
506
  });
369
507
  }
370
508
  serializeLifecycle(operation) {
@@ -400,59 +538,65 @@ class EventBus {
400
538
  return firstValueFrom(this.requestStream(event, false));
401
539
  }
402
540
  requestStream(event, sendControlEvents = true) {
403
- if (this.stompConnectionManager.active) {
404
- return new Observable2((subscriber) => {
405
- if (this.requestRepliesObservable == null) {
406
- this.requestRepliesSubject = new Subject2;
407
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
408
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
409
- }
410
- let serverSignaledCompletion = false;
411
- const correlationId = uuidv42();
412
- this.activeCorrelationIds.add(correlationId);
413
- subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
414
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
415
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
416
- })).subscribe({
417
- next(value) {
418
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
419
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
420
- serverSignaledCompletion = true;
421
- subscriber.complete();
422
- } else {
423
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
424
- }
425
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
541
+ return new Observable2((subscriber) => {
542
+ const replyToCri = this.stompConnectionManager.replyToCri;
543
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
544
+ subscriber.error(this.createSendUnavailableError());
545
+ return;
546
+ }
547
+ if (this.requestRepliesObservable == null) {
548
+ this.requestRepliesSubject = new Subject2;
549
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
550
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
551
+ }
552
+ let serverSignaledCompletion = false;
553
+ let replyDestinationReset = false;
554
+ const correlationId = uuidv42();
555
+ this.activeCorrelationIds.add(correlationId);
556
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
557
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
558
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
559
+ })).subscribe({
560
+ next(value) {
561
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
562
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
426
563
  serverSignaledCompletion = true;
427
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
564
+ if (value.data.isPresent() || !sendControlEvents) {
565
+ subscriber.next(value);
566
+ }
567
+ subscriber.complete();
428
568
  } else {
429
- subscriber.next(value);
569
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
430
570
  }
431
- },
432
- error(err) {
433
- subscriber.error(err);
434
- },
435
- complete() {
436
- subscriber.complete();
571
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
572
+ serverSignaledCompletion = true;
573
+ subscriber.error(RpcError.fromEvent(value));
574
+ } else {
575
+ subscriber.next(value);
437
576
  }
438
- });
439
- subscriber.add(defaultMessagesSubscription);
440
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
441
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
442
- this.send(event);
443
- subscriber.add(() => {
444
- if (sendControlEvents && !serverSignaledCompletion) {
445
- try {
446
- this.sendCancel(event.cri, correlationId);
447
- } catch (e) {
448
- this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
449
- }
577
+ },
578
+ error(err) {
579
+ replyDestinationReset = true;
580
+ subscriber.error(err);
581
+ },
582
+ complete() {
583
+ subscriber.complete();
584
+ }
585
+ });
586
+ subscriber.add(defaultMessagesSubscription);
587
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
588
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
589
+ this.send(event);
590
+ subscriber.add(() => {
591
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
592
+ try {
593
+ this.sendCancel(event.cri, correlationId);
594
+ } catch (e) {
595
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
450
596
  }
451
- });
597
+ }
452
598
  });
453
- } else {
454
- return throwError(() => this.createSendUnavailableError());
455
- }
599
+ });
456
600
  }
457
601
  listen(_serverInfo) {
458
602
  return Promise.reject("Not implemented");
@@ -460,10 +604,6 @@ class EventBus {
460
604
  observe(cri) {
461
605
  return this._observe(cri);
462
606
  }
463
- cleanup() {
464
- this.resetRequestReplies("Connection disconnected");
465
- this.serverInfo = null;
466
- }
467
607
  cancelIfUnexpected(value) {
468
608
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
469
609
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -485,7 +625,7 @@ class EventBus {
485
625
  const cancelEvent = new Event(cri);
486
626
  cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
487
627
  cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
488
- cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
628
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
489
629
  this.send(cancelEvent);
490
630
  }
491
631
  resetRequestReplies(reason) {
@@ -522,7 +662,7 @@ class EventBus {
522
662
  headers.set(prop, message.headers[prop]);
523
663
  }
524
664
  }
525
- return new Event(destination, headers, message.binaryBody);
665
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
526
666
  }));
527
667
  }
528
668
  }
@@ -859,6 +999,10 @@ class BasicReturnValueConverter {
859
999
  }
860
1000
  }
861
1001
 
1002
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1003
+ import { isObservable } from "rxjs";
1004
+ import { finalize } from "rxjs/operators";
1005
+
862
1006
  // packages/core/src/api/ServiceIdentifier.ts
863
1007
  class ServiceIdentifier {
864
1008
  namespace;
@@ -1038,7 +1182,7 @@ import opentelemetry, { context as context2, propagation as propagation2, trace,
1038
1182
  // packages/core/package.json
1039
1183
  var package_default = {
1040
1184
  name: "@kinotic-ai/core",
1041
- version: "5.0.0-beta.10",
1185
+ version: "5.0.0-beta.11",
1042
1186
  type: "module",
1043
1187
  files: [
1044
1188
  "dist"
@@ -1132,6 +1276,9 @@ class ServiceInvocationSupervisor {
1132
1276
  serviceInstance;
1133
1277
  methodSubscription = null;
1134
1278
  unscopedSubscription = null;
1279
+ activeStreams = new Map;
1280
+ connectionLostSubscription = null;
1281
+ connectionGeneration = 0;
1135
1282
  methodMap;
1136
1283
  scopeOptionalMethods;
1137
1284
  tracer;
@@ -1180,6 +1327,12 @@ class ServiceInvocationSupervisor {
1180
1327
  this.unscopedSubscription = this.subscribeAt(unscopedBase);
1181
1328
  this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1182
1329
  }
1330
+ this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
1331
+ this.connectionGeneration++;
1332
+ for (const stream of this.activeStreams.values()) {
1333
+ stream.subscription.unsubscribe();
1334
+ }
1335
+ });
1183
1336
  }
1184
1337
  subscribeAt(criBase) {
1185
1338
  return this._eventBus.observe(criBase).subscribe({
@@ -1205,6 +1358,13 @@ class ServiceInvocationSupervisor {
1205
1358
  this.methodSubscription = null;
1206
1359
  this.unscopedSubscription?.unsubscribe();
1207
1360
  this.unscopedSubscription = null;
1361
+ this.connectionLostSubscription?.unsubscribe();
1362
+ this.connectionLostSubscription = null;
1363
+ const serviceName = this.serviceIdentifier.qualifiedName();
1364
+ for (const stream of this.activeStreams.values()) {
1365
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1366
+ stream.subscription.unsubscribe();
1367
+ }
1208
1368
  this.log.info("ServiceInvocationSupervisor stopped");
1209
1369
  }
1210
1370
  buildMethodMap(serviceInstance) {
@@ -1244,7 +1404,15 @@ class ServiceInvocationSupervisor {
1244
1404
  if (!correlationId) {
1245
1405
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1246
1406
  }
1247
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1407
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1408
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1409
+ const stream = this.activeStreams.get(correlationId);
1410
+ if (stream) {
1411
+ stream.subscription.unsubscribe();
1412
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1413
+ throw new Error(`Unknown control header value ${control}`);
1414
+ }
1415
+ }
1248
1416
  }
1249
1417
  async processInvocationRequest(event) {
1250
1418
  const incomingCri = createCRI(event.cri);
@@ -1261,6 +1429,7 @@ class ServiceInvocationSupervisor {
1261
1429
  }
1262
1430
  const methodName = path;
1263
1431
  const span = this.startInvocationSpan(event, methodName);
1432
+ const generation = this.connectionGeneration;
1264
1433
  try {
1265
1434
  const args = this.argumentResolver.resolveArguments(event);
1266
1435
  const injectContext = receivesContext(this.serviceInstance, methodName);
@@ -1271,7 +1440,9 @@ class ServiceInvocationSupervisor {
1271
1440
  serviceContext = await interceptor.intercept(event, serviceContext);
1272
1441
  } catch (e) {
1273
1442
  this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1274
- this.handleException(event, new Error("Internal server error"));
1443
+ if (this.replyOwed(generation)) {
1444
+ this.handleException(event, new Error("Internal server error"));
1445
+ }
1275
1446
  this.failSpan(span, e);
1276
1447
  return;
1277
1448
  }
@@ -1287,20 +1458,14 @@ class ServiceInvocationSupervisor {
1287
1458
  try {
1288
1459
  result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
1289
1460
  if (result instanceof Promise) {
1290
- result.then((resolved) => {
1291
- this.processMethodInvocationResult(event, resolved);
1292
- span.end();
1293
- }, (error) => {
1294
- this.handleException(event, error);
1295
- this.failSpan(span, error);
1461
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1462
+ this.failInvocation(event, e, span, generation);
1296
1463
  });
1297
1464
  } else {
1298
- this.processMethodInvocationResult(event, result);
1299
- span.end();
1465
+ this.processMethodInvocationResult(event, result, span, generation);
1300
1466
  }
1301
1467
  } catch (e) {
1302
- this.handleException(event, e);
1303
- this.failSpan(span, e);
1468
+ this.failInvocation(event, e, span, generation);
1304
1469
  }
1305
1470
  } catch (e) {
1306
1471
  this.failSpan(span, e);
@@ -1327,9 +1492,75 @@ class ServiceInvocationSupervisor {
1327
1492
  span.setStatus({ code: SpanStatusCode.ERROR });
1328
1493
  span.end();
1329
1494
  }
1330
- processMethodInvocationResult(event, result) {
1331
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1332
- this.sendReply(outgoingEvent);
1495
+ replyOwed(generation) {
1496
+ return generation === this.connectionGeneration;
1497
+ }
1498
+ failInvocation(event, error, span, generation) {
1499
+ if (this.replyOwed(generation)) {
1500
+ this.handleException(event, error);
1501
+ }
1502
+ this.failSpan(span, error);
1503
+ }
1504
+ processMethodInvocationResult(event, result, span, generation) {
1505
+ if (!this.replyOwed(generation)) {
1506
+ span.end();
1507
+ } else if (isObservable(result)) {
1508
+ this.streamResult(event, result, span);
1509
+ } else {
1510
+ const reply = this.returnValueConverter.convert(event.headers, result);
1511
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1512
+ this.sendReply(reply);
1513
+ span.end();
1514
+ }
1515
+ }
1516
+ streamResult(event, stream, span) {
1517
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1518
+ if (!correlationId) {
1519
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1520
+ }
1521
+ let subscription = null;
1522
+ let failed = false;
1523
+ subscription = stream.pipe(finalize(() => {
1524
+ this.activeStreams.delete(correlationId);
1525
+ span.end();
1526
+ })).subscribe({
1527
+ next: (value) => {
1528
+ if (failed) {
1529
+ return;
1530
+ }
1531
+ try {
1532
+ const reply = this.returnValueConverter.convert(event.headers, value);
1533
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1534
+ this.sendReply(reply);
1535
+ } catch (e) {
1536
+ failed = true;
1537
+ this.handleException(event, e);
1538
+ span.recordException(e);
1539
+ span.setStatus({ code: SpanStatusCode.ERROR });
1540
+ subscription?.unsubscribe();
1541
+ }
1542
+ },
1543
+ error: (error) => {
1544
+ if (failed) {
1545
+ return;
1546
+ }
1547
+ this.handleException(event, error);
1548
+ span.recordException(error);
1549
+ span.setStatus({ code: SpanStatusCode.ERROR });
1550
+ },
1551
+ complete: () => {
1552
+ if (failed) {
1553
+ return;
1554
+ }
1555
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1556
+ }
1557
+ });
1558
+ if (failed) {
1559
+ subscription.unsubscribe();
1560
+ }
1561
+ if (!subscription.closed) {
1562
+ this.activeStreams.set(correlationId, { request: event, subscription });
1563
+ }
1333
1564
  }
1334
1565
  sendReply(event) {
1335
1566
  try {
@@ -1339,11 +1570,17 @@ class ServiceInvocationSupervisor {
1339
1570
  }
1340
1571
  }
1341
1572
  handleException(event, error) {
1342
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1343
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1344
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1345
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1346
- this.sendReply(errorEvent);
1573
+ try {
1574
+ const errorMessage = error?.message || "Unknown error";
1575
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1576
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1577
+ ["error" /* ERROR_HEADER */, errorMessage],
1578
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1579
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1580
+ this.sendReply(errorEvent);
1581
+ } catch (e) {
1582
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1583
+ }
1347
1584
  }
1348
1585
  validateReplyTo(event) {
1349
1586
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1548,21 +1785,6 @@ class KinoticSingleton {
1548
1785
  }
1549
1786
  }
1550
1787
  var Kinotic = new KinoticSingleton;
1551
- // packages/core/src/api/UiVersionUtil.ts
1552
- async function checkUiVersion(builtCommit, versionUrl = "/version.json") {
1553
- if (!builtCommit) {
1554
- throw new Error("builtCommit is required");
1555
- }
1556
- let servedCommit = null;
1557
- try {
1558
- const response = await fetch(versionUrl, { cache: "no-store" });
1559
- if (response.ok) {
1560
- const body = await response.json();
1561
- servedCommit = typeof body.commitSha === "string" && body.commitSha.length > 0 ? body.commitSha : null;
1562
- }
1563
- } catch {}
1564
- return { stale: servedCommit !== null && servedCommit !== builtCommit, servedCommit };
1565
- }
1566
1788
  // packages/core/src/api/crud/AbstractIterablePage.ts
1567
1789
  class AbstractIterablePage {
1568
1790
  pageable;
@@ -1815,7 +2037,6 @@ export {
1815
2037
  receivesContext,
1816
2038
  isAdvertised,
1817
2039
  createCRI,
1818
- checkUiVersion,
1819
2040
  buildServerUrl,
1820
2041
  buildBrokerUrl,
1821
2042
  Zone,
@@ -1828,6 +2049,7 @@ export {
1828
2049
  ServerInfo,
1829
2050
  ScopeOptional,
1830
2051
  Scope,
2052
+ RpcError,
1831
2053
  Publish,
1832
2054
  ParticipantConstants,
1833
2055
  Pageable,