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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -19,13 +19,15 @@ var __toESM = (mod, isNodeMode, target) => {
19
19
  return cached;
20
20
  }
21
21
  target = mod != null ? __create(__getProtoOf(mod)) : {};
22
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
- for (let key of __getOwnPropNames(mod))
24
- if (!__hasOwnProp.call(to, key))
25
- __defProp(to, key, {
26
- get: __accessProp.bind(mod, key),
27
- enumerable: true
28
- });
22
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ if (mod && typeof mod === "object" || typeof mod === "function") {
24
+ for (let key of __getOwnPropNames(mod))
25
+ if (!__hasOwnProp.call(to, key))
26
+ __defProp(to, key, {
27
+ get: __accessProp.bind(mod, key),
28
+ enumerable: true
29
+ });
30
+ }
29
31
  if (canCache)
30
32
  cache.set(mod, to);
31
33
  return to;
@@ -64,48 +66,54 @@ var __export = (target, all) => {
64
66
  // packages/core/src/index.ts
65
67
  var exports_src = {};
66
68
  __export(exports_src, {
67
- validateZone: () => validateZone,
68
- validateLabel: () => validateLabel,
69
- receivesContext: () => receivesContext,
70
- isAdvertised: () => isAdvertised,
71
- createCRI: () => createCRI,
72
- buildServerUrl: () => buildServerUrl,
73
- buildBrokerUrl: () => buildBrokerUrl,
74
- Zone: () => Zone,
75
- Version: () => Version,
76
- TextEventFactory: () => TextEventFactory,
77
- Sort: () => Sort,
78
- SessionKeepAliveMode: () => SessionKeepAliveMode,
79
- SessionCredentialsResolver: () => SessionCredentialsResolver,
80
- ServiceRegistry: () => ServiceRegistry,
81
- ServerInfo: () => ServerInfo,
82
- Scope: () => Scope,
83
- Publish: () => Publish,
84
- ParticipantConstants: () => ParticipantConstants,
85
- Pageable: () => Pageable,
86
- Order: () => Order,
87
- OffsetPageable: () => OffsetPageable,
88
- NullHandling: () => NullHandling,
89
- KinoticSingleton: () => KinoticSingleton,
90
- Kinotic: () => Kinotic,
91
- JsonEventFactory: () => JsonEventFactory,
92
- FunctionalIterablePage: () => FunctionalIterablePage,
93
- EventConstants: () => EventConstants,
94
- EventBus: () => EventBus,
95
- Event: () => Event,
96
- EnvCredentialsResolver: () => EnvCredentialsResolver,
97
- Direction: () => Direction,
98
- DefaultCRI: () => DefaultCRI,
99
- DataSourceUtils: () => DataSourceUtils,
100
- CursorPageable: () => CursorPageable,
101
- CrudServiceProxyFactory: () => CrudServiceProxyFactory,
102
- CrudServiceProxy: () => CrudServiceProxy,
103
- Context: () => Context,
104
- ConnectedInfo: () => ConnectedInfo,
105
- ChainedCredentialsResolver: () => ChainedCredentialsResolver,
106
- BearerCredentialsResolver: () => BearerCredentialsResolver,
69
+ AbstractIterablePage: () => AbstractIterablePage,
70
+ AuthorizationException: () => AuthorizationException,
107
71
  BasicCredentialsResolver: () => BasicCredentialsResolver,
108
- AbstractIterablePage: () => AbstractIterablePage
72
+ BearerCredentialsResolver: () => BearerCredentialsResolver,
73
+ ChainedCredentialsResolver: () => ChainedCredentialsResolver,
74
+ ConnectedInfo: () => ConnectedInfo,
75
+ Context: () => Context,
76
+ CrudServiceProxy: () => CrudServiceProxy,
77
+ CrudServiceProxyFactory: () => CrudServiceProxyFactory,
78
+ CursorPageable: () => CursorPageable,
79
+ DataSourceUtils: () => DataSourceUtils,
80
+ DefaultCRI: () => DefaultCRI,
81
+ Direction: () => Direction,
82
+ EnvCredentialsResolver: () => EnvCredentialsResolver,
83
+ Event: () => Event,
84
+ EventBus: () => EventBus,
85
+ EventConstants: () => EventConstants,
86
+ FunctionalIterablePage: () => FunctionalIterablePage,
87
+ JsonEventFactory: () => JsonEventFactory,
88
+ Kinotic: () => Kinotic,
89
+ KinoticSingleton: () => KinoticSingleton,
90
+ NullHandling: () => NullHandling,
91
+ OffsetPageable: () => OffsetPageable,
92
+ Order: () => Order,
93
+ Pageable: () => Pageable,
94
+ ParticipantConstants: () => ParticipantConstants,
95
+ Publish: () => Publish,
96
+ RpcError: () => RpcError,
97
+ Scope: () => Scope,
98
+ ScopeOptional: () => ScopeOptional,
99
+ ServerInfo: () => ServerInfo,
100
+ ServiceIdentifier: () => ServiceIdentifier,
101
+ ServiceRegistry: () => ServiceRegistry,
102
+ SessionCredentialsResolver: () => SessionCredentialsResolver,
103
+ SessionKeepAliveMode: () => SessionKeepAliveMode,
104
+ Sort: () => Sort,
105
+ TextEventFactory: () => TextEventFactory,
106
+ Version: () => Version,
107
+ Zone: () => Zone,
108
+ buildBrokerUrl: () => buildBrokerUrl,
109
+ buildServerUrl: () => buildServerUrl,
110
+ createCRI: () => createCRI,
111
+ declareServiceDefinitions: () => declareServiceDefinitions,
112
+ isAdvertised: () => isAdvertised,
113
+ receivesContext: () => receivesContext,
114
+ scopeOptionalMethodNames: () => scopeOptionalMethodNames,
115
+ validateLabel: () => validateLabel,
116
+ validateZone: () => validateZone
109
117
  });
110
118
  module.exports = __toCommonJS(exports_src);
111
119
 
@@ -116,103 +124,196 @@ class ServerInfo {
116
124
  useSSL;
117
125
  }
118
126
  function buildServerUrl(server, scheme) {
119
- return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
127
+ const host = server.host.includes(":") && !server.host.startsWith("[") ? "[" + server.host + "]" : server.host;
128
+ return scheme + (server.useSSL ? "s" : "") + "://" + host + (server.port ? ":" + server.port : "");
120
129
  }
121
130
  function buildBrokerUrl(server) {
122
- return buildServerUrl(server, "ws") + "/v1";
131
+ return buildServerUrl(server, "ws") + "/api/v1";
123
132
  }
124
133
  var SessionKeepAliveMode;
125
- ((SessionKeepAliveMode2) => {
126
- SessionKeepAliveMode2["NONE"] = "NONE";
127
- SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
128
- SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
134
+ ((SessionKeepAliveMode) => {
135
+ SessionKeepAliveMode["NONE"] = "NONE";
136
+ SessionKeepAliveMode["ACTIVITY"] = "ACTIVITY";
137
+ SessionKeepAliveMode["CONNECTION"] = "CONNECTION";
129
138
  })(SessionKeepAliveMode ||= {});
130
139
  // packages/core/src/api/event/IEventBus.ts
131
140
  var EventConstants;
132
- ((EventConstants2) => {
133
- EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
134
- EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
135
- EventConstants2["REPLY_TO_HEADER"] = "reply-to";
136
- EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
137
- EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
138
- EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
139
- EventConstants2["ORIGIN_CRI_HEADER"] = "__origin-cri";
140
- EventConstants2["ERROR_HEADER"] = "error";
141
- EventConstants2["COMPLETE_HEADER"] = "complete";
142
- EventConstants2["CONTROL_HEADER"] = "control";
143
- EventConstants2["CONTROL_VALUE_COMPLETE"] = "complete";
144
- EventConstants2["CONTROL_VALUE_CANCEL"] = "cancel";
145
- EventConstants2["CONTROL_VALUE_SUSPEND"] = "suspend";
146
- EventConstants2["CONTROL_VALUE_RESUME"] = "resume";
147
- EventConstants2["SERVICE_DESTINATION_PREFIX"] = "srv://";
148
- EventConstants2["SERVICE_DESTINATION_SCHEME"] = "srv";
149
- EventConstants2["STREAM_DESTINATION_PREFIX"] = "stream://";
150
- EventConstants2["STREAM_DESTINATION_SCHEME"] = "stream";
151
- EventConstants2["REPLY_DESTINATION_PREFIX"] = "reply://";
152
- EventConstants2["REPLY_DESTINATION_SCHEME"] = "reply";
153
- EventConstants2["CONTENT_JSON"] = "application/json";
154
- EventConstants2["CONTENT_TEXT"] = "text/plain";
155
- EventConstants2["CONTENT_OCTET_STREAM"] = "application/octet-stream";
156
- EventConstants2["TRACEPARENT_HEADER"] = "traceparent";
157
- EventConstants2["TRACESTATE_HEADER"] = "tracestate";
141
+ ((EventConstants) => {
142
+ EventConstants["CONTENT_TYPE_HEADER"] = "content-type";
143
+ EventConstants["CONTENT_LENGTH_HEADER"] = "content-length";
144
+ EventConstants["REPLY_TO_HEADER"] = "reply-to";
145
+ EventConstants["SENDER_HEADER"] = "sender";
146
+ EventConstants["CONNECTED_INFO_HEADER"] = "connected-info";
147
+ EventConstants["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
148
+ EventConstants["CORRELATION_ID_HEADER"] = "__correlation-id";
149
+ EventConstants["ORIGIN_CRI_HEADER"] = "__origin-cri";
150
+ EventConstants["ERROR_HEADER"] = "error";
151
+ EventConstants["COMPLETE_HEADER"] = "complete";
152
+ EventConstants["CONTROL_HEADER"] = "control";
153
+ EventConstants["CONTROL_VALUE_COMPLETE"] = "complete";
154
+ EventConstants["CONTROL_VALUE_CANCEL"] = "cancel";
155
+ EventConstants["CONTROL_VALUE_SUSPEND"] = "suspend";
156
+ EventConstants["CONTROL_VALUE_RESUME"] = "resume";
157
+ EventConstants["SERVICE_DESTINATION_PREFIX"] = "srv://";
158
+ EventConstants["SERVICE_DESTINATION_SCHEME"] = "srv";
159
+ EventConstants["STREAM_DESTINATION_PREFIX"] = "stream://";
160
+ EventConstants["STREAM_DESTINATION_SCHEME"] = "stream";
161
+ EventConstants["REPLY_DESTINATION_PREFIX"] = "reply://";
162
+ EventConstants["REPLY_DESTINATION_SCHEME"] = "reply";
163
+ EventConstants["CONTENT_JSON"] = "application/json";
164
+ EventConstants["CONTENT_TEXT"] = "text/plain";
165
+ EventConstants["CONTENT_OCTET_STREAM"] = "application/octet-stream";
166
+ EventConstants["TRACEPARENT_HEADER"] = "traceparent";
167
+ EventConstants["TRACESTATE_HEADER"] = "tracestate";
158
168
  })(EventConstants ||= {});
159
169
 
170
+ // packages/core/src/internal/api/Logger.ts
171
+ var import_debug = __toESM(require("debug"), 1);
172
+ function createDebugLogger(namespace) {
173
+ const debugLogger = import_debug.default(namespace);
174
+ return {
175
+ trace: (...args) => debugLogger("TRACE", ...args),
176
+ debug: (...args) => debugLogger("DEBUG", ...args),
177
+ info: (...args) => debugLogger("INFO", ...args),
178
+ warn: (...args) => debugLogger("WARN", ...args),
179
+ error: (...args) => debugLogger("ERROR", ...args)
180
+ };
181
+ }
182
+
160
183
  // packages/core/src/internal/api/StompConnectionManager.ts
161
184
  var import_rx_stomp = require("@stomp/rx-stomp");
162
185
  var import_stompjs = require("@stomp/stompjs");
163
- var import_debug = __toESM(require("debug"));
186
+ var import_debug2 = __toESM(require("debug"), 1);
164
187
  var import_rxjs = require("rxjs");
188
+ var import_operators = require("rxjs/operators");
165
189
  var import_uuid = require("uuid");
190
+
191
+ // packages/core/src/internal/api/StompActivation.ts
192
+ class StompActivation {
193
+ _ended = false;
194
+ wake = null;
195
+ preparedSocket = null;
196
+ attempt = null;
197
+ failPending = null;
198
+ abortController = new AbortController;
199
+ subscriptions = [];
200
+ get ended() {
201
+ return this._ended;
202
+ }
203
+ get signal() {
204
+ return this.abortController.signal;
205
+ }
206
+ end() {
207
+ this._ended = true;
208
+ this.wake?.();
209
+ this.wake = null;
210
+ this.abortController.abort();
211
+ }
212
+ delay(ms) {
213
+ return new Promise((resolve) => {
214
+ const timer = setTimeout(() => {
215
+ this.wake = null;
216
+ resolve();
217
+ }, ms);
218
+ this.wake = () => {
219
+ clearTimeout(timer);
220
+ resolve();
221
+ };
222
+ });
223
+ }
224
+ own(subscription) {
225
+ this.subscriptions.push(subscription);
226
+ }
227
+ pending(fail) {
228
+ this.failPending = fail;
229
+ }
230
+ established() {
231
+ this.failPending = null;
232
+ }
233
+ failIfPending(reason) {
234
+ const fail = this.failPending;
235
+ this.failPending = null;
236
+ fail?.(reason);
237
+ }
238
+ unsubscribeAll() {
239
+ for (const subscription of this.subscriptions) {
240
+ subscription.unsubscribe();
241
+ }
242
+ this.subscriptions.length = 0;
243
+ }
244
+ }
245
+
246
+ // packages/core/src/internal/api/StompConnectionManager.ts
166
247
  var SESSION_CHECK_PATH = "/api/auth/me";
167
248
 
168
249
  class StompConnectionManager {
169
250
  lastWebsocketError = null;
170
251
  maxConnectionAttemptsReached = false;
171
- replyToCriChangedHandler = null;
172
- rxStomp = null;
252
+ connectionEndedHandler = null;
253
+ rxStomp = new import_rx_stomp.RxStomp;
254
+ activation = null;
255
+ teardown = null;
173
256
  INITIAL_RECONNECT_DELAY = 2000;
174
257
  JITTER_MAX = 5000;
175
258
  MAX_RECONNECT_DELAY = 120000;
259
+ CONNECTION_TIMEOUT = 1e4;
176
260
  connectionAttempts = 0;
177
- debugLogger = import_debug.default("kinoitc:stomp");
178
- fatalErrorsSubject = new import_rxjs.Subject;
179
- _fatalErrors = this.fatalErrorsSubject.asObservable();
261
+ debugLogger = import_debug2.default("kinotic:stomp");
262
+ connectionEstablishedSubject = new import_rxjs.Subject;
263
+ connectionAttemptFailedSubject = new import_rxjs.Subject;
180
264
  initialConnectionSuccessful = false;
181
- serverHeadersSubscription = null;
182
- stompErrorsSubscription = null;
183
- uuidv4 = import_uuid.v4();
265
+ rxStompHasConnected = false;
184
266
  _replyToCri = null;
185
267
  get replyToCri() {
186
268
  return this._replyToCri;
187
269
  }
188
270
  get active() {
189
- return !!this.rxStomp;
271
+ return this.activation !== null;
190
272
  }
191
273
  get connected() {
192
- return this.rxStomp != null && this.rxStomp.connected();
274
+ return this.activation !== null && this.rxStomp.connected();
275
+ }
276
+ get connectionEstablished() {
277
+ return this.connectionEstablishedSubject.asObservable();
193
278
  }
194
- get fatalErrors() {
195
- return this._fatalErrors;
279
+ get connectionAttemptFailed() {
280
+ return this.connectionAttemptFailedSubject.asObservable();
196
281
  }
197
282
  async activate(options) {
198
283
  if (!options?.server?.host) {
199
284
  throw new Error("No host provided");
200
285
  }
201
- if (this.rxStomp) {
286
+ if (this.activation) {
287
+ throw new Error("Stomp connection already active");
288
+ }
289
+ await this.teardown;
290
+ if (this.activation) {
202
291
  throw new Error("Stomp connection already active");
203
292
  }
204
293
  const server = options.server;
205
294
  const credentialsResolver = options.credentials;
295
+ const activation = new StompActivation;
296
+ this.activation = activation;
206
297
  let headerAuth = false;
207
- if (!options.webSocketFactory) {
208
- if (!credentialsResolver) {
209
- throw new Error("No credentials supplied and no default resolution applied");
298
+ try {
299
+ if (!options.webSocketFactory) {
300
+ if (!credentialsResolver) {
301
+ throw new Error("No credentials supplied and no default resolution applied");
302
+ }
303
+ const resolved = await credentialsResolver.resolve(server);
304
+ if (resolved === null) {
305
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
306
+ }
307
+ headerAuth = resolved.authHeaders != null;
210
308
  }
211
- const resolved = await credentialsResolver.resolve(server);
212
- if (resolved === null) {
213
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
309
+ if (activation.ended) {
310
+ throw new Error("Deactivated before the connection was established");
214
311
  }
215
- headerAuth = resolved.authHeaders != null;
312
+ } catch (e) {
313
+ if (this.activation === activation) {
314
+ this.activation = null;
315
+ }
316
+ throw e;
216
317
  }
217
318
  return new Promise((resolve, reject) => {
218
319
  this.connectionAttempts = 0;
@@ -220,63 +321,29 @@ class StompConnectionManager {
220
321
  this.lastWebsocketError = null;
221
322
  this.maxConnectionAttemptsReached = false;
222
323
  const url = buildBrokerUrl(server);
223
- this.rxStomp = new import_rx_stomp.RxStomp;
224
- let preparedSocket = null;
225
- const userWebSocketFactory = options.webSocketFactory;
226
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
324
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
325
+ const takePreparedSocket = () => {
326
+ const socket = activation.preparedSocket;
327
+ activation.preparedSocket = null;
328
+ return socket;
329
+ };
227
330
  const stompConfig = {
228
331
  brokerURL: url,
229
332
  connectHeaders: {
230
333
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
231
334
  },
232
- heartbeatIncoming: 120000,
335
+ heartbeatIncoming: 30000,
233
336
  heartbeatOutgoing: 30000,
337
+ connectionTimeout: this.CONNECTION_TIMEOUT,
234
338
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
235
339
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
236
340
  reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
237
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
238
- beforeConnect: async () => {
239
- if (!usesPreparedSocket) {
240
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
241
- try {
242
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
243
- if (res.status === 401) {
244
- await this.signalFatal(new Error("Authentication required"));
245
- return;
246
- }
247
- } catch {}
248
- }
249
- if (options?.maxConnectionAttempts) {
250
- this.connectionAttempts++;
251
- if (this.connectionAttempts > options.maxConnectionAttempts) {
252
- this.maxConnectionAttemptsReached = true;
253
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
254
- return;
255
- } else {
256
- await this.connectionJitterDelay();
257
- }
258
- } else {
259
- await this.connectionJitterDelay();
260
- }
261
- if (userWebSocketFactory) {
262
- try {
263
- preparedSocket = await userWebSocketFactory();
264
- } catch (e) {
265
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
266
- }
267
- } else if (headerAuth) {
268
- try {
269
- const resolved = await credentialsResolver.resolve(server);
270
- if (resolved?.authHeaders == null) {
271
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
272
- } else {
273
- const WS = WebSocket;
274
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
275
- }
276
- } catch (e) {
277
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
278
- }
279
- }
341
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
342
+ beforeConnect: () => {
343
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
344
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
345
+ activation.attempt = attempt.then(settled, settled);
346
+ return attempt;
280
347
  }
281
348
  };
282
349
  if (this.debugLogger.enabled) {
@@ -285,93 +352,209 @@ class StompConnectionManager {
285
352
  };
286
353
  }
287
354
  this.rxStomp.configure(stompConfig);
288
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
355
+ activation.own(this.rxStomp.webSocketErrors$.subscribe((value) => {
289
356
  this.lastWebsocketError = value;
290
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
291
- this.maxConnectionAttemptsReached = true;
292
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
293
- }
294
- });
295
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
357
+ }));
358
+ activation.own(this.rxStomp.stompErrors$.subscribe((frame) => {
296
359
  const stompError = new Error(frame.headers["message"], { cause: frame });
297
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
298
- });
299
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
300
- connectedSubscription.unsubscribe();
301
- initialFailureSubscription.unsubscribe();
302
- if (!this.initialConnectionSuccessful) {
303
- this.initialConnectionSuccessful = true;
304
- }
305
- });
306
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
307
- connectedSubscription.unsubscribe();
308
- initialFailureSubscription.unsubscribe();
309
- reject(err.message);
310
- });
311
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
360
+ this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
361
+ }));
362
+ activation.own(this.rxStomp.connected$.subscribe(() => {
363
+ activation.established();
364
+ this.initialConnectionSuccessful = true;
365
+ this.connectionAttempts = 0;
366
+ }));
367
+ activation.pending(reject);
368
+ activation.own(this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe((value) => {
369
+ this.rxStompHasConnected = true;
312
370
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
313
371
  if (connectedInfoJson == null) {
314
372
  if (!this.initialConnectionSuccessful) {
315
- await this.deactivate();
316
- reject("Server did not return proper data for successful login");
373
+ this.failConnection(activation, new Error("Server did not return proper data for successful login"));
317
374
  }
318
375
  return;
319
376
  }
320
377
  const connectedInfo = JSON.parse(connectedInfoJson);
321
378
  if (connectedInfo.replyToId == null) {
322
379
  if (!this.initialConnectionSuccessful) {
323
- await this.deactivate();
324
- reject("Server did not return a replyToId for successful login");
380
+ this.failConnection(activation, new Error("Server did not return a replyToId for successful login"));
325
381
  }
326
382
  return;
327
383
  }
328
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
384
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + import_uuid.v4() + "@kinotic.js.EventBus/replyHandler";
385
+ this._replyToCri = newReplyToCri;
329
386
  if (!this.initialConnectionSuccessful) {
330
- this._replyToCri = newReplyToCri;
331
387
  resolve(connectedInfo);
332
- } else if (this._replyToCri !== newReplyToCri) {
333
- this._replyToCri = newReplyToCri;
334
- this.replyToCriChangedHandler?.(newReplyToCri);
335
388
  }
336
- });
389
+ this.connectionEstablishedSubject.next(connectedInfo);
390
+ }));
391
+ let previousState = this.rxStomp.connectionState$.getValue();
392
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
393
+ if (state === import_rx_stomp.RxStompState.CLOSED && this.activation === activation) {
394
+ if (previousState === import_rx_stomp.RxStompState.OPEN) {
395
+ this.connectionEndedHandler?.(null);
396
+ } else if (previousState === import_rx_stomp.RxStompState.CONNECTING) {
397
+ if (options.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
398
+ this.maxConnectionAttemptsReached = true;
399
+ this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
400
+ } else {
401
+ this.connectionAttemptFailedSubject.next();
402
+ }
403
+ }
404
+ }
405
+ previousState = state;
406
+ }));
337
407
  this.rxStomp.activate();
338
408
  });
339
409
  }
