@kinotic-ai/core 5.0.0-beta.0 → 5.0.0-beta.10
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/README.md +2 -2
- package/dist/index.cjs +527 -296
- package/dist/index.d.cts +202 -71
- package/dist/index.d.ts +202 -71
- package/dist/index.js +521 -290
- package/dist/node/index.cjs +79 -0
- package/dist/node/index.d.cts +9 -0
- package/dist/node/index.d.ts +9 -0
- package/dist/node/index.js +14 -0
- package/package.json +28 -19
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
// packages/core/src/api/
|
|
1
|
+
// packages/core/src/api/ConnectOptions.ts
|
|
2
2
|
class ServerInfo {
|
|
3
3
|
host;
|
|
4
4
|
port;
|
|
5
5
|
useSSL;
|
|
6
6
|
}
|
|
7
|
+
function buildServerUrl(server, scheme) {
|
|
8
|
+
return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
|
|
9
|
+
}
|
|
10
|
+
function buildBrokerUrl(server) {
|
|
11
|
+
return buildServerUrl(server, "ws") + "/v1";
|
|
12
|
+
}
|
|
7
13
|
var SessionKeepAliveMode;
|
|
8
14
|
((SessionKeepAliveMode2) => {
|
|
9
15
|
SessionKeepAliveMode2["NONE"] = "NONE";
|
|
10
16
|
SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
|
|
11
17
|
SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
|
|
12
18
|
})(SessionKeepAliveMode ||= {});
|
|
13
|
-
|
|
14
|
-
class ConnectionInfo extends ServerInfo {
|
|
15
|
-
webSocketFactory;
|
|
16
|
-
maxConnectionAttempts;
|
|
17
|
-
sessionKeepAlive = "ACTIVITY" /* ACTIVITY */;
|
|
18
|
-
}
|
|
19
19
|
// packages/core/src/api/event/IEventBus.ts
|
|
20
20
|
var EventConstants;
|
|
21
21
|
((EventConstants2) => {
|
|
@@ -46,39 +46,25 @@ var EventConstants;
|
|
|
46
46
|
EventConstants2["TRACESTATE_HEADER"] = "tracestate";
|
|
47
47
|
})(EventConstants ||= {});
|
|
48
48
|
|
|
49
|
-
// packages/core/src/internal/api/
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
for (const [key, value] of incomingHeaders) {
|
|
61
|
-
if (key.startsWith("__")) {
|
|
62
|
-
newHeaders.set(key, value);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
if (headers) {
|
|
66
|
-
for (const [key, value] of headers) {
|
|
67
|
-
newHeaders.set(key, value);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
return new Event(replyCRI, newHeaders, body || undefined);
|
|
71
|
-
}
|
|
72
|
-
static buildBrokerUrl(serverInfo) {
|
|
73
|
-
return "ws" + (serverInfo.useSSL ? "s" : "") + "://" + serverInfo.host + (serverInfo.port ? ":" + serverInfo.port : "") + "/v1";
|
|
74
|
-
}
|
|
49
|
+
// packages/core/src/internal/api/Logger.ts
|
|
50
|
+
import debug from "debug";
|
|
51
|
+
function createDebugLogger(namespace) {
|
|
52
|
+
const debugLogger = debug(namespace);
|
|
53
|
+
return {
|
|
54
|
+
trace: (...args) => debugLogger("TRACE", ...args),
|
|
55
|
+
debug: (...args) => debugLogger("DEBUG", ...args),
|
|
56
|
+
info: (...args) => debugLogger("INFO", ...args),
|
|
57
|
+
warn: (...args) => debugLogger("WARN", ...args),
|
|
58
|
+
error: (...args) => debugLogger("ERROR", ...args)
|
|
59
|
+
};
|
|
75
60
|
}
|
|
76
61
|
|
|
77
62
|
// packages/core/src/internal/api/StompConnectionManager.ts
|
|
78
63
|
import { RxStomp } from "@stomp/rx-stomp";
|
|
79
64
|
import { ReconnectionTimeMode } from "@stomp/stompjs";
|
|
80
|
-
import
|
|
65
|
+
import debug2 from "debug";
|
|
81
66
|
import { Subject } from "rxjs";
|
|
67
|
+
import { skip } from "rxjs/operators";
|
|
82
68
|
import { v4 as uuidv4 } from "uuid";
|
|
83
69
|
var SESSION_CHECK_PATH = "/api/auth/me";
|
|
84
70
|
|
|
@@ -86,15 +72,20 @@ class StompConnectionManager {
|
|
|
86
72
|
lastWebsocketError = null;
|
|
87
73
|
maxConnectionAttemptsReached = false;
|
|
88
74
|
replyToCriChangedHandler = null;
|
|
89
|
-
rxStomp =
|
|
75
|
+
rxStomp = new RxStomp;
|
|
76
|
+
isActive = false;
|
|
77
|
+
initialConnectedSubscription = null;
|
|
78
|
+
initialFailureSubscription = null;
|
|
79
|
+
webSocketErrorsSubscription = null;
|
|
90
80
|
INITIAL_RECONNECT_DELAY = 2000;
|
|
91
81
|
JITTER_MAX = 5000;
|
|
92
82
|
MAX_RECONNECT_DELAY = 120000;
|
|
93
83
|
connectionAttempts = 0;
|
|
94
|
-
debugLogger =
|
|
84
|
+
debugLogger = debug2("kinotic:stomp");
|
|
95
85
|
fatalErrorsSubject = new Subject;
|
|
96
86
|
_fatalErrors = this.fatalErrorsSubject.asObservable();
|
|
97
87
|
initialConnectionSuccessful = false;
|
|
88
|
+
rxStompHasConnected = false;
|
|
98
89
|
serverHeadersSubscription = null;
|
|
99
90
|
stompErrorsSubscription = null;
|
|
100
91
|
uuidv4 = uuidv4();
|
|
@@ -103,61 +94,70 @@ class StompConnectionManager {
|
|
|
103
94
|
return this._replyToCri;
|
|
104
95
|
}
|
|
105
96
|
get active() {
|
|
106
|
-
return
|
|
97
|
+
return this.isActive;
|
|
107
98
|
}
|
|
108
99
|
get connected() {
|
|
109
|
-
return this.
|
|
100
|
+
return this.isActive && this.rxStomp.connected();
|
|
110
101
|
}
|
|
111
102
|
get fatalErrors() {
|
|
112
103
|
return this._fatalErrors;
|
|
113
104
|
}
|
|
114
|
-
activate(
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
105
|
+
async activate(options) {
|
|
106
|
+
if (!options?.server?.host) {
|
|
107
|
+
throw new Error("No host provided");
|
|
108
|
+
}
|
|
109
|
+
if (this.isActive) {
|
|
110
|
+
throw new Error("Stomp connection already active");
|
|
111
|
+
}
|
|
112
|
+
const server = options.server;
|
|
113
|
+
const credentialsResolver = options.credentials;
|
|
114
|
+
let headerAuth = false;
|
|
115
|
+
if (!options.webSocketFactory) {
|
|
116
|
+
if (!credentialsResolver) {
|
|
117
|
+
throw new Error("No credentials supplied and no default resolution applied");
|
|
123
118
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
119
|
+
const resolved = await credentialsResolver.resolve(server);
|
|
120
|
+
if (resolved === null) {
|
|
121
|
+
throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
|
|
127
122
|
}
|
|
123
|
+
headerAuth = resolved.authHeaders != null;
|
|
124
|
+
}
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
128
126
|
this.connectionAttempts = 0;
|
|
129
127
|
this.initialConnectionSuccessful = false;
|
|
130
128
|
this.lastWebsocketError = null;
|
|
131
129
|
this.maxConnectionAttemptsReached = false;
|
|
132
|
-
const url =
|
|
133
|
-
this.rxStomp = new RxStomp;
|
|
130
|
+
const url = buildBrokerUrl(server);
|
|
134
131
|
let preparedSocket = null;
|
|
135
|
-
const userWebSocketFactory =
|
|
132
|
+
const userWebSocketFactory = options.webSocketFactory;
|
|
133
|
+
const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
|
|
136
134
|
const stompConfig = {
|
|
137
135
|
brokerURL: url,
|
|
138
136
|
connectHeaders: {
|
|
139
|
-
["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]:
|
|
137
|
+
["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
|
|
140
138
|
},
|
|
141
139
|
heartbeatIncoming: 120000,
|
|
142
140
|
heartbeatOutgoing: 30000,
|
|
143
141
|
reconnectDelay: this.INITIAL_RECONNECT_DELAY,
|
|
144
142
|
maxReconnectDelay: this.MAX_RECONNECT_DELAY,
|
|
145
143
|
reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
|
|
146
|
-
webSocketFactory:
|
|
144
|
+
webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
|
|
147
145
|
beforeConnect: async () => {
|
|
148
|
-
if (!
|
|
149
|
-
const sessionCheckUrl =
|
|
146
|
+
if (!usesPreparedSocket) {
|
|
147
|
+
const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
|
|
150
148
|
try {
|
|
151
149
|
const res = await fetch(sessionCheckUrl, { credentials: "include" });
|
|
152
150
|
if (res.status === 401) {
|
|
153
151
|
await this.signalFatal(new Error("Authentication required"));
|
|
154
152
|
return;
|
|
155
153
|
}
|
|
156
|
-
} catch {
|
|
154
|
+
} catch (e) {
|
|
155
|
+
this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
|
|
156
|
+
}
|
|
157
157
|
}
|
|
158
|
-
if (
|
|
158
|
+
if (options?.maxConnectionAttempts) {
|
|
159
159
|
this.connectionAttempts++;
|
|
160
|
-
if (this.connectionAttempts >
|
|
160
|
+
if (this.connectionAttempts > options.maxConnectionAttempts) {
|
|
161
161
|
this.maxConnectionAttemptsReached = true;
|
|
162
162
|
await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
|
|
163
163
|
return;
|
|
@@ -173,6 +173,18 @@ class StompConnectionManager {
|
|
|
173
173
|
} catch (e) {
|
|
174
174
|
await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
|
|
175
175
|
}
|
|
176
|
+
} else if (headerAuth) {
|
|
177
|
+
try {
|
|
178
|
+
const resolved = await credentialsResolver.resolve(server);
|
|
179
|
+
if (resolved?.authHeaders == null) {
|
|
180
|
+
await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
|
|
181
|
+
} else {
|
|
182
|
+
const WS = WebSocket;
|
|
183
|
+
preparedSocket = new WS(url, { headers: resolved.authHeaders });
|
|
184
|
+
}
|
|
185
|
+
} catch (e) {
|
|
186
|
+
await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
|
|
187
|
+
}
|
|
176
188
|
}
|
|
177
189
|
}
|
|
178
190
|
};
|
|
@@ -182,26 +194,31 @@ class StompConnectionManager {
|
|
|
182
194
|
};
|
|
183
195
|
}
|
|
184
196
|
this.rxStomp.configure(stompConfig);
|
|
185
|
-
this.rxStomp.webSocketErrors$.subscribe((value) => {
|
|
197
|
+
this.webSocketErrorsSubscription = this.rxStomp.webSocketErrors$.subscribe(async (value) => {
|
|
186
198
|
this.lastWebsocketError = value;
|
|
199
|
+
if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
|
|
200
|
+
this.maxConnectionAttemptsReached = true;
|
|
201
|
+
await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
|
|
202
|
+
}
|
|
187
203
|
});
|
|
188
204
|
this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
|
|
189
205
|
const stompError = new Error(frame.headers["message"], { cause: frame });
|
|
190
206
|
await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
|
|
191
207
|
});
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
initialFailureSubscription
|
|
208
|
+
this.initialConnectedSubscription = this.rxStomp.connected$.subscribe(() => {
|
|
209
|
+
this.initialConnectedSubscription?.unsubscribe();
|
|
210
|
+
this.initialFailureSubscription?.unsubscribe();
|
|
195
211
|
if (!this.initialConnectionSuccessful) {
|
|
196
212
|
this.initialConnectionSuccessful = true;
|
|
197
213
|
}
|
|
198
214
|
});
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
initialFailureSubscription
|
|
215
|
+
this.initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
|
|
216
|
+
this.initialConnectedSubscription?.unsubscribe();
|
|
217
|
+
this.initialFailureSubscription?.unsubscribe();
|
|
202
218
|
reject(err.message);
|
|
203
219
|
});
|
|
204
|
-
this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
|
|
220
|
+
this.serverHeadersSubscription = this.rxStomp.serverHeaders$.pipe(skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
|
|
221
|
+
this.rxStompHasConnected = true;
|
|
205
222
|
const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
|
|
206
223
|
if (connectedInfoJson == null) {
|
|
207
224
|
if (!this.initialConnectionSuccessful) {
|
|
@@ -218,7 +235,7 @@ class StompConnectionManager {
|
|
|
218
235
|
}
|
|
219
236
|
return;
|
|
220
237
|
}
|
|
221
|
-
const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@
|
|
238
|
+
const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinotic.js.EventBus/replyHandler";
|
|
222
239
|
if (!this.initialConnectionSuccessful) {
|
|
223
240
|
this._replyToCri = newReplyToCri;
|
|
224
241
|
resolve(connectedInfo);
|
|
@@ -227,21 +244,23 @@ class StompConnectionManager {
|
|
|
227
244
|
this.replyToCriChangedHandler?.(newReplyToCri);
|
|
228
245
|
}
|
|
229
246
|
});
|
|
247
|
+
this.isActive = true;
|
|
230
248
|
this.rxStomp.activate();
|
|
231
249
|
});
|
|
232
250
|
}
|
|
233
251
|
async deactivate(force) {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
await rxStomp.deactivate({ force });
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
252
|
+
if (this.isActive) {
|
|
253
|
+
this.isActive = false;
|
|
254
|
+
await this.rxStomp.deactivate({ force });
|
|
255
|
+
this.initialConnectedSubscription?.unsubscribe();
|
|
256
|
+
this.initialConnectedSubscription = null;
|
|
257
|
+
this.webSocketErrorsSubscription?.unsubscribe();
|
|
258
|
+
this.webSocketErrorsSubscription = null;
|
|
259
|
+
this.serverHeadersSubscription?.unsubscribe();
|
|
260
|
+
this.serverHeadersSubscription = null;
|
|
261
|
+
this.stompErrorsSubscription?.unsubscribe();
|
|
262
|
+
this.stompErrorsSubscription = null;
|
|
263
|
+
this._replyToCri = null;
|
|
245
264
|
}
|
|
246
265
|
return;
|
|
247
266
|
}
|
|
@@ -303,6 +322,7 @@ class Event {
|
|
|
303
322
|
|
|
304
323
|
class EventBus {
|
|
305
324
|
serverInfo = null;
|
|
325
|
+
log = createDebugLogger("kinotic:EventBus");
|
|
306
326
|
stompConnectionManager = new StompConnectionManager;
|
|
307
327
|
connectionLifecycle = Promise.resolve();
|
|
308
328
|
replyToCri = null;
|
|
@@ -328,15 +348,12 @@ class EventBus {
|
|
|
328
348
|
isConnected() {
|
|
329
349
|
return this.stompConnectionManager.connected;
|
|
330
350
|
}
|
|
331
|
-
connect(
|
|
351
|
+
connect(options) {
|
|
332
352
|
return this.serializeLifecycle(async () => {
|
|
333
353
|
if (!this.stompConnectionManager.active) {
|
|
334
354
|
this.cleanup();
|
|
335
|
-
const connectedInfo = await this.stompConnectionManager.activate(
|
|
336
|
-
this.serverInfo =
|
|
337
|
-
this.serverInfo.host = connectionInfo.host;
|
|
338
|
-
this.serverInfo.port = connectionInfo.port;
|
|
339
|
-
this.serverInfo.useSSL = connectionInfo.useSSL;
|
|
355
|
+
const connectedInfo = await this.stompConnectionManager.activate(options);
|
|
356
|
+
this.serverInfo = { ...options.server };
|
|
340
357
|
this.replyToCri = this.stompConnectionManager.replyToCri;
|
|
341
358
|
return connectedInfo;
|
|
342
359
|
} else {
|
|
@@ -356,7 +373,7 @@ class EventBus {
|
|
|
356
373
|
return result;
|
|
357
374
|
}
|
|
358
375
|
send(event) {
|
|
359
|
-
if (this.stompConnectionManager.
|
|
376
|
+
if (this.stompConnectionManager.connected) {
|
|
360
377
|
const headers = {};
|
|
361
378
|
for (const [key, value] of event.headers.entries()) {
|
|
362
379
|
headers[key] = value;
|
|
@@ -372,7 +389,8 @@ class EventBus {
|
|
|
372
389
|
this.stompConnectionManager.rxStomp.publish({
|
|
373
390
|
destination: event.cri,
|
|
374
391
|
headers,
|
|
375
|
-
binaryBody: event.data.orUndefined()
|
|
392
|
+
binaryBody: event.data.orUndefined(),
|
|
393
|
+
retryIfDisconnected: false
|
|
376
394
|
});
|
|
377
395
|
} else {
|
|
378
396
|
throw this.createSendUnavailableError();
|
|
@@ -382,7 +400,7 @@ class EventBus {
|
|
|
382
400
|
return firstValueFrom(this.requestStream(event, false));
|
|
383
401
|
}
|
|
384
402
|
requestStream(event, sendControlEvents = true) {
|
|
385
|
-
if (this.stompConnectionManager
|
|
403
|
+
if (this.stompConnectionManager.active) {
|
|
386
404
|
return new Observable2((subscriber) => {
|
|
387
405
|
if (this.requestRepliesObservable == null) {
|
|
388
406
|
this.requestRepliesSubject = new Subject2;
|
|
@@ -392,6 +410,7 @@ class EventBus {
|
|
|
392
410
|
let serverSignaledCompletion = false;
|
|
393
411
|
const correlationId = uuidv42();
|
|
394
412
|
this.activeCorrelationIds.add(correlationId);
|
|
413
|
+
subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
|
|
395
414
|
const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
|
|
396
415
|
return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
|
|
397
416
|
})).subscribe({
|
|
@@ -421,15 +440,15 @@ class EventBus {
|
|
|
421
440
|
event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
|
|
422
441
|
event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
423
442
|
this.send(event);
|
|
424
|
-
|
|
425
|
-
this.activeCorrelationIds.delete(correlationId);
|
|
443
|
+
subscriber.add(() => {
|
|
426
444
|
if (sendControlEvents && !serverSignaledCompletion) {
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
445
|
+
try {
|
|
446
|
+
this.sendCancel(event.cri, correlationId);
|
|
447
|
+
} catch (e) {
|
|
448
|
+
this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
|
|
449
|
+
}
|
|
431
450
|
}
|
|
432
|
-
};
|
|
451
|
+
});
|
|
433
452
|
});
|
|
434
453
|
} else {
|
|
435
454
|
return throwError(() => this.createSendUnavailableError());
|
|
@@ -455,13 +474,19 @@ class EventBus {
|
|
|
455
474
|
return;
|
|
456
475
|
}
|
|
457
476
|
try {
|
|
458
|
-
|
|
459
|
-
cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
|
|
460
|
-
cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
461
|
-
this.send(cancelEvent);
|
|
477
|
+
this.sendCancel(originCri, correlationId);
|
|
462
478
|
this.recentlyReaped.add(correlationId);
|
|
463
479
|
setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
|
|
464
|
-
} catch {
|
|
480
|
+
} catch (e) {
|
|
481
|
+
this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
sendCancel(cri, correlationId) {
|
|
485
|
+
const cancelEvent = new Event(cri);
|
|
486
|
+
cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
|
|
487
|
+
cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
488
|
+
cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
|
|
489
|
+
this.send(cancelEvent);
|
|
465
490
|
}
|
|
466
491
|
resetRequestReplies(reason) {
|
|
467
492
|
if (this.requestRepliesSubject != null) {
|
|
@@ -476,29 +501,167 @@ class EventBus {
|
|
|
476
501
|
}
|
|
477
502
|
}
|
|
478
503
|
createSendUnavailableError() {
|
|
479
|
-
let ret
|
|
504
|
+
let ret;
|
|
480
505
|
if (this.stompConnectionManager.maxConnectionAttemptsReached) {
|
|
481
506
|
ret = "Max connection attempts reached event bus is not available";
|
|
507
|
+
} else if (this.stompConnectionManager.active) {
|
|
508
|
+
ret = "The event bus is not connected to the server";
|
|
509
|
+
} else {
|
|
510
|
+
ret = "You must call connect on the event bus before sending any request";
|
|
482
511
|
}
|
|
483
512
|
return new Error(ret);
|
|
484
513
|
}
|
|
485
514
|
_observe(cri) {
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
headers.set(prop, message.headers[prop]);
|
|
495
|
-
}
|
|
515
|
+
return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
|
|
516
|
+
const headers = new Map;
|
|
517
|
+
let destination = "";
|
|
518
|
+
for (const prop of Object.keys(message.headers)) {
|
|
519
|
+
if (prop === "destination") {
|
|
520
|
+
destination = message.headers[prop];
|
|
521
|
+
} else {
|
|
522
|
+
headers.set(prop, message.headers[prop]);
|
|
496
523
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
}
|
|
500
|
-
|
|
524
|
+
}
|
|
525
|
+
return new Event(destination, headers, message.binaryBody);
|
|
526
|
+
}));
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// packages/core/src/api/security/ChainedCredentialsResolver.ts
|
|
531
|
+
class ChainedCredentialsResolver {
|
|
532
|
+
name;
|
|
533
|
+
resolvers;
|
|
534
|
+
constructor(...resolvers) {
|
|
535
|
+
this.resolvers = resolvers;
|
|
536
|
+
this.name = `ChainedCredentialsResolver(${resolvers.map((r) => r.name).join(" -> ")})`;
|
|
537
|
+
}
|
|
538
|
+
async resolve(server) {
|
|
539
|
+
for (const resolver of this.resolvers) {
|
|
540
|
+
const resolved = await resolver.resolve(server);
|
|
541
|
+
if (resolved !== null) {
|
|
542
|
+
return resolved;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// packages/core/src/api/security/BasicCredentialsResolver.ts
|
|
550
|
+
class BasicCredentialsResolver {
|
|
551
|
+
name = "BasicCredentialsResolver";
|
|
552
|
+
credentials;
|
|
553
|
+
constructor(clientId, clientSecret, organizationId, applicationId) {
|
|
554
|
+
const authHeaders = { clientId, clientSecret };
|
|
555
|
+
if (organizationId != null)
|
|
556
|
+
authHeaders.organizationId = organizationId;
|
|
557
|
+
if (applicationId != null)
|
|
558
|
+
authHeaders.applicationId = applicationId;
|
|
559
|
+
this.credentials = { authHeaders, organizationId, applicationId };
|
|
560
|
+
}
|
|
561
|
+
async resolve(_server) {
|
|
562
|
+
return this.credentials;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// packages/core/src/api/security/BearerCredentialsResolver.ts
|
|
567
|
+
class BearerCredentialsResolver {
|
|
568
|
+
name = "BearerCredentialsResolver";
|
|
569
|
+
token;
|
|
570
|
+
constructor(token) {
|
|
571
|
+
this.token = token;
|
|
572
|
+
}
|
|
573
|
+
async resolve(_server) {
|
|
574
|
+
const token = typeof this.token === "function" ? await this.token() : this.token;
|
|
575
|
+
return { authHeaders: { Authorization: `Bearer ${token}` } };
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// packages/core/src/api/security/EnvCredentialsResolver.ts
|
|
580
|
+
class EnvCredentialsResolver {
|
|
581
|
+
name = "EnvCredentialsResolver";
|
|
582
|
+
async resolve(server) {
|
|
583
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
584
|
+
let ret = null;
|
|
585
|
+
if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
|
|
586
|
+
ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
|
|
587
|
+
} else if (env?.KINOTIC_TOKEN) {
|
|
588
|
+
ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
|
|
501
589
|
}
|
|
590
|
+
return ret;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// packages/core/src/api/security/SessionCredentialsResolver.ts
|
|
595
|
+
class SessionCredentialsResolver {
|
|
596
|
+
name = "SessionCredentialsResolver";
|
|
597
|
+
async resolve(_server) {
|
|
598
|
+
return typeof document !== "undefined" ? {} : null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// packages/core/src/internal/api/Util.ts
|
|
603
|
+
var DEFAULT_PORT = 58503;
|
|
604
|
+
var DEFAULT_HOST = "api.kinotic.ai";
|
|
605
|
+
|
|
606
|
+
class Util {
|
|
607
|
+
static createReplyEvent(incomingHeaders, headers, body) {
|
|
608
|
+
if (!incomingHeaders) {
|
|
609
|
+
throw new Error("incomingHeaders cannot be null");
|
|
610
|
+
}
|
|
611
|
+
const replyCRI = incomingHeaders.get("reply-to" /* REPLY_TO_HEADER */);
|
|
612
|
+
if (!replyCRI || replyCRI.trim() === "") {
|
|
613
|
+
throw new Error("No reply-to header found, cannot create outgoing message");
|
|
614
|
+
}
|
|
615
|
+
const newHeaders = new Map;
|
|
616
|
+
for (const [key, value] of incomingHeaders) {
|
|
617
|
+
if (key.startsWith("__")) {
|
|
618
|
+
newHeaders.set(key, value);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
if (headers) {
|
|
622
|
+
for (const [key, value] of headers) {
|
|
623
|
+
newHeaders.set(key, value);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return new Event(replyCRI, newHeaders, body || undefined);
|
|
627
|
+
}
|
|
628
|
+
static resolveConnectOptions(options) {
|
|
629
|
+
const opts = options ?? {};
|
|
630
|
+
const server = opts.server ?? {};
|
|
631
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
632
|
+
const location = typeof window !== "undefined" ? window.location : undefined;
|
|
633
|
+
let host = server.host ?? env?.KINOTIC_SERVER_HOST;
|
|
634
|
+
const hostFromLocation = host == null && location != null;
|
|
635
|
+
const hostDefaulted = host == null && location == null;
|
|
636
|
+
if (host == null) {
|
|
637
|
+
host = location?.hostname ?? DEFAULT_HOST;
|
|
638
|
+
}
|
|
639
|
+
let useSSL = server.useSSL;
|
|
640
|
+
if (useSSL == null) {
|
|
641
|
+
if (env?.KINOTIC_SERVER_USE_SSL != null) {
|
|
642
|
+
useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
|
|
643
|
+
} else if (hostFromLocation) {
|
|
644
|
+
useSSL = location.protocol === "https:";
|
|
645
|
+
} else {
|
|
646
|
+
useSSL = hostDefaulted;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
let port = server.port;
|
|
650
|
+
if (port === undefined) {
|
|
651
|
+
if (env?.KINOTIC_SERVER_PORT != null) {
|
|
652
|
+
port = Number(env.KINOTIC_SERVER_PORT);
|
|
653
|
+
} else if (hostFromLocation) {
|
|
654
|
+
port = location.port ? Number(location.port) : null;
|
|
655
|
+
} else {
|
|
656
|
+
port = useSSL ? null : DEFAULT_PORT;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return {
|
|
660
|
+
...opts,
|
|
661
|
+
server: { host, port, useSSL },
|
|
662
|
+
sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
|
|
663
|
+
credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
|
|
664
|
+
};
|
|
502
665
|
}
|
|
503
666
|
}
|
|
504
667
|
|
|
@@ -691,23 +854,11 @@ class JsonArgumentResolver {
|
|
|
691
854
|
// packages/core/src/internal/api/ReturnValueConverter.ts
|
|
692
855
|
class BasicReturnValueConverter {
|
|
693
856
|
convert(incomingMetadata, returnValue) {
|
|
694
|
-
|
|
857
|
+
const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
|
|
858
|
+
return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
|
|
695
859
|
}
|
|
696
860
|
}
|
|
697
861
|
|
|
698
|
-
// packages/core/src/internal/api/Logger.ts
|
|
699
|
-
import debug2 from "debug";
|
|
700
|
-
function createDebugLogger(namespace) {
|
|
701
|
-
const debugLogger = debug2(namespace);
|
|
702
|
-
return {
|
|
703
|
-
trace: (...args) => debugLogger("TRACE", ...args),
|
|
704
|
-
debug: (...args) => debugLogger("DEBUG", ...args),
|
|
705
|
-
info: (...args) => debugLogger("INFO", ...args),
|
|
706
|
-
warn: (...args) => debugLogger("WARN", ...args),
|
|
707
|
-
error: (...args) => debugLogger("ERROR", ...args)
|
|
708
|
-
};
|
|
709
|
-
}
|
|
710
|
-
|
|
711
862
|
// packages/core/src/api/ServiceIdentifier.ts
|
|
712
863
|
class ServiceIdentifier {
|
|
713
864
|
namespace;
|
|
@@ -743,6 +894,9 @@ class ServiceIdentifier {
|
|
|
743
894
|
}
|
|
744
895
|
return this._cri;
|
|
745
896
|
}
|
|
897
|
+
unscopedCri() {
|
|
898
|
+
return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
|
|
899
|
+
}
|
|
746
900
|
}
|
|
747
901
|
|
|
748
902
|
// packages/core/src/api/ZoneUtil.ts
|
|
@@ -762,6 +916,7 @@ function validateLabel(label) {
|
|
|
762
916
|
|
|
763
917
|
// packages/core/src/api/KinoticDecorators.ts
|
|
764
918
|
var scopeFunctions = new WeakSet;
|
|
919
|
+
var scopeOptionalFunctions = new WeakSet;
|
|
765
920
|
var versionRegistry = new WeakMap;
|
|
766
921
|
var zonesRegistry = new WeakMap;
|
|
767
922
|
var advertisedRegistry = new WeakMap;
|
|
@@ -799,6 +954,23 @@ function resolveScope(instance) {
|
|
|
799
954
|
function Scope(value, _context) {
|
|
800
955
|
scopeFunctions.add(value);
|
|
801
956
|
}
|
|
957
|
+
function ScopeOptional(value, _context) {
|
|
958
|
+
scopeOptionalFunctions.add(value);
|
|
959
|
+
}
|
|
960
|
+
function scopeOptionalMethodNames(instance) {
|
|
961
|
+
const ret = new Set;
|
|
962
|
+
let proto = Object.getPrototypeOf(instance);
|
|
963
|
+
while (proto && proto !== Object.prototype) {
|
|
964
|
+
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
965
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
966
|
+
if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
|
|
967
|
+
ret.add(key);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
proto = Object.getPrototypeOf(proto);
|
|
971
|
+
}
|
|
972
|
+
return ret;
|
|
973
|
+
}
|
|
802
974
|
function Version(version) {
|
|
803
975
|
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
|
|
804
976
|
throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
|
|
@@ -861,6 +1033,93 @@ function Publish(namespace, name, advertise = false) {
|
|
|
861
1033
|
};
|
|
862
1034
|
}
|
|
863
1035
|
|
|
1036
|
+
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
1037
|
+
import opentelemetry, { context as context2, propagation as propagation2, trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
|
|
1038
|
+
// packages/core/package.json
|
|
1039
|
+
var package_default = {
|
|
1040
|
+
name: "@kinotic-ai/core",
|
|
1041
|
+
version: "5.0.0-beta.10",
|
|
1042
|
+
type: "module",
|
|
1043
|
+
files: [
|
|
1044
|
+
"dist"
|
|
1045
|
+
],
|
|
1046
|
+
module: "./dist/index.js",
|
|
1047
|
+
main: "./dist/index.cjs",
|
|
1048
|
+
types: "./dist/index.d.ts",
|
|
1049
|
+
exports: {
|
|
1050
|
+
".": {
|
|
1051
|
+
import: {
|
|
1052
|
+
types: "./dist/index.d.ts",
|
|
1053
|
+
default: "./dist/index.js"
|
|
1054
|
+
},
|
|
1055
|
+
require: {
|
|
1056
|
+
types: "./dist/index.d.cts",
|
|
1057
|
+
default: "./dist/index.cjs"
|
|
1058
|
+
}
|
|
1059
|
+
},
|
|
1060
|
+
"./node": {
|
|
1061
|
+
import: {
|
|
1062
|
+
types: "./dist/node/index.d.ts",
|
|
1063
|
+
default: "./dist/node/index.js"
|
|
1064
|
+
},
|
|
1065
|
+
require: {
|
|
1066
|
+
types: "./dist/node/index.d.cts",
|
|
1067
|
+
default: "./dist/node/index.cjs"
|
|
1068
|
+
}
|
|
1069
|
+
},
|
|
1070
|
+
"./package.json": "./package.json"
|
|
1071
|
+
},
|
|
1072
|
+
homepage: "https://github.com/kinotic-ai/kinotic",
|
|
1073
|
+
repository: {
|
|
1074
|
+
type: "git",
|
|
1075
|
+
url: "git+https://github.com/kinotic-ai/kinotic.git",
|
|
1076
|
+
directory: "kinotic-js/workspace/packages/core"
|
|
1077
|
+
},
|
|
1078
|
+
license: "Elastic License 2.0",
|
|
1079
|
+
publishConfig: {
|
|
1080
|
+
access: "public"
|
|
1081
|
+
},
|
|
1082
|
+
scripts: {
|
|
1083
|
+
"type-check": "tsc --noEmit",
|
|
1084
|
+
test: "vitest run",
|
|
1085
|
+
coverage: "vitest run --coverage",
|
|
1086
|
+
"ui-test": "vitest --ui --coverage.enabled=true --mode development"
|
|
1087
|
+
},
|
|
1088
|
+
devDependencies: {
|
|
1089
|
+
"@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
|
|
1090
|
+
"@opentelemetry/resources": "^2.10.0",
|
|
1091
|
+
"@opentelemetry/sdk-metrics": "^2.10.0",
|
|
1092
|
+
"@opentelemetry/sdk-node": "^0.221.0",
|
|
1093
|
+
"@opentelemetry/sdk-trace-node": "^2.10.0",
|
|
1094
|
+
"@types/debug": "^4.1.13",
|
|
1095
|
+
"@types/node": "^25.6.0",
|
|
1096
|
+
"@types/ws": "^8.18.0",
|
|
1097
|
+
"@vitest/coverage-v8": "^4.1.4",
|
|
1098
|
+
"@vitest/runner": "^4.1.4",
|
|
1099
|
+
"@vitest/ui": "^4.1.4",
|
|
1100
|
+
allure: "^3.14.3",
|
|
1101
|
+
"allure-vitest": "^3.10.2",
|
|
1102
|
+
dotenv: "^17.4.1",
|
|
1103
|
+
"properties-file": "^4.0.0",
|
|
1104
|
+
testcontainers: "^11.14.0",
|
|
1105
|
+
tslib: "^2.8.1",
|
|
1106
|
+
typescript: "^6.0.2",
|
|
1107
|
+
vitest: "^4.1.4"
|
|
1108
|
+
},
|
|
1109
|
+
dependencies: {
|
|
1110
|
+
"@opentelemetry/api": "^1.9.1",
|
|
1111
|
+
"@opentelemetry/semantic-conventions": "^1.40.0",
|
|
1112
|
+
"@stomp/rx-stomp": "^2.4.0",
|
|
1113
|
+
"@stomp/stompjs": "^7.3.0",
|
|
1114
|
+
debug: "^4.4.3",
|
|
1115
|
+
"p-tap": "^4.0.0",
|
|
1116
|
+
rxjs: "^7.8.2",
|
|
1117
|
+
"typescript-optional": "3.0.0-alpha.3",
|
|
1118
|
+
uuid: "^13.0.0",
|
|
1119
|
+
ws: "^8.21.0"
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
|
|
864
1123
|
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
865
1124
|
class ServiceInvocationSupervisor {
|
|
866
1125
|
log;
|
|
@@ -872,7 +1131,10 @@ class ServiceInvocationSupervisor {
|
|
|
872
1131
|
serviceIdentifier;
|
|
873
1132
|
serviceInstance;
|
|
874
1133
|
methodSubscription = null;
|
|
1134
|
+
unscopedSubscription = null;
|
|
875
1135
|
methodMap;
|
|
1136
|
+
scopeOptionalMethods;
|
|
1137
|
+
tracer;
|
|
876
1138
|
constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
|
|
877
1139
|
if (!serviceIdentifier)
|
|
878
1140
|
throw new Error("ServiceIdentifier must not be null");
|
|
@@ -886,10 +1148,12 @@ class ServiceInvocationSupervisor {
|
|
|
886
1148
|
this.serviceInstance = serviceInstance;
|
|
887
1149
|
this._eventBus = eventBusService;
|
|
888
1150
|
this.interceptorProvider = interceptorProvider;
|
|
889
|
-
this.log = options.logger || createDebugLogger("
|
|
1151
|
+
this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
|
|
890
1152
|
this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
|
|
891
1153
|
this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
|
|
892
1154
|
this.methodMap = this.buildMethodMap(serviceInstance);
|
|
1155
|
+
this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
|
|
1156
|
+
this.tracer = opentelemetry.trace.getTracer(package_default.name, package_default.version);
|
|
893
1157
|
}
|
|
894
1158
|
isActive() {
|
|
895
1159
|
return this.active;
|
|
@@ -909,7 +1173,16 @@ class ServiceInvocationSupervisor {
|
|
|
909
1173
|
}
|
|
910
1174
|
this.active = true;
|
|
911
1175
|
const criBase = this.serviceIdentifier.cri().baseResource();
|
|
912
|
-
this.methodSubscription = this.
|
|
1176
|
+
this.methodSubscription = this.subscribeAt(criBase);
|
|
1177
|
+
this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
|
|
1178
|
+
if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
|
|
1179
|
+
const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
|
|
1180
|
+
this.unscopedSubscription = this.subscribeAt(unscopedBase);
|
|
1181
|
+
this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
subscribeAt(criBase) {
|
|
1185
|
+
return this._eventBus.observe(criBase).subscribe({
|
|
913
1186
|
next: async (event) => {
|
|
914
1187
|
await this.processEvent(event);
|
|
915
1188
|
},
|
|
@@ -922,7 +1195,6 @@ class ServiceInvocationSupervisor {
|
|
|
922
1195
|
this.active = false;
|
|
923
1196
|
}
|
|
924
1197
|
});
|
|
925
|
-
this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
|
|
926
1198
|
}
|
|
927
1199
|
stop() {
|
|
928
1200
|
if (!this.active) {
|
|
@@ -931,6 +1203,8 @@ class ServiceInvocationSupervisor {
|
|
|
931
1203
|
this.active = false;
|
|
932
1204
|
this.methodSubscription?.unsubscribe();
|
|
933
1205
|
this.methodSubscription = null;
|
|
1206
|
+
this.unscopedSubscription?.unsubscribe();
|
|
1207
|
+
this.unscopedSubscription = null;
|
|
934
1208
|
this.log.info("ServiceInvocationSupervisor stopped");
|
|
935
1209
|
}
|
|
936
1210
|
buildMethodMap(serviceInstance) {
|
|
@@ -973,7 +1247,8 @@ class ServiceInvocationSupervisor {
|
|
|
973
1247
|
this.log.trace(`Processing control event for correlationId: ${correlationId}`);
|
|
974
1248
|
}
|
|
975
1249
|
async processInvocationRequest(event) {
|
|
976
|
-
const
|
|
1250
|
+
const incomingCri = createCRI(event.cri);
|
|
1251
|
+
const path = incomingCri.path();
|
|
977
1252
|
if (!path) {
|
|
978
1253
|
throw new Error("The methodId must not be blank");
|
|
979
1254
|
}
|
|
@@ -981,49 +1256,94 @@ class ServiceInvocationSupervisor {
|
|
|
981
1256
|
if (!handlerMethod) {
|
|
982
1257
|
throw new Error(`No method resolved for methodId ${path}`);
|
|
983
1258
|
}
|
|
1259
|
+
if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
|
|
1260
|
+
throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
|
|
1261
|
+
}
|
|
984
1262
|
const methodName = path;
|
|
985
|
-
const
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1263
|
+
const span = this.startInvocationSpan(event, methodName);
|
|
1264
|
+
try {
|
|
1265
|
+
const args = this.argumentResolver.resolveArguments(event);
|
|
1266
|
+
const injectContext = receivesContext(this.serviceInstance, methodName);
|
|
1267
|
+
let serviceContext = {};
|
|
1268
|
+
const interceptor = this.interceptorProvider();
|
|
1269
|
+
if (interceptor) {
|
|
1270
|
+
try {
|
|
1271
|
+
serviceContext = await interceptor.intercept(event, serviceContext);
|
|
1272
|
+
} catch (e) {
|
|
1273
|
+
this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
|
|
1274
|
+
this.handleException(event, new Error("Internal server error"));
|
|
1275
|
+
this.failSpan(span, e);
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
if (injectContext) {
|
|
1280
|
+
args.push(serviceContext);
|
|
1281
|
+
}
|
|
1282
|
+
const expectedArgsCount = handlerMethod.length;
|
|
1283
|
+
if (args.length !== expectedArgsCount) {
|
|
1284
|
+
throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
|
|
1285
|
+
}
|
|
1286
|
+
let result;
|
|
990
1287
|
try {
|
|
991
|
-
|
|
1288
|
+
result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
|
|
1289
|
+
if (result instanceof Promise) {
|
|
1290
|
+
result.then((resolved) => {
|
|
1291
|
+
this.processMethodInvocationResult(event, resolved);
|
|
1292
|
+
span.end();
|
|
1293
|
+
}, (error) => {
|
|
1294
|
+
this.handleException(event, error);
|
|
1295
|
+
this.failSpan(span, error);
|
|
1296
|
+
});
|
|
1297
|
+
} else {
|
|
1298
|
+
this.processMethodInvocationResult(event, result);
|
|
1299
|
+
span.end();
|
|
1300
|
+
}
|
|
992
1301
|
} catch (e) {
|
|
993
|
-
this.
|
|
994
|
-
this.
|
|
995
|
-
return;
|
|
1302
|
+
this.handleException(event, e);
|
|
1303
|
+
this.failSpan(span, e);
|
|
996
1304
|
}
|
|
1305
|
+
} catch (e) {
|
|
1306
|
+
this.failSpan(span, e);
|
|
1307
|
+
throw e;
|
|
997
1308
|
}
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
}
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
|
|
1309
|
+
}
|
|
1310
|
+
startInvocationSpan(event, methodName) {
|
|
1311
|
+
const carrier = {};
|
|
1312
|
+
for (const [key, value] of event.headers.entries()) {
|
|
1313
|
+
carrier[key] = value;
|
|
1004
1314
|
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1315
|
+
const serviceName = this.serviceIdentifier.qualifiedName();
|
|
1316
|
+
return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
|
|
1317
|
+
kind: SpanKind.SERVER,
|
|
1318
|
+
attributes: {
|
|
1319
|
+
"rpc.system": "kinotic",
|
|
1320
|
+
"rpc.service": serviceName,
|
|
1321
|
+
"rpc.method": methodName
|
|
1012
1322
|
}
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1015
|
-
|
|
1323
|
+
}, propagation2.extract(context2.active(), carrier));
|
|
1324
|
+
}
|
|
1325
|
+
failSpan(span, error) {
|
|
1326
|
+
span.recordException(error);
|
|
1327
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1328
|
+
span.end();
|
|
1016
1329
|
}
|
|
1017
1330
|
processMethodInvocationResult(event, result) {
|
|
1018
1331
|
const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
|
|
1019
|
-
this.
|
|
1332
|
+
this.sendReply(outgoingEvent);
|
|
1333
|
+
}
|
|
1334
|
+
sendReply(event) {
|
|
1335
|
+
try {
|
|
1336
|
+
this._eventBus.send(event);
|
|
1337
|
+
} catch (e) {
|
|
1338
|
+
this.log.warn(`Could not send reply to ${event.cri}`, e);
|
|
1339
|
+
}
|
|
1020
1340
|
}
|
|
1021
1341
|
handleException(event, error) {
|
|
1022
1342
|
const errorEvent = Util.createReplyEvent(event.headers, new Map([
|
|
1023
1343
|
["error" /* ERROR_HEADER */, error.message || "Unknown error"],
|
|
1024
1344
|
["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
|
|
1025
1345
|
]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
|
|
1026
|
-
this.
|
|
1346
|
+
this.sendReply(errorEvent);
|
|
1027
1347
|
}
|
|
1028
1348
|
validateReplyTo(event) {
|
|
1029
1349
|
const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
|
|
@@ -1044,89 +1364,12 @@ class ServiceInvocationSupervisor {
|
|
|
1044
1364
|
}
|
|
1045
1365
|
|
|
1046
1366
|
// packages/core/src/api/ServiceRegistry.ts
|
|
1047
|
-
import
|
|
1367
|
+
import opentelemetry2, { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
|
|
1048
1368
|
import {
|
|
1049
1369
|
ATTR_SERVER_ADDRESS,
|
|
1050
1370
|
ATTR_SERVER_PORT
|
|
1051
1371
|
} from "@opentelemetry/semantic-conventions";
|
|
1052
1372
|
import { first, map as map2 } from "rxjs/operators";
|
|
1053
|
-
// packages/core/package.json
|
|
1054
|
-
var package_default = {
|
|
1055
|
-
name: "@kinotic-ai/core",
|
|
1056
|
-
version: "5.0.0-beta.0",
|
|
1057
|
-
type: "module",
|
|
1058
|
-
files: [
|
|
1059
|
-
"dist"
|
|
1060
|
-
],
|
|
1061
|
-
module: "./dist/index.js",
|
|
1062
|
-
main: "./dist/index.cjs",
|
|
1063
|
-
types: "./dist/index.d.ts",
|
|
1064
|
-
exports: {
|
|
1065
|
-
".": {
|
|
1066
|
-
import: {
|
|
1067
|
-
types: "./dist/index.d.ts",
|
|
1068
|
-
default: "./dist/index.js"
|
|
1069
|
-
},
|
|
1070
|
-
require: {
|
|
1071
|
-
types: "./dist/index.d.cts",
|
|
1072
|
-
default: "./dist/index.cjs"
|
|
1073
|
-
}
|
|
1074
|
-
},
|
|
1075
|
-
"./package.json": "./package.json"
|
|
1076
|
-
},
|
|
1077
|
-
homepage: "https://github.com/kinotic-ai/kinotic",
|
|
1078
|
-
license: "Elastic License 2.0",
|
|
1079
|
-
publishConfig: {
|
|
1080
|
-
access: "public"
|
|
1081
|
-
},
|
|
1082
|
-
scripts: {
|
|
1083
|
-
"type-check": "tsc --noEmit",
|
|
1084
|
-
test: "vitest run",
|
|
1085
|
-
coverage: "vitest run --coverage",
|
|
1086
|
-
"ui-test": "vitest --ui --coverage.enabled=true --mode development"
|
|
1087
|
-
},
|
|
1088
|
-
devDependencies: {
|
|
1089
|
-
"@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
|
|
1090
|
-
"@opentelemetry/resources": "^2.6.1",
|
|
1091
|
-
"@opentelemetry/sdk-metrics": "^2.6.1",
|
|
1092
|
-
"@opentelemetry/sdk-node": "^0.214.0",
|
|
1093
|
-
"@opentelemetry/sdk-trace-node": "^2.6.1",
|
|
1094
|
-
"@types/node": "^25.6.0",
|
|
1095
|
-
"@types/uuid": "^11.0.0",
|
|
1096
|
-
"@types/ws": "^8.18.1",
|
|
1097
|
-
"@vitest/coverage-v8": "^4.1.4",
|
|
1098
|
-
"@vitest/runner": "^4.1.4",
|
|
1099
|
-
"@vitest/ui": "^4.1.4",
|
|
1100
|
-
allure: "^3.4.1",
|
|
1101
|
-
"allure-vitest": "^3.7.1",
|
|
1102
|
-
dotenv: "^17.4.1",
|
|
1103
|
-
"properties-file": "^4.0.0",
|
|
1104
|
-
testcontainers: "^11.14.0",
|
|
1105
|
-
tslib: "^2.8.1",
|
|
1106
|
-
typescript: "^6.0.2",
|
|
1107
|
-
vitest: "^4.1.4",
|
|
1108
|
-
ws: "^8.20.0"
|
|
1109
|
-
},
|
|
1110
|
-
dependencies: {
|
|
1111
|
-
"@opentelemetry/api": "^1.9.1",
|
|
1112
|
-
"@opentelemetry/semantic-conventions": "^1.40.0",
|
|
1113
|
-
"@stomp/rx-stomp": "^2.4.0",
|
|
1114
|
-
"@stomp/stompjs": "^7.3.0",
|
|
1115
|
-
"@types/debug": "^4.1.13",
|
|
1116
|
-
debug: "^4.4.3",
|
|
1117
|
-
"p-tap": "^4.0.0",
|
|
1118
|
-
rxjs: "^7.8.2",
|
|
1119
|
-
"typescript-optional": "3.0.0-alpha.3",
|
|
1120
|
-
uuid: "^13.0.0"
|
|
1121
|
-
},
|
|
1122
|
-
peerDependenciesMeta: {
|
|
1123
|
-
typescript: {
|
|
1124
|
-
optional: true
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
};
|
|
1128
|
-
|
|
1129
|
-
// packages/core/src/api/ServiceRegistry.ts
|
|
1130
1373
|
class JsonEventFactory {
|
|
1131
1374
|
create(cri, args) {
|
|
1132
1375
|
const event = new Event(cri);
|
|
@@ -1165,7 +1408,7 @@ class ServiceRegistry {
|
|
|
1165
1408
|
_eventBus;
|
|
1166
1409
|
supervisors = new Map;
|
|
1167
1410
|
contextInterceptor = null;
|
|
1168
|
-
debugLogger = debug3("
|
|
1411
|
+
debugLogger = debug3("kinotic:serviceRegistry");
|
|
1169
1412
|
constructor(eventBus) {
|
|
1170
1413
|
this._eventBus = eventBus;
|
|
1171
1414
|
}
|
|
@@ -1215,16 +1458,16 @@ class ServiceProxy {
|
|
|
1215
1458
|
}
|
|
1216
1459
|
this.serviceIdentifier = serviceIdentifier;
|
|
1217
1460
|
this.serviceRegistry = serviceRegistry;
|
|
1218
|
-
this.tracer =
|
|
1461
|
+
this.tracer = opentelemetry2.trace.getTracer(package_default.name, package_default.version);
|
|
1219
1462
|
}
|
|
1220
1463
|
invoke(methodIdentifier, args, scope, eventFactory) {
|
|
1221
1464
|
return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
|
|
1222
|
-
kind:
|
|
1465
|
+
kind: SpanKind2.CLIENT
|
|
1223
1466
|
}, async (span) => {
|
|
1224
1467
|
if (scope) {
|
|
1225
|
-
span.setAttribute("
|
|
1468
|
+
span.setAttribute("kinotic.scope", scope);
|
|
1226
1469
|
}
|
|
1227
|
-
span.setAttribute("rpc.system", "
|
|
1470
|
+
span.setAttribute("rpc.system", "kinotic");
|
|
1228
1471
|
span.setAttribute("rpc.service", this.serviceIdentifier);
|
|
1229
1472
|
span.setAttribute("rpc.method", methodIdentifier);
|
|
1230
1473
|
return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(first()).toPromise().then(async (value) => {
|
|
@@ -1232,7 +1475,7 @@ class ServiceProxy {
|
|
|
1232
1475
|
return value;
|
|
1233
1476
|
}, async (ex) => {
|
|
1234
1477
|
span.recordException(ex);
|
|
1235
|
-
span.setStatus({ code:
|
|
1478
|
+
span.setStatus({ code: SpanStatusCode2.ERROR });
|
|
1236
1479
|
span.end();
|
|
1237
1480
|
throw ex;
|
|
1238
1481
|
});
|
|
@@ -1248,7 +1491,7 @@ class ServiceProxy {
|
|
|
1248
1491
|
eventFactoryToUse = eventFactory;
|
|
1249
1492
|
}
|
|
1250
1493
|
let eventBusToUse = this.serviceRegistry.eventBus;
|
|
1251
|
-
const span =
|
|
1494
|
+
const span = opentelemetry2.trace.getActiveSpan();
|
|
1252
1495
|
if (span) {
|
|
1253
1496
|
span.setAttribute(ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
|
|
1254
1497
|
span.setAttribute(ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
|
|
@@ -1290,8 +1533,8 @@ class KinoticSingleton {
|
|
|
1290
1533
|
this._eventBus = eventBus;
|
|
1291
1534
|
this.serviceRegistry.eventBus = eventBus;
|
|
1292
1535
|
}
|
|
1293
|
-
connect(
|
|
1294
|
-
return this._eventBus.connect(
|
|
1536
|
+
connect(options) {
|
|
1537
|
+
return this._eventBus.connect(Util.resolveConnectOptions(options));
|
|
1295
1538
|
}
|
|
1296
1539
|
disconnect(force) {
|
|
1297
1540
|
return this._eventBus.disconnect(force);
|
|
@@ -1305,6 +1548,21 @@ class KinoticSingleton {
|
|
|
1305
1548
|
}
|
|
1306
1549
|
}
|
|
1307
1550
|
var Kinotic = new KinoticSingleton;
|
|
1551
|
+
// packages/core/src/api/UiVersionUtil.ts
|
|
1552
|
+
async function checkUiVersion(builtCommit, versionUrl = "/version.json") {
|
|
1553
|
+
if (!builtCommit) {
|
|
1554
|
+
throw new Error("builtCommit is required");
|
|
1555
|
+
}
|
|
1556
|
+
let servedCommit = null;
|
|
1557
|
+
try {
|
|
1558
|
+
const response = await fetch(versionUrl, { cache: "no-store" });
|
|
1559
|
+
if (response.ok) {
|
|
1560
|
+
const body = await response.json();
|
|
1561
|
+
servedCommit = typeof body.commitSha === "string" && body.commitSha.length > 0 ? body.commitSha : null;
|
|
1562
|
+
}
|
|
1563
|
+
} catch {}
|
|
1564
|
+
return { stale: servedCommit !== null && servedCommit !== builtCommit, servedCommit };
|
|
1565
|
+
}
|
|
1308
1566
|
// packages/core/src/api/crud/AbstractIterablePage.ts
|
|
1309
1567
|
class AbstractIterablePage {
|
|
1310
1568
|
pageable;
|
|
@@ -1412,6 +1670,9 @@ class CrudServiceProxy {
|
|
|
1412
1670
|
deleteById(id) {
|
|
1413
1671
|
return this.serviceProxy.invoke("deleteById", [id]);
|
|
1414
1672
|
}
|
|
1673
|
+
deleteByIdSync(id) {
|
|
1674
|
+
return this.serviceProxy.invoke("deleteByIdSync", [id]);
|
|
1675
|
+
}
|
|
1415
1676
|
async findAll(pageable) {
|
|
1416
1677
|
const page = await this.findAllSinglePage(pageable);
|
|
1417
1678
|
return new FindAllIterablePage(pageable, page, this);
|
|
@@ -1534,41 +1795,6 @@ class Order {
|
|
|
1534
1795
|
class Sort {
|
|
1535
1796
|
orders = [];
|
|
1536
1797
|
}
|
|
1537
|
-
// packages/core/src/api/security/AuthenticatedWebSocketFactory.ts
|
|
1538
|
-
function createAuthenticatedWebSocketFactory(serverInfo, authProvider) {
|
|
1539
|
-
const brokerUrl = Util.buildBrokerUrl(serverInfo);
|
|
1540
|
-
return async () => {
|
|
1541
|
-
const headers = await authProvider.getAuthHeaders();
|
|
1542
|
-
const WS = WebSocket;
|
|
1543
|
-
return new WS(brokerUrl, { headers });
|
|
1544
|
-
};
|
|
1545
|
-
}
|
|
1546
|
-
// packages/core/src/api/security/BasicAuthProvider.ts
|
|
1547
|
-
class BasicAuthProvider {
|
|
1548
|
-
authHeader;
|
|
1549
|
-
constructor(login, passcode) {
|
|
1550
|
-
const bytes = new TextEncoder().encode(`${login}:${passcode}`);
|
|
1551
|
-
let binary = "";
|
|
1552
|
-
for (const byte of bytes) {
|
|
1553
|
-
binary += String.fromCharCode(byte);
|
|
1554
|
-
}
|
|
1555
|
-
this.authHeader = `Basic ${btoa(binary)}`;
|
|
1556
|
-
}
|
|
1557
|
-
getAuthHeaders() {
|
|
1558
|
-
return { Authorization: this.authHeader };
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
// packages/core/src/api/security/BearerTokenAuthProvider.ts
|
|
1562
|
-
class BearerTokenAuthProvider {
|
|
1563
|
-
token;
|
|
1564
|
-
constructor(token) {
|
|
1565
|
-
this.token = token;
|
|
1566
|
-
}
|
|
1567
|
-
async getAuthHeaders() {
|
|
1568
|
-
const token = typeof this.token === "function" ? await this.token() : this.token;
|
|
1569
|
-
return { Authorization: `Bearer ${token}` };
|
|
1570
|
-
}
|
|
1571
|
-
}
|
|
1572
1798
|
// packages/core/src/api/security/ConnectedInfo.ts
|
|
1573
1799
|
class ConnectedInfo {
|
|
1574
1800
|
replyToId;
|
|
@@ -1577,26 +1803,30 @@ class ConnectedInfo {
|
|
|
1577
1803
|
// packages/core/src/api/security/ParticipantConstants.ts
|
|
1578
1804
|
class ParticipantConstants {
|
|
1579
1805
|
static PARTICIPANT_TYPE_METADATA_KEY = "type";
|
|
1580
|
-
static PARTICIPANT_TYPE_DEVICE = "device";
|
|
1581
|
-
static PARTICIPANT_TYPE_CLI = "cli";
|
|
1582
1806
|
static PARTICIPANT_TYPE_USER = "user";
|
|
1583
|
-
static
|
|
1807
|
+
static PARTICIPANT_TYPE_DELEGATE = "delegate";
|
|
1808
|
+
static PARTICIPANT_TYPE_MACHINE = "machine";
|
|
1584
1809
|
static CLI_PARTICIPANT_ID = "-42-Kinotic-CLI-42-";
|
|
1585
1810
|
}
|
|
1586
1811
|
export {
|
|
1587
1812
|
validateZone,
|
|
1588
1813
|
validateLabel,
|
|
1814
|
+
scopeOptionalMethodNames,
|
|
1589
1815
|
receivesContext,
|
|
1590
1816
|
isAdvertised,
|
|
1591
1817
|
createCRI,
|
|
1592
|
-
|
|
1818
|
+
checkUiVersion,
|
|
1819
|
+
buildServerUrl,
|
|
1820
|
+
buildBrokerUrl,
|
|
1593
1821
|
Zone,
|
|
1594
1822
|
Version,
|
|
1595
1823
|
TextEventFactory,
|
|
1596
1824
|
Sort,
|
|
1597
1825
|
SessionKeepAliveMode,
|
|
1826
|
+
SessionCredentialsResolver,
|
|
1598
1827
|
ServiceRegistry,
|
|
1599
1828
|
ServerInfo,
|
|
1829
|
+
ScopeOptional,
|
|
1600
1830
|
Scope,
|
|
1601
1831
|
Publish,
|
|
1602
1832
|
ParticipantConstants,
|
|
@@ -1611,6 +1841,7 @@ export {
|
|
|
1611
1841
|
EventConstants,
|
|
1612
1842
|
EventBus,
|
|
1613
1843
|
Event,
|
|
1844
|
+
EnvCredentialsResolver,
|
|
1614
1845
|
Direction,
|
|
1615
1846
|
DefaultCRI,
|
|
1616
1847
|
DataSourceUtils,
|
|
@@ -1618,9 +1849,9 @@ export {
|
|
|
1618
1849
|
CrudServiceProxyFactory,
|
|
1619
1850
|
CrudServiceProxy,
|
|
1620
1851
|
Context,
|
|
1621
|
-
ConnectionInfo,
|
|
1622
1852
|
ConnectedInfo,
|
|
1623
|
-
|
|
1624
|
-
|
|
1853
|
+
ChainedCredentialsResolver,
|
|
1854
|
+
BearerCredentialsResolver,
|
|
1855
|
+
BasicCredentialsResolver,
|
|
1625
1856
|
AbstractIterablePage
|
|
1626
1857
|
};
|