@kinotic-ai/core 5.0.0-beta.3 → 5.0.0-beta.31

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
@@ -5,103 +5,205 @@ class ServerInfo {
5
5
  useSSL;
6
6
  }
7
7
  function buildServerUrl(server, scheme) {
8
- return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
8
+ const host = server.host.includes(":") && !server.host.startsWith("[") ? "[" + server.host + "]" : server.host;
9
+ return scheme + (server.useSSL ? "s" : "") + "://" + host + (server.port ? ":" + server.port : "");
9
10
  }
10
11
  function buildBrokerUrl(server) {
11
- return buildServerUrl(server, "ws") + "/v1";
12
+ return buildServerUrl(server, "ws") + "/api/v1";
12
13
  }
13
14
  var SessionKeepAliveMode;
14
- ((SessionKeepAliveMode2) => {
15
- SessionKeepAliveMode2["NONE"] = "NONE";
16
- SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
17
- SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
15
+ ((SessionKeepAliveMode) => {
16
+ SessionKeepAliveMode["NONE"] = "NONE";
17
+ SessionKeepAliveMode["ACTIVITY"] = "ACTIVITY";
18
+ SessionKeepAliveMode["CONNECTION"] = "CONNECTION";
18
19
  })(SessionKeepAliveMode ||= {});
19
20
  // packages/core/src/api/event/IEventBus.ts
20
21
  var EventConstants;
21
- ((EventConstants2) => {
22
- EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
23
- EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
24
- EventConstants2["REPLY_TO_HEADER"] = "reply-to";
25
- EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
26
- EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
27
- EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
28
- EventConstants2["ORIGIN_CRI_HEADER"] = "__origin-cri";
29
- EventConstants2["ERROR_HEADER"] = "error";
30
- EventConstants2["COMPLETE_HEADER"] = "complete";
31
- EventConstants2["CONTROL_HEADER"] = "control";
32
- EventConstants2["CONTROL_VALUE_COMPLETE"] = "complete";
33
- EventConstants2["CONTROL_VALUE_CANCEL"] = "cancel";
34
- EventConstants2["CONTROL_VALUE_SUSPEND"] = "suspend";
35
- EventConstants2["CONTROL_VALUE_RESUME"] = "resume";
36
- EventConstants2["SERVICE_DESTINATION_PREFIX"] = "srv://";
37
- EventConstants2["SERVICE_DESTINATION_SCHEME"] = "srv";
38
- EventConstants2["STREAM_DESTINATION_PREFIX"] = "stream://";
39
- EventConstants2["STREAM_DESTINATION_SCHEME"] = "stream";
40
- EventConstants2["REPLY_DESTINATION_PREFIX"] = "reply://";
41
- EventConstants2["REPLY_DESTINATION_SCHEME"] = "reply";
42
- EventConstants2["CONTENT_JSON"] = "application/json";
43
- EventConstants2["CONTENT_TEXT"] = "text/plain";
44
- EventConstants2["CONTENT_OCTET_STREAM"] = "application/octet-stream";
45
- EventConstants2["TRACEPARENT_HEADER"] = "traceparent";
46
- EventConstants2["TRACESTATE_HEADER"] = "tracestate";
22
+ ((EventConstants) => {
23
+ EventConstants["CONTENT_TYPE_HEADER"] = "content-type";
24
+ EventConstants["CONTENT_LENGTH_HEADER"] = "content-length";
25
+ EventConstants["REPLY_TO_HEADER"] = "reply-to";
26
+ EventConstants["SENDER_HEADER"] = "sender";
27
+ EventConstants["CONNECTED_INFO_HEADER"] = "connected-info";
28
+ EventConstants["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
29
+ EventConstants["CORRELATION_ID_HEADER"] = "__correlation-id";
30
+ EventConstants["ORIGIN_CRI_HEADER"] = "__origin-cri";
31
+ EventConstants["ERROR_HEADER"] = "error";
32
+ EventConstants["COMPLETE_HEADER"] = "complete";
33
+ EventConstants["CONTROL_HEADER"] = "control";
34
+ EventConstants["CONTROL_VALUE_COMPLETE"] = "complete";
35
+ EventConstants["CONTROL_VALUE_CANCEL"] = "cancel";
36
+ EventConstants["CONTROL_VALUE_SUSPEND"] = "suspend";
37
+ EventConstants["CONTROL_VALUE_RESUME"] = "resume";
38
+ EventConstants["SERVICE_DESTINATION_PREFIX"] = "srv://";
39
+ EventConstants["SERVICE_DESTINATION_SCHEME"] = "srv";
40
+ EventConstants["STREAM_DESTINATION_PREFIX"] = "stream://";
41
+ EventConstants["STREAM_DESTINATION_SCHEME"] = "stream";
42
+ EventConstants["REPLY_DESTINATION_PREFIX"] = "reply://";
43
+ EventConstants["REPLY_DESTINATION_SCHEME"] = "reply";
44
+ EventConstants["CONTENT_JSON"] = "application/json";
45
+ EventConstants["CONTENT_TEXT"] = "text/plain";
46
+ EventConstants["CONTENT_OCTET_STREAM"] = "application/octet-stream";
47
+ EventConstants["TRACEPARENT_HEADER"] = "traceparent";
48
+ EventConstants["TRACESTATE_HEADER"] = "tracestate";
47
49
  })(EventConstants ||= {});
48
50
 
51
+ // packages/core/src/internal/api/Logger.ts
52
+ import debug from "debug";
53
+ function createDebugLogger(namespace) {
54
+ const debugLogger = debug(namespace);
55
+ return {
56
+ trace: (...args) => debugLogger("TRACE", ...args),
57
+ debug: (...args) => debugLogger("DEBUG", ...args),
58
+ info: (...args) => debugLogger("INFO", ...args),
59
+ warn: (...args) => debugLogger("WARN", ...args),
60
+ error: (...args) => debugLogger("ERROR", ...args)
61
+ };
62
+ }
63
+
49
64
  // packages/core/src/internal/api/StompConnectionManager.ts
50
- import { RxStomp } from "@stomp/rx-stomp";
65
+ import { RxStomp, RxStompState } from "@stomp/rx-stomp";
51
66
  import { ReconnectionTimeMode } from "@stomp/stompjs";
52
- import debug from "debug";
67
+ import debug2 from "debug";
53
68
  import { Subject } from "rxjs";
69
+ import { skip } from "rxjs/operators";
54
70
  import { v4 as uuidv4 } from "uuid";
71
+
72
+ // packages/core/src/internal/api/SessionRoutes.ts
55
73
  var SESSION_CHECK_PATH = "/api/auth/me";
74
+ var LOGOUT_PATH = "/api/auth/logout";
75
+ async function holdsLogin(server, signal) {
76
+ const response = await fetch(buildServerUrl(server, "http") + SESSION_CHECK_PATH, { credentials: "include", signal });
77
+ return response.status !== 401;
78
+ }
79
+ async function endLogin(server, signal) {
80
+ await fetch(buildServerUrl(server, "http") + LOGOUT_PATH, { method: "POST", credentials: "include", signal });
81
+ }
82
+
83
+ // packages/core/src/internal/api/StompActivation.ts
84
+ class StompActivation {
85
+ _ended = false;
86
+ wake = null;
87
+ preparedSocket = null;
88
+ attempt = null;
89
+ failPending = null;
90
+ abortController = new AbortController;
91
+ subscriptions = [];
92
+ get ended() {
93
+ return this._ended;
94
+ }
95
+ get signal() {
96
+ return this.abortController.signal;
97
+ }
98
+ end() {
99
+ this._ended = true;
100
+ this.wake?.();
101
+ this.wake = null;
102
+ this.abortController.abort();
103
+ }
104
+ delay(ms) {
105
+ return new Promise((resolve) => {
106
+ const timer = setTimeout(() => {
107
+ this.wake = null;
108
+ resolve();
109
+ }, ms);
110
+ this.wake = () => {
111
+ clearTimeout(timer);
112
+ resolve();
113
+ };
114
+ });
115
+ }
116
+ own(subscription) {
117
+ this.subscriptions.push(subscription);
118
+ }
119
+ pending(fail) {
120
+ this.failPending = fail;
121
+ }
122
+ established() {
123
+ this.failPending = null;
124
+ }
125
+ failIfPending(reason) {
126
+ const fail = this.failPending;
127
+ this.failPending = null;
128
+ fail?.(reason);
129
+ }
130
+ unsubscribeAll() {
131
+ for (const subscription of this.subscriptions) {
132
+ subscription.unsubscribe();
133
+ }
134
+ this.subscriptions.length = 0;
135
+ }
136
+ }
56
137
 
138
+ // packages/core/src/internal/api/StompConnectionManager.ts
57
139
  class StompConnectionManager {
58
140
  lastWebsocketError = null;
59
141
  maxConnectionAttemptsReached = false;
60
- replyToCriChangedHandler = null;
61
- rxStomp = null;
142
+ connectionEndedHandler = null;
143
+ rxStomp = new RxStomp;
144
+ activation = null;
145
+ teardown = null;
62
146
  INITIAL_RECONNECT_DELAY = 2000;
63
147
  JITTER_MAX = 5000;
64
148
  MAX_RECONNECT_DELAY = 120000;
149
+ CONNECTION_TIMEOUT = 1e4;
65
150
  connectionAttempts = 0;
66
- debugLogger = debug("kinoitc:stomp");
67
- fatalErrorsSubject = new Subject;
68
- _fatalErrors = this.fatalErrorsSubject.asObservable();
151
+ debugLogger = debug2("kinotic:stomp");
152
+ connectionEstablishedSubject = new Subject;
153
+ connectionAttemptFailedSubject = new Subject;
69
154
  initialConnectionSuccessful = false;
70
- serverHeadersSubscription = null;
71
- stompErrorsSubscription = null;
72
- uuidv4 = uuidv4();
155
+ rxStompHasConnected = false;
73
156
  _replyToCri = null;
74
157
  get replyToCri() {
75
158
  return this._replyToCri;
76
159
  }
77
160
  get active() {
78
- return !!this.rxStomp;
161
+ return this.activation !== null;
79
162
  }
80
163
  get connected() {
81
- return this.rxStomp != null && this.rxStomp.connected();
164
+ return this.activation !== null && this.rxStomp.connected();
165
+ }
166
+ get connectionEstablished() {
167
+ return this.connectionEstablishedSubject.asObservable();
82
168
  }
83
- get fatalErrors() {
84
- return this._fatalErrors;
169
+ get connectionAttemptFailed() {
170
+ return this.connectionAttemptFailedSubject.asObservable();
85
171
  }
86
172
  async activate(options) {
87
173
  if (!options?.server?.host) {
88
174
  throw new Error("No host provided");
89
175
  }
90
- if (this.rxStomp) {
176
+ if (this.activation) {
177
+ throw new Error("Stomp connection already active");
178
+ }
179
+ await this.teardown;
180
+ if (this.activation) {
91
181
  throw new Error("Stomp connection already active");
92
182
  }
93
183
  const server = options.server;
94
184
  const credentialsResolver = options.credentials;
185
+ const activation = new StompActivation;
186
+ this.activation = activation;
95
187
  let headerAuth = false;
96
- if (!options.webSocketFactory) {
97
- if (!credentialsResolver) {
98
- throw new Error("No credentials supplied and no default resolution applied");
188
+ try {
189
+ if (!options.webSocketFactory) {
190
+ if (!credentialsResolver) {
191
+ throw new Error("No credentials supplied and no default resolution applied");
192
+ }
193
+ const resolved = await credentialsResolver.resolve(server);
194
+ if (resolved === null) {
195
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
196
+ }
197
+ headerAuth = resolved.authHeaders != null;
198
+ }
199
+ if (activation.ended) {
200
+ throw new Error("Deactivated before the connection was established");
99
201
  }
100
- const resolved = await credentialsResolver.resolve(server);
101
- if (resolved === null) {
102
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
202
+ } catch (e) {
203
+ if (this.activation === activation) {
204
+ this.activation = null;
103
205
  }
104
- headerAuth = resolved.authHeaders != null;
206
+ throw e;
105
207
  }
106
208
  return new Promise((resolve, reject) => {
107
209
  this.connectionAttempts = 0;
@@ -109,63 +211,29 @@ class StompConnectionManager {
109
211
  this.lastWebsocketError = null;
110
212
  this.maxConnectionAttemptsReached = false;
111
213
  const url = buildBrokerUrl(server);
112
- this.rxStomp = new RxStomp;
113
- let preparedSocket = null;
114
- const userWebSocketFactory = options.webSocketFactory;
115
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
214
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
215
+ const takePreparedSocket = () => {
216
+ const socket = activation.preparedSocket;
217
+ activation.preparedSocket = null;
218
+ return socket;
219
+ };
116
220
  const stompConfig = {
117
221
  brokerURL: url,
118
222
  connectHeaders: {
119
223
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
120
224
  },
121
- heartbeatIncoming: 120000,
225
+ heartbeatIncoming: 30000,
122
226
  heartbeatOutgoing: 30000,
227
+ connectionTimeout: this.CONNECTION_TIMEOUT,
123
228
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
124
229
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
125
230
  reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
126
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
127
- beforeConnect: async () => {
128
- if (!usesPreparedSocket) {
129
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
130
- try {
131
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
132
- if (res.status === 401) {
133
- await this.signalFatal(new Error("Authentication required"));
134
- return;
135
- }
136
- } catch {}
137
- }
138
- if (options?.maxConnectionAttempts) {
139
- this.connectionAttempts++;
140
- if (this.connectionAttempts > options.maxConnectionAttempts) {
141
- this.maxConnectionAttemptsReached = true;
142
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
143
- return;
144
- } else {
145
- await this.connectionJitterDelay();
146
- }
147
- } else {
148
- await this.connectionJitterDelay();
149
- }
150
- if (userWebSocketFactory) {
151
- try {
152
- preparedSocket = await userWebSocketFactory();
153
- } catch (e) {
154
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
155
- }
156
- } else if (headerAuth) {
157
- try {
158
- const resolved = await credentialsResolver.resolve(server);
159
- if (resolved?.authHeaders == null) {
160
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
161
- } else {
162
- const WS = WebSocket;
163
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
164
- }
165
- } catch (e) {
166
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
167
- }
168
- }
231
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
232
+ beforeConnect: () => {
233
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
234
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
235
+ activation.attempt = attempt.then(settled, settled);
236
+ return attempt;
169
237
  }
170
238
  };
171
239
  if (this.debugLogger.enabled) {
@@ -174,93 +242,205 @@ class StompConnectionManager {
174
242
  };
175
243
  }
176
244
  this.rxStomp.configure(stompConfig);
177
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
245
+ activation.own(this.rxStomp.webSocketErrors$.subscribe((value) => {
178
246
  this.lastWebsocketError = value;
179
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
180
- this.maxConnectionAttemptsReached = true;
181
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
182
- }
183
- });
184
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
247
+ }));
248
+ activation.own(this.rxStomp.stompErrors$.subscribe((frame) => {
185
249
  const stompError = new Error(frame.headers["message"], { cause: frame });
186
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
187
- });
188
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
189
- connectedSubscription.unsubscribe();
190
- initialFailureSubscription.unsubscribe();
191
- if (!this.initialConnectionSuccessful) {
192
- this.initialConnectionSuccessful = true;
193
- }
194
- });
195
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
196
- connectedSubscription.unsubscribe();
197
- initialFailureSubscription.unsubscribe();
198
- reject(err.message);
199
- });
200
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
250
+ this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
251
+ }));
252
+ activation.own(this.rxStomp.connected$.subscribe(() => {
253
+ activation.established();
254
+ this.initialConnectionSuccessful = true;
255
+ this.connectionAttempts = 0;
256
+ }));
257
+ activation.pending(reject);
258
+ activation.own(this.rxStomp.serverHeaders$.pipe(skip(this.rxStompHasConnected ? 1 : 0)).subscribe((value) => {
259
+ this.rxStompHasConnected = true;
201
260
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
202
261
  if (connectedInfoJson == null) {
203
262
  if (!this.initialConnectionSuccessful) {
204
- await this.deactivate();
205
- reject("Server did not return proper data for successful login");
263
+ this.failConnection(activation, new Error("Server did not return proper data for successful login"));
206
264
  }
207
265
  return;
208
266
  }
209
267
  const connectedInfo = JSON.parse(connectedInfoJson);
210
268
  if (connectedInfo.replyToId == null) {
211
269
  if (!this.initialConnectionSuccessful) {
212
- await this.deactivate();
213
- reject("Server did not return a replyToId for successful login");
270
+ this.failConnection(activation, new Error("Server did not return a replyToId for successful login"));
214
271
  }
215
272
  return;
216
273
  }
217
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
274
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + uuidv4() + "@kinotic.js.EventBus/replyHandler";
275
+ this._replyToCri = newReplyToCri;
218
276
  if (!this.initialConnectionSuccessful) {
219
- this._replyToCri = newReplyToCri;
220
277
  resolve(connectedInfo);
221
- } else if (this._replyToCri !== newReplyToCri) {
222
- this._replyToCri = newReplyToCri;
223
- this.replyToCriChangedHandler?.(newReplyToCri);
224
278
  }
225
- });
279
+ this.connectionEstablishedSubject.next(connectedInfo);
280
+ }));
281
+ let previousState = this.rxStomp.connectionState$.getValue();
282
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
283
+ if (state === RxStompState.CLOSED && this.activation === activation) {
284
+ if (previousState === RxStompState.OPEN) {
285
+ this.connectionEndedHandler?.(null);
286
+ } else if (previousState === RxStompState.CONNECTING) {
287
+ if (options.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
288
+ this.maxConnectionAttemptsReached = true;
289
+ this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
290
+ } else {
291
+ this.connectionAttemptFailedSubject.next();
292
+ }
293
+ }
294
+ }
295
+ previousState = state;
296
+ }));
226
297
  this.rxStomp.activate();
227
298
  });