340
- async deactivate(force) {
341
- const rxStomp = this.rxStomp;
342
- if (rxStomp) {
343
- await rxStomp.deactivate({ force });
344
- if (this.rxStomp === rxStomp) {
345
- this.serverHeadersSubscription?.unsubscribe();
346
- this.serverHeadersSubscription = null;
347
- this.stompErrorsSubscription?.unsubscribe();
348
- this.stompErrorsSubscription = null;
349
- this.rxStomp = null;
350
- this._replyToCri = null;
410
+ async prepareAttempt(activation, options, server, headerAuth) {
411
+ const credentialsResolver = options.credentials;
412
+ const userWebSocketFactory = options.webSocketFactory;
413
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
414
+ const url = buildBrokerUrl(server);
415
+ if (!usesPreparedSocket) {
416
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
417
+ try {
418
+ const res = await fetch(sessionCheckUrl, {
419
+ credentials: "include",
420
+ signal: AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)])
421
+ });
422
+ if (res.status === 401) {
423
+ this.failConnection(activation, new Error("Authentication required"));
424
+ return;
425
+ }
426
+ } catch (e) {
427
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
428
+ }
429
+ }
430
+ if (options?.maxConnectionAttempts) {
431
+ this.connectionAttempts++;
432
+ }
433
+ await this.connectionJitterDelay(activation);
434
+ if (activation.ended) {
435
+ return;
436
+ }
437
+ if (userWebSocketFactory) {
438
+ try {
439
+ activation.preparedSocket = await userWebSocketFactory();
440
+ } catch (e) {
441
+ this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
442
+ }
443
+ } else if (headerAuth) {
444
+ try {
445
+ const resolved = await credentialsResolver.resolve(server);
446
+ if (resolved?.authHeaders == null) {
447
+ this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
448
+ } else {
449
+ const WS = WebSocket;
450
+ const socket = new WS(url, { headers: resolved.authHeaders });
451
+ this.endOnRejectedUpgrade(activation, socket);
452
+ activation.preparedSocket = socket;
453
+ }
454
+ } catch (e) {
455
+ this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
456
+ }
457
+ }
458
+ if (activation.ended && activation.preparedSocket) {
459
+ activation.preparedSocket.close();
460
+ activation.preparedSocket = null;
461
+ }
462
+ }
463
+ endOnRejectedUpgrade(activation, socket) {
464
+ const emitter = socket;
465
+ if (typeof emitter.on === "function") {
466
+ emitter.on("unexpected-response", (_request, response) => {
467
+ const status = response.statusCode ?? 0;
468
+ if (status >= 400 && status < 500) {
469
+ this.failConnection(activation, new Error("Connection rejected with status " + status));
470
+ }
471
+ socket.close();
472
+ });
473
+ }
474
+ }
475
+ deactivate(force, reason = null) {
476
+ const activation = this.activation;
477
+ let ret;
478
+ if (activation) {
479
+ this.activation = null;
480
+ activation.end();
481
+ const wasOpen = this.rxStomp.connected();
482
+ this._replyToCri = null;
483
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
484
+ activation.preparedSocket?.close();
485
+ activation.preparedSocket = null;
486
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
487
+ activation.unsubscribeAll();
488
+ this.teardown = null;
489
+ });
490
+ this.teardown = teardown;
491
+ if (wasOpen || reason !== null) {
492
+ this.connectionEndedHandler?.(reason);
351
493
  }
