@kinotic-ai/core 5.0.0-beta.1 → 5.0.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.cjs +853 -399
- package/dist/index.d.cts +201 -69
- package/dist/index.d.ts +201 -69
- package/dist/index.js +851 -397
- 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.cjs
CHANGED
|
@@ -66,18 +66,23 @@ var exports_src = {};
|
|
|
66
66
|
__export(exports_src, {
|
|
67
67
|
validateZone: () => validateZone,
|
|
68
68
|
validateLabel: () => validateLabel,
|
|
69
|
+
scopeOptionalMethodNames: () => scopeOptionalMethodNames,
|
|
69
70
|
receivesContext: () => receivesContext,
|
|
70
71
|
isAdvertised: () => isAdvertised,
|
|
71
72
|
createCRI: () => createCRI,
|
|
72
|
-
|
|
73
|
+
buildServerUrl: () => buildServerUrl,
|
|
74
|
+
buildBrokerUrl: () => buildBrokerUrl,
|
|
73
75
|
Zone: () => Zone,
|
|
74
76
|
Version: () => Version,
|
|
75
77
|
TextEventFactory: () => TextEventFactory,
|
|
76
78
|
Sort: () => Sort,
|
|
77
79
|
SessionKeepAliveMode: () => SessionKeepAliveMode,
|
|
80
|
+
SessionCredentialsResolver: () => SessionCredentialsResolver,
|
|
78
81
|
ServiceRegistry: () => ServiceRegistry,
|
|
79
82
|
ServerInfo: () => ServerInfo,
|
|
83
|
+
ScopeOptional: () => ScopeOptional,
|
|
80
84
|
Scope: () => Scope,
|
|
85
|
+
RpcError: () => RpcError,
|
|
81
86
|
Publish: () => Publish,
|
|
82
87
|
ParticipantConstants: () => ParticipantConstants,
|
|
83
88
|
Pageable: () => Pageable,
|
|
@@ -91,6 +96,7 @@ __export(exports_src, {
|
|
|
91
96
|
EventConstants: () => EventConstants,
|
|
92
97
|
EventBus: () => EventBus,
|
|
93
98
|
Event: () => Event,
|
|
99
|
+
EnvCredentialsResolver: () => EnvCredentialsResolver,
|
|
94
100
|
Direction: () => Direction,
|
|
95
101
|
DefaultCRI: () => DefaultCRI,
|
|
96
102
|
DataSourceUtils: () => DataSourceUtils,
|
|
@@ -98,32 +104,32 @@ __export(exports_src, {
|
|
|
98
104
|
CrudServiceProxyFactory: () => CrudServiceProxyFactory,
|
|
99
105
|
CrudServiceProxy: () => CrudServiceProxy,
|
|
100
106
|
Context: () => Context,
|
|
101
|
-
ConnectionInfo: () => ConnectionInfo,
|
|
102
107
|
ConnectedInfo: () => ConnectedInfo,
|
|
103
|
-
|
|
104
|
-
|
|
108
|
+
ChainedCredentialsResolver: () => ChainedCredentialsResolver,
|
|
109
|
+
BearerCredentialsResolver: () => BearerCredentialsResolver,
|
|
110
|
+
BasicCredentialsResolver: () => BasicCredentialsResolver,
|
|
105
111
|
AbstractIterablePage: () => AbstractIterablePage
|
|
106
112
|
});
|
|
107
113
|
module.exports = __toCommonJS(exports_src);
|
|
108
114
|
|
|
109
|
-
// packages/core/src/api/
|
|
115
|
+
// packages/core/src/api/ConnectOptions.ts
|
|
110
116
|
class ServerInfo {
|
|
111
117
|
host;
|
|
112
118
|
port;
|
|
113
119
|
useSSL;
|
|
114
120
|
}
|
|
121
|
+
function buildServerUrl(server, scheme) {
|
|
122
|
+
return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
|
|
123
|
+
}
|
|
124
|
+
function buildBrokerUrl(server) {
|
|
125
|
+
return buildServerUrl(server, "ws") + "/v1";
|
|
126
|
+
}
|
|
115
127
|
var SessionKeepAliveMode;
|
|
116
128
|
((SessionKeepAliveMode2) => {
|
|
117
129
|
SessionKeepAliveMode2["NONE"] = "NONE";
|
|
118
130
|
SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
|
|
119
131
|
SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
|
|
120
132
|
})(SessionKeepAliveMode ||= {});
|
|
121
|
-
|
|
122
|
-
class ConnectionInfo extends ServerInfo {
|
|
123
|
-
webSocketFactory;
|
|
124
|
-
maxConnectionAttempts;
|
|
125
|
-
sessionKeepAlive = "ACTIVITY" /* ACTIVITY */;
|
|
126
|
-
}
|
|
127
133
|
// packages/core/src/api/event/IEventBus.ts
|
|
128
134
|
var EventConstants;
|
|
129
135
|
((EventConstants2) => {
|
|
@@ -154,134 +160,173 @@ var EventConstants;
|
|
|
154
160
|
EventConstants2["TRACESTATE_HEADER"] = "tracestate";
|
|
155
161
|
})(EventConstants ||= {});
|
|
156
162
|
|
|
157
|
-
// packages/core/src/internal/api/
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
for (const [key, value] of incomingHeaders) {
|
|
169
|
-
if (key.startsWith("__")) {
|
|
170
|
-
newHeaders.set(key, value);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
if (headers) {
|
|
174
|
-
for (const [key, value] of headers) {
|
|
175
|
-
newHeaders.set(key, value);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
return new Event(replyCRI, newHeaders, body || undefined);
|
|
179
|
-
}
|
|
180
|
-
static buildBrokerUrl(serverInfo) {
|
|
181
|
-
return "ws" + (serverInfo.useSSL ? "s" : "") + "://" + serverInfo.host + (serverInfo.port ? ":" + serverInfo.port : "") + "/v1";
|
|
182
|
-
}
|
|
163
|
+
// packages/core/src/internal/api/Logger.ts
|
|
164
|
+
var import_debug = __toESM(require("debug"));
|
|
165
|
+
function createDebugLogger(namespace) {
|
|
166
|
+
const debugLogger = import_debug.default(namespace);
|
|
167
|
+
return {
|
|
168
|
+
trace: (...args) => debugLogger("TRACE", ...args),
|
|
169
|
+
debug: (...args) => debugLogger("DEBUG", ...args),
|
|
170
|
+
info: (...args) => debugLogger("INFO", ...args),
|
|
171
|
+
warn: (...args) => debugLogger("WARN", ...args),
|
|
172
|
+
error: (...args) => debugLogger("ERROR", ...args)
|
|
173
|
+
};
|
|
183
174
|
}
|
|
184
175
|
|
|
185
176
|
// packages/core/src/internal/api/StompConnectionManager.ts
|
|
186
177
|
var import_rx_stomp = require("@stomp/rx-stomp");
|
|
187
178
|
var import_stompjs = require("@stomp/stompjs");
|
|
188
|
-
var
|
|
179
|
+
var import_debug2 = __toESM(require("debug"));
|
|
189
180
|
var import_rxjs = require("rxjs");
|
|
181
|
+
var import_operators = require("rxjs/operators");
|
|
190
182
|
var import_uuid = require("uuid");
|
|
183
|
+
|
|
184
|
+
// packages/core/src/internal/api/StompActivation.ts
|
|
185
|
+
class StompActivation {
|
|
186
|
+
_ended = false;
|
|
187
|
+
wake = null;
|
|
188
|
+
preparedSocket = null;
|
|
189
|
+
attempt = null;
|
|
190
|
+
failPending = null;
|
|
191
|
+
subscriptions = [];
|
|
192
|
+
get ended() {
|
|
193
|
+
return this._ended;
|
|
194
|
+
}
|
|
195
|
+
end() {
|
|
196
|
+
this._ended = true;
|
|
197
|
+
this.wake?.();
|
|
198
|
+
this.wake = null;
|
|
199
|
+
}
|
|
200
|
+
delay(ms) {
|
|
201
|
+
return new Promise((resolve) => {
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
this.wake = null;
|
|
204
|
+
resolve();
|
|
205
|
+
}, ms);
|
|
206
|
+
this.wake = () => {
|
|
207
|
+
clearTimeout(timer);
|
|
208
|
+
resolve();
|
|
209
|
+
};
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
own(subscription) {
|
|
213
|
+
this.subscriptions.push(subscription);
|
|
214
|
+
}
|
|
215
|
+
pending(fail) {
|
|
216
|
+
this.failPending = fail;
|
|
217
|
+
}
|
|
218
|
+
established() {
|
|
219
|
+
this.failPending = null;
|
|
220
|
+
}
|
|
221
|
+
failIfPending(reason) {
|
|
222
|
+
const fail = this.failPending;
|
|
223
|
+
this.failPending = null;
|
|
224
|
+
fail?.(reason);
|
|
225
|
+
}
|
|
226
|
+
unsubscribeAll() {
|
|
227
|
+
for (const subscription of this.subscriptions) {
|
|
228
|
+
subscription.unsubscribe();
|
|
229
|
+
}
|
|
230
|
+
this.subscriptions.length = 0;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// packages/core/src/internal/api/StompConnectionManager.ts
|
|
191
235
|
var SESSION_CHECK_PATH = "/api/auth/me";
|
|
192
236
|
|
|
193
237
|
class StompConnectionManager {
|
|
194
238
|
lastWebsocketError = null;
|
|
195
239
|
maxConnectionAttemptsReached = false;
|
|
196
|
-
|
|
197
|
-
rxStomp =
|
|
240
|
+
connectionLostHandler = null;
|
|
241
|
+
rxStomp = new import_rx_stomp.RxStomp;
|
|
242
|
+
activation = null;
|
|
243
|
+
teardown = null;
|
|
198
244
|
INITIAL_RECONNECT_DELAY = 2000;
|
|
199
245
|
JITTER_MAX = 5000;
|
|
200
246
|
MAX_RECONNECT_DELAY = 120000;
|
|
201
247
|
connectionAttempts = 0;
|
|
202
|
-
debugLogger =
|
|
248
|
+
debugLogger = import_debug2.default("kinotic:stomp");
|
|
203
249
|
fatalErrorsSubject = new import_rxjs.Subject;
|
|
204
250
|
_fatalErrors = this.fatalErrorsSubject.asObservable();
|
|
205
251
|
initialConnectionSuccessful = false;
|
|
206
|
-
|
|
207
|
-
stompErrorsSubscription = null;
|
|
208
|
-
uuidv4 = import_uuid.v4();
|
|
252
|
+
rxStompHasConnected = false;
|
|
209
253
|
_replyToCri = null;
|
|
210
254
|
get replyToCri() {
|
|
211
255
|
return this._replyToCri;
|
|
212
256
|
}
|
|
213
257
|
get active() {
|
|
214
|
-
return
|
|
258
|
+
return this.activation !== null;
|
|
215
259
|
}
|
|
216
260
|
get connected() {
|
|
217
|
-
return this.
|
|
261
|
+
return this.activation !== null && this.rxStomp.connected();
|
|
218
262
|
}
|
|
219
263
|
get fatalErrors() {
|
|
220
264
|
return this._fatalErrors;
|
|
221
265
|
}
|
|
222
|
-
activate(
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
266
|
+
async activate(options) {
|
|
267
|
+
if (!options?.server?.host) {
|
|
268
|
+
throw new Error("No host provided");
|
|
269
|
+
}
|
|
270
|
+
if (this.activation) {
|
|
271
|
+
throw new Error("Stomp connection already active");
|
|
272
|
+
}
|
|
273
|
+
await this.teardown;
|
|
274
|
+
if (this.activation) {
|
|
275
|
+
throw new Error("Stomp connection already active");
|
|
276
|
+
}
|
|
277
|
+
const server = options.server;
|
|
278
|
+
const credentialsResolver = options.credentials;
|
|
279
|
+
const activation = new StompActivation;
|
|
280
|
+
this.activation = activation;
|
|
281
|
+
let headerAuth = false;
|
|
282
|
+
try {
|
|
283
|
+
if (!options.webSocketFactory) {
|
|
284
|
+
if (!credentialsResolver) {
|
|
285
|
+
throw new Error("No credentials supplied and no default resolution applied");
|
|
286
|
+
}
|
|
287
|
+
const resolved = await credentialsResolver.resolve(server);
|
|
288
|
+
if (resolved === null) {
|
|
289
|
+
throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
|
|
290
|
+
}
|
|
291
|
+
headerAuth = resolved.authHeaders != null;
|
|
227
292
|
}
|
|
228
|
-
if (
|
|
229
|
-
|
|
230
|
-
return;
|
|
293
|
+
if (activation.ended) {
|
|
294
|
+
throw new Error("Deactivated before the connection was established");
|
|
231
295
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
296
|
+
} catch (e) {
|
|
297
|
+
if (this.activation === activation) {
|
|
298
|
+
this.activation = null;
|
|
235
299
|
}
|
|
300
|
+
throw e;
|
|
301
|
+
}
|
|
302
|
+
return new Promise((resolve, reject) => {
|
|
236
303
|
this.connectionAttempts = 0;
|
|
237
304
|
this.initialConnectionSuccessful = false;
|
|
238
305
|
this.lastWebsocketError = null;
|
|
239
306
|
this.maxConnectionAttemptsReached = false;
|
|
240
|
-
const url =
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
307
|
+
const url = buildBrokerUrl(server);
|
|
308
|
+
const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
|
|
309
|
+
const takePreparedSocket = () => {
|
|
310
|
+
const socket = activation.preparedSocket;
|
|
311
|
+
activation.preparedSocket = null;
|
|
312
|
+
return socket;
|
|
313
|
+
};
|
|
244
314
|
const stompConfig = {
|
|
245
315
|
brokerURL: url,
|
|
246
316
|
connectHeaders: {
|
|
247
|
-
["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]:
|
|
317
|
+
["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
|
|
248
318
|
},
|
|
249
|
-
heartbeatIncoming:
|
|
319
|
+
heartbeatIncoming: 30000,
|
|
250
320
|
heartbeatOutgoing: 30000,
|
|
251
321
|
reconnectDelay: this.INITIAL_RECONNECT_DELAY,
|
|
252
322
|
maxReconnectDelay: this.MAX_RECONNECT_DELAY,
|
|
253
323
|
reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
|
|
254
|
-
webSocketFactory:
|
|
255
|
-
beforeConnect:
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
if (res.status === 401) {
|
|
261
|
-
await this.signalFatal(new Error("Authentication required"));
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
} catch {}
|
|
265
|
-
}
|
|
266
|
-
if (connectionInfo?.maxConnectionAttempts) {
|
|
267
|
-
this.connectionAttempts++;
|
|
268
|
-
if (this.connectionAttempts > connectionInfo.maxConnectionAttempts) {
|
|
269
|
-
this.maxConnectionAttemptsReached = true;
|
|
270
|
-
await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
|
|
271
|
-
return;
|
|
272
|
-
} else {
|
|
273
|
-
await this.connectionJitterDelay();
|
|
274
|
-
}
|
|
275
|
-
} else {
|
|
276
|
-
await this.connectionJitterDelay();
|
|
277
|
-
}
|
|
278
|
-
if (userWebSocketFactory) {
|
|
279
|
-
try {
|
|
280
|
-
preparedSocket = await userWebSocketFactory();
|
|
281
|
-
} catch (e) {
|
|
282
|
-
await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
|
|
283
|
-
}
|
|
284
|
-
}
|
|
324
|
+
webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
|
|
325
|
+
beforeConnect: () => {
|
|
326
|
+
const attempt = this.prepareAttempt(activation, options, server, headerAuth);
|
|
327
|
+
const settled = () => new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
328
|
+
activation.attempt = attempt.then(settled, settled);
|
|
329
|
+
return attempt;
|
|
285
330
|
}
|
|
286
331
|
};
|
|
287
332
|
if (this.debugLogger.enabled) {
|
|
@@ -290,89 +335,198 @@ class StompConnectionManager {
|
|
|
290
335
|
};
|
|
291
336
|
}
|
|
292
337
|
this.rxStomp.configure(stompConfig);
|
|
293
|
-
this.rxStomp.webSocketErrors$.subscribe((value) => {
|
|
338
|
+
activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
|
|
294
339
|
this.lastWebsocketError = value;
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
|
|
299
|
-
});
|
|
300
|
-
const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
|
|
301
|
-
connectedSubscription.unsubscribe();
|
|
302
|
-
initialFailureSubscription.unsubscribe();
|
|
303
|
-
if (!this.initialConnectionSuccessful) {
|
|
304
|
-
this.initialConnectionSuccessful = true;
|
|
340
|
+
if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
|
|
341
|
+
this.maxConnectionAttemptsReached = true;
|
|
342
|
+
await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
|
|
305
343
|
}
|
|
306
|
-
});
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
344
|
+
}));
|
|
345
|
+
activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
|
|
346
|
+
const stompError = new Error(frame.headers["message"], { cause: frame });
|
|
347
|
+
await this.signalFatal(activation, new Error("STOMP connection error", { cause: stompError }));
|
|
348
|
+
}));
|
|
349
|
+
activation.own(this.rxStomp.connected$.subscribe(() => {
|
|
350
|
+
activation.established();
|
|
351
|
+
this.initialConnectionSuccessful = true;
|
|
352
|
+
this.connectionAttempts = 0;
|
|
353
|
+
}));
|
|
354
|
+
activation.pending(reject);
|
|
355
|
+
activation.own(this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
|
|
356
|
+
this.rxStompHasConnected = true;
|
|
313
357
|
const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
|
|
314
358
|
if (connectedInfoJson == null) {
|
|
315
359
|
if (!this.initialConnectionSuccessful) {
|
|
360
|
+
activation.failIfPending(new Error("Server did not return proper data for successful login"));
|
|
316
361
|
await this.deactivate();
|
|
317
|
-
reject("Server did not return proper data for successful login");
|
|
318
362
|
}
|
|
319
363
|
return;
|
|
320
364
|
}
|
|
321
365
|
const connectedInfo = JSON.parse(connectedInfoJson);
|
|
322
366
|
if (connectedInfo.replyToId == null) {
|
|
323
367
|
if (!this.initialConnectionSuccessful) {
|
|
368
|
+
activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
|
|
324
369
|
await this.deactivate();
|
|
325
|
-
reject("Server did not return a replyToId for successful login");
|
|
326
370
|
}
|
|
327
371
|
return;
|
|
328
372
|
}
|
|
329
|
-
const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" +
|
|
373
|
+
const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + import_uuid.v4() + "@kinotic.js.EventBus/replyHandler";
|
|
374
|
+
this._replyToCri = newReplyToCri;
|
|
330
375
|
if (!this.initialConnectionSuccessful) {
|
|
331
|
-
this._replyToCri = newReplyToCri;
|
|
332
376
|
resolve(connectedInfo);
|
|
333
|
-
} else if (this._replyToCri !== newReplyToCri) {
|
|
334
|
-
this._replyToCri = newReplyToCri;
|
|
335
|
-
this.replyToCriChangedHandler?.(newReplyToCri);
|
|
336
377
|
}
|
|
337
|
-
});
|
|
378
|
+
}));
|
|
379
|
+
let previousState = this.rxStomp.connectionState$.getValue();
|
|
380
|
+
activation.own(this.rxStomp.connectionState$.subscribe((state) => {
|
|
381
|
+
if (state === import_rx_stomp.RxStompState.CLOSED && previousState === import_rx_stomp.RxStompState.OPEN && this.activation === activation) {
|
|
382
|
+
this.connectionLostHandler?.();
|
|
383
|
+
}
|
|
384
|
+
previousState = state;
|
|
385
|
+
}));
|
|
338
386
|
this.rxStomp.activate();
|
|
339
387
|
});
|
|
340
388
|
}
|
|
341
|
-
async
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
389
|
+
async prepareAttempt(activation, options, server, headerAuth) {
|
|
390
|
+
const credentialsResolver = options.credentials;
|
|
391
|
+
const userWebSocketFactory = options.webSocketFactory;
|
|
392
|
+
const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
|
|
393
|
+
const url = buildBrokerUrl(server);
|
|
394
|
+
if (!usesPreparedSocket) {
|
|
395
|
+
const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
|
|
396
|
+
try {
|
|
397
|
+
const res = await fetch(sessionCheckUrl, { credentials: "include" });
|
|
398
|
+
if (res.status === 401) {
|
|
399
|
+
await this.signalFatal(activation, new Error("Authentication required"));
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
} catch (e) {
|
|
403
|
+
this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (options?.maxConnectionAttempts) {
|
|
407
|
+
this.connectionAttempts++;
|
|
408
|
+
if (this.connectionAttempts > options.maxConnectionAttempts) {
|
|
409
|
+
this.maxConnectionAttemptsReached = true;
|
|
410
|
+
await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
|
|
411
|
+
return;
|
|
412
|
+
} else {
|
|
413
|
+
await this.connectionJitterDelay(activation);
|
|
414
|
+
}
|
|
415
|
+
} else {
|
|
416
|
+
await this.connectionJitterDelay(activation);
|
|
417
|
+
}
|
|
418
|
+
if (activation.ended) {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
if (userWebSocketFactory) {
|
|
422
|
+
try {
|
|
423
|
+
activation.preparedSocket = await userWebSocketFactory();
|
|
424
|
+
} catch (e) {
|
|
425
|
+
await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
|
|
426
|
+
}
|
|
427
|
+
} else if (headerAuth) {
|
|
428
|
+
try {
|
|
429
|
+
const resolved = await credentialsResolver.resolve(server);
|
|
430
|
+
if (resolved?.authHeaders == null) {
|
|
431
|
+
await this.signalFatal(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
|
|
432
|
+
} else {
|
|
433
|
+
const WS = WebSocket;
|
|
434
|
+
activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
|
|
435
|
+
}
|
|
436
|
+
} catch (e) {
|
|
437
|
+
await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
|
|
352
438
|
}
|
|
353
439
|
}
|
|
354
|
-
|
|
440
|
+
if (activation.ended && activation.preparedSocket) {
|
|
441
|
+
activation.preparedSocket.close();
|
|
442
|
+
activation.preparedSocket = null;
|
|
443
|
+
}
|
|
355
444
|
}
|
|
356
|
-
|
|
445
|
+
deactivate(force) {
|
|
446
|
+
const activation = this.activation;
|
|
447
|
+
let ret;
|
|
448
|
+
if (activation) {
|
|
449
|
+
this.activation = null;
|
|
450
|
+
activation.end();
|
|
451
|
+
const wasOpen = this.rxStomp.connected();
|
|
452
|
+
this._replyToCri = null;
|
|
453
|
+
activation.failIfPending(new Error("Deactivated before the connection was established"));
|
|
454
|
+
activation.preparedSocket?.close();
|
|
455
|
+
activation.preparedSocket = null;
|
|
456
|
+
const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
|
|
457
|
+
activation.unsubscribeAll();
|
|
458
|
+
this.teardown = null;
|
|
459
|
+
if (wasOpen) {
|
|
460
|
+
this.connectionLostHandler?.();
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
this.teardown = teardown;
|
|
464
|
+
ret = teardown;
|
|
465
|
+
} else {
|
|
466
|
+
ret = this.teardown ?? Promise.resolve();
|
|
467
|
+
}
|
|
468
|
+
return ret;
|
|
469
|
+
}
|
|
470
|
+
async connectionJitterDelay(activation) {
|
|
357
471
|
if (this.initialConnectionSuccessful) {
|
|
358
472
|
const randomJitter = Math.random() * this.JITTER_MAX;
|
|
359
473
|
this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
|
|
360
|
-
|
|
474
|
+
await activation.delay(randomJitter);
|
|
361
475
|
}
|
|
362
476
|
}
|
|
363
|
-
async signalFatal(err) {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
477
|
+
async signalFatal(activation, err) {
|
|
478
|
+
if (!activation.ended) {
|
|
479
|
+
this.debugLogger("Fatal error, deactivating connection: %O", err);
|
|
480
|
+
activation.failIfPending(err);
|
|
481
|
+
await this.deactivate();
|
|
482
|
+
this.fatalErrorsSubject.next(err);
|
|
483
|
+
}
|
|
367
484
|
}
|
|
368
485
|
}
|
|
369
486
|
|
|
370
487
|
// packages/core/src/api/event/EventBus.ts
|
|
371
488
|
var import_api = require("@opentelemetry/api");
|
|
372
489
|
var import_rxjs2 = require("rxjs");
|
|
373
|
-
var
|
|
490
|
+
var import_operators2 = require("rxjs/operators");
|
|
374
491
|
var import_typescript_optional = require("typescript-optional");
|
|
375
492
|
var import_uuid2 = require("uuid");
|
|
493
|
+
|
|
494
|
+
// packages/core/src/api/event/RpcError.ts
|
|
495
|
+
class RpcError extends Error {
|
|
496
|
+
exceptionName;
|
|
497
|
+
exceptionClass;
|
|
498
|
+
constructor(message, exceptionName, exceptionClass) {
|
|
499
|
+
super(message);
|
|
500
|
+
this.name = "RpcError";
|
|
501
|
+
this.exceptionName = exceptionName;
|
|
502
|
+
this.exceptionClass = exceptionClass;
|
|
503
|
+
}
|
|
504
|
+
static fromEvent(reply) {
|
|
505
|
+
const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
|
|
506
|
+
let ret;
|
|
507
|
+
const detail = describedException(reply);
|
|
508
|
+
if (detail !== undefined) {
|
|
509
|
+
ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
|
|
510
|
+
} else {
|
|
511
|
+
ret = new RpcError(message, "", "");
|
|
512
|
+
}
|
|
513
|
+
return ret;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function describedException(reply) {
|
|
517
|
+
let ret = undefined;
|
|
518
|
+
if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
|
|
519
|
+
try {
|
|
520
|
+
const parsed = JSON.parse(reply.getDataString());
|
|
521
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
522
|
+
ret = parsed;
|
|
523
|
+
}
|
|
524
|
+
} catch {}
|
|
525
|
+
}
|
|
526
|
+
return ret;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// packages/core/src/api/event/EventBus.ts
|
|
376
530
|
class Event {
|
|
377
531
|
cri;
|
|
378
532
|
headers;
|
|
@@ -411,41 +565,45 @@ class Event {
|
|
|
411
565
|
|
|
412
566
|
class EventBus {
|
|
413
567
|
serverInfo = null;
|
|
568
|
+
log = createDebugLogger("kinotic:EventBus");
|
|
414
569
|
stompConnectionManager = new StompConnectionManager;
|
|
415
570
|
connectionLifecycle = Promise.resolve();
|
|
416
|
-
|
|
571
|
+
disconnectRequests = 0;
|
|
417
572
|
requestRepliesObservable = null;
|
|
418
573
|
requestRepliesSubject = null;
|
|
419
574
|
requestRepliesSubscription = null;
|
|
420
575
|
activeCorrelationIds = new Set;
|
|
421
576
|
recentlyReaped = new Set;
|
|
577
|
+
connectionLostSubject = new import_rxjs2.Subject;
|
|
422
578
|
static REAP_DEBOUNCE_MS = 5000;
|
|
423
579
|
constructor() {
|
|
424
|
-
this.stompConnectionManager.fatalErrors.subscribe(() => this.
|
|
425
|
-
this.stompConnectionManager.
|
|
426
|
-
this.
|
|
427
|
-
this.
|
|
580
|
+
this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
|
|
581
|
+
this.stompConnectionManager.connectionLostHandler = () => {
|
|
582
|
+
this.resetRequestReplies("Connection lost");
|
|
583
|
+
this.connectionLostSubject.next();
|
|
428
584
|
};
|
|
429
585
|
}
|
|
430
586
|
get fatalErrors() {
|
|
431
587
|
return this.stompConnectionManager.fatalErrors;
|
|
432
588
|
}
|
|
589
|
+
get connectionLost() {
|
|
590
|
+
return this.connectionLostSubject.asObservable();
|
|
591
|
+
}
|
|
433
592
|
isConnectionActive() {
|
|
434
593
|
return this.stompConnectionManager.active;
|
|
435
594
|
}
|
|
436
595
|
isConnected() {
|
|
437
596
|
return this.stompConnectionManager.connected;
|
|
438
597
|
}
|
|
439
|
-
connect(
|
|
598
|
+
connect(options) {
|
|
599
|
+
const disconnectsWhenQueued = this.disconnectRequests;
|
|
440
600
|
return this.serializeLifecycle(async () => {
|
|
601
|
+
if (this.disconnectRequests !== disconnectsWhenQueued) {
|
|
602
|
+
throw new Error("Disconnected before the connection was started");
|
|
603
|
+
}
|
|
441
604
|
if (!this.stompConnectionManager.active) {
|
|
442
|
-
this.
|
|
443
|
-
|
|
444
|
-
this.serverInfo = new ServerInfo;
|
|
445
|
-
this.serverInfo.host = connectionInfo.host;
|
|
446
|
-
this.serverInfo.port = connectionInfo.port;
|
|
447
|
-
this.serverInfo.useSSL = connectionInfo.useSSL;
|
|
448
|
-
this.replyToCri = this.stompConnectionManager.replyToCri;
|
|
605
|
+
const connectedInfo = await this.stompConnectionManager.activate(options);
|
|
606
|
+
this.serverInfo = { ...options.server };
|
|
449
607
|
return connectedInfo;
|
|
450
608
|
} else {
|
|
451
609
|
throw new Error("Event Bus connection already active");
|
|
@@ -453,9 +611,12 @@ class EventBus {
|
|
|
453
611
|
});
|
|
454
612
|
}
|
|
455
613
|
disconnect(force) {
|
|
614
|
+
this.disconnectRequests++;
|
|
615
|
+
const deactivated = this.stompConnectionManager.deactivate(force);
|
|
456
616
|
return this.serializeLifecycle(async () => {
|
|
617
|
+
await deactivated;
|
|
457
618
|
await this.stompConnectionManager.deactivate(force);
|
|
458
|
-
this.
|
|
619
|
+
this.serverInfo = null;
|
|
459
620
|
});
|
|
460
621
|
}
|
|
461
622
|
serializeLifecycle(operation) {
|
|
@@ -464,7 +625,7 @@ class EventBus {
|
|
|
464
625
|
return result;
|
|
465
626
|
}
|
|
466
627
|
send(event) {
|
|
467
|
-
if (this.stompConnectionManager.
|
|
628
|
+
if (this.stompConnectionManager.connected) {
|
|
468
629
|
const headers = {};
|
|
469
630
|
for (const [key, value] of event.headers.entries()) {
|
|
470
631
|
headers[key] = value;
|
|
@@ -480,7 +641,8 @@ class EventBus {
|
|
|
480
641
|
this.stompConnectionManager.rxStomp.publish({
|
|
481
642
|
destination: event.cri,
|
|
482
643
|
headers,
|
|
483
|
-
binaryBody: event.data.orUndefined()
|
|
644
|
+
binaryBody: event.data.orUndefined(),
|
|
645
|
+
retryIfDisconnected: false
|
|
484
646
|
});
|
|
485
647
|
} else {
|
|
486
648
|
throw this.createSendUnavailableError();
|
|
@@ -490,58 +652,65 @@ class EventBus {
|
|
|
490
652
|
return import_rxjs2.firstValueFrom(this.requestStream(event, false));
|
|
491
653
|
}
|
|
492
654
|
requestStream(event, sendControlEvents = true) {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
this.
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
655
|
+
return new import_rxjs2.Observable((subscriber) => {
|
|
656
|
+
const replyToCri = this.stompConnectionManager.replyToCri;
|
|
657
|
+
if (!this.stompConnectionManager.connected || replyToCri == null) {
|
|
658
|
+
subscriber.error(this.createSendUnavailableError());
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
if (this.requestRepliesObservable == null) {
|
|
662
|
+
this.requestRepliesSubject = new import_rxjs2.Subject;
|
|
663
|
+
this.requestRepliesObservable = this._observe(replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
|
|
664
|
+
this.requestRepliesSubscription = this.requestRepliesObservable.connect();
|
|
665
|
+
}
|
|
666
|
+
let serverSignaledCompletion = false;
|
|
667
|
+
let replyDestinationReset = false;
|
|
668
|
+
const correlationId = import_uuid2.v4();
|
|
669
|
+
this.activeCorrelationIds.add(correlationId);
|
|
670
|
+
subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
|
|
671
|
+
const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
|
|
672
|
+
return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
|
|
673
|
+
})).subscribe({
|
|
674
|
+
next(value) {
|
|
675
|
+
if (value.hasHeader("control" /* CONTROL_HEADER */)) {
|
|
676
|
+
if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
|
|
515
677
|
serverSignaledCompletion = true;
|
|
516
|
-
|
|
678
|
+
if (value.data.isPresent() || !sendControlEvents) {
|
|
679
|
+
subscriber.next(value);
|
|
680
|
+
}
|
|
681
|
+
subscriber.complete();
|
|
517
682
|
} else {
|
|
518
|
-
subscriber.
|
|
683
|
+
subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
|
|
519
684
|
}
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
subscriber.error(
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
subscriber.complete();
|
|
685
|
+
} else if (value.hasHeader("error" /* ERROR_HEADER */)) {
|
|
686
|
+
serverSignaledCompletion = true;
|
|
687
|
+
subscriber.error(RpcError.fromEvent(value));
|
|
688
|
+
} else {
|
|
689
|
+
subscriber.next(value);
|
|
526
690
|
}
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
691
|
+
},
|
|
692
|
+
error(err) {
|
|
693
|
+
replyDestinationReset = true;
|
|
694
|
+
subscriber.error(err);
|
|
695
|
+
},
|
|
696
|
+
complete() {
|
|
697
|
+
subscriber.complete();
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
subscriber.add(defaultMessagesSubscription);
|
|
701
|
+
event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
|
|
702
|
+
event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
703
|
+
this.send(event);
|
|
704
|
+
subscriber.add(() => {
|
|
705
|
+
if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
|
|
706
|
+
try {
|
|
707
|
+
this.sendCancel(event.cri, correlationId);
|
|
708
|
+
} catch (e) {
|
|
709
|
+
this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
|
|
539
710
|
}
|
|
540
|
-
}
|
|
711
|
+
}
|
|
541
712
|
});
|
|
542
|
-
}
|
|
543
|
-
return import_rxjs2.throwError(() => this.createSendUnavailableError());
|
|
544
|
-
}
|
|
713
|
+
});
|
|
545
714
|
}
|
|
546
715
|
listen(_serverInfo) {
|
|
547
716
|
return Promise.reject("Not implemented");
|
|
@@ -549,10 +718,6 @@ class EventBus {
|
|
|
549
718
|
observe(cri) {
|
|
550
719
|
return this._observe(cri);
|
|
551
720
|
}
|
|
552
|
-
cleanup() {
|
|
553
|
-
this.resetRequestReplies("Connection disconnected");
|
|
554
|
-
this.serverInfo = null;
|
|
555
|
-
}
|
|
556
721
|
cancelIfUnexpected(value) {
|
|
557
722
|
const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
|
|
558
723
|
if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
|
|
@@ -563,13 +728,19 @@ class EventBus {
|
|
|
563
728
|
return;
|
|
564
729
|
}
|
|
565
730
|
try {
|
|
566
|
-
|
|
567
|
-
cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
|
|
568
|
-
cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
569
|
-
this.send(cancelEvent);
|
|
731
|
+
this.sendCancel(originCri, correlationId);
|
|
570
732
|
this.recentlyReaped.add(correlationId);
|
|
571
733
|
setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
|
|
572
|
-
} catch {
|
|
734
|
+
} catch (e) {
|
|
735
|
+
this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
sendCancel(cri, correlationId) {
|
|
739
|
+
const cancelEvent = new Event(cri);
|
|
740
|
+
cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
|
|
741
|
+
cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
742
|
+
cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
|
|
743
|
+
this.send(cancelEvent);
|
|
573
744
|
}
|
|
574
745
|
resetRequestReplies(reason) {
|
|
575
746
|
if (this.requestRepliesSubject != null) {
|
|
@@ -584,29 +755,167 @@ class EventBus {
|
|
|
584
755
|
}
|
|
585
756
|
}
|
|
586
757
|
createSendUnavailableError() {
|
|
587
|
-
let ret
|
|
758
|
+
let ret;
|
|
588
759
|
if (this.stompConnectionManager.maxConnectionAttemptsReached) {
|
|
589
760
|
ret = "Max connection attempts reached event bus is not available";
|
|
761
|
+
} else if (this.stompConnectionManager.active) {
|
|
762
|
+
ret = "The event bus is not connected to the server";
|
|
763
|
+
} else {
|
|
764
|
+
ret = "You must call connect on the event bus before sending any request";
|
|
590
765
|
}
|
|
591
766
|
return new Error(ret);
|
|
592
767
|
}
|
|
593
768
|
_observe(cri) {
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
headers.set(prop, message.headers[prop]);
|
|
603
|
-
}
|
|
769
|
+
return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators2.map((message) => {
|
|
770
|
+
const headers = new Map;
|
|
771
|
+
let destination = "";
|
|
772
|
+
for (const prop of Object.keys(message.headers)) {
|
|
773
|
+
if (prop === "destination") {
|
|
774
|
+
destination = message.headers[prop];
|
|
775
|
+
} else {
|
|
776
|
+
headers.set(prop, message.headers[prop]);
|
|
604
777
|
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
}
|
|
608
|
-
|
|
778
|
+
}
|
|
779
|
+
return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
|
|
780
|
+
}));
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// packages/core/src/api/security/ChainedCredentialsResolver.ts
|
|
785
|
+
class ChainedCredentialsResolver {
|
|
786
|
+
name;
|
|
787
|
+
resolvers;
|
|
788
|
+
constructor(...resolvers) {
|
|
789
|
+
this.resolvers = resolvers;
|
|
790
|
+
this.name = `ChainedCredentialsResolver(${resolvers.map((r) => r.name).join(" -> ")})`;
|
|
791
|
+
}
|
|
792
|
+
async resolve(server) {
|
|
793
|
+
for (const resolver of this.resolvers) {
|
|
794
|
+
const resolved = await resolver.resolve(server);
|
|
795
|
+
if (resolved !== null) {
|
|
796
|
+
return resolved;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// packages/core/src/api/security/BasicCredentialsResolver.ts
|
|
804
|
+
class BasicCredentialsResolver {
|
|
805
|
+
name = "BasicCredentialsResolver";
|
|
806
|
+
credentials;
|
|
807
|
+
constructor(clientId, clientSecret, organizationId, applicationId) {
|
|
808
|
+
const authHeaders = { clientId, clientSecret };
|
|
809
|
+
if (organizationId != null)
|
|
810
|
+
authHeaders.organizationId = organizationId;
|
|
811
|
+
if (applicationId != null)
|
|
812
|
+
authHeaders.applicationId = applicationId;
|
|
813
|
+
this.credentials = { authHeaders, organizationId, applicationId };
|
|
814
|
+
}
|
|
815
|
+
async resolve(_server) {
|
|
816
|
+
return this.credentials;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// packages/core/src/api/security/BearerCredentialsResolver.ts
|
|
821
|
+
class BearerCredentialsResolver {
|
|
822
|
+
name = "BearerCredentialsResolver";
|
|
823
|
+
token;
|
|
824
|
+
constructor(token) {
|
|
825
|
+
this.token = token;
|
|
826
|
+
}
|
|
827
|
+
async resolve(_server) {
|
|
828
|
+
const token = typeof this.token === "function" ? await this.token() : this.token;
|
|
829
|
+
return { authHeaders: { Authorization: `Bearer ${token}` } };
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// packages/core/src/api/security/EnvCredentialsResolver.ts
|
|
834
|
+
class EnvCredentialsResolver {
|
|
835
|
+
name = "EnvCredentialsResolver";
|
|
836
|
+
async resolve(server) {
|
|
837
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
838
|
+
let ret = null;
|
|
839
|
+
if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
|
|
840
|
+
ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
|
|
841
|
+
} else if (env?.KINOTIC_TOKEN) {
|
|
842
|
+
ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
|
|
843
|
+
}
|
|
844
|
+
return ret;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// packages/core/src/api/security/SessionCredentialsResolver.ts
|
|
849
|
+
class SessionCredentialsResolver {
|
|
850
|
+
name = "SessionCredentialsResolver";
|
|
851
|
+
async resolve(_server) {
|
|
852
|
+
return typeof document !== "undefined" ? {} : null;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// packages/core/src/internal/api/Util.ts
|
|
857
|
+
var DEFAULT_PORT = 58503;
|
|
858
|
+
var DEFAULT_HOST = "api.kinotic.ai";
|
|
859
|
+
|
|
860
|
+
class Util {
|
|
861
|
+
static createReplyEvent(incomingHeaders, headers, body) {
|
|
862
|
+
if (!incomingHeaders) {
|
|
863
|
+
throw new Error("incomingHeaders cannot be null");
|
|
864
|
+
}
|
|
865
|
+
const replyCRI = incomingHeaders.get("reply-to" /* REPLY_TO_HEADER */);
|
|
866
|
+
if (!replyCRI || replyCRI.trim() === "") {
|
|
867
|
+
throw new Error("No reply-to header found, cannot create outgoing message");
|
|
868
|
+
}
|
|
869
|
+
const newHeaders = new Map;
|
|
870
|
+
for (const [key, value] of incomingHeaders) {
|
|
871
|
+
if (key.startsWith("__")) {
|
|
872
|
+
newHeaders.set(key, value);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
if (headers) {
|
|
876
|
+
for (const [key, value] of headers) {
|
|
877
|
+
newHeaders.set(key, value);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
return new Event(replyCRI, newHeaders, body || undefined);
|
|
881
|
+
}
|
|
882
|
+
static resolveConnectOptions(options) {
|
|
883
|
+
const opts = options ?? {};
|
|
884
|
+
const server = opts.server ?? {};
|
|
885
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
886
|
+
const location = typeof window !== "undefined" ? window.location : undefined;
|
|
887
|
+
let host = server.host ?? env?.KINOTIC_SERVER_HOST;
|
|
888
|
+
const hostFromLocation = host == null && location != null;
|
|
889
|
+
const hostDefaulted = host == null && location == null;
|
|
890
|
+
if (host == null) {
|
|
891
|
+
host = location?.hostname ?? DEFAULT_HOST;
|
|
892
|
+
}
|
|
893
|
+
let useSSL = server.useSSL;
|
|
894
|
+
if (useSSL == null) {
|
|
895
|
+
if (env?.KINOTIC_SERVER_USE_SSL != null) {
|
|
896
|
+
useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
|
|
897
|
+
} else if (hostFromLocation) {
|
|
898
|
+
useSSL = location.protocol === "https:";
|
|
899
|
+
} else {
|
|
900
|
+
useSSL = hostDefaulted;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
let port = server.port;
|
|
904
|
+
if (port === undefined) {
|
|
905
|
+
if (env?.KINOTIC_SERVER_PORT != null) {
|
|
906
|
+
port = Number(env.KINOTIC_SERVER_PORT);
|
|
907
|
+
} else if (hostFromLocation) {
|
|
908
|
+
port = location.port ? Number(location.port) : null;
|
|
909
|
+
} else {
|
|
910
|
+
port = useSSL ? null : DEFAULT_PORT;
|
|
911
|
+
}
|
|
609
912
|
}
|
|
913
|
+
return {
|
|
914
|
+
...opts,
|
|
915
|
+
server: { host, port, useSSL },
|
|
916
|
+
sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
|
|
917
|
+
credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
|
|
918
|
+
};
|
|
610
919
|
}
|
|
611
920
|
}
|
|
612
921
|
|
|
@@ -799,22 +1108,14 @@ class JsonArgumentResolver {
|
|
|
799
1108
|
// packages/core/src/internal/api/ReturnValueConverter.ts
|
|
800
1109
|
class BasicReturnValueConverter {
|
|
801
1110
|
convert(incomingMetadata, returnValue) {
|
|
802
|
-
|
|
1111
|
+
const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
|
|
1112
|
+
return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
|
|
803
1113
|
}
|
|
804
1114
|
}
|
|
805
1115
|
|
|
806
|
-
// packages/core/src/internal/api/
|
|
807
|
-
var
|
|
808
|
-
|
|
809
|
-
const debugLogger = import_debug2.default(namespace);
|
|
810
|
-
return {
|
|
811
|
-
trace: (...args) => debugLogger("TRACE", ...args),
|
|
812
|
-
debug: (...args) => debugLogger("DEBUG", ...args),
|
|
813
|
-
info: (...args) => debugLogger("INFO", ...args),
|
|
814
|
-
warn: (...args) => debugLogger("WARN", ...args),
|
|
815
|
-
error: (...args) => debugLogger("ERROR", ...args)
|
|
816
|
-
};
|
|
817
|
-
}
|
|
1116
|
+
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
1117
|
+
var import_rxjs3 = require("rxjs");
|
|
1118
|
+
var import_operators3 = require("rxjs/operators");
|
|
818
1119
|
|
|
819
1120
|
// packages/core/src/api/ServiceIdentifier.ts
|
|
820
1121
|
class ServiceIdentifier {
|
|
@@ -851,6 +1152,9 @@ class ServiceIdentifier {
|
|
|
851
1152
|
}
|
|
852
1153
|
return this._cri;
|
|
853
1154
|
}
|
|
1155
|
+
unscopedCri() {
|
|
1156
|
+
return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
|
|
1157
|
+
}
|
|
854
1158
|
}
|
|
855
1159
|
|
|
856
1160
|
// packages/core/src/api/ZoneUtil.ts
|
|
@@ -870,6 +1174,7 @@ function validateLabel(label) {
|
|
|
870
1174
|
|
|
871
1175
|
// packages/core/src/api/KinoticDecorators.ts
|
|
872
1176
|
var scopeFunctions = new WeakSet;
|
|
1177
|
+
var scopeOptionalFunctions = new WeakSet;
|
|
873
1178
|
var versionRegistry = new WeakMap;
|
|
874
1179
|
var zonesRegistry = new WeakMap;
|
|
875
1180
|
var advertisedRegistry = new WeakMap;
|
|
@@ -907,6 +1212,23 @@ function resolveScope(instance) {
|
|
|
907
1212
|
function Scope(value, _context) {
|
|
908
1213
|
scopeFunctions.add(value);
|
|
909
1214
|
}
|
|
1215
|
+
function ScopeOptional(value, _context) {
|
|
1216
|
+
scopeOptionalFunctions.add(value);
|
|
1217
|
+
}
|
|
1218
|
+
function scopeOptionalMethodNames(instance) {
|
|
1219
|
+
const ret = new Set;
|
|
1220
|
+
let proto = Object.getPrototypeOf(instance);
|
|
1221
|
+
while (proto && proto !== Object.prototype) {
|
|
1222
|
+
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
1223
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
1224
|
+
if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
|
|
1225
|
+
ret.add(key);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
proto = Object.getPrototypeOf(proto);
|
|
1229
|
+
}
|
|
1230
|
+
return ret;
|
|
1231
|
+
}
|
|
910
1232
|
function Version(version) {
|
|
911
1233
|
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
|
|
912
1234
|
throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
|
|
@@ -969,6 +1291,93 @@ function Publish(namespace, name, advertise = false) {
|
|
|
969
1291
|
};
|
|
970
1292
|
}
|
|
971
1293
|
|
|
1294
|
+
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
1295
|
+
var import_api2 = __toESM(require("@opentelemetry/api"));
|
|
1296
|
+
// packages/core/package.json
|
|
1297
|
+
var package_default = {
|
|
1298
|
+
name: "@kinotic-ai/core",
|
|
1299
|
+
version: "5.0.0-beta.11",
|
|
1300
|
+
type: "module",
|
|
1301
|
+
files: [
|
|
1302
|
+
"dist"
|
|
1303
|
+
],
|
|
1304
|
+
module: "./dist/index.js",
|
|
1305
|
+
main: "./dist/index.cjs",
|
|
1306
|
+
types: "./dist/index.d.ts",
|
|
1307
|
+
exports: {
|
|
1308
|
+
".": {
|
|
1309
|
+
import: {
|
|
1310
|
+
types: "./dist/index.d.ts",
|
|
1311
|
+
default: "./dist/index.js"
|
|
1312
|
+
},
|
|
1313
|
+
require: {
|
|
1314
|
+
types: "./dist/index.d.cts",
|
|
1315
|
+
default: "./dist/index.cjs"
|
|
1316
|
+
}
|
|
1317
|
+
},
|
|
1318
|
+
"./node": {
|
|
1319
|
+
import: {
|
|
1320
|
+
types: "./dist/node/index.d.ts",
|
|
1321
|
+
default: "./dist/node/index.js"
|
|
1322
|
+
},
|
|
1323
|
+
require: {
|
|
1324
|
+
types: "./dist/node/index.d.cts",
|
|
1325
|
+
default: "./dist/node/index.cjs"
|
|
1326
|
+
}
|
|
1327
|
+
},
|
|
1328
|
+
"./package.json": "./package.json"
|
|
1329
|
+
},
|
|
1330
|
+
homepage: "https://github.com/kinotic-ai/kinotic",
|
|
1331
|
+
repository: {
|
|
1332
|
+
type: "git",
|
|
1333
|
+
url: "git+https://github.com/kinotic-ai/kinotic.git",
|
|
1334
|
+
directory: "kinotic-js/workspace/packages/core"
|
|
1335
|
+
},
|
|
1336
|
+
license: "Elastic License 2.0",
|
|
1337
|
+
publishConfig: {
|
|
1338
|
+
access: "public"
|
|
1339
|
+
},
|
|
1340
|
+
scripts: {
|
|
1341
|
+
"type-check": "tsc --noEmit",
|
|
1342
|
+
test: "vitest run",
|
|
1343
|
+
coverage: "vitest run --coverage",
|
|
1344
|
+
"ui-test": "vitest --ui --coverage.enabled=true --mode development"
|
|
1345
|
+
},
|
|
1346
|
+
devDependencies: {
|
|
1347
|
+
"@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
|
|
1348
|
+
"@opentelemetry/resources": "^2.10.0",
|
|
1349
|
+
"@opentelemetry/sdk-metrics": "^2.10.0",
|
|
1350
|
+
"@opentelemetry/sdk-node": "^0.221.0",
|
|
1351
|
+
"@opentelemetry/sdk-trace-node": "^2.10.0",
|
|
1352
|
+
"@types/debug": "^4.1.13",
|
|
1353
|
+
"@types/node": "^25.6.0",
|
|
1354
|
+
"@types/ws": "^8.18.0",
|
|
1355
|
+
"@vitest/coverage-v8": "^4.1.4",
|
|
1356
|
+
"@vitest/runner": "^4.1.4",
|
|
1357
|
+
"@vitest/ui": "^4.1.4",
|
|
1358
|
+
allure: "^3.14.3",
|
|
1359
|
+
"allure-vitest": "^3.10.2",
|
|
1360
|
+
dotenv: "^17.4.1",
|
|
1361
|
+
"properties-file": "^4.0.0",
|
|
1362
|
+
testcontainers: "^11.14.0",
|
|
1363
|
+
tslib: "^2.8.1",
|
|
1364
|
+
typescript: "^6.0.2",
|
|
1365
|
+
vitest: "^4.1.4"
|
|
1366
|
+
},
|
|
1367
|
+
dependencies: {
|
|
1368
|
+
"@opentelemetry/api": "^1.9.1",
|
|
1369
|
+
"@opentelemetry/semantic-conventions": "^1.40.0",
|
|
1370
|
+
"@stomp/rx-stomp": "^2.4.0",
|
|
1371
|
+
"@stomp/stompjs": "^7.3.0",
|
|
1372
|
+
debug: "^4.4.3",
|
|
1373
|
+
"p-tap": "^4.0.0",
|
|
1374
|
+
rxjs: "^7.8.2",
|
|
1375
|
+
"typescript-optional": "3.0.0-alpha.3",
|
|
1376
|
+
uuid: "^13.0.0",
|
|
1377
|
+
ws: "^8.21.0"
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
|
|
972
1381
|
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
973
1382
|
class ServiceInvocationSupervisor {
|
|
974
1383
|
log;
|
|
@@ -980,7 +1389,13 @@ class ServiceInvocationSupervisor {
|
|
|
980
1389
|
serviceIdentifier;
|
|
981
1390
|
serviceInstance;
|
|
982
1391
|
methodSubscription = null;
|
|
1392
|
+
unscopedSubscription = null;
|
|
1393
|
+
activeStreams = new Map;
|
|
1394
|
+
connectionLostSubscription = null;
|
|
1395
|
+
connectionGeneration = 0;
|
|
983
1396
|
methodMap;
|
|
1397
|
+
scopeOptionalMethods;
|
|
1398
|
+
tracer;
|
|
984
1399
|
constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
|
|
985
1400
|
if (!serviceIdentifier)
|
|
986
1401
|
throw new Error("ServiceIdentifier must not be null");
|
|
@@ -994,10 +1409,12 @@ class ServiceInvocationSupervisor {
|
|
|
994
1409
|
this.serviceInstance = serviceInstance;
|
|
995
1410
|
this._eventBus = eventBusService;
|
|
996
1411
|
this.interceptorProvider = interceptorProvider;
|
|
997
|
-
this.log = options.logger || createDebugLogger("
|
|
1412
|
+
this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
|
|
998
1413
|
this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
|
|
999
1414
|
this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
|
|
1000
1415
|
this.methodMap = this.buildMethodMap(serviceInstance);
|
|
1416
|
+
this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
|
|
1417
|
+
this.tracer = import_api2.default.trace.getTracer(package_default.name, package_default.version);
|
|
1001
1418
|
}
|
|
1002
1419
|
isActive() {
|
|
1003
1420
|
return this.active;
|
|
@@ -1017,7 +1434,22 @@ class ServiceInvocationSupervisor {
|
|
|
1017
1434
|
}
|
|
1018
1435
|
this.active = true;
|
|
1019
1436
|
const criBase = this.serviceIdentifier.cri().baseResource();
|
|
1020
|
-
this.methodSubscription = this.
|
|
1437
|
+
this.methodSubscription = this.subscribeAt(criBase);
|
|
1438
|
+
this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
|
|
1439
|
+
if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
|
|
1440
|
+
const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
|
|
1441
|
+
this.unscopedSubscription = this.subscribeAt(unscopedBase);
|
|
1442
|
+
this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
|
|
1443
|
+
}
|
|
1444
|
+
this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
|
|
1445
|
+
this.connectionGeneration++;
|
|
1446
|
+
for (const stream of this.activeStreams.values()) {
|
|
1447
|
+
stream.subscription.unsubscribe();
|
|
1448
|
+
}
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
subscribeAt(criBase) {
|
|
1452
|
+
return this._eventBus.observe(criBase).subscribe({
|
|
1021
1453
|
next: async (event) => {
|
|
1022
1454
|
await this.processEvent(event);
|
|
1023
1455
|
},
|
|
@@ -1030,7 +1462,6 @@ class ServiceInvocationSupervisor {
|
|
|
1030
1462
|
this.active = false;
|
|
1031
1463
|
}
|
|
1032
1464
|
});
|
|
1033
|
-
this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
|
|
1034
1465
|
}
|
|
1035
1466
|
stop() {
|
|
1036
1467
|
if (!this.active) {
|
|
@@ -1039,6 +1470,15 @@ class ServiceInvocationSupervisor {
|
|
|
1039
1470
|
this.active = false;
|
|
1040
1471
|
this.methodSubscription?.unsubscribe();
|
|
1041
1472
|
this.methodSubscription = null;
|
|
1473
|
+
this.unscopedSubscription?.unsubscribe();
|
|
1474
|
+
this.unscopedSubscription = null;
|
|
1475
|
+
this.connectionLostSubscription?.unsubscribe();
|
|
1476
|
+
this.connectionLostSubscription = null;
|
|
1477
|
+
const serviceName = this.serviceIdentifier.qualifiedName();
|
|
1478
|
+
for (const stream of this.activeStreams.values()) {
|
|
1479
|
+
this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
|
|
1480
|
+
stream.subscription.unsubscribe();
|
|
1481
|
+
}
|
|
1042
1482
|
this.log.info("ServiceInvocationSupervisor stopped");
|
|
1043
1483
|
}
|
|
1044
1484
|
buildMethodMap(serviceInstance) {
|
|
@@ -1078,10 +1518,19 @@ class ServiceInvocationSupervisor {
|
|
|
1078
1518
|
if (!correlationId) {
|
|
1079
1519
|
throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
|
|
1080
1520
|
}
|
|
1081
|
-
|
|
1521
|
+
const control = event.getHeader("control" /* CONTROL_HEADER */);
|
|
1522
|
+
this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
|
|
1523
|
+
const stream = this.activeStreams.get(correlationId);
|
|
1524
|
+
if (stream) {
|
|
1525
|
+
stream.subscription.unsubscribe();
|
|
1526
|
+
if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
|
|
1527
|
+
throw new Error(`Unknown control header value ${control}`);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1082
1530
|
}
|
|
1083
1531
|
async processInvocationRequest(event) {
|
|
1084
|
-
const
|
|
1532
|
+
const incomingCri = createCRI(event.cri);
|
|
1533
|
+
const path = incomingCri.path();
|
|
1085
1534
|
if (!path) {
|
|
1086
1535
|
throw new Error("The methodId must not be blank");
|
|
1087
1536
|
}
|
|
@@ -1089,49 +1538,163 @@ class ServiceInvocationSupervisor {
|
|
|
1089
1538
|
if (!handlerMethod) {
|
|
1090
1539
|
throw new Error(`No method resolved for methodId ${path}`);
|
|
1091
1540
|
}
|
|
1541
|
+
if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
|
|
1542
|
+
throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
|
|
1543
|
+
}
|
|
1092
1544
|
const methodName = path;
|
|
1093
|
-
const
|
|
1094
|
-
const
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1545
|
+
const span = this.startInvocationSpan(event, methodName);
|
|
1546
|
+
const generation = this.connectionGeneration;
|
|
1547
|
+
try {
|
|
1548
|
+
const args = this.argumentResolver.resolveArguments(event);
|
|
1549
|
+
const injectContext = receivesContext(this.serviceInstance, methodName);
|
|
1550
|
+
let serviceContext = {};
|
|
1551
|
+
const interceptor = this.interceptorProvider();
|
|
1552
|
+
if (interceptor) {
|
|
1553
|
+
try {
|
|
1554
|
+
serviceContext = await interceptor.intercept(event, serviceContext);
|
|
1555
|
+
} catch (e) {
|
|
1556
|
+
this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
|
|
1557
|
+
if (this.replyOwed(generation)) {
|
|
1558
|
+
this.handleException(event, new Error("Internal server error"));
|
|
1559
|
+
}
|
|
1560
|
+
this.failSpan(span, e);
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
if (injectContext) {
|
|
1565
|
+
args.push(serviceContext);
|
|
1566
|
+
}
|
|
1567
|
+
const expectedArgsCount = handlerMethod.length;
|
|
1568
|
+
if (args.length !== expectedArgsCount) {
|
|
1569
|
+
throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
|
|
1570
|
+
}
|
|
1571
|
+
let result;
|
|
1098
1572
|
try {
|
|
1099
|
-
|
|
1573
|
+
result = import_api2.context.with(import_api2.trace.setSpan(import_api2.context.active(), span), () => handlerMethod(...args));
|
|
1574
|
+
if (result instanceof Promise) {
|
|
1575
|
+
result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
|
|
1576
|
+
this.failInvocation(event, e, span, generation);
|
|
1577
|
+
});
|
|
1578
|
+
} else {
|
|
1579
|
+
this.processMethodInvocationResult(event, result, span, generation);
|
|
1580
|
+
}
|
|
1100
1581
|
} catch (e) {
|
|
1101
|
-
this.
|
|
1102
|
-
this.handleException(event, new Error("Internal server error"));
|
|
1103
|
-
return;
|
|
1582
|
+
this.failInvocation(event, e, span, generation);
|
|
1104
1583
|
}
|
|
1584
|
+
} catch (e) {
|
|
1585
|
+
this.failSpan(span, e);
|
|
1586
|
+
throw e;
|
|
1105
1587
|
}
|
|
1106
|
-
|
|
1107
|
-
|
|
1588
|
+
}
|
|
1589
|
+
startInvocationSpan(event, methodName) {
|
|
1590
|
+
const carrier = {};
|
|
1591
|
+
for (const [key, value] of event.headers.entries()) {
|
|
1592
|
+
carrier[key] = value;
|
|
1108
1593
|
}
|
|
1109
|
-
const
|
|
1110
|
-
|
|
1111
|
-
|
|
1594
|
+
const serviceName = this.serviceIdentifier.qualifiedName();
|
|
1595
|
+
return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
|
|
1596
|
+
kind: import_api2.SpanKind.SERVER,
|
|
1597
|
+
attributes: {
|
|
1598
|
+
"rpc.system": "kinotic",
|
|
1599
|
+
"rpc.service": serviceName,
|
|
1600
|
+
"rpc.method": methodName
|
|
1601
|
+
}
|
|
1602
|
+
}, import_api2.propagation.extract(import_api2.context.active(), carrier));
|
|
1603
|
+
}
|
|
1604
|
+
failSpan(span, error) {
|
|
1605
|
+
span.recordException(error);
|
|
1606
|
+
span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
|
|
1607
|
+
span.end();
|
|
1608
|
+
}
|
|
1609
|
+
replyOwed(generation) {
|
|
1610
|
+
return generation === this.connectionGeneration;
|
|
1611
|
+
}
|
|
1612
|
+
failInvocation(event, error, span, generation) {
|
|
1613
|
+
if (this.replyOwed(generation)) {
|
|
1614
|
+
this.handleException(event, error);
|
|
1112
1615
|
}
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1616
|
+
this.failSpan(span, error);
|
|
1617
|
+
}
|
|
1618
|
+
processMethodInvocationResult(event, result, span, generation) {
|
|
1619
|
+
if (!this.replyOwed(generation)) {
|
|
1620
|
+
span.end();
|
|
1621
|
+
} else if (import_rxjs3.isObservable(result)) {
|
|
1622
|
+
this.streamResult(event, result, span);
|
|
1623
|
+
} else {
|
|
1624
|
+
const reply = this.returnValueConverter.convert(event.headers, result);
|
|
1625
|
+
reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
|
|
1626
|
+
this.sendReply(reply);
|
|
1627
|
+
span.end();
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
streamResult(event, stream, span) {
|
|
1631
|
+
const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
|
|
1632
|
+
if (!correlationId) {
|
|
1633
|
+
throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
|
|
1634
|
+
}
|
|
1635
|
+
let subscription = null;
|
|
1636
|
+
let failed = false;
|
|
1637
|
+
subscription = stream.pipe(import_operators3.finalize(() => {
|
|
1638
|
+
this.activeStreams.delete(correlationId);
|
|
1639
|
+
span.end();
|
|
1640
|
+
})).subscribe({
|
|
1641
|
+
next: (value) => {
|
|
1642
|
+
if (failed) {
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
try {
|
|
1646
|
+
const reply = this.returnValueConverter.convert(event.headers, value);
|
|
1647
|
+
reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
|
|
1648
|
+
this.sendReply(reply);
|
|
1649
|
+
} catch (e) {
|
|
1650
|
+
failed = true;
|
|
1651
|
+
this.handleException(event, e);
|
|
1652
|
+
span.recordException(e);
|
|
1653
|
+
span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
|
|
1654
|
+
subscription?.unsubscribe();
|
|
1655
|
+
}
|
|
1656
|
+
},
|
|
1657
|
+
error: (error) => {
|
|
1658
|
+
if (failed) {
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
this.handleException(event, error);
|
|
1662
|
+
span.recordException(error);
|
|
1663
|
+
span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
|
|
1664
|
+
},
|
|
1665
|
+
complete: () => {
|
|
1666
|
+
if (failed) {
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
1669
|
+
this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
|
|
1120
1670
|
}
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1671
|
+
});
|
|
1672
|
+
if (failed) {
|
|
1673
|
+
subscription.unsubscribe();
|
|
1674
|
+
}
|
|
1675
|
+
if (!subscription.closed) {
|
|
1676
|
+
this.activeStreams.set(correlationId, { request: event, subscription });
|
|
1123
1677
|
}
|
|
1124
1678
|
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1679
|
+
sendReply(event) {
|
|
1680
|
+
try {
|
|
1681
|
+
this._eventBus.send(event);
|
|
1682
|
+
} catch (e) {
|
|
1683
|
+
this.log.warn(`Could not send reply to ${event.cri}`, e);
|
|
1684
|
+
}
|
|
1128
1685
|
}
|
|
1129
1686
|
handleException(event, error) {
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1687
|
+
try {
|
|
1688
|
+
const errorMessage = error?.message || "Unknown error";
|
|
1689
|
+
const exceptionName = error instanceof Error ? error.constructor.name : "Error";
|
|
1690
|
+
const errorEvent = Util.createReplyEvent(event.headers, new Map([
|
|
1691
|
+
["error" /* ERROR_HEADER */, errorMessage],
|
|
1692
|
+
["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
|
|
1693
|
+
]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
|
|
1694
|
+
this.sendReply(errorEvent);
|
|
1695
|
+
} catch (e) {
|
|
1696
|
+
this.log.warn(`Could not build the error reply for ${event.cri}`, e);
|
|
1697
|
+
}
|
|
1135
1698
|
}
|
|
1136
1699
|
validateReplyTo(event) {
|
|
1137
1700
|
const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
|
|
@@ -1152,86 +1715,9 @@ class ServiceInvocationSupervisor {
|
|
|
1152
1715
|
}
|
|
1153
1716
|
|
|
1154
1717
|
// packages/core/src/api/ServiceRegistry.ts
|
|
1155
|
-
var
|
|
1718
|
+
var import_api3 = __toESM(require("@opentelemetry/api"));
|
|
1156
1719
|
var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
|
|
1157
|
-
var
|
|
1158
|
-
// packages/core/package.json
|
|
1159
|
-
var package_default = {
|
|
1160
|
-
name: "@kinotic-ai/core",
|
|
1161
|
-
version: "5.0.0-beta.1",
|
|
1162
|
-
type: "module",
|
|
1163
|
-
files: [
|
|
1164
|
-
"dist"
|
|
1165
|
-
],
|
|
1166
|
-
module: "./dist/index.js",
|
|
1167
|
-
main: "./dist/index.cjs",
|
|
1168
|
-
types: "./dist/index.d.ts",
|
|
1169
|
-
exports: {
|
|
1170
|
-
".": {
|
|
1171
|
-
import: {
|
|
1172
|
-
types: "./dist/index.d.ts",
|
|
1173
|
-
default: "./dist/index.js"
|
|
1174
|
-
},
|
|
1175
|
-
require: {
|
|
1176
|
-
types: "./dist/index.d.cts",
|
|
1177
|
-
default: "./dist/index.cjs"
|
|
1178
|
-
}
|
|
1179
|
-
},
|
|
1180
|
-
"./package.json": "./package.json"
|
|
1181
|
-
},
|
|
1182
|
-
homepage: "https://github.com/kinotic-ai/kinotic",
|
|
1183
|
-
license: "Elastic License 2.0",
|
|
1184
|
-
publishConfig: {
|
|
1185
|
-
access: "public"
|
|
1186
|
-
},
|
|
1187
|
-
scripts: {
|
|
1188
|
-
"type-check": "tsc --noEmit",
|
|
1189
|
-
test: "vitest run",
|
|
1190
|
-
coverage: "vitest run --coverage",
|
|
1191
|
-
"ui-test": "vitest --ui --coverage.enabled=true --mode development"
|
|
1192
|
-
},
|
|
1193
|
-
devDependencies: {
|
|
1194
|
-
"@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
|
|
1195
|
-
"@opentelemetry/resources": "^2.6.1",
|
|
1196
|
-
"@opentelemetry/sdk-metrics": "^2.6.1",
|
|
1197
|
-
"@opentelemetry/sdk-node": "^0.214.0",
|
|
1198
|
-
"@opentelemetry/sdk-trace-node": "^2.6.1",
|
|
1199
|
-
"@types/node": "^25.6.0",
|
|
1200
|
-
"@types/uuid": "^11.0.0",
|
|
1201
|
-
"@types/ws": "^8.18.1",
|
|
1202
|
-
"@vitest/coverage-v8": "^4.1.4",
|
|
1203
|
-
"@vitest/runner": "^4.1.4",
|
|
1204
|
-
"@vitest/ui": "^4.1.4",
|
|
1205
|
-
allure: "^3.4.1",
|
|
1206
|
-
"allure-vitest": "^3.7.1",
|
|
1207
|
-
dotenv: "^17.4.1",
|
|
1208
|
-
"properties-file": "^4.0.0",
|
|
1209
|
-
testcontainers: "^11.14.0",
|
|
1210
|
-
tslib: "^2.8.1",
|
|
1211
|
-
typescript: "^6.0.2",
|
|
1212
|
-
vitest: "^4.1.4",
|
|
1213
|
-
ws: "^8.20.0"
|
|
1214
|
-
},
|
|
1215
|
-
dependencies: {
|
|
1216
|
-
"@opentelemetry/api": "^1.9.1",
|
|
1217
|
-
"@opentelemetry/semantic-conventions": "^1.40.0",
|
|
1218
|
-
"@stomp/rx-stomp": "^2.4.0",
|
|
1219
|
-
"@stomp/stompjs": "^7.3.0",
|
|
1220
|
-
"@types/debug": "^4.1.13",
|
|
1221
|
-
debug: "^4.4.3",
|
|
1222
|
-
"p-tap": "^4.0.0",
|
|
1223
|
-
rxjs: "^7.8.2",
|
|
1224
|
-
"typescript-optional": "3.0.0-alpha.3",
|
|
1225
|
-
uuid: "^13.0.0"
|
|
1226
|
-
},
|
|
1227
|
-
peerDependenciesMeta: {
|
|
1228
|
-
typescript: {
|
|
1229
|
-
optional: true
|
|
1230
|
-
}
|
|
1231
|
-
}
|
|
1232
|
-
};
|
|
1233
|
-
|
|
1234
|
-
// packages/core/src/api/ServiceRegistry.ts
|
|
1720
|
+
var import_operators4 = require("rxjs/operators");
|
|
1235
1721
|
class JsonEventFactory {
|
|
1236
1722
|
create(cri, args) {
|
|
1237
1723
|
const event = new Event(cri);
|
|
@@ -1270,7 +1756,7 @@ class ServiceRegistry {
|
|
|
1270
1756
|
_eventBus;
|
|
1271
1757
|
supervisors = new Map;
|
|
1272
1758
|
contextInterceptor = null;
|
|
1273
|
-
debugLogger = import_debug3.default("
|
|
1759
|
+
debugLogger = import_debug3.default("kinotic:serviceRegistry");
|
|
1274
1760
|
constructor(eventBus) {
|
|
1275
1761
|
this._eventBus = eventBus;
|
|
1276
1762
|
}
|
|
@@ -1320,24 +1806,24 @@ class ServiceProxy {
|
|
|
1320
1806
|
}
|
|
1321
1807
|
this.serviceIdentifier = serviceIdentifier;
|
|
1322
1808
|
this.serviceRegistry = serviceRegistry;
|
|
1323
|
-
this.tracer =
|
|
1809
|
+
this.tracer = import_api3.default.trace.getTracer(package_default.name, package_default.version);
|
|
1324
1810
|
}
|
|
1325
1811
|
invoke(methodIdentifier, args, scope, eventFactory) {
|
|
1326
1812
|
return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
|
|
1327
|
-
kind:
|
|
1813
|
+
kind: import_api3.SpanKind.CLIENT
|
|
1328
1814
|
}, async (span) => {
|
|
1329
1815
|
if (scope) {
|
|
1330
|
-
span.setAttribute("
|
|
1816
|
+
span.setAttribute("kinotic.scope", scope);
|
|
1331
1817
|
}
|
|
1332
|
-
span.setAttribute("rpc.system", "
|
|
1818
|
+
span.setAttribute("rpc.system", "kinotic");
|
|
1333
1819
|
span.setAttribute("rpc.service", this.serviceIdentifier);
|
|
1334
1820
|
span.setAttribute("rpc.method", methodIdentifier);
|
|
1335
|
-
return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(
|
|
1821
|
+
return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators4.first()).toPromise().then(async (value) => {
|
|
1336
1822
|
span.end();
|
|
1337
1823
|
return value;
|
|
1338
1824
|
}, async (ex) => {
|
|
1339
1825
|
span.recordException(ex);
|
|
1340
|
-
span.setStatus({ code:
|
|
1826
|
+
span.setStatus({ code: import_api3.SpanStatusCode.ERROR });
|
|
1341
1827
|
span.end();
|
|
1342
1828
|
throw ex;
|
|
1343
1829
|
});
|
|
@@ -1353,13 +1839,13 @@ class ServiceProxy {
|
|
|
1353
1839
|
eventFactoryToUse = eventFactory;
|
|
1354
1840
|
}
|
|
1355
1841
|
let eventBusToUse = this.serviceRegistry.eventBus;
|
|
1356
|
-
const span =
|
|
1842
|
+
const span = import_api3.default.trace.getActiveSpan();
|
|
1357
1843
|
if (span) {
|
|
1358
1844
|
span.setAttribute(import_semantic_conventions.ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
|
|
1359
1845
|
span.setAttribute(import_semantic_conventions.ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
|
|
1360
1846
|
}
|
|
1361
1847
|
let event = eventFactoryToUse.create(cri, args);
|
|
1362
|
-
return eventBusToUse.requestStream(event, sendControlEvents).pipe(
|
|
1848
|
+
return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators4.map((value) => {
|
|
1363
1849
|
const contentType = value.getHeader("content-type" /* CONTENT_TYPE_HEADER */);
|
|
1364
1850
|
if (contentType !== undefined) {
|
|
1365
1851
|
if (contentType === "application/json" /* CONTENT_JSON */) {
|
|
@@ -1395,8 +1881,8 @@ class KinoticSingleton {
|
|
|
1395
1881
|
this._eventBus = eventBus;
|
|
1396
1882
|
this.serviceRegistry.eventBus = eventBus;
|
|
1397
1883
|
}
|
|
1398
|
-
connect(
|
|
1399
|
-
return this._eventBus.connect(
|
|
1884
|
+
connect(options) {
|
|
1885
|
+
return this._eventBus.connect(Util.resolveConnectOptions(options));
|
|
1400
1886
|
}
|
|
1401
1887
|
disconnect(force) {
|
|
1402
1888
|
return this._eventBus.disconnect(force);
|
|
@@ -1517,6 +2003,9 @@ class CrudServiceProxy {
|
|
|
1517
2003
|
deleteById(id) {
|
|
1518
2004
|
return this.serviceProxy.invoke("deleteById", [id]);
|
|
1519
2005
|
}
|
|
2006
|
+
deleteByIdSync(id) {
|
|
2007
|
+
return this.serviceProxy.invoke("deleteByIdSync", [id]);
|
|
2008
|
+
}
|
|
1520
2009
|
async findAll(pageable) {
|
|
1521
2010
|
const page = await this.findAllSinglePage(pageable);
|
|
1522
2011
|
return new FindAllIterablePage(pageable, page, this);
|
|
@@ -1639,41 +2128,6 @@ class Order {
|
|
|
1639
2128
|
class Sort {
|
|
1640
2129
|
orders = [];
|
|
1641
2130
|
}
|
|
1642
|
-
// packages/core/src/api/security/AuthenticatedWebSocketFactory.ts
|
|
1643
|
-
function createAuthenticatedWebSocketFactory(serverInfo, authProvider) {
|
|
1644
|
-
const brokerUrl = Util.buildBrokerUrl(serverInfo);
|
|
1645
|
-
return async () => {
|
|
1646
|
-
const headers = await authProvider.getAuthHeaders();
|
|
1647
|
-
const WS = WebSocket;
|
|
1648
|
-
return new WS(brokerUrl, { headers });
|
|
1649
|
-
};
|
|
1650
|
-
}
|
|
1651
|
-
// packages/core/src/api/security/BasicAuthProvider.ts
|
|
1652
|
-
class BasicAuthProvider {
|
|
1653
|
-
authHeader;
|
|
1654
|
-
constructor(login, passcode) {
|
|
1655
|
-
const bytes = new TextEncoder().encode(`${login}:${passcode}`);
|
|
1656
|
-
let binary = "";
|
|
1657
|
-
for (const byte of bytes) {
|
|
1658
|
-
binary += String.fromCharCode(byte);
|
|
1659
|
-
}
|
|
1660
|
-
this.authHeader = `Basic ${btoa(binary)}`;
|
|
1661
|
-
}
|
|
1662
|
-
getAuthHeaders() {
|
|
1663
|
-
return { Authorization: this.authHeader };
|
|
1664
|
-
}
|
|
1665
|
-
}
|
|
1666
|
-
// packages/core/src/api/security/BearerTokenAuthProvider.ts
|
|
1667
|
-
class BearerTokenAuthProvider {
|
|
1668
|
-
token;
|
|
1669
|
-
constructor(token) {
|
|
1670
|
-
this.token = token;
|
|
1671
|
-
}
|
|
1672
|
-
async getAuthHeaders() {
|
|
1673
|
-
const token = typeof this.token === "function" ? await this.token() : this.token;
|
|
1674
|
-
return { Authorization: `Bearer ${token}` };
|
|
1675
|
-
}
|
|
1676
|
-
}
|
|
1677
2131
|
// packages/core/src/api/security/ConnectedInfo.ts
|
|
1678
2132
|
class ConnectedInfo {
|
|
1679
2133
|
replyToId;
|