228
299
  }
229
- async deactivate(force) {
230
- const rxStomp = this.rxStomp;
231
- if (rxStomp) {
232
- await rxStomp.deactivate({ force });
233
- if (this.rxStomp === rxStomp) {
234
- this.serverHeadersSubscription?.unsubscribe();
235
- this.serverHeadersSubscription = null;
236
- this.stompErrorsSubscription?.unsubscribe();
237
- this.stompErrorsSubscription = null;
238
- this.rxStomp = null;
239
- this._replyToCri = null;
300
+ async prepareAttempt(activation, options, server, headerAuth) {
301
+ const credentialsResolver = options.credentials;
302
+ const userWebSocketFactory = options.webSocketFactory;
303
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
304
+ const url = buildBrokerUrl(server);
305
+ if (!usesPreparedSocket) {
306
+ try {
307
+ const signedIn = await holdsLogin(server, AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)]));
308
+ if (!signedIn) {
309
+ this.failConnection(activation, new Error("Authentication required"));
310
+ return;
311
+ }
312
+ } catch (e) {
313
+ this.debugLogger("Session check of %s failed: %O", server.host, e);
314
+ }
315
+ }
316
+ if (options?.maxConnectionAttempts) {
317
+ this.connectionAttempts++;
318
+ }
319
+ await this.connectionJitterDelay(activation);
320
+ if (activation.ended) {
321
+ return;
322
+ }
323
+ if (userWebSocketFactory) {
324
+ try {
325
+ activation.preparedSocket = await userWebSocketFactory();
326
+ } catch (e) {
327
+ this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
328
+ }
329
+ } else if (headerAuth) {
330
+ try {
331
+ const resolved = await credentialsResolver.resolve(server);
332
+ if (resolved?.authHeaders == null) {
333
+ this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
334
+ } else {
335
+ const WS = WebSocket;
336
+ const socket = new WS(url, { headers: resolved.authHeaders });
337
+ this.endOnRejectedUpgrade(activation, socket);
338
+ activation.preparedSocket = socket;
339
+ }
340
+ } catch (e) {
341
+ this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
342
+ }
343
+ }
344
+ if (activation.ended && activation.preparedSocket) {
345
+ activation.preparedSocket.close();
346
+ activation.preparedSocket = null;
347
+ }
348
+ }
349
+ endOnRejectedUpgrade(activation, socket) {
350
+ const emitter = socket;
351
+ if (typeof emitter.on === "function") {
352
+ emitter.on("unexpected-response", (_request, response) => {
353
+ const status = response.statusCode ?? 0;
354
+ if (status >= 400 && status < 500) {
355
+ this.failConnection(activation, new Error("Connection rejected with status " + status));
356
+ }
357
+ socket.close();
358
+ });
359
+ }
360
+ }
361
+ deactivate(force, reason = null) {
362
+ const activation = this.activation;
363
+ let ret;
364
+ if (activation) {
365
+ this.activation = null;
366
+ activation.end();
367
+ const wasOpen = this.rxStomp.connected();
368
+ this._replyToCri = null;
369
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
370
+ activation.preparedSocket?.close();
371
+ activation.preparedSocket = null;
372
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
373
+ activation.unsubscribeAll();
374
+ this.teardown = null;
375
+ });
376
+ this.teardown = teardown;
377
+ if (wasOpen || reason !== null) {
378
+ this.connectionEndedHandler?.(reason);
240
379
  }