494
+ ret = teardown;
495
+ } else {
496
+ ret = this.teardown ?? Promise.resolve();
352
497
  }
353
- return;
498
+ return ret;
354
499
  }
355
- async connectionJitterDelay() {
500
+ async connectionJitterDelay(activation) {
356
501
  if (this.initialConnectionSuccessful) {
357
502
  const randomJitter = Math.random() * this.JITTER_MAX;
358
503
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
359
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
504
+ await activation.delay(randomJitter);
360
505
  }
361
506
  }
362
- async signalFatal(err) {
363
- this.debugLogger("Fatal error, deactivating connection: %O", err);
364
- await this.deactivate();
365
- this.fatalErrorsSubject.next(err);
507
+ failConnection(activation, err) {
508
+ if (!activation.ended) {
509
+ this.debugLogger("Connection failed, ending it: %O", err);
510
+ this.deactivate(undefined, err).catch((e) => this.debugLogger("Closing the failed connection failed: %O", e));
511
+ }
366
512
  }
367
513
  }
368
514
 
369
515
  // packages/core/src/api/event/EventBus.ts
370
516
  var import_api = require("@opentelemetry/api");
371
517
  var import_rxjs2 = require("rxjs");
372
- var import_operators = require("rxjs/operators");
518
+ var import_operators2 = require("rxjs/operators");
373
519
  var import_typescript_optional = require("typescript-optional");
374
520
  var import_uuid2 = require("uuid");
521
+
522
+ // packages/core/src/api/event/RpcError.ts
523
+ class RpcError extends Error {
524
+ exceptionName;
525
+ exceptionClass;
526
+ constructor(message, exceptionName, exceptionClass) {
527
+ super(message);
528
+ this.name = "RpcError";
529
+ this.exceptionName = exceptionName;
530
+ this.exceptionClass = exceptionClass;
531
+ }
532
+ static fromEvent(reply) {
533
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
534
+ let ret;
535
+ const detail = describedException(reply);
536
+ if (detail !== undefined) {
537
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
538
+ } else {
539
+ ret = new RpcError(message, "", "");
540
+ }
541
+ return ret;
542
+ }
543
+ }
544
+ function describedException(reply) {
545
+ let ret = undefined;
546
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
547
+ try {
548
+ const parsed = JSON.parse(reply.getDataString());
549
+ if (parsed !== null && typeof parsed === "object") {
550
+ ret = parsed;
551
+ }
552
+ } catch {}
553
+ }
554
+ return ret;
555
+ }
556
+
557
+ // packages/core/src/api/event/EventBus.ts
375
558
  class Event {
376
559
  cri;
377
560
  headers;
@@ -410,24 +593,34 @@ class Event {
410
593
 
411
594
  class EventBus {
412
595
  serverInfo = null;
596
+ log = createDebugLogger("kinotic:EventBus");
413
597
  stompConnectionManager = new StompConnectionManager;
414
598
  connectionLifecycle = Promise.resolve();
415
- replyToCri = null;
599
+ disconnectRequests = 0;
416
600
  requestRepliesObservable = null;
417
601
  requestRepliesSubject = null;
418
602
  requestRepliesSubscription = null;
419
603
  activeCorrelationIds = new Set;
420
604
  recentlyReaped = new Set;
605
+ connectionEndedSubject = new import_rxjs2.Subject;
421
606
  static REAP_DEBOUNCE_MS = 5000;
422
607
  constructor() {
423
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
424
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
425
- this.replyToCri = replyToCri;
426
- this.resetRequestReplies("Reply destination changed");
608
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
609
+ this.resetRequestReplies("Connection lost");
610
+ if (!this.stompConnectionManager.active) {
611
+ this.serverInfo = null;
612
+ }
613
+ this.connectionEndedSubject.next(reason);
427
614
  };
428
615
  }
429
- get fatalErrors() {
430
- return this.stompConnectionManager.fatalErrors;
616
+ get connectionEnded() {
617
+ return this.connectionEndedSubject.asObservable();
618
+ }
619
+ get connectionEstablished() {
620
+ return this.stompConnectionManager.connectionEstablished;
621
+ }
622
+ get connectionAttemptFailed() {
623
+ return this.stompConnectionManager.connectionAttemptFailed;
431
624
  }
432
625
  isConnectionActive() {
433
626
  return this.stompConnectionManager.active;
@@ -436,12 +629,14 @@ class EventBus {
436
629
  return this.stompConnectionManager.connected;
437
630
  }
438
631
  connect(options) {
632
+ const disconnectsWhenQueued = this.disconnectRequests;
439
633
  return this.serializeLifecycle(async () => {
634
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
635
+ throw new Error("Disconnected before the connection was started");
636
+ }
440
637
  if (!this.stompConnectionManager.active) {
441
- this.cleanup();
442
638
  const connectedInfo = await this.stompConnectionManager.activate(options);
443
639
  this.serverInfo = { ...options.server };
444
- this.replyToCri = this.stompConnectionManager.replyToCri;
445
640
  return connectedInfo;
446
641
  } else {
447
642
  throw new Error("Event Bus connection already active");
@@ -449,9 +644,12 @@ class EventBus {
449
644
  });
450
645
  }
451
646
  disconnect(force) {
647
+ this.disconnectRequests++;
648
+ const deactivated = this.stompConnectionManager.deactivate(force);
452
649
  return this.serializeLifecycle(async () => {
650
+ await deactivated;
453
651
  await this.stompConnectionManager.deactivate(force);
454
- this.cleanup();
652
+ this.serverInfo = null;
455
653
  });
456
654
  }
457
655
  serializeLifecycle(operation) {
@@ -460,7 +658,7 @@ class EventBus {
460
658
  return result;
461
659
  }
462
660
  send(event) {
463
- if (this.stompConnectionManager.rxStomp) {
661
+ if (this.stompConnectionManager.connected) {
464
662
  const headers = {};
465
663
  for (const [key, value] of event.headers.entries()) {
466
664
  headers[key] = value;
@@ -476,7 +674,8 @@ class EventBus {
476
674
  this.stompConnectionManager.rxStomp.publish({
477
675
  destination: event.cri,
478
676
  headers,
479
- binaryBody: event.data.orUndefined()
677
+ binaryBody: event.data.orUndefined(),
678
+ retryIfDisconnected: false
480
679
  });
481
680
  } else {
482
681
  throw this.createSendUnavailableError();
@@ -486,58 +685,65 @@ class EventBus {
486
685
  return import_rxjs2.firstValueFrom(this.requestStream(event, false));
487
686
  }
488
687
  requestStream(event, sendControlEvents = true) {
489
- if (this.stompConnectionManager?.rxStomp) {
490
- return new import_rxjs2.Observable((subscriber) => {
491
- if (this.requestRepliesObservable == null) {
492
- this.requestRepliesSubject = new import_rxjs2.Subject;
493
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(import_operators.tap((value) => this.cancelIfUnexpected(value)), import_operators.multicast(this.requestRepliesSubject));
494
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
495
- }
496
- let serverSignaledCompletion = false;
497
- const correlationId = import_uuid2.v4();
498
- this.activeCorrelationIds.add(correlationId);
499
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators.filter((value) => {
500
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
501
- })).subscribe({
502
- next(value) {
503
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
504
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
505
- serverSignaledCompletion = true;
506
- subscriber.complete();
507
- } else {
508
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
509
- }
510
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
688
+ return new import_rxjs2.Observable((subscriber) => {
689
+ const replyToCri = this.stompConnectionManager.replyToCri;
690
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
691
+ subscriber.error(this.createSendUnavailableError());
692
+ return;
693
+ }
694
+ if (this.requestRepliesObservable == null) {
695
+ this.requestRepliesSubject = new import_rxjs2.Subject;
696
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
697
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
698
+ }
699
+ let serverSignaledCompletion = false;
700
+ let replyDestinationReset = false;
701
+ const correlationId = import_uuid2.v4();
702
+ this.activeCorrelationIds.add(correlationId);
703
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
704
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
705
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
706
+ })).subscribe({
707
+ next(value) {
708
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
709
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
511
710
  serverSignaledCompletion = true;
512
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
711
+ if (value.data.isPresent() || !sendControlEvents) {
712
+ subscriber.next(value);
713
+ }
714
+ subscriber.complete();
513
715
  } else {
514
- subscriber.next(value);
716
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
515
717
  }
516
- },
517
- error(err) {
518
- subscriber.error(err);
519
- },
520
- complete() {
521
- subscriber.complete();
718
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
719
+ serverSignaledCompletion = true;
720
+ subscriber.error(RpcError.fromEvent(value));
721
+ } else {
722
+ subscriber.next(value);
522
723
  }
523
- });
524
- subscriber.add(defaultMessagesSubscription);
525
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
526
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
527
- this.send(event);
528
- return () => {
529
- this.activeCorrelationIds.delete(correlationId);
530
- if (sendControlEvents && !serverSignaledCompletion) {
531
- const controlEvent = new Event(event.cri);
532
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
533
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
534
- this.send(controlEvent);
724
+ },
725
+ error(err) {
726
+ replyDestinationReset = true;
727
+ subscriber.error(err);
728
+ },
729
+ complete() {
730
+ subscriber.complete();
731
+ }
732
+ });
733
+ subscriber.add(defaultMessagesSubscription);
734
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
735
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
736
+ this.send(event);
737
+ subscriber.add(() => {
738
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
739
+ try {
740
+ this.sendCancel(event.cri, correlationId);
741
+ } catch (e) {
742
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
535
743
  }
536
- };
744
+ }
537
745
  });
538
- } else {
539
- return import_rxjs2.throwError(() => this.createSendUnavailableError());
540
- }
746
+ });
541
747
  }
542
748
  listen(_serverInfo) {
543
749
  return Promise.reject("Not implemented");
@@ -545,10 +751,6 @@ class EventBus {
545
751
  observe(cri) {
546
752
  return this._observe(cri);
547
753
  }
548
- cleanup() {
549
- this.resetRequestReplies("Connection disconnected");
550
- this.serverInfo = null;
551
- }
552
754
  cancelIfUnexpected(value) {
553
755
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
554
756
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -559,13 +761,19 @@ class EventBus {
559
761
  return;
560
762
  }
561
763
  try {
562
- const cancelEvent = new Event(originCri);
563
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
564
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
565
- this.send(cancelEvent);
764
+ this.sendCancel(originCri, correlationId);
566
765
  this.recentlyReaped.add(correlationId);
567
766
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
568
- } catch {}
767
+ } catch (e) {
768
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
769
+ }
770
+ }
771
+ sendCancel(cri, correlationId) {
772
+ const cancelEvent = new Event(cri);
773
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
774
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
775
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
776
+ this.send(cancelEvent);
569
777
  }
570
778
  resetRequestReplies(reason) {
571
779
  if (this.requestRepliesSubject != null) {
@@ -580,29 +788,29 @@ class EventBus {
580
788
  }
581
789
  }
582
790
  createSendUnavailableError() {
583
- let ret = "You must call connect on the event bus before sending any request";
791
+ let ret;
584
792
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
585
793
  ret = "Max connection attempts reached event bus is not available";
794
+ } else if (this.stompConnectionManager.active) {
795
+ ret = "The event bus is not connected to the server";
796
+ } else {
797
+ ret = "You must call connect on the event bus before sending any request";
586
798
  }
587
799
  return new Error(ret);
588
800
  }
589
801
  _observe(cri) {
590
- if (this.stompConnectionManager?.rxStomp) {
591
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators.map((message) => {
592
- const headers = new Map;
593
- let destination = "";
594
- for (const prop of Object.keys(message.headers)) {
595
- if (prop === "destination") {
596
- destination = message.headers[prop];
597
- } else {
598
- headers.set(prop, message.headers[prop]);
599
- }
802
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators2.map((message) => {
803
+ const headers = new Map;
804
+ let destination = "";
805
+ for (const prop of Object.keys(message.headers)) {
806
+ if (prop === "destination") {
807
+ destination = message.headers[prop];
808
+ } else {
809
+ headers.set(prop, message.headers[prop]);
600
810
  }
601
- return new Event(destination, headers, message.binaryBody);
602
- }));
603
- } else {
604
- throw this.createSendUnavailableError();
605
- }
811
+ }
812
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
813
+ }));
606
814
  }
607
815
  }
608
816
 
@@ -680,7 +888,8 @@ class SessionCredentialsResolver {
680
888
 
681
889
  // packages/core/src/internal/api/Util.ts
682
890
  var DEFAULT_PORT = 58503;
683
- var DEFAULT_HOST = "api.kinotic.com";
891
+ var DEFAULT_HOST = "api.kinotic.ai";
892
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
684
893
 
685
894
  class Util {
686
895
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -711,7 +920,6 @@ class Util {
711
920
  const location = typeof window !== "undefined" ? window.location : undefined;
712
921
  let host = server.host ?? env?.KINOTIC_SERVER_HOST;
713
922
  const hostFromLocation = host == null && location != null;
714
- const hostDefaulted = host == null && location == null;
715
923
  if (host == null) {
716
924
  host = location?.hostname ?? DEFAULT_HOST;
717
925
  }
@@ -722,7 +930,7 @@ class Util {
722
930
  } else if (hostFromLocation) {
723
931
  useSSL = location.protocol === "https:";
724
932
  } else {
725
- useSSL = hostDefaulted;
933
+ useSSL = !LOOPBACK_HOSTS.includes(host.toLowerCase());
726
934
  }
727
935
  }
728
936
  let port = server.port;
@@ -745,7 +953,7 @@ class Util {
745
953
  }
746
954
 
747
955
  // packages/core/src/api/ServiceRegistry.ts
748
- var import_debug3 = __toESM(require("debug"));
956
+ var import_debug3 = __toESM(require("debug"), 1);
749
957
 
750
958
  // packages/core/src/api/event/DefaultCRI.ts
751
959
  var ZONE_DELIMITER = "~";
@@ -933,22 +1141,14 @@ class JsonArgumentResolver {
933
1141
  // packages/core/src/internal/api/ReturnValueConverter.ts
934
1142
  class BasicReturnValueConverter {
935
1143
  convert(incomingMetadata, returnValue) {
936
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
1144
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
1145
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
937
1146
  }
938
1147
  }
939
1148
 
940
- // packages/core/src/internal/api/Logger.ts
941
- var import_debug2 = __toESM(require("debug"));
942
- function createDebugLogger(namespace) {
943
- const debugLogger = import_debug2.default(namespace);
944
- return {
945
- trace: (...args) => debugLogger("TRACE", ...args),
946
- debug: (...args) => debugLogger("DEBUG", ...args),
947
- info: (...args) => debugLogger("INFO", ...args),
948
- warn: (...args) => debugLogger("WARN", ...args),
949
- error: (...args) => debugLogger("ERROR", ...args)
950
- };
951
- }
1149
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1150
+ var import_rxjs3 = require("rxjs");
1151
+ var import_operators3 = require("rxjs/operators");
952
1152
 
953
1153
  // packages/core/src/api/ServiceIdentifier.ts
954
1154
  class ServiceIdentifier {
@@ -985,6 +1185,9 @@ class ServiceIdentifier {
985
1185
  }
986
1186
  return this._cri;
987
1187
  }
1188
+ unscopedCri() {
1189
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1190
+ }
988
1191
  }
989
1192
 
990
1193
  // packages/core/src/api/ZoneUtil.ts
@@ -1004,6 +1207,7 @@ function validateLabel(label) {
1004
1207
 
1005
1208
  // packages/core/src/api/KinoticDecorators.ts
1006
1209
  var scopeFunctions = new WeakSet;
1210
+ var scopeOptionalFunctions = new WeakSet;
1007
1211
  var versionRegistry = new WeakMap;
1008
1212
  var zonesRegistry = new WeakMap;
1009
1213
  var advertisedRegistry = new WeakMap;
@@ -1041,6 +1245,23 @@ function resolveScope(instance) {
1041
1245
  function Scope(value, _context) {
1042
1246
  scopeFunctions.add(value);
1043
1247
  }
1248
+ function ScopeOptional(value, _context) {
1249
+ scopeOptionalFunctions.add(value);
1250
+ }
1251
+ function scopeOptionalMethodNames(instance) {
1252
+ const ret = new Set;
1253
+ let proto = Object.getPrototypeOf(instance);
1254
+ while (proto && proto !== Object.prototype) {
1255
+ for (const key of Object.getOwnPropertyNames(proto)) {
1256
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1257
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1258
+ ret.add(key);
1259
+ }
1260
+ }
1261
+ proto = Object.getPrototypeOf(proto);
1262
+ }
1263
+ return ret;
1264
+ }
1044
1265
  function Version(version) {
1045
1266
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
1046
1267
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -1103,6 +1324,94 @@ function Publish(namespace, name, advertise = false) {
1103
1324
  };
1104
1325
  }
1105
1326
 
1327
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1328
+ var import_api2 = __toESM(require("@opentelemetry/api"), 1);
1329
+ // packages/core/package.json
1330
+ var package_default = {
1331
+ name: "@kinotic-ai/core",
1332
+ version: "5.0.0-beta.30",
1333
+ type: "module",
1334
+ files: [
1335
+ "dist"
1336
+ ],
1337
+ module: "./dist/index.js",
1338
+ main: "./dist/index.cjs",
1339
+ types: "./dist/index.d.ts",
1340
+ exports: {
1341
+ ".": {
1342
+ import: {
1343
+ types: "./dist/index.d.ts",
1344
+ default: "./dist/index.js"
1345
+ },
1346
+ require: {
1347
+ types: "./dist/index.d.cts",
1348
+ default: "./dist/index.cjs"
1349
+ }
1350
+ },
1351
+ "./node": {
1352
+ import: {
1353
+ types: "./dist/node/index.d.ts",
1354
+ default: "./dist/node/index.js"
1355
+ },
1356
+ require: {
1357
+ types: "./dist/node/index.d.cts",
1358
+ default: "./dist/node/index.cjs"
1359
+ }
1360
+ },
1361
+ "./package.json": "./package.json"
1362
+ },
1363
+ homepage: "https://github.com/kinotic-ai/kinotic",
1364
+ repository: {
1365
+ type: "git",
1366
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1367
+ directory: "kinotic-js/workspace/packages/core"
1368
+ },
1369
+ license: "Apache-2.0",
1370
+ publishConfig: {
1371
+ access: "public"
1372
+ },
1373
+ scripts: {
1374
+ "type-check": "tsc --noEmit",
1375
+ test: "vitest run",
1376
+ coverage: "vitest run --coverage",
1377
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1378
+ },
1379
+ devDependencies: {
1380
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1381
+ "@opentelemetry/resources": "^2.10.0",
1382
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1383
+ "@opentelemetry/sdk-node": "^0.221.0",
1384
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1385
+ "@types/debug": "^4.1.13",
1386
+ "@types/node": "^25.6.0",
1387
+ "@types/ws": "^8.18.0",
1388
+ "@vitest/coverage-v8": "^4.1.4",
1389
+ "@vitest/runner": "^4.1.4",
1390
+ "@vitest/ui": "^4.1.4",
1391
+ allure: "^3.19.1",
1392
+ "allure-vitest": "^3.13.0",
1393
+ dotenv: "^17.4.1",
1394
+ "properties-file": "^4.0.0",
1395
+ testcontainers: "^11.14.0",
1396
+ tslib: "^2.8.1",
1397
+ typescript: "^6.0.2",
1398
+ vitest: "^4.1.4"
1399
+ },
1400
+ dependencies: {
1401
+ "@kinotic-ai/idl": "workspace:^",
1402
+ "@opentelemetry/api": "^1.9.1",
1403
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1404
+ "@stomp/rx-stomp": "^2.4.0",
1405
+ "@stomp/stompjs": "^7.3.0",
1406
+ debug: "^4.4.3",
1407
+ "p-tap": "^4.0.0",
1408
+ rxjs: "^7.8.2",
1409
+ "typescript-optional": "3.0.0-alpha.3",
1410
+ uuid: "^13.0.0",
1411
+ ws: "^8.21.0"
1412
+ }
1413
+ };
1414
+
1106
1415
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1107
1416
  class ServiceInvocationSupervisor {
1108
1417
  log;
@@ -1114,7 +1423,13 @@ class ServiceInvocationSupervisor {
1114
1423
  serviceIdentifier;
1115
1424
  serviceInstance;
1116
1425
  methodSubscription = null;
1426
+ unscopedSubscription = null;
1427
+ activeStreams = new Map;
1428
+ connectionEndedSubscription = null;
1429
+ connectionGeneration = 0;
1117
1430
  methodMap;
1431
+ scopeOptionalMethods;
1432
+ tracer;
1118
1433
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1119
1434
  if (!serviceIdentifier)
1120
1435
  throw new Error("ServiceIdentifier must not be null");
@@ -1128,10 +1443,12 @@ class ServiceInvocationSupervisor {
1128
1443
  this.serviceInstance = serviceInstance;
1129
1444
  this._eventBus = eventBusService;
1130
1445
  this.interceptorProvider = interceptorProvider;
1131
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1446
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1132
1447
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1133
1448
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1134
1449
  this.methodMap = this.buildMethodMap(serviceInstance);
1450
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1451
+ this.tracer = import_api2.default.trace.getTracer(package_default.name, package_default.version);
1135
1452
  }
1136
1453
  isActive() {
1137
1454
  return this.active;
@@ -1151,7 +1468,22 @@ class ServiceInvocationSupervisor {
1151
1468
  }
1152
1469
  this.active = true;
1153
1470
  const criBase = this.serviceIdentifier.cri().baseResource();
1154
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1471
+ this.methodSubscription = this.subscribeAt(criBase);
1472
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1473
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1474
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1475
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1476
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1477
+ }
1478
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1479
+ this.connectionGeneration++;
1480
+ for (const stream of this.activeStreams.values()) {
1481
+ stream.subscription.unsubscribe();
1482
+ }
1483
+ });
1484
+ }
1485
+ subscribeAt(criBase) {
1486
+ return this._eventBus.observe(criBase).subscribe({
1155
1487
  next: async (event) => {
1156
1488
  await this.processEvent(event);
1157
1489
  },
@@ -1164,7 +1496,6 @@ class ServiceInvocationSupervisor {
1164
1496
  this.active = false;
1165
1497
  }
1166
1498
  });
1167
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1168
1499
  }
1169
1500
  stop() {
1170
1501
  if (!this.active) {
@@ -1173,6 +1504,15 @@ class ServiceInvocationSupervisor {
1173
1504
  this.active = false;
1174
1505
  this.methodSubscription?.unsubscribe();
1175
1506
  this.methodSubscription = null;
1507
+ this.unscopedSubscription?.unsubscribe();
1508
+ this.unscopedSubscription = null;
1509
+ this.connectionEndedSubscription?.unsubscribe();
1510
+ this.connectionEndedSubscription = null;
1511
+ const serviceName = this.serviceIdentifier.qualifiedName();
1512
+ for (const stream of this.activeStreams.values()) {
1513
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1514
+ stream.subscription.unsubscribe();
1515
+ }
1176
1516
  this.log.info("ServiceInvocationSupervisor stopped");
1177
1517
  }
1178
1518
  buildMethodMap(serviceInstance) {
@@ -1212,10 +1552,19 @@ class ServiceInvocationSupervisor {
1212
1552
  if (!correlationId) {
1213
1553
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1214
1554
  }
1215
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1555
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1556
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1557
+ const stream = this.activeStreams.get(correlationId);
1558
+ if (stream) {
1559
+ stream.subscription.unsubscribe();
1560
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1561
+ throw new Error(`Unknown control header value ${control}`);
1562
+ }
1563
+ }
1216
1564
  }
1217
1565
  async processInvocationRequest(event) {
1218
- const path = createCRI(event.cri).path();
1566
+ const incomingCri = createCRI(event.cri);
1567
+ const path = incomingCri.path();
1219
1568
  if (!path) {
1220
1569
  throw new Error("The methodId must not be blank");
1221
1570
  }
@@ -1223,49 +1572,175 @@ class ServiceInvocationSupervisor {
1223
1572
  if (!handlerMethod) {
1224
1573
  throw new Error(`No method resolved for methodId ${path}`);
1225
1574
  }
1575
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1576
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1577
+ }
1226
1578
  const methodName = path;
1227
- const args = this.argumentResolver.resolveArguments(event);
1228
- const injectContext = receivesContext(this.serviceInstance, methodName);
1229
- let context2 = {};
1230
- const interceptor = this.interceptorProvider();
1231
- if (interceptor) {
1579
+ const span = this.startInvocationSpan(event, methodName);
1580
+ const generation = this.connectionGeneration;
1581
+ try {
1582
+ const args = this.argumentResolver.resolveArguments(event);
1583
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1584
+ let serviceContext = {};
1585
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1586
+ if (sender) {
1587
+ serviceContext.participant = JSON.parse(sender);
1588
+ }
1589
+ const interceptor = this.interceptorProvider();
1590
+ if (interceptor) {
1591
+ try {
1592
+ serviceContext = await interceptor.intercept(event, serviceContext);
1593
+ } catch (e) {
1594
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1595
+ if (this.replyOwed(generation)) {
1596
+ this.handleException(event, new Error("Internal server error"));
1597
+ }
1598
+ this.failSpan(span, e);
1599
+ return;
1600
+ }
1601
+ }
1602
+ if (injectContext) {
1603
+ args.push(serviceContext);
1604
+ }
1605
+ const expectedArgsCount = handlerMethod.length;
1606
+ if (args.length !== expectedArgsCount) {
1607
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1608
+ }
1609
+ let result;
1232
1610
  try {
1233
- context2 = await interceptor.intercept(event, context2);
1611
+ result = import_api2.context.with(import_api2.trace.setSpan(import_api2.context.active(), span), () => handlerMethod(...args));
1612
+ if (result instanceof Promise) {
1613
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1614
+ this.failInvocation(event, e, span, generation);
1615
+ });
1616
+ } else {
1617
+ this.processMethodInvocationResult(event, result, span, generation);
1618
+ }
1234
1619
  } catch (e) {
1235
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1236
- this.handleException(event, new Error("Internal server error"));
1237
- return;
1620
+ this.failInvocation(event, e, span, generation);
1621
+ }
1622
+ } catch (e) {
1623
+ this.failSpan(span, e);
1624
+ throw e;
1625
+ }
1626
+ }
1627
+ startInvocationSpan(event, methodName) {
1628
+ const carrier = {};
1629
+ for (const [key, value] of event.headers.entries()) {
1630
+ carrier[key] = value;
1631
+ }
1632
+ const serviceName = this.serviceIdentifier.qualifiedName();
1633
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1634
+ kind: import_api2.SpanKind.SERVER,
1635
+ attributes: {
1636
+ "rpc.system": "kinotic",
1637
+ "rpc.service": serviceName,
1638
+ "rpc.method": methodName
1238
1639
  }
1640
+ }, import_api2.propagation.extract(import_api2.context.active(), carrier));
1641
+ }
1642
+ failSpan(span, error) {
1643
+ span.recordException(error);
1644
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1645
+ span.end();
1646
+ }
1647
+ replyOwed(generation) {
1648
+ return generation === this.connectionGeneration;
1649
+ }
1650
+ failInvocation(event, error, span, generation) {
1651
+ if (this.replyOwed(generation)) {
1652
+ this.handleException(event, error);
1239
1653
  }
1240
- if (injectContext) {
1241
- args.push(context2);
1654
+ this.failSpan(span, error);
1655
+ }
1656
+ processMethodInvocationResult(event, result, span, generation) {
1657
+ if (!this.replyOwed(generation)) {
1658
+ span.end();
1659
+ } else if (import_rxjs3.isObservable(result)) {
1660
+ this.streamResult(event, result, span);
1661
+ } else {
1662
+ const reply = this.returnValueConverter.convert(event.headers, result);
1663
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1664
+ this.sendReply(reply);
1665
+ span.end();
1242
1666
  }
1243
- const expectedArgsCount = handlerMethod.length;
1244
- if (args.length !== expectedArgsCount) {
1245
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1667
+ }
1668
+ streamResult(event, stream, span) {
1669
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1670
+ if (!correlationId) {
1671
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1246
1672
  }
1247
- let result;
1248
- try {
1249
- result = handlerMethod(...args);
1250
- if (result instanceof Promise) {
1251
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1252
- } else {
1253
- this.processMethodInvocationResult(event, result);
1673
+ if (this.activeStreams.has(correlationId)) {
1674
+ const error = new Error(`stream ${correlationId} already active`);
1675
+ this.handleException(event, error);
1676
+ this.failSpan(span, error);
1677
+ return;
1678
+ }
1679
+ let subscription = null;
1680
+ let failed = false;
1681
+ subscription = stream.pipe(import_operators3.finalize(() => {
1682
+ if (this.activeStreams.get(correlationId)?.subscription === subscription) {
1683
+ this.activeStreams.delete(correlationId);
1254
1684
  }
1255
- } catch (e) {
1256
- this.handleException(event, e);
1685
+ span.end();
1686
+ })).subscribe({
1687
+ next: (value) => {
1688
+ if (failed) {
1689
+ return;
1690
+ }
1691
+ try {
1692
+ const reply = this.returnValueConverter.convert(event.headers, value);
1693
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1694
+ this.sendReply(reply);
1695
+ } catch (e) {
1696
+ failed = true;
1697
+ this.handleException(event, e);
1698
+ span.recordException(e);
1699
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1700
+ subscription?.unsubscribe();
1701
+ }
1702
+ },
1703
+ error: (error) => {
1704
+ if (failed) {
1705
+ return;
1706
+ }
1707
+ this.handleException(event, error);
1708
+ span.recordException(error);
1709
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1710
+ },
1711
+ complete: () => {
1712
+ if (failed) {
1713
+ return;
1714
+ }
1715
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1716
+ }
1717
+ });
1718
+ if (failed) {
1719
+ subscription.unsubscribe();
1720
+ }
1721
+ if (!subscription.closed) {
1722
+ this.activeStreams.set(correlationId, { request: event, subscription });
1257
1723
  }
1258
1724
  }
1259
- processMethodInvocationResult(event, result) {
1260
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1261
- this._eventBus.send(outgoingEvent);
1725
+ sendReply(event) {
1726
+ try {
1727
+ this._eventBus.send(event);
1728
+ } catch (e) {
1729
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1730
+ }
1262
1731
  }
1263
1732
  handleException(event, error) {
1264
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1265
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1266
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1267
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1268
- this._eventBus.send(errorEvent);
1733
+ try {
1734
+ const errorMessage = error?.message || "Unknown error";
1735
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1736
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1737
+ ["error" /* ERROR_HEADER */, errorMessage],
1738
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1739
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1740
+ this.sendReply(errorEvent);
1741
+ } catch (e) {
1742
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1743
+ }
1269
1744
  }
1270
1745
  validateReplyTo(event) {
1271
1746
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1286,97 +1761,9 @@ class ServiceInvocationSupervisor {
1286
1761
  }
1287
1762
 
1288
1763
  // packages/core/src/api/ServiceRegistry.ts
1289
- var import_api2 = __toESM(require("@opentelemetry/api"));
1764
+ var import_api3 = __toESM(require("@opentelemetry/api"), 1);
1290
1765
  var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
1291
- var import_operators2 = require("rxjs/operators");
1292
- // packages/core/package.json
1293
- var package_default = {
1294
- name: "@kinotic-ai/core",
1295
- version: "5.0.0-beta.3",
1296
- type: "module",
1297
- files: [
1298
- "dist"
1299
- ],
1300
- module: "./dist/index.js",
1301
- main: "./dist/index.cjs",
1302
- types: "./dist/index.d.ts",
1303
- exports: {
1304
- ".": {
1305
- import: {
1306
- types: "./dist/index.d.ts",
1307
- default: "./dist/index.js"
1308
- },
1309
- require: {
1310
- types: "./dist/index.d.cts",
1311
- default: "./dist/index.cjs"
1312
- }
1313
- },
1314
- "./node": {
1315
- import: {
1316
- types: "./dist/node/index.d.ts",
1317
- default: "./dist/node/index.js"
1318
- },
1319
- require: {
1320
- types: "./dist/node/index.d.cts",
1321
- default: "./dist/node/index.cjs"
1322
- }
1323
- },
1324
- "./package.json": "./package.json"
1325
- },
1326
- homepage: "https://github.com/kinotic-ai/kinotic",
1327
- license: "Elastic License 2.0",
1328
- publishConfig: {
1329
- access: "public"
1330
- },
1331
- scripts: {
1332
- "type-check": "tsc --noEmit",
1333
- test: "vitest run",
1334
- coverage: "vitest run --coverage",
1335
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1336
- },
1337
- devDependencies: {
1338
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1339
- "@opentelemetry/resources": "^2.6.1",
1340
- "@opentelemetry/sdk-metrics": "^2.6.1",
1341
- "@opentelemetry/sdk-node": "^0.214.0",
1342
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1343
- "@types/node": "^25.6.0",
1344
- "@types/uuid": "^11.0.0",
1345
- "@types/ws": "^8.18.0",
1346
- "@vitest/coverage-v8": "^4.1.4",
1347
- "@vitest/runner": "^4.1.4",
1348
- "@vitest/ui": "^4.1.4",
1349
- allure: "^3.4.1",
1350
- "allure-vitest": "^3.7.1",
1351
- dotenv: "^17.4.1",
1352
- "properties-file": "^4.0.0",
1353
- testcontainers: "^11.14.0",
1354
- tslib: "^2.8.1",
1355
- typescript: "^6.0.2",
1356
- vitest: "^4.1.4",
1357
- ws: "^8.20.0"
1358
- },
1359
- dependencies: {
1360
- "@opentelemetry/api": "^1.9.1",
1361
- "@opentelemetry/semantic-conventions": "^1.40.0",
1362
- "@stomp/rx-stomp": "^2.4.0",
1363
- "@stomp/stompjs": "^7.3.0",
1364
- "@types/debug": "^4.1.13",
1365
- debug: "^4.4.3",
1366
- "p-tap": "^4.0.0",
1367
- rxjs: "^7.8.2",
1368
- "typescript-optional": "3.0.0-alpha.3",
1369
- uuid: "^13.0.0",
1370
- ws: "^8.18.0"
1371
- },
1372
- peerDependenciesMeta: {
1373
- typescript: {
1374
- optional: true
1375
- }
1376
- }
1377
- };
1378
-
1379
- // packages/core/src/api/ServiceRegistry.ts
1766
+ var import_operators4 = require("rxjs/operators");
1380
1767
  class JsonEventFactory {
1381
1768
  create(cri, args) {
1382
1769
  const event = new Event(cri);
@@ -1410,12 +1797,61 @@ class TextEventFactory {
1410
1797
  return event;
1411
1798
  }
1412
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
+ }
1413
1848
 
1414
1849
  class ServiceRegistry {
1415
1850
  _eventBus;
1416
1851
  supervisors = new Map;
1852
+ entries = new Map;
1417
1853
  contextInterceptor = null;
1418
- debugLogger = import_debug3.default("kinoitc:serviceRegistry");
1854
+ debugLogger = import_debug3.default("kinotic:serviceRegistry");
1419
1855
  constructor(eventBus) {
1420
1856
  this._eventBus = eventBus;
1421
1857
  }
@@ -1435,9 +1871,16 @@ class ServiceRegistry {
1435
1871
  const criString = serviceIdentifier.cri().raw();
1436
1872
  if (!this.supervisors.has(criString)) {
1437
1873
  this.debugLogger(`Registering service for CRI: ${criString}`);
1874
+ const entry = directoryEntryOf(service, serviceIdentifier);
1438
1875
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1439
1876
  this.supervisors.set(criString, supervisor);
1440
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
+ }
1441
1884
  }
1442
1885
  }
1443
1886
  unRegister(serviceIdentifier) {
@@ -1447,8 +1890,18 @@ class ServiceRegistry {
1447
1890
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1448
1891
  supervisor.stop();
1449
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);
1450
1899
  }
1451
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
+ }
1452
1905
  registerContextInterceptor(interceptor) {
1453
1906
  this.contextInterceptor = interceptor;
1454
1907
  }
@@ -1465,24 +1918,24 @@ class ServiceProxy {
1465
1918
  }
1466
1919
  this.serviceIdentifier = serviceIdentifier;
1467
1920
  this.serviceRegistry = serviceRegistry;
1468
- this.tracer = import_api2.default.trace.getTracer("kinoitc.client", package_default.version);
1921
+ this.tracer = import_api3.default.trace.getTracer(package_default.name, package_default.version);
1469
1922
  }
1470
1923
  invoke(methodIdentifier, args, scope, eventFactory) {
1471
1924
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1472
- kind: import_api2.SpanKind.CLIENT
1925
+ kind: import_api3.SpanKind.CLIENT
1473
1926
  }, async (span) => {
1474
1927
  if (scope) {
1475
- span.setAttribute("kinoitc.scope", scope);
1928
+ span.setAttribute("kinotic.scope", scope);
1476
1929
  }
1477
- span.setAttribute("rpc.system", "kinoitc");
1930
+ span.setAttribute("rpc.system", "kinotic");
1478
1931
  span.setAttribute("rpc.service", this.serviceIdentifier);
1479
1932
  span.setAttribute("rpc.method", methodIdentifier);
1480
- return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators2.first()).toPromise().then(async (value) => {
1933
+ return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators4.first()).toPromise().then(async (value) => {
1481
1934
  span.end();
1482
1935
  return value;
1483
1936
  }, async (ex) => {
1484
1937
  span.recordException(ex);
1485
- span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1938
+ span.setStatus({ code: import_api3.SpanStatusCode.ERROR });
1486
1939
  span.end();
1487
1940
  throw ex;
1488
1941
  });
@@ -1498,13 +1951,13 @@ class ServiceProxy {
1498
1951
  eventFactoryToUse = eventFactory;
1499
1952
  }
1500
1953
  let eventBusToUse = this.serviceRegistry.eventBus;
1501
- const span = import_api2.default.trace.getActiveSpan();
1954
+ const span = import_api3.default.trace.getActiveSpan();
1502
1955
  if (span) {
1503
1956
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1504
1957
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
1505
1958
  }
1506
1959
  let event = eventFactoryToUse.create(cri, args);
1507
- return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators2.map((value) => {
1960
+ return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators4.map((value) => {
1508
1961
  const contentType = value.getHeader("content-type" /* CONTENT_TYPE_HEADER */);
1509
1962
  if (contentType !== undefined) {
1510
1963
  if (contentType === "application/json" /* CONTENT_JSON */) {
@@ -1540,8 +1993,10 @@ class KinoticSingleton {
1540
1993
  this._eventBus = eventBus;
1541
1994
  this.serviceRegistry.eventBus = eventBus;
1542
1995
  }
1543
- connect(options) {
1544
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1996
+ async connect(options) {
1997
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1998
+ await this.serviceRegistry.registerEntries();
1999
+ return ret;
1545
2000
  }
1546
2001
  disconnect(force) {
1547
2002
  return this._eventBus.disconnect(force);
@@ -1662,6 +2117,9 @@ class CrudServiceProxy {
1662
2117
  deleteById(id) {
1663
2118
  return this.serviceProxy.invoke("deleteById", [id]);
1664
2119
  }
2120
+ deleteByIdSync(id) {
2121
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
2122
+ }
1665
2123
  async findAll(pageable) {
1666
2124
  const page = await this.findAllSinglePage(pageable);
1667
2125
  return new FindAllIterablePage(pageable, page, this);
@@ -1752,15 +2210,15 @@ class CursorPageable extends Pageable {
1752
2210
  }
1753
2211
  // packages/core/src/api/crud/Sort.ts
1754
2212
  var Direction;
1755
- ((Direction2) => {
1756
- Direction2["ASC"] = "ASC";
1757
- Direction2["DESC"] = "DESC";
2213
+ ((Direction) => {
2214
+ Direction["ASC"] = "ASC";
2215
+ Direction["DESC"] = "DESC";
1758
2216
  })(Direction ||= {});
1759
2217
  var NullHandling;
1760
- ((NullHandling2) => {
1761
- NullHandling2["NATIVE"] = "NATIVE";
1762
- NullHandling2["NULLS_FIRST"] = "NULLS_FIRST";
1763
- NullHandling2["NULLS_LAST"] = "NULLS_LAST";
2218
+ ((NullHandling) => {
2219
+ NullHandling["NATIVE"] = "NATIVE";
2220
+ NullHandling["NULLS_FIRST"] = "NULLS_FIRST";
2221
+ NullHandling["NULLS_LAST"] = "NULLS_LAST";
1764
2222
  })(NullHandling ||= {});
1765
2223
 
1766
2224
  class Order {
@@ -1784,6 +2242,13 @@ class Order {
1784
2242
  class Sort {
1785
2243
  orders = [];
1786
2244
  }
2245
+ // packages/core/src/api/security/AuthorizationException.ts
2246
+ class AuthorizationException extends Error {
2247
+ constructor(message = "Access denied") {
2248
+ super(message);
2249
+ this.name = "AuthorizationException";
2250
+ }
2251
+ }
1787
2252
  // packages/core/src/api/security/ConnectedInfo.ts
1788
2253
  class ConnectedInfo {
1789
2254
  replyToId;