380
+ ret = teardown;
381
+ } else {
382
+ ret = this.teardown ?? Promise.resolve();
241
383
  }
242
- return;
384
+ return ret;
243
385
  }
244
- async connectionJitterDelay() {
386
+ async connectionJitterDelay(activation) {
245
387
  if (this.initialConnectionSuccessful) {
246
388
  const randomJitter = Math.random() * this.JITTER_MAX;
247
389
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
248
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
390
+ await activation.delay(randomJitter);
249
391
  }
250
392
  }
251
- async signalFatal(err) {
252
- this.debugLogger("Fatal error, deactivating connection: %O", err);
253
- await this.deactivate();
254
- this.fatalErrorsSubject.next(err);
393
+ failConnection(activation, err) {
394
+ if (!activation.ended) {
395
+ this.debugLogger("Connection failed, ending it: %O", err);
396
+ this.deactivate(undefined, err).catch((e) => this.debugLogger("Closing the failed connection failed: %O", e));
397
+ }
255
398
  }
256
399
  }
257
400
 
258
401
  // packages/core/src/api/event/EventBus.ts
259
402
  import { context, propagation } from "@opentelemetry/api";
260
- import { firstValueFrom, Observable as Observable2, Subject as Subject2, throwError } from "rxjs";
403
+ import { firstValueFrom, Observable as Observable2, Subject as Subject2 } from "rxjs";
261
404
  import { filter, map, multicast, tap } from "rxjs/operators";
262
405
  import { Optional } from "typescript-optional";
263
406
  import { v4 as uuidv42 } from "uuid";
407
+
408
+ // packages/core/src/api/event/RpcError.ts
409
+ class RpcError extends Error {
410
+ exceptionName;
411
+ exceptionClass;
412
+ constructor(message, exceptionName, exceptionClass) {
413
+ super(message);
414
+ this.name = "RpcError";
415
+ this.exceptionName = exceptionName;
416
+ this.exceptionClass = exceptionClass;
417
+ }
418
+ static fromEvent(reply) {
419
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
420
+ let ret;
421
+ const detail = describedException(reply);
422
+ if (detail !== undefined) {
423
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
424
+ } else {
425
+ ret = new RpcError(message, "", "");
426
+ }
427
+ return ret;
428
+ }
429
+ }
430
+ function describedException(reply) {
431
+ let ret = undefined;
432
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
433
+ try {
434
+ const parsed = JSON.parse(reply.getDataString());
435
+ if (parsed !== null && typeof parsed === "object") {
436
+ ret = parsed;
437
+ }
438
+ } catch {}
439
+ }
440
+ return ret;
441
+ }
442
+
443
+ // packages/core/src/api/event/EventBus.ts
264
444
  class Event {
265
445
  cri;
266
446
  headers;
@@ -299,24 +479,34 @@ class Event {
299
479
 
300
480
  class EventBus {
301
481
  serverInfo = null;
482
+ log = createDebugLogger("kinotic:EventBus");
302
483
  stompConnectionManager = new StompConnectionManager;
303
484
  connectionLifecycle = Promise.resolve();
304
- replyToCri = null;
485
+ disconnectRequests = 0;
305
486
  requestRepliesObservable = null;
306
487
  requestRepliesSubject = null;
307
488
  requestRepliesSubscription = null;
308
489
  activeCorrelationIds = new Set;
309
490
  recentlyReaped = new Set;
491
+ connectionEndedSubject = new Subject2;
310
492
  static REAP_DEBOUNCE_MS = 5000;
311
493
  constructor() {
312
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
313
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
314
- this.replyToCri = replyToCri;
315
- this.resetRequestReplies("Reply destination changed");
494
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
495
+ this.resetRequestReplies("Connection lost");
496
+ if (!this.stompConnectionManager.active) {
497
+ this.serverInfo = null;
498
+ }
499
+ this.connectionEndedSubject.next(reason);
316
500
  };
317
501
  }
318
- get fatalErrors() {
319
- return this.stompConnectionManager.fatalErrors;
502
+ get connectionEnded() {
503
+ return this.connectionEndedSubject.asObservable();
504
+ }
505
+ get connectionEstablished() {
506
+ return this.stompConnectionManager.connectionEstablished;
507
+ }
508
+ get connectionAttemptFailed() {
509
+ return this.stompConnectionManager.connectionAttemptFailed;
320
510
  }
321
511
  isConnectionActive() {
322
512
  return this.stompConnectionManager.active;
@@ -325,12 +515,14 @@ class EventBus {
325
515
  return this.stompConnectionManager.connected;
326
516
  }
327
517
  connect(options) {
518
+ const disconnectsWhenQueued = this.disconnectRequests;
328
519
  return this.serializeLifecycle(async () => {
520
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
521
+ throw new Error("Disconnected before the connection was started");
522
+ }
329
523
  if (!this.stompConnectionManager.active) {
330
- this.cleanup();
331
524
  const connectedInfo = await this.stompConnectionManager.activate(options);
332
525
  this.serverInfo = { ...options.server };
333
- this.replyToCri = this.stompConnectionManager.replyToCri;
334
526
  return connectedInfo;
335
527
  } else {
336
528
  throw new Error("Event Bus connection already active");
@@ -338,9 +530,12 @@ class EventBus {
338
530
  });
339
531
  }
340
532
  disconnect(force) {
533
+ this.disconnectRequests++;
534
+ const deactivated = this.stompConnectionManager.deactivate(force);
341
535
  return this.serializeLifecycle(async () => {
536
+ await deactivated;
342
537
  await this.stompConnectionManager.deactivate(force);
343
- this.cleanup();
538
+ this.serverInfo = null;
344
539
  });
345
540
  }
346
541
  serializeLifecycle(operation) {
@@ -349,7 +544,7 @@ class EventBus {
349
544
  return result;
350
545
  }
351
546
  send(event) {
352
- if (this.stompConnectionManager.rxStomp) {
547
+ if (this.stompConnectionManager.connected) {
353
548
  const headers = {};
354
549
  for (const [key, value] of event.headers.entries()) {
355
550
  headers[key] = value;
@@ -365,7 +560,8 @@ class EventBus {
365
560
  this.stompConnectionManager.rxStomp.publish({
366
561
  destination: event.cri,
367
562
  headers,
368
- binaryBody: event.data.orUndefined()
563
+ binaryBody: event.data.orUndefined(),
564
+ retryIfDisconnected: false
369
565
  });
370
566
  } else {
371
567
  throw this.createSendUnavailableError();
@@ -375,58 +571,65 @@ class EventBus {
375
571
  return firstValueFrom(this.requestStream(event, false));
376
572
  }
377
573
  requestStream(event, sendControlEvents = true) {
378
- if (this.stompConnectionManager?.rxStomp) {
379
- return new Observable2((subscriber) => {
380
- if (this.requestRepliesObservable == null) {
381
- this.requestRepliesSubject = new Subject2;
382
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
383
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
384
- }
385
- let serverSignaledCompletion = false;
386
- const correlationId = uuidv42();
387
- this.activeCorrelationIds.add(correlationId);
388
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
389
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
390
- })).subscribe({
391
- next(value) {
392
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
393
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
394
- serverSignaledCompletion = true;
395
- subscriber.complete();
396
- } else {
397
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
398
- }
399
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
574
+ return new Observable2((subscriber) => {
575
+ const replyToCri = this.stompConnectionManager.replyToCri;
576
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
577
+ subscriber.error(this.createSendUnavailableError());
578
+ return;
579
+ }
580
+ if (this.requestRepliesObservable == null) {
581
+ this.requestRepliesSubject = new Subject2;
582
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
583
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
584
+ }
585
+ let serverSignaledCompletion = false;
586
+ let replyDestinationReset = false;
587
+ const correlationId = uuidv42();
588
+ this.activeCorrelationIds.add(correlationId);
589
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
590
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
591
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
592
+ })).subscribe({
593
+ next(value) {
594
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
595
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
400
596
  serverSignaledCompletion = true;
401
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
597
+ if (value.data.isPresent() || !sendControlEvents) {
598
+ subscriber.next(value);
599
+ }
600
+ subscriber.complete();
402
601
  } else {
403
- subscriber.next(value);
602
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
404
603
  }
405
- },
406
- error(err) {
407
- subscriber.error(err);
408
- },
409
- complete() {
410
- subscriber.complete();
604
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
605
+ serverSignaledCompletion = true;
606
+ subscriber.error(RpcError.fromEvent(value));
607
+ } else {
608
+ subscriber.next(value);
411
609
  }
412
- });
413
- subscriber.add(defaultMessagesSubscription);
414
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
415
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
416
- this.send(event);
417
- return () => {
418
- this.activeCorrelationIds.delete(correlationId);
419
- if (sendControlEvents && !serverSignaledCompletion) {
420
- const controlEvent = new Event(event.cri);
421
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
422
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
423
- this.send(controlEvent);
610
+ },
611
+ error(err) {
612
+ replyDestinationReset = true;
613
+ subscriber.error(err);
614
+ },
615
+ complete() {
616
+ subscriber.complete();
617
+ }
618
+ });
619
+ subscriber.add(defaultMessagesSubscription);
620
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
621
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
622
+ this.send(event);
623
+ subscriber.add(() => {
624
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
625
+ try {
626
+ this.sendCancel(event.cri, correlationId);
627
+ } catch (e) {
628
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
424
629
  }
425
- };
630
+ }
426
631
  });
427
- } else {
428
- return throwError(() => this.createSendUnavailableError());
429
- }
632
+ });
430
633
  }
431
634
  listen(_serverInfo) {
432
635
  return Promise.reject("Not implemented");
@@ -434,10 +637,6 @@ class EventBus {
434
637
  observe(cri) {
435
638
  return this._observe(cri);
436
639
  }
437
- cleanup() {
438
- this.resetRequestReplies("Connection disconnected");
439
- this.serverInfo = null;
440
- }
441
640
  cancelIfUnexpected(value) {
442
641
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
443
642
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -448,13 +647,19 @@ class EventBus {
448
647
  return;
449
648
  }
450
649
  try {
451
- const cancelEvent = new Event(originCri);
452
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
453
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
454
- this.send(cancelEvent);
650
+ this.sendCancel(originCri, correlationId);
455
651
  this.recentlyReaped.add(correlationId);
456
652
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
457
- } catch {}
653
+ } catch (e) {
654
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
655
+ }
656
+ }
657
+ sendCancel(cri, correlationId) {
658
+ const cancelEvent = new Event(cri);
659
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
660
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
661
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
662
+ this.send(cancelEvent);
458
663
  }
459
664
  resetRequestReplies(reason) {
460
665
  if (this.requestRepliesSubject != null) {
@@ -469,29 +674,29 @@ class EventBus {
469
674
  }
470
675
  }
471
676
  createSendUnavailableError() {
472
- let ret = "You must call connect on the event bus before sending any request";
677
+ let ret;
473
678
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
474
679
  ret = "Max connection attempts reached event bus is not available";
680
+ } else if (this.stompConnectionManager.active) {
681
+ ret = "The event bus is not connected to the server";
682
+ } else {
683
+ ret = "You must call connect on the event bus before sending any request";
475
684
  }
476
685
  return new Error(ret);
477
686
  }
478
687
  _observe(cri) {
479
- if (this.stompConnectionManager?.rxStomp) {
480
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
481
- const headers = new Map;
482
- let destination = "";
483
- for (const prop of Object.keys(message.headers)) {
484
- if (prop === "destination") {
485
- destination = message.headers[prop];
486
- } else {
487
- headers.set(prop, message.headers[prop]);
488
- }
688
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
689
+ const headers = new Map;
690
+ let destination = "";
691
+ for (const prop of Object.keys(message.headers)) {
692
+ if (prop === "destination") {
693
+ destination = message.headers[prop];
694
+ } else {
695
+ headers.set(prop, message.headers[prop]);
489
696
  }
490
- return new Event(destination, headers, message.binaryBody);
491
- }));
492
- } else {
493
- throw this.createSendUnavailableError();
494
- }
697
+ }
698
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
699
+ }));
495
700
  }
496
701
  }
497
702
 
@@ -569,7 +774,8 @@ class SessionCredentialsResolver {
569
774
 
570
775
  // packages/core/src/internal/api/Util.ts
571
776
  var DEFAULT_PORT = 58503;
572
- var DEFAULT_HOST = "api.kinotic.com";
777
+ var DEFAULT_HOST = "api.kinotic.ai";
778
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
573
779
 
574
780
  class Util {
575
781
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -600,7 +806,6 @@ class Util {
600
806
  const location = typeof window !== "undefined" ? window.location : undefined;
601
807
  let host = server.host ?? env?.KINOTIC_SERVER_HOST;
602
808
  const hostFromLocation = host == null && location != null;
603
- const hostDefaulted = host == null && location == null;
604
809
  if (host == null) {
605
810
  host = location?.hostname ?? DEFAULT_HOST;
606
811
  }
@@ -611,7 +816,7 @@ class Util {
611
816
  } else if (hostFromLocation) {
612
817
  useSSL = location.protocol === "https:";
613
818
  } else {
614
- useSSL = hostDefaulted;
819
+ useSSL = !LOOPBACK_HOSTS.includes(host.toLowerCase());
615
820
  }
616
821
  }
617
822
  let port = server.port;
@@ -633,8 +838,119 @@ class Util {
633
838
  }
634
839
  }
635
840
 
636
- // packages/core/src/api/ServiceRegistry.ts
841
+ // packages/core/src/internal/api/Session.ts
637
842
  import debug3 from "debug";
843
+ import { Subject as Subject3, Subscription as Subscription2 } from "rxjs";
844
+
845
+ // packages/core/src/api/security/SessionEndType.ts
846
+ var SessionEndType;
847
+ ((SessionEndType) => {
848
+ SessionEndType["SIGNED_OUT"] = "SIGNED_OUT";
849
+ SessionEndType["CONNECTION_LOST"] = "CONNECTION_LOST";
850
+ })(SessionEndType ||= {});
851
+
852
+ // packages/core/src/internal/api/Session.ts
853
+ var SESSION_REQUEST_TIMEOUT_MS = 5000;
854
+
855
+ class Session {
856
+ kinotic;
857
+ _connectedInfo = null;
858
+ server = null;
859
+ inFlight = Promise.resolve();
860
+ requests = 0;
861
+ subscriptions = new Subscription2;
862
+ endedSubject = new Subject3;
863
+ debugLogger = debug3("kinotic:session");
864
+ constructor(kinotic) {
865
+ this.kinotic = kinotic;
866
+ this.observe(kinotic.eventBus);
867
+ }
868
+ get connectedInfo() {
869
+ return this._connectedInfo;
870
+ }
871
+ get ended() {
872
+ return this.endedSubject.asObservable();
873
+ }
874
+ release() {
875
+ this._connectedInfo = null;
876
+ }
877
+ observe(eventBus) {
878
+ this.subscriptions.unsubscribe();
879
+ this.subscriptions = new Subscription2;
880
+ this.subscriptions.add(eventBus.connectionEstablished.subscribe((connectedInfo) => {
881
+ if (this._connectedInfo !== null) {
882
+ this._connectedInfo = connectedInfo;
883
+ }
884
+ }));
885
+ this.subscriptions.add(eventBus.connectionEnded.subscribe((reason) => {
886
+ if (this._connectedInfo !== null && !this.kinotic.eventBus.isConnectionActive()) {
887
+ this._connectedInfo = null;
888
+ if (reason !== null) {
889
+ this.classifyEnd(reason);
890
+ }
891
+ }
892
+ }));
893
+ }
894
+ resume(options) {
895
+ this.requests++;
896
+ return this.serialize(async () => {
897
+ this._connectedInfo = null;
898
+ try {
899
+ await this.kinotic.disconnect();
900
+ } catch (e) {
901
+ this.debugLogger("Closing the previous connection failed: %O", e);
902
+ }
903
+ const resolved = Util.resolveConnectOptions(options);
904
+ this.server = resolved.server;
905
+ let ret;
906
+ try {
907
+ ret = await this.kinotic.connect(resolved);
908
+ } catch (e) {
909
+ await this.kinotic.disconnect().catch((error) => this.debugLogger("Closing the failed connection failed: %O", error));
910
+ throw e;
911
+ }
912
+ this._connectedInfo = ret;
913
+ return ret;
914
+ });
915
+ }
916
+ logout() {
917
+ this.requests++;
918
+ return this.serialize(async () => {
919
+ this._connectedInfo = null;
920
+ const server = this.kinotic.eventBus.serverInfo ?? this.server ?? Util.resolveConnectOptions().server;
921
+ try {
922
+ await endLogin(server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
923
+ } catch (e) {
924
+ this.debugLogger("The logout request failed: %O", e);
925
+ }
926
+ try {
927
+ await this.kinotic.disconnect();
928
+ } catch (e) {
929
+ this.debugLogger("Closing the connection failed: %O", e);
930
+ }
931
+ });
932
+ }
933
+ async classifyEnd(cause) {
934
+ const requestsAtEnd = this.requests;
935
+ let signedOut = false;
936
+ try {
937
+ signedOut = !await holdsLogin(this.server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
938
+ } catch (e) {
939
+ this.debugLogger("The session check failed: %O", e);
940
+ }
941
+ if (this.requests === requestsAtEnd) {
942
+ this.endedSubject.next({ type: signedOut ? "SIGNED_OUT" /* SIGNED_OUT */ : "CONNECTION_LOST" /* CONNECTION_LOST */, cause });
943
+ }
944
+ }
945
+ serialize(operation) {
946
+ const result = this.inFlight.then(operation);
947
+ this.inFlight = result.catch(() => {});
948
+ return result;
949
+ }
950
+ }
951
+
952
+ // packages/core/src/api/ServiceRegistry.ts
953
+ import debug4 from "debug";
638
954
 
639
955
  // packages/core/src/api/event/DefaultCRI.ts
640
956
  var ZONE_DELIMITER = "~";
@@ -822,22 +1138,14 @@ class JsonArgumentResolver {
822
1138
  // packages/core/src/internal/api/ReturnValueConverter.ts
823
1139
  class BasicReturnValueConverter {
824
1140
  convert(incomingMetadata, returnValue) {
825
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
1141
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
1142
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
826
1143
  }
827
1144
  }
828
1145
 
829
- // packages/core/src/internal/api/Logger.ts
830
- import debug2 from "debug";
831
- function createDebugLogger(namespace) {
832
- const debugLogger = debug2(namespace);
833
- return {
834
- trace: (...args) => debugLogger("TRACE", ...args),
835
- debug: (...args) => debugLogger("DEBUG", ...args),
836
- info: (...args) => debugLogger("INFO", ...args),
837
- warn: (...args) => debugLogger("WARN", ...args),
838
- error: (...args) => debugLogger("ERROR", ...args)
839
- };
840
- }
1146
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1147
+ import { isObservable } from "rxjs";
1148
+ import { finalize } from "rxjs/operators";
841
1149
 
842
1150
  // packages/core/src/api/ServiceIdentifier.ts
843
1151
  class ServiceIdentifier {
@@ -874,6 +1182,9 @@ class ServiceIdentifier {
874
1182
  }
875
1183
  return this._cri;
876
1184
  }
1185
+ unscopedCri() {
1186
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1187
+ }
877
1188
  }
878
1189
 
879
1190
  // packages/core/src/api/ZoneUtil.ts
@@ -893,6 +1204,7 @@ function validateLabel(label) {
893
1204
 
894
1205
  // packages/core/src/api/KinoticDecorators.ts
895
1206
  var scopeFunctions = new WeakSet;
1207
+ var scopeOptionalFunctions = new WeakSet;
896
1208
  var versionRegistry = new WeakMap;
897
1209
  var zonesRegistry = new WeakMap;
898
1210
  var advertisedRegistry = new WeakMap;
@@ -930,6 +1242,23 @@ function resolveScope(instance) {
930
1242
  function Scope(value, _context) {
931
1243
  scopeFunctions.add(value);
932
1244
  }
1245
+ function ScopeOptional(value, _context) {
1246
+ scopeOptionalFunctions.add(value);
1247
+ }
1248
+ function scopeOptionalMethodNames(instance) {
1249
+ const ret = new Set;
1250
+ let proto = Object.getPrototypeOf(instance);
1251
+ while (proto && proto !== Object.prototype) {
1252
+ for (const key of Object.getOwnPropertyNames(proto)) {
1253
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1254
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1255
+ ret.add(key);
1256
+ }
1257
+ }
1258
+ proto = Object.getPrototypeOf(proto);
1259
+ }
1260
+ return ret;
1261
+ }
933
1262
  function Version(version) {
934
1263
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
935
1264
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -993,57 +1322,168 @@ function Publish(namespace, name, advertise = false) {
993
1322
  }
994
1323
 
995
1324
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
996
- class ServiceInvocationSupervisor {
997
- log;
998
- active = false;
999
- _eventBus;
1000
- interceptorProvider;
1001
- argumentResolver;
1002
- returnValueConverter;
1003
- serviceIdentifier;
1004
- serviceInstance;
1005
- methodSubscription = null;
1006
- methodMap;
1007
- constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1008
- if (!serviceIdentifier)
1009
- throw new Error("ServiceIdentifier must not be null");
1010
- if (!serviceInstance)
1011
- throw new Error("Service instance must not be null");
1012
- if (!eventBusService)
1013
- throw new Error("IEventBus must not be null");
1014
- if (!interceptorProvider)
1015
- throw new Error("interceptorProvider must not be null");
1016
- this.serviceIdentifier = serviceIdentifier;
1017
- this.serviceInstance = serviceInstance;
1018
- this._eventBus = eventBusService;
1019
- this.interceptorProvider = interceptorProvider;
1020
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1021
- this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1022
- this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1023
- this.methodMap = this.buildMethodMap(serviceInstance);
1024
- }
1025
- isActive() {
1026
- return this.active;
1027
- }
1028
- set eventBus(eventBus) {
1029
- if (this.active) {
1030
- this.stop();
1031
- this._eventBus = eventBus;
1032
- this.start();
1033
- } else {
1034
- this._eventBus = eventBus;
1035
- }
1036
- }
1037
- start() {
1038
- if (this.active) {
1039
- throw new Error("Service already started");
1040
- }
1041
- this.active = true;
1042
- const criBase = this.serviceIdentifier.cri().baseResource();
1043
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1044
- next: async (event) => {
1045
- await this.processEvent(event);
1046
- },
1325
+ import opentelemetry, { context as context2, propagation as propagation2, trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
1326
+ // packages/core/package.json
1327
+ var package_default = {
1328
+ name: "@kinotic-ai/core",
1329
+ version: "5.0.0-beta.31",
1330
+ type: "module",
1331
+ files: [
1332
+ "dist"
1333
+ ],
1334
+ module: "./dist/index.js",
1335
+ main: "./dist/index.cjs",
1336
+ types: "./dist/index.d.ts",
1337
+ exports: {
1338
+ ".": {
1339
+ import: {
1340
+ types: "./dist/index.d.ts",
1341
+ default: "./dist/index.js"
1342
+ },
1343
+ require: {
1344
+ types: "./dist/index.d.cts",
1345
+ default: "./dist/index.cjs"
1346
+ }
1347
+ },
1348
+ "./node": {
1349
+ import: {
1350
+ types: "./dist/node/index.d.ts",
1351
+ default: "./dist/node/index.js"
1352
+ },
1353
+ require: {
1354
+ types: "./dist/node/index.d.cts",
1355
+ default: "./dist/node/index.cjs"
1356
+ }
1357
+ },
1358
+ "./package.json": "./package.json"
1359
+ },
1360
+ homepage: "https://github.com/kinotic-ai/kinotic",
1361
+ repository: {
1362
+ type: "git",
1363
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1364
+ directory: "kinotic-js/workspace/packages/core"
1365
+ },
1366
+ license: "Apache-2.0",
1367
+ publishConfig: {
1368
+ access: "public"
1369
+ },
1370
+ scripts: {
1371
+ "type-check": "tsc --noEmit",
1372
+ test: "vitest run",
1373
+ coverage: "vitest run --coverage",
1374
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1375
+ },
1376
+ devDependencies: {
1377
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1378
+ "@opentelemetry/resources": "^2.10.0",
1379
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1380
+ "@opentelemetry/sdk-node": "^0.221.0",
1381
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1382
+ "@types/debug": "^4.1.13",
1383
+ "@types/node": "^25.6.0",
1384
+ "@types/ws": "^8.18.0",
1385
+ "@vitest/coverage-v8": "^4.1.4",
1386
+ "@vitest/runner": "^4.1.4",
1387
+ "@vitest/ui": "^4.1.4",
1388
+ allure: "^3.19.1",
1389
+ "allure-vitest": "^3.13.0",
1390
+ dotenv: "^17.4.1",
1391
+ "properties-file": "^4.0.0",
1392
+ testcontainers: "^11.14.0",
1393
+ tslib: "^2.8.1",
1394
+ typescript: "^6.0.2",
1395
+ vitest: "^4.1.4"
1396
+ },
1397
+ dependencies: {
1398
+ "@kinotic-ai/idl": "workspace:^",
1399
+ "@opentelemetry/api": "^1.9.1",
1400
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1401
+ "@stomp/rx-stomp": "^2.4.0",
1402
+ "@stomp/stompjs": "^7.3.0",
1403
+ debug: "^4.4.3",
1404
+ "p-tap": "^4.0.0",
1405
+ rxjs: "^7.8.2",
1406
+ "typescript-optional": "3.0.0-alpha.3",
1407
+ uuid: "^13.0.0",
1408
+ ws: "^8.21.0"
1409
+ }
1410
+ };
1411
+
1412
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1413
+ class ServiceInvocationSupervisor {
1414
+ log;
1415
+ active = false;
1416
+ _eventBus;
1417
+ interceptorProvider;
1418
+ argumentResolver;
1419
+ returnValueConverter;
1420
+ serviceIdentifier;
1421
+ serviceInstance;
1422
+ methodSubscription = null;
1423
+ unscopedSubscription = null;
1424
+ activeStreams = new Map;
1425
+ connectionEndedSubscription = null;
1426
+ connectionGeneration = 0;
1427
+ methodMap;
1428
+ scopeOptionalMethods;
1429
+ tracer;
1430
+ constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1431
+ if (!serviceIdentifier)
1432
+ throw new Error("ServiceIdentifier must not be null");
1433
+ if (!serviceInstance)
1434
+ throw new Error("Service instance must not be null");
1435
+ if (!eventBusService)
1436
+ throw new Error("IEventBus must not be null");
1437
+ if (!interceptorProvider)
1438
+ throw new Error("interceptorProvider must not be null");
1439
+ this.serviceIdentifier = serviceIdentifier;
1440
+ this.serviceInstance = serviceInstance;
1441
+ this._eventBus = eventBusService;
1442
+ this.interceptorProvider = interceptorProvider;
1443
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1444
+ this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1445
+ this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1446
+ this.methodMap = this.buildMethodMap(serviceInstance);
1447
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1448
+ this.tracer = opentelemetry.trace.getTracer(package_default.name, package_default.version);
1449
+ }
1450
+ isActive() {
1451
+ return this.active;
1452
+ }
1453
+ set eventBus(eventBus) {
1454
+ if (this.active) {
1455
+ this.stop();
1456
+ this._eventBus = eventBus;
1457
+ this.start();
1458
+ } else {
1459
+ this._eventBus = eventBus;
1460
+ }
1461
+ }
1462
+ start() {
1463
+ if (this.active) {
1464
+ throw new Error("Service already started");
1465
+ }
1466
+ this.active = true;
1467
+ const criBase = this.serviceIdentifier.cri().baseResource();
1468
+ this.methodSubscription = this.subscribeAt(criBase);
1469
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1470
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1471
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1472
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1473
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1474
+ }
1475
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1476
+ this.connectionGeneration++;
1477
+ for (const stream of this.activeStreams.values()) {
1478
+ stream.subscription.unsubscribe();
1479
+ }
1480
+ });
1481
+ }
1482
+ subscribeAt(criBase) {
1483
+ return this._eventBus.observe(criBase).subscribe({
1484
+ next: async (event) => {
1485
+ await this.processEvent(event);
1486
+ },
1047
1487
  error: (error) => {
1048
1488
  this.log.error("Event listener error", error);
1049
1489
  this.active = false;
@@ -1053,7 +1493,6 @@ class ServiceInvocationSupervisor {
1053
1493
  this.active = false;
1054
1494
  }
1055
1495
  });
1056
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1057
1496
  }
1058
1497
  stop() {
1059
1498
  if (!this.active) {
@@ -1062,6 +1501,15 @@ class ServiceInvocationSupervisor {
1062
1501
  this.active = false;
1063
1502
  this.methodSubscription?.unsubscribe();
1064
1503
  this.methodSubscription = null;
1504
+ this.unscopedSubscription?.unsubscribe();
1505
+ this.unscopedSubscription = null;
1506
+ this.connectionEndedSubscription?.unsubscribe();
1507
+ this.connectionEndedSubscription = null;
1508
+ const serviceName = this.serviceIdentifier.qualifiedName();
1509
+ for (const stream of this.activeStreams.values()) {
1510
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1511
+ stream.subscription.unsubscribe();
1512
+ }
1065
1513
  this.log.info("ServiceInvocationSupervisor stopped");
1066
1514
  }
1067
1515
  buildMethodMap(serviceInstance) {
@@ -1101,10 +1549,19 @@ class ServiceInvocationSupervisor {
1101
1549
  if (!correlationId) {
1102
1550
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1103
1551
  }
1104
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1552
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1553
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1554
+ const stream = this.activeStreams.get(correlationId);
1555
+ if (stream) {
1556
+ stream.subscription.unsubscribe();
1557
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1558
+ throw new Error(`Unknown control header value ${control}`);
1559
+ }
1560
+ }
1105
1561
  }
1106
1562
  async processInvocationRequest(event) {
1107
- const path = createCRI(event.cri).path();
1563
+ const incomingCri = createCRI(event.cri);
1564
+ const path = incomingCri.path();
1108
1565
  if (!path) {
1109
1566
  throw new Error("The methodId must not be blank");
1110
1567
  }
@@ -1112,49 +1569,175 @@ class ServiceInvocationSupervisor {
1112
1569
  if (!handlerMethod) {
1113
1570
  throw new Error(`No method resolved for methodId ${path}`);
1114
1571
  }
1572
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1573
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1574
+ }
1115
1575
  const methodName = path;
1116
- const args = this.argumentResolver.resolveArguments(event);
1117
- const injectContext = receivesContext(this.serviceInstance, methodName);
1118
- let context2 = {};
1119
- const interceptor = this.interceptorProvider();
1120
- if (interceptor) {
1576
+ const span = this.startInvocationSpan(event, methodName);
1577
+ const generation = this.connectionGeneration;
1578
+ try {
1579
+ const args = this.argumentResolver.resolveArguments(event);
1580
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1581
+ let serviceContext = {};
1582
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1583
+ if (sender) {
1584
+ serviceContext.participant = JSON.parse(sender);
1585
+ }
1586
+ const interceptor = this.interceptorProvider();
1587
+ if (interceptor) {
1588
+ try {
1589
+ serviceContext = await interceptor.intercept(event, serviceContext);
1590
+ } catch (e) {
1591
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1592
+ if (this.replyOwed(generation)) {
1593
+ this.handleException(event, new Error("Internal server error"));
1594
+ }
1595
+ this.failSpan(span, e);
1596
+ return;
1597
+ }
1598
+ }
1599
+ if (injectContext) {
1600
+ args.push(serviceContext);
1601
+ }
1602
+ const expectedArgsCount = handlerMethod.length;
1603
+ if (args.length !== expectedArgsCount) {
1604
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1605
+ }
1606
+ let result;
1121
1607
  try {
1122
- context2 = await interceptor.intercept(event, context2);
1608
+ result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
1609
+ if (result instanceof Promise) {
1610
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1611
+ this.failInvocation(event, e, span, generation);
1612
+ });
1613
+ } else {
1614
+ this.processMethodInvocationResult(event, result, span, generation);
1615
+ }
1123
1616
  } catch (e) {
1124
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1125
- this.handleException(event, new Error("Internal server error"));
1126
- return;
1617
+ this.failInvocation(event, e, span, generation);
1618
+ }
1619
+ } catch (e) {
1620
+ this.failSpan(span, e);
1621
+ throw e;
1622
+ }
1623
+ }
1624
+ startInvocationSpan(event, methodName) {
1625
+ const carrier = {};
1626
+ for (const [key, value] of event.headers.entries()) {
1627
+ carrier[key] = value;
1628
+ }
1629
+ const serviceName = this.serviceIdentifier.qualifiedName();
1630
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1631
+ kind: SpanKind.SERVER,
1632
+ attributes: {
1633
+ "rpc.system": "kinotic",
1634
+ "rpc.service": serviceName,
1635
+ "rpc.method": methodName
1127
1636
  }
1637
+ }, propagation2.extract(context2.active(), carrier));
1638
+ }
1639
+ failSpan(span, error) {
1640
+ span.recordException(error);
1641
+ span.setStatus({ code: SpanStatusCode.ERROR });
1642
+ span.end();
1643
+ }
1644
+ replyOwed(generation) {
1645
+ return generation === this.connectionGeneration;
1646
+ }
1647
+ failInvocation(event, error, span, generation) {
1648
+ if (this.replyOwed(generation)) {
1649
+ this.handleException(event, error);
1128
1650
  }
1129
- if (injectContext) {
1130
- args.push(context2);
1651
+ this.failSpan(span, error);
1652
+ }
1653
+ processMethodInvocationResult(event, result, span, generation) {
1654
+ if (!this.replyOwed(generation)) {
1655
+ span.end();
1656
+ } else if (isObservable(result)) {
1657
+ this.streamResult(event, result, span);
1658
+ } else {
1659
+ const reply = this.returnValueConverter.convert(event.headers, result);
1660
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1661
+ this.sendReply(reply);
1662
+ span.end();
1131
1663
  }
1132
- const expectedArgsCount = handlerMethod.length;
1133
- if (args.length !== expectedArgsCount) {
1134
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1664
+ }
1665
+ streamResult(event, stream, span) {
1666
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1667
+ if (!correlationId) {
1668
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1135
1669
  }
1136
- let result;
1137
- try {
1138
- result = handlerMethod(...args);
1139
- if (result instanceof Promise) {
1140
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1141
- } else {
1142
- this.processMethodInvocationResult(event, result);
1670
+ if (this.activeStreams.has(correlationId)) {
1671
+ const error = new Error(`stream ${correlationId} already active`);
1672
+ this.handleException(event, error);
1673
+ this.failSpan(span, error);
1674
+ return;
1675
+ }
1676
+ let subscription = null;
1677
+ let failed = false;
1678
+ subscription = stream.pipe(finalize(() => {
1679
+ if (this.activeStreams.get(correlationId)?.subscription === subscription) {
1680
+ this.activeStreams.delete(correlationId);
1143
1681
  }
1144
- } catch (e) {
1145
- this.handleException(event, e);
1682
+ span.end();
1683
+ })).subscribe({
1684
+ next: (value) => {
1685
+ if (failed) {
1686
+ return;
1687
+ }
1688
+ try {
1689
+ const reply = this.returnValueConverter.convert(event.headers, value);
1690
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1691
+ this.sendReply(reply);
1692
+ } catch (e) {
1693
+ failed = true;
1694
+ this.handleException(event, e);
1695
+ span.recordException(e);
1696
+ span.setStatus({ code: SpanStatusCode.ERROR });
1697
+ subscription?.unsubscribe();
1698
+ }
1699
+ },
1700
+ error: (error) => {
1701
+ if (failed) {
1702
+ return;
1703
+ }
1704
+ this.handleException(event, error);
1705
+ span.recordException(error);
1706
+ span.setStatus({ code: SpanStatusCode.ERROR });
1707
+ },
1708
+ complete: () => {
1709
+ if (failed) {
1710
+ return;
1711
+ }
1712
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1713
+ }
1714
+ });
1715
+ if (failed) {
1716
+ subscription.unsubscribe();
1717
+ }
1718
+ if (!subscription.closed) {
1719
+ this.activeStreams.set(correlationId, { request: event, subscription });
1146
1720
  }
1147
1721
  }
1148
- processMethodInvocationResult(event, result) {
1149
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1150
- this._eventBus.send(outgoingEvent);
1722
+ sendReply(event) {
1723
+ try {
1724
+ this._eventBus.send(event);
1725
+ } catch (e) {
1726
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1727
+ }
1151
1728
  }
1152
1729
  handleException(event, error) {
1153
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1154
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1155
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1156
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1157
- this._eventBus.send(errorEvent);
1730
+ try {
1731
+ const errorMessage = error?.message || "Unknown error";
1732
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1733
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1734
+ ["error" /* ERROR_HEADER */, errorMessage],
1735
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1736
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1737
+ this.sendReply(errorEvent);
1738
+ } catch (e) {
1739
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1740
+ }
1158
1741
  }
1159
1742
  validateReplyTo(event) {
1160
1743
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1175,100 +1758,12 @@ class ServiceInvocationSupervisor {
1175
1758
  }
1176
1759
 
1177
1760
  // packages/core/src/api/ServiceRegistry.ts
1178
- import opentelemetry, { SpanKind, SpanStatusCode } from "@opentelemetry/api";
1761
+ import opentelemetry2, { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
1179
1762
  import {
1180
1763
  ATTR_SERVER_ADDRESS,
1181
1764
  ATTR_SERVER_PORT
1182
1765
  } from "@opentelemetry/semantic-conventions";
1183
1766
  import { first, map as map2 } from "rxjs/operators";
1184
- // packages/core/package.json
1185
- var package_default = {
1186
- name: "@kinotic-ai/core",
1187
- version: "5.0.0-beta.3",
1188
- type: "module",
1189
- files: [
1190
- "dist"
1191
- ],
1192
- module: "./dist/index.js",
1193
- main: "./dist/index.cjs",
1194
- types: "./dist/index.d.ts",
1195
- exports: {
1196
- ".": {
1197
- import: {
1198
- types: "./dist/index.d.ts",
1199
- default: "./dist/index.js"
1200
- },
1201
- require: {
1202
- types: "./dist/index.d.cts",
1203
- default: "./dist/index.cjs"
1204
- }
1205
- },
1206
- "./node": {
1207
- import: {
1208
- types: "./dist/node/index.d.ts",
1209
- default: "./dist/node/index.js"
1210
- },
1211
- require: {
1212
- types: "./dist/node/index.d.cts",
1213
- default: "./dist/node/index.cjs"
1214
- }
1215
- },
1216
- "./package.json": "./package.json"
1217
- },
1218
- homepage: "https://github.com/kinotic-ai/kinotic",
1219
- license: "Elastic License 2.0",
1220
- publishConfig: {
1221
- access: "public"
1222
- },
1223
- scripts: {
1224
- "type-check": "tsc --noEmit",
1225
- test: "vitest run",
1226
- coverage: "vitest run --coverage",
1227
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1228
- },
1229
- devDependencies: {
1230
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1231
- "@opentelemetry/resources": "^2.6.1",
1232
- "@opentelemetry/sdk-metrics": "^2.6.1",
1233
- "@opentelemetry/sdk-node": "^0.214.0",
1234
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1235
- "@types/node": "^25.6.0",
1236
- "@types/uuid": "^11.0.0",
1237
- "@types/ws": "^8.18.0",
1238
- "@vitest/coverage-v8": "^4.1.4",
1239
- "@vitest/runner": "^4.1.4",
1240
- "@vitest/ui": "^4.1.4",
1241
- allure: "^3.4.1",
1242
- "allure-vitest": "^3.7.1",
1243
- dotenv: "^17.4.1",
1244
- "properties-file": "^4.0.0",
1245
- testcontainers: "^11.14.0",
1246
- tslib: "^2.8.1",
1247
- typescript: "^6.0.2",
1248
- vitest: "^4.1.4",
1249
- ws: "^8.20.0"
1250
- },
1251
- dependencies: {
1252
- "@opentelemetry/api": "^1.9.1",
1253
- "@opentelemetry/semantic-conventions": "^1.40.0",
1254
- "@stomp/rx-stomp": "^2.4.0",
1255
- "@stomp/stompjs": "^7.3.0",
1256
- "@types/debug": "^4.1.13",
1257
- debug: "^4.4.3",
1258
- "p-tap": "^4.0.0",
1259
- rxjs: "^7.8.2",
1260
- "typescript-optional": "3.0.0-alpha.3",
1261
- uuid: "^13.0.0",
1262
- ws: "^8.18.0"
1263
- },
1264
- peerDependenciesMeta: {
1265
- typescript: {
1266
- optional: true
1267
- }
1268
- }
1269
- };
1270
-
1271
- // packages/core/src/api/ServiceRegistry.ts
1272
1767
  class JsonEventFactory {
1273
1768
  create(cri, args) {
1274
1769
  const event = new Event(cri);
@@ -1302,12 +1797,61 @@ class TextEventFactory {
1302
1797
  return event;
1303
1798
  }
1304
1799
  }
1800
+ var APPLICATION_SERVICE_DIRECTORY = "app-api~org.kinotic.app.api.services.ApplicationServiceDirectory";
1801
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1802
+ var declaredDefinitions = new Map;
1803
+ function declareServiceDefinitions(definitions) {
1804
+ for (const definition of definitions) {
1805
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1806
+ }
1807
+ }
1808
+ function qualifiedNameOf(namespace, name) {
1809
+ return namespace ? `${namespace}.${name}` : name;
1810
+ }
1811
+ function servedFunctions(serviceInstance) {
1812
+ const ret = new Set;
1813
+ let proto = Object.getPrototypeOf(serviceInstance);
1814
+ while (proto && proto !== Object.prototype) {
1815
+ for (const key of Object.getOwnPropertyNames(proto)) {
1816
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1817
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1818
+ ret.add(key);
1819
+ }
1820
+ }
1821
+ proto = Object.getPrototypeOf(proto);
1822
+ }
1823
+ return [...ret].sort();
1824
+ }
1825
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1826
+ let ret = null;
1827
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1828
+ if (application) {
1829
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1830
+ const definition = declaredDefinitions.get(qualifiedName);
1831
+ if (definition) {
1832
+ const declared = definition.functions.map((f) => f.name).sort();
1833
+ const served = servedFunctions(serviceInstance);
1834
+ if (declared.join() !== served.join()) {
1835
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1836
+ }
1837
+ ret = {
1838
+ applicationId: application[1],
1839
+ zone: serviceIdentifier.zone,
1840
+ version: serviceIdentifier.version ?? null,
1841
+ advertised: isAdvertised(serviceInstance),
1842
+ serviceDefinition: definition
1843
+ };
1844
+ }
1845
+ }
1846
+ return ret;
1847
+ }
1305
1848
 
1306
1849
  class ServiceRegistry {
1307
1850
  _eventBus;
1308
1851
  supervisors = new Map;
1852
+ entries = new Map;
1309
1853
  contextInterceptor = null;
1310
- debugLogger = debug3("kinoitc:serviceRegistry");
1854
+ debugLogger = debug4("kinotic:serviceRegistry");
1311
1855
  constructor(eventBus) {
1312
1856
  this._eventBus = eventBus;
1313
1857
  }
@@ -1327,9 +1871,16 @@ class ServiceRegistry {
1327
1871
  const criString = serviceIdentifier.cri().raw();
1328
1872
  if (!this.supervisors.has(criString)) {
1329
1873
  this.debugLogger(`Registering service for CRI: ${criString}`);
1874
+ const entry = directoryEntryOf(service, serviceIdentifier);
1330
1875
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1331
1876
  this.supervisors.set(criString, supervisor);
1332
1877
  supervisor.start();
1878
+ if (entry) {
1879
+ this.entries.set(criString, entry);
1880
+ if (this.eventBus.isConnected()) {
1881
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1882
+ }
1883
+ }
1333
1884
  }
1334
1885
  }
1335
1886
  unRegister(serviceIdentifier) {
@@ -1339,8 +1890,18 @@ class ServiceRegistry {
1339
1890
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1340
1891
  supervisor.stop();
1341
1892
  this.supervisors.delete(criString);
1893
+ this.entries.delete(criString);
1894
+ }
1895
+ }
1896
+ async registerEntries() {
1897
+ for (const entry of this.entries.values()) {
1898
+ await this.registerEntry(entry);
1342
1899
  }
1343
1900
  }
1901
+ async registerEntry(entry) {
1902
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
1903
+ await this.serviceProxy(APPLICATION_SERVICE_DIRECTORY).invoke("register", [entry]);
1904
+ }
1344
1905
  registerContextInterceptor(interceptor) {
1345
1906
  this.contextInterceptor = interceptor;
1346
1907
  }
@@ -1357,16 +1918,16 @@ class ServiceProxy {
1357
1918
  }
1358
1919
  this.serviceIdentifier = serviceIdentifier;
1359
1920
  this.serviceRegistry = serviceRegistry;
1360
- this.tracer = opentelemetry.trace.getTracer("kinoitc.client", package_default.version);
1921
+ this.tracer = opentelemetry2.trace.getTracer(package_default.name, package_default.version);
1361
1922
  }
1362
1923
  invoke(methodIdentifier, args, scope, eventFactory) {
1363
1924
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1364
- kind: SpanKind.CLIENT
1925
+ kind: SpanKind2.CLIENT
1365
1926
  }, async (span) => {
1366
1927
  if (scope) {
1367
- span.setAttribute("kinoitc.scope", scope);
1928
+ span.setAttribute("kinotic.scope", scope);
1368
1929
  }
1369
- span.setAttribute("rpc.system", "kinoitc");
1930
+ span.setAttribute("rpc.system", "kinotic");
1370
1931
  span.setAttribute("rpc.service", this.serviceIdentifier);
1371
1932
  span.setAttribute("rpc.method", methodIdentifier);
1372
1933
  return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(first()).toPromise().then(async (value) => {
@@ -1374,7 +1935,7 @@ class ServiceProxy {
1374
1935
  return value;
1375
1936
  }, async (ex) => {
1376
1937
  span.recordException(ex);
1377
- span.setStatus({ code: SpanStatusCode.ERROR });
1938
+ span.setStatus({ code: SpanStatusCode2.ERROR });
1378
1939
  span.end();
1379
1940
  throw ex;
1380
1941
  });
@@ -1390,7 +1951,7 @@ class ServiceProxy {
1390
1951
  eventFactoryToUse = eventFactory;
1391
1952
  }
1392
1953
  let eventBusToUse = this.serviceRegistry.eventBus;
1393
- const span = opentelemetry.trace.getActiveSpan();
1954
+ const span = opentelemetry2.trace.getActiveSpan();
1394
1955
  if (span) {
1395
1956
  span.setAttribute(ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1396
1957
  span.setAttribute(ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
@@ -1419,11 +1980,16 @@ class ServiceProxy {
1419
1980
  class KinoticSingleton {
1420
1981
  _eventBus;
1421
1982
  serviceRegistry;
1983
+ _session;
1422
1984
  zonePrefix = null;
1423
1985
  defaultZone = null;
1424
1986
  constructor() {
1425
1987
  this._eventBus = new EventBus;
1426
1988
  this.serviceRegistry = new ServiceRegistry(this._eventBus);
1989
+ this._session = new Session(this);
1990
+ }
1991
+ get session() {
1992
+ return this._session;
1427
1993
  }
1428
1994
  get eventBus() {
1429
1995
  return this._eventBus;
@@ -1431,11 +1997,15 @@ class KinoticSingleton {
1431
1997
  set eventBus(eventBus) {
1432
1998
  this._eventBus = eventBus;
1433
1999
  this.serviceRegistry.eventBus = eventBus;
2000
+ this._session.observe(eventBus);
1434
2001
  }
1435
- connect(options) {
1436
- return this._eventBus.connect(Util.resolveConnectOptions(options));
2002
+ async connect(options) {
2003
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
2004
+ await this.serviceRegistry.registerEntries();
2005
+ return ret;
1437
2006
  }
1438
2007
  disconnect(force) {
2008
+ this._session.release();
1439
2009
  return this._eventBus.disconnect(force);
1440
2010
  }
1441
2011
  serviceProxy(serviceIdentifier) {
@@ -1554,6 +2124,9 @@ class CrudServiceProxy {
1554
2124
  deleteById(id) {
1555
2125
  return this.serviceProxy.invoke("deleteById", [id]);
1556
2126
  }
2127
+ deleteByIdSync(id) {
2128
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
2129
+ }
1557
2130
  async findAll(pageable) {
1558
2131
  const page = await this.findAllSinglePage(pageable);
1559
2132
  return new FindAllIterablePage(pageable, page, this);
@@ -1644,15 +2217,15 @@ class CursorPageable extends Pageable {
1644
2217
  }
1645
2218
  // packages/core/src/api/crud/Sort.ts
1646
2219
  var Direction;
1647
- ((Direction2) => {
1648
- Direction2["ASC"] = "ASC";
1649
- Direction2["DESC"] = "DESC";
2220
+ ((Direction) => {
2221
+ Direction["ASC"] = "ASC";
2222
+ Direction["DESC"] = "DESC";
1650
2223
  })(Direction ||= {});
1651
2224
  var NullHandling;
1652
- ((NullHandling2) => {
1653
- NullHandling2["NATIVE"] = "NATIVE";
1654
- NullHandling2["NULLS_FIRST"] = "NULLS_FIRST";
1655
- NullHandling2["NULLS_LAST"] = "NULLS_LAST";
2225
+ ((NullHandling) => {
2226
+ NullHandling["NATIVE"] = "NATIVE";
2227
+ NullHandling["NULLS_FIRST"] = "NULLS_FIRST";
2228
+ NullHandling["NULLS_LAST"] = "NULLS_LAST";
1656
2229
  })(NullHandling ||= {});
1657
2230
 
1658
2231
  class Order {
@@ -1676,6 +2249,13 @@ class Order {
1676
2249
  class Sort {
1677
2250
  orders = [];
1678
2251
  }
2252
+ // packages/core/src/api/security/AuthorizationException.ts
2253
+ class AuthorizationException extends Error {
2254
+ constructor(message = "Access denied") {
2255
+ super(message);
2256
+ this.name = "AuthorizationException";
2257
+ }
2258
+ }
1679
2259
  // packages/core/src/api/security/ConnectedInfo.ts
1680
2260
  class ConnectedInfo {
1681
2261
  replyToId;
@@ -1690,46 +2270,53 @@ class ParticipantConstants {
1690
2270
  static CLI_PARTICIPANT_ID = "-42-Kinotic-CLI-42-";
1691
2271
  }
1692
2272
  export {
1693
- validateZone,
1694
- validateLabel,
1695
- receivesContext,
1696
- isAdvertised,
1697
- createCRI,
1698
- buildServerUrl,
1699
- buildBrokerUrl,
1700
- Zone,
1701
- Version,
1702
- TextEventFactory,
1703
- Sort,
1704
- SessionKeepAliveMode,
1705
- SessionCredentialsResolver,
1706
- ServiceRegistry,
1707
- ServerInfo,
1708
- Scope,
1709
- Publish,
1710
- ParticipantConstants,
1711
- Pageable,
1712
- Order,
1713
- OffsetPageable,
1714
- NullHandling,
1715
- KinoticSingleton,
1716
- Kinotic,
1717
- JsonEventFactory,
1718
- FunctionalIterablePage,
1719
- EventConstants,
1720
- EventBus,
1721
- Event,
1722
- EnvCredentialsResolver,
1723
- Direction,
1724
- DefaultCRI,
1725
- DataSourceUtils,
1726
- CursorPageable,
1727
- CrudServiceProxyFactory,
1728
- CrudServiceProxy,
1729
- Context,
1730
- ConnectedInfo,
1731
- ChainedCredentialsResolver,
1732
- BearerCredentialsResolver,
2273
+ AbstractIterablePage,
2274
+ AuthorizationException,
1733
2275
  BasicCredentialsResolver,
1734
- AbstractIterablePage
2276
+ BearerCredentialsResolver,
2277
+ ChainedCredentialsResolver,
2278
+ ConnectedInfo,
2279
+ Context,
2280
+ CrudServiceProxy,
2281
+ CrudServiceProxyFactory,
2282
+ CursorPageable,
2283
+ DataSourceUtils,
2284
+ DefaultCRI,
2285
+ Direction,
2286
+ EnvCredentialsResolver,
2287
+ Event,
2288
+ EventBus,
2289
+ EventConstants,
2290
+ FunctionalIterablePage,
2291
+ JsonEventFactory,
2292
+ Kinotic,
2293
+ KinoticSingleton,
2294
+ NullHandling,
2295
+ OffsetPageable,
2296
+ Order,
2297
+ Pageable,
2298
+ ParticipantConstants,
2299
+ Publish,
2300
+ RpcError,
2301
+ Scope,
2302
+ ScopeOptional,
2303
+ ServerInfo,
2304
+ ServiceIdentifier,
2305
+ ServiceRegistry,
2306
+ SessionCredentialsResolver,
2307
+ SessionEndType,
2308
+ SessionKeepAliveMode,
2309
+ Sort,
2310
+ TextEventFactory,
2311
+ Version,
2312
+ Zone,
2313
+ buildBrokerUrl,
2314
+ buildServerUrl,
2315
+ createCRI,
2316
+ declareServiceDefinitions,
2317
+ isAdvertised,
2318
+ receivesContext,
2319
+ scopeOptionalMethodNames,
2320
+ validateLabel,
2321
+ validateZone
1735
2322
  };