@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.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,134 +46,173 @@ 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
|
-
import { RxStomp } from "@stomp/rx-stomp";
|
|
63
|
+
import { RxStomp, RxStompState } 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";
|
|
69
|
+
|
|
70
|
+
// packages/core/src/internal/api/StompActivation.ts
|
|
71
|
+
class StompActivation {
|
|
72
|
+
_ended = false;
|
|
73
|
+
wake = null;
|
|
74
|
+
preparedSocket = null;
|
|
75
|
+
attempt = null;
|
|
76
|
+
failPending = null;
|
|
77
|
+
subscriptions = [];
|
|
78
|
+
get ended() {
|
|
79
|
+
return this._ended;
|
|
80
|
+
}
|
|
81
|
+
end() {
|
|
82
|
+
this._ended = true;
|
|
83
|
+
this.wake?.();
|
|
84
|
+
this.wake = null;
|
|
85
|
+
}
|
|
86
|
+
delay(ms) {
|
|
87
|
+
return new Promise((resolve) => {
|
|
88
|
+
const timer = setTimeout(() => {
|
|
89
|
+
this.wake = null;
|
|
90
|
+
resolve();
|
|
91
|
+
}, ms);
|
|
92
|
+
this.wake = () => {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
resolve();
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
own(subscription) {
|
|
99
|
+
this.subscriptions.push(subscription);
|
|
100
|
+
}
|
|
101
|
+
pending(fail) {
|
|
102
|
+
this.failPending = fail;
|
|
103
|
+
}
|
|
104
|
+
established() {
|
|
105
|
+
this.failPending = null;
|
|
106
|
+
}
|
|
107
|
+
failIfPending(reason) {
|
|
108
|
+
const fail = this.failPending;
|
|
109
|
+
this.failPending = null;
|
|
110
|
+
fail?.(reason);
|
|
111
|
+
}
|
|
112
|
+
unsubscribeAll() {
|
|
113
|
+
for (const subscription of this.subscriptions) {
|
|
114
|
+
subscription.unsubscribe();
|
|
115
|
+
}
|
|
116
|
+
this.subscriptions.length = 0;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// packages/core/src/internal/api/StompConnectionManager.ts
|
|
83
121
|
var SESSION_CHECK_PATH = "/api/auth/me";
|
|
84
122
|
|
|
85
123
|
class StompConnectionManager {
|
|
86
124
|
lastWebsocketError = null;
|
|
87
125
|
maxConnectionAttemptsReached = false;
|
|
88
|
-
|
|
89
|
-
rxStomp =
|
|
126
|
+
connectionLostHandler = null;
|
|
127
|
+
rxStomp = new RxStomp;
|
|
128
|
+
activation = null;
|
|
129
|
+
teardown = null;
|
|
90
130
|
INITIAL_RECONNECT_DELAY = 2000;
|
|
91
131
|
JITTER_MAX = 5000;
|
|
92
132
|
MAX_RECONNECT_DELAY = 120000;
|
|
93
133
|
connectionAttempts = 0;
|
|
94
|
-
debugLogger =
|
|
134
|
+
debugLogger = debug2("kinotic:stomp");
|
|
95
135
|
fatalErrorsSubject = new Subject;
|
|
96
136
|
_fatalErrors = this.fatalErrorsSubject.asObservable();
|
|
97
137
|
initialConnectionSuccessful = false;
|
|
98
|
-
|
|
99
|
-
stompErrorsSubscription = null;
|
|
100
|
-
uuidv4 = uuidv4();
|
|
138
|
+
rxStompHasConnected = false;
|
|
101
139
|
_replyToCri = null;
|
|
102
140
|
get replyToCri() {
|
|
103
141
|
return this._replyToCri;
|
|
104
142
|
}
|
|
105
143
|
get active() {
|
|
106
|
-
return
|
|
144
|
+
return this.activation !== null;
|
|
107
145
|
}
|
|
108
146
|
get connected() {
|
|
109
|
-
return this.
|
|
147
|
+
return this.activation !== null && this.rxStomp.connected();
|
|
110
148
|
}
|
|
111
149
|
get fatalErrors() {
|
|
112
150
|
return this._fatalErrors;
|
|
113
151
|
}
|
|
114
|
-
activate(
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
152
|
+
async activate(options) {
|
|
153
|
+
if (!options?.server?.host) {
|
|
154
|
+
throw new Error("No host provided");
|
|
155
|
+
}
|
|
156
|
+
if (this.activation) {
|
|
157
|
+
throw new Error("Stomp connection already active");
|
|
158
|
+
}
|
|
159
|
+
await this.teardown;
|
|
160
|
+
if (this.activation) {
|
|
161
|
+
throw new Error("Stomp connection already active");
|
|
162
|
+
}
|
|
163
|
+
const server = options.server;
|
|
164
|
+
const credentialsResolver = options.credentials;
|
|
165
|
+
const activation = new StompActivation;
|
|
166
|
+
this.activation = activation;
|
|
167
|
+
let headerAuth = false;
|
|
168
|
+
try {
|
|
169
|
+
if (!options.webSocketFactory) {
|
|
170
|
+
if (!credentialsResolver) {
|
|
171
|
+
throw new Error("No credentials supplied and no default resolution applied");
|
|
172
|
+
}
|
|
173
|
+
const resolved = await credentialsResolver.resolve(server);
|
|
174
|
+
if (resolved === null) {
|
|
175
|
+
throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
|
|
176
|
+
}
|
|
177
|
+
headerAuth = resolved.authHeaders != null;
|
|
119
178
|
}
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
return;
|
|
179
|
+
if (activation.ended) {
|
|
180
|
+
throw new Error("Deactivated before the connection was established");
|
|
123
181
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
182
|
+
} catch (e) {
|
|
183
|
+
if (this.activation === activation) {
|
|
184
|
+
this.activation = null;
|
|
127
185
|
}
|
|
186
|
+
throw e;
|
|
187
|
+
}
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
128
189
|
this.connectionAttempts = 0;
|
|
129
190
|
this.initialConnectionSuccessful = false;
|
|
130
191
|
this.lastWebsocketError = null;
|
|
131
192
|
this.maxConnectionAttemptsReached = false;
|
|
132
|
-
const url =
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
193
|
+
const url = buildBrokerUrl(server);
|
|
194
|
+
const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
|
|
195
|
+
const takePreparedSocket = () => {
|
|
196
|
+
const socket = activation.preparedSocket;
|
|
197
|
+
activation.preparedSocket = null;
|
|
198
|
+
return socket;
|
|
199
|
+
};
|
|
136
200
|
const stompConfig = {
|
|
137
201
|
brokerURL: url,
|
|
138
202
|
connectHeaders: {
|
|
139
|
-
["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]:
|
|
203
|
+
["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
|
|
140
204
|
},
|
|
141
|
-
heartbeatIncoming:
|
|
205
|
+
heartbeatIncoming: 30000,
|
|
142
206
|
heartbeatOutgoing: 30000,
|
|
143
207
|
reconnectDelay: this.INITIAL_RECONNECT_DELAY,
|
|
144
208
|
maxReconnectDelay: this.MAX_RECONNECT_DELAY,
|
|
145
209
|
reconnectTimeMode: ReconnectionTimeMode.EXPONENTIAL,
|
|
146
|
-
webSocketFactory:
|
|
147
|
-
beforeConnect:
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
if (res.status === 401) {
|
|
153
|
-
await this.signalFatal(new Error("Authentication required"));
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
} catch {}
|
|
157
|
-
}
|
|
158
|
-
if (connectionInfo?.maxConnectionAttempts) {
|
|
159
|
-
this.connectionAttempts++;
|
|
160
|
-
if (this.connectionAttempts > connectionInfo.maxConnectionAttempts) {
|
|
161
|
-
this.maxConnectionAttemptsReached = true;
|
|
162
|
-
await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
|
|
163
|
-
return;
|
|
164
|
-
} else {
|
|
165
|
-
await this.connectionJitterDelay();
|
|
166
|
-
}
|
|
167
|
-
} else {
|
|
168
|
-
await this.connectionJitterDelay();
|
|
169
|
-
}
|
|
170
|
-
if (userWebSocketFactory) {
|
|
171
|
-
try {
|
|
172
|
-
preparedSocket = await userWebSocketFactory();
|
|
173
|
-
} catch (e) {
|
|
174
|
-
await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
|
|
175
|
-
}
|
|
176
|
-
}
|
|
210
|
+
webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
|
|
211
|
+
beforeConnect: () => {
|
|
212
|
+
const attempt = this.prepareAttempt(activation, options, server, headerAuth);
|
|
213
|
+
const settled = () => new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
214
|
+
activation.attempt = attempt.then(settled, settled);
|
|
215
|
+
return attempt;
|
|
177
216
|
}
|
|
178
217
|
};
|
|
179
218
|
if (this.debugLogger.enabled) {
|
|
@@ -182,89 +221,198 @@ class StompConnectionManager {
|
|
|
182
221
|
};
|
|
183
222
|
}
|
|
184
223
|
this.rxStomp.configure(stompConfig);
|
|
185
|
-
this.rxStomp.webSocketErrors$.subscribe((value) => {
|
|
224
|
+
activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
|
|
186
225
|
this.lastWebsocketError = value;
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
|
|
191
|
-
});
|
|
192
|
-
const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
|
|
193
|
-
connectedSubscription.unsubscribe();
|
|
194
|
-
initialFailureSubscription.unsubscribe();
|
|
195
|
-
if (!this.initialConnectionSuccessful) {
|
|
196
|
-
this.initialConnectionSuccessful = true;
|
|
226
|
+
if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
|
|
227
|
+
this.maxConnectionAttemptsReached = true;
|
|
228
|
+
await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
|
|
197
229
|
}
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
230
|
+
}));
|
|
231
|
+
activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
|
|
232
|
+
const stompError = new Error(frame.headers["message"], { cause: frame });
|
|
233
|
+
await this.signalFatal(activation, new Error("STOMP connection error", { cause: stompError }));
|
|
234
|
+
}));
|
|
235
|
+
activation.own(this.rxStomp.connected$.subscribe(() => {
|
|
236
|
+
activation.established();
|
|
237
|
+
this.initialConnectionSuccessful = true;
|
|
238
|
+
this.connectionAttempts = 0;
|
|
239
|
+
}));
|
|
240
|
+
activation.pending(reject);
|
|
241
|
+
activation.own(this.rxStomp.serverHeaders$.pipe(skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
|
|
242
|
+
this.rxStompHasConnected = true;
|
|
205
243
|
const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
|
|
206
244
|
if (connectedInfoJson == null) {
|
|
207
245
|
if (!this.initialConnectionSuccessful) {
|
|
246
|
+
activation.failIfPending(new Error("Server did not return proper data for successful login"));
|
|
208
247
|
await this.deactivate();
|
|
209
|
-
reject("Server did not return proper data for successful login");
|
|
210
248
|
}
|
|
211
249
|
return;
|
|
212
250
|
}
|
|
213
251
|
const connectedInfo = JSON.parse(connectedInfoJson);
|
|
214
252
|
if (connectedInfo.replyToId == null) {
|
|
215
253
|
if (!this.initialConnectionSuccessful) {
|
|
254
|
+
activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
|
|
216
255
|
await this.deactivate();
|
|
217
|
-
reject("Server did not return a replyToId for successful login");
|
|
218
256
|
}
|
|
219
257
|
return;
|
|
220
258
|
}
|
|
221
|
-
const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" +
|
|
259
|
+
const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + uuidv4() + "@kinotic.js.EventBus/replyHandler";
|
|
260
|
+
this._replyToCri = newReplyToCri;
|
|
222
261
|
if (!this.initialConnectionSuccessful) {
|
|
223
|
-
this._replyToCri = newReplyToCri;
|
|
224
262
|
resolve(connectedInfo);
|
|
225
|
-
} else if (this._replyToCri !== newReplyToCri) {
|
|
226
|
-
this._replyToCri = newReplyToCri;
|
|
227
|
-
this.replyToCriChangedHandler?.(newReplyToCri);
|
|
228
263
|
}
|
|
229
|
-
});
|
|
264
|
+
}));
|
|
265
|
+
let previousState = this.rxStomp.connectionState$.getValue();
|
|
266
|
+
activation.own(this.rxStomp.connectionState$.subscribe((state) => {
|
|
267
|
+
if (state === RxStompState.CLOSED && previousState === RxStompState.OPEN && this.activation === activation) {
|
|
268
|
+
this.connectionLostHandler?.();
|
|
269
|
+
}
|
|
270
|
+
previousState = state;
|
|
271
|
+
}));
|
|
230
272
|
this.rxStomp.activate();
|
|
231
273
|
});
|
|
232
274
|
}
|
|
233
|
-
async
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
275
|
+
async prepareAttempt(activation, options, server, headerAuth) {
|
|
276
|
+
const credentialsResolver = options.credentials;
|
|
277
|
+
const userWebSocketFactory = options.webSocketFactory;
|
|
278
|
+
const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
|
|
279
|
+
const url = buildBrokerUrl(server);
|
|
280
|
+
if (!usesPreparedSocket) {
|
|
281
|
+
const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
|
|
282
|
+
try {
|
|
283
|
+
const res = await fetch(sessionCheckUrl, { credentials: "include" });
|
|
284
|
+
if (res.status === 401) {
|
|
285
|
+
await this.signalFatal(activation, new Error("Authentication required"));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
} catch (e) {
|
|
289
|
+
this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (options?.maxConnectionAttempts) {
|
|
293
|
+
this.connectionAttempts++;
|
|
294
|
+
if (this.connectionAttempts > options.maxConnectionAttempts) {
|
|
295
|
+
this.maxConnectionAttemptsReached = true;
|
|
296
|
+
await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
|
|
297
|
+
return;
|
|
298
|
+
} else {
|
|
299
|
+
await this.connectionJitterDelay(activation);
|
|
300
|
+
}
|
|
301
|
+
} else {
|
|
302
|
+
await this.connectionJitterDelay(activation);
|
|
303
|
+
}
|
|
304
|
+
if (activation.ended) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (userWebSocketFactory) {
|
|
308
|
+
try {
|
|
309
|
+
activation.preparedSocket = await userWebSocketFactory();
|
|
310
|
+
} catch (e) {
|
|
311
|
+
await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
|
|
312
|
+
}
|
|
313
|
+
} else if (headerAuth) {
|
|
314
|
+
try {
|
|
315
|
+
const resolved = await credentialsResolver.resolve(server);
|
|
316
|
+
if (resolved?.authHeaders == null) {
|
|
317
|
+
await this.signalFatal(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
|
|
318
|
+
} else {
|
|
319
|
+
const WS = WebSocket;
|
|
320
|
+
activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
|
|
321
|
+
}
|
|
322
|
+
} catch (e) {
|
|
323
|
+
await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
|
|
244
324
|
}
|
|
245
325
|
}
|
|
246
|
-
|
|
326
|
+
if (activation.ended && activation.preparedSocket) {
|
|
327
|
+
activation.preparedSocket.close();
|
|
328
|
+
activation.preparedSocket = null;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
deactivate(force) {
|
|
332
|
+
const activation = this.activation;
|
|
333
|
+
let ret;
|
|
334
|
+
if (activation) {
|
|
335
|
+
this.activation = null;
|
|
336
|
+
activation.end();
|
|
337
|
+
const wasOpen = this.rxStomp.connected();
|
|
338
|
+
this._replyToCri = null;
|
|
339
|
+
activation.failIfPending(new Error("Deactivated before the connection was established"));
|
|
340
|
+
activation.preparedSocket?.close();
|
|
341
|
+
activation.preparedSocket = null;
|
|
342
|
+
const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
|
|
343
|
+
activation.unsubscribeAll();
|
|
344
|
+
this.teardown = null;
|
|
345
|
+
if (wasOpen) {
|
|
346
|
+
this.connectionLostHandler?.();
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
this.teardown = teardown;
|
|
350
|
+
ret = teardown;
|
|
351
|
+
} else {
|
|
352
|
+
ret = this.teardown ?? Promise.resolve();
|
|
353
|
+
}
|
|
354
|
+
return ret;
|
|
247
355
|
}
|
|
248
|
-
async connectionJitterDelay() {
|
|
356
|
+
async connectionJitterDelay(activation) {
|
|
249
357
|
if (this.initialConnectionSuccessful) {
|
|
250
358
|
const randomJitter = Math.random() * this.JITTER_MAX;
|
|
251
359
|
this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
|
|
252
|
-
|
|
360
|
+
await activation.delay(randomJitter);
|
|
253
361
|
}
|
|
254
362
|
}
|
|
255
|
-
async signalFatal(err) {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
363
|
+
async signalFatal(activation, err) {
|
|
364
|
+
if (!activation.ended) {
|
|
365
|
+
this.debugLogger("Fatal error, deactivating connection: %O", err);
|
|
366
|
+
activation.failIfPending(err);
|
|
367
|
+
await this.deactivate();
|
|
368
|
+
this.fatalErrorsSubject.next(err);
|
|
369
|
+
}
|
|
259
370
|
}
|
|
260
371
|
}
|
|
261
372
|
|
|
262
373
|
// packages/core/src/api/event/EventBus.ts
|
|
263
374
|
import { context, propagation } from "@opentelemetry/api";
|
|
264
|
-
import { firstValueFrom, Observable as Observable2, Subject as Subject2
|
|
375
|
+
import { firstValueFrom, Observable as Observable2, Subject as Subject2 } from "rxjs";
|
|
265
376
|
import { filter, map, multicast, tap } from "rxjs/operators";
|
|
266
377
|
import { Optional } from "typescript-optional";
|
|
267
378
|
import { v4 as uuidv42 } from "uuid";
|
|
379
|
+
|
|
380
|
+
// packages/core/src/api/event/RpcError.ts
|
|
381
|
+
class RpcError extends Error {
|
|
382
|
+
exceptionName;
|
|
383
|
+
exceptionClass;
|
|
384
|
+
constructor(message, exceptionName, exceptionClass) {
|
|
385
|
+
super(message);
|
|
386
|
+
this.name = "RpcError";
|
|
387
|
+
this.exceptionName = exceptionName;
|
|
388
|
+
this.exceptionClass = exceptionClass;
|
|
389
|
+
}
|
|
390
|
+
static fromEvent(reply) {
|
|
391
|
+
const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
|
|
392
|
+
let ret;
|
|
393
|
+
const detail = describedException(reply);
|
|
394
|
+
if (detail !== undefined) {
|
|
395
|
+
ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
|
|
396
|
+
} else {
|
|
397
|
+
ret = new RpcError(message, "", "");
|
|
398
|
+
}
|
|
399
|
+
return ret;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
function describedException(reply) {
|
|
403
|
+
let ret = undefined;
|
|
404
|
+
if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
|
|
405
|
+
try {
|
|
406
|
+
const parsed = JSON.parse(reply.getDataString());
|
|
407
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
408
|
+
ret = parsed;
|
|
409
|
+
}
|
|
410
|
+
} catch {}
|
|
411
|
+
}
|
|
412
|
+
return ret;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// packages/core/src/api/event/EventBus.ts
|
|
268
416
|
class Event {
|
|
269
417
|
cri;
|
|
270
418
|
headers;
|
|
@@ -303,41 +451,45 @@ class Event {
|
|
|
303
451
|
|
|
304
452
|
class EventBus {
|
|
305
453
|
serverInfo = null;
|
|
454
|
+
log = createDebugLogger("kinotic:EventBus");
|
|
306
455
|
stompConnectionManager = new StompConnectionManager;
|
|
307
456
|
connectionLifecycle = Promise.resolve();
|
|
308
|
-
|
|
457
|
+
disconnectRequests = 0;
|
|
309
458
|
requestRepliesObservable = null;
|
|
310
459
|
requestRepliesSubject = null;
|
|
311
460
|
requestRepliesSubscription = null;
|
|
312
461
|
activeCorrelationIds = new Set;
|
|
313
462
|
recentlyReaped = new Set;
|
|
463
|
+
connectionLostSubject = new Subject2;
|
|
314
464
|
static REAP_DEBOUNCE_MS = 5000;
|
|
315
465
|
constructor() {
|
|
316
|
-
this.stompConnectionManager.fatalErrors.subscribe(() => this.
|
|
317
|
-
this.stompConnectionManager.
|
|
318
|
-
this.
|
|
319
|
-
this.
|
|
466
|
+
this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
|
|
467
|
+
this.stompConnectionManager.connectionLostHandler = () => {
|
|
468
|
+
this.resetRequestReplies("Connection lost");
|
|
469
|
+
this.connectionLostSubject.next();
|
|
320
470
|
};
|
|
321
471
|
}
|
|
322
472
|
get fatalErrors() {
|
|
323
473
|
return this.stompConnectionManager.fatalErrors;
|
|
324
474
|
}
|
|
475
|
+
get connectionLost() {
|
|
476
|
+
return this.connectionLostSubject.asObservable();
|
|
477
|
+
}
|
|
325
478
|
isConnectionActive() {
|
|
326
479
|
return this.stompConnectionManager.active;
|
|
327
480
|
}
|
|
328
481
|
isConnected() {
|
|
329
482
|
return this.stompConnectionManager.connected;
|
|
330
483
|
}
|
|
331
|
-
connect(
|
|
484
|
+
connect(options) {
|
|
485
|
+
const disconnectsWhenQueued = this.disconnectRequests;
|
|
332
486
|
return this.serializeLifecycle(async () => {
|
|
487
|
+
if (this.disconnectRequests !== disconnectsWhenQueued) {
|
|
488
|
+
throw new Error("Disconnected before the connection was started");
|
|
489
|
+
}
|
|
333
490
|
if (!this.stompConnectionManager.active) {
|
|
334
|
-
this.
|
|
335
|
-
|
|
336
|
-
this.serverInfo = new ServerInfo;
|
|
337
|
-
this.serverInfo.host = connectionInfo.host;
|
|
338
|
-
this.serverInfo.port = connectionInfo.port;
|
|
339
|
-
this.serverInfo.useSSL = connectionInfo.useSSL;
|
|
340
|
-
this.replyToCri = this.stompConnectionManager.replyToCri;
|
|
491
|
+
const connectedInfo = await this.stompConnectionManager.activate(options);
|
|
492
|
+
this.serverInfo = { ...options.server };
|
|
341
493
|
return connectedInfo;
|
|
342
494
|
} else {
|
|
343
495
|
throw new Error("Event Bus connection already active");
|
|
@@ -345,9 +497,12 @@ class EventBus {
|
|
|
345
497
|
});
|
|
346
498
|
}
|
|
347
499
|
disconnect(force) {
|
|
500
|
+
this.disconnectRequests++;
|
|
501
|
+
const deactivated = this.stompConnectionManager.deactivate(force);
|
|
348
502
|
return this.serializeLifecycle(async () => {
|
|
503
|
+
await deactivated;
|
|
349
504
|
await this.stompConnectionManager.deactivate(force);
|
|
350
|
-
this.
|
|
505
|
+
this.serverInfo = null;
|
|
351
506
|
});
|
|
352
507
|
}
|
|
353
508
|
serializeLifecycle(operation) {
|
|
@@ -356,7 +511,7 @@ class EventBus {
|
|
|
356
511
|
return result;
|
|
357
512
|
}
|
|
358
513
|
send(event) {
|
|
359
|
-
if (this.stompConnectionManager.
|
|
514
|
+
if (this.stompConnectionManager.connected) {
|
|
360
515
|
const headers = {};
|
|
361
516
|
for (const [key, value] of event.headers.entries()) {
|
|
362
517
|
headers[key] = value;
|
|
@@ -372,7 +527,8 @@ class EventBus {
|
|
|
372
527
|
this.stompConnectionManager.rxStomp.publish({
|
|
373
528
|
destination: event.cri,
|
|
374
529
|
headers,
|
|
375
|
-
binaryBody: event.data.orUndefined()
|
|
530
|
+
binaryBody: event.data.orUndefined(),
|
|
531
|
+
retryIfDisconnected: false
|
|
376
532
|
});
|
|
377
533
|
} else {
|
|
378
534
|
throw this.createSendUnavailableError();
|
|
@@ -382,58 +538,65 @@ class EventBus {
|
|
|
382
538
|
return firstValueFrom(this.requestStream(event, false));
|
|
383
539
|
}
|
|
384
540
|
requestStream(event, sendControlEvents = true) {
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
this.
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
541
|
+
return new Observable2((subscriber) => {
|
|
542
|
+
const replyToCri = this.stompConnectionManager.replyToCri;
|
|
543
|
+
if (!this.stompConnectionManager.connected || replyToCri == null) {
|
|
544
|
+
subscriber.error(this.createSendUnavailableError());
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (this.requestRepliesObservable == null) {
|
|
548
|
+
this.requestRepliesSubject = new Subject2;
|
|
549
|
+
this.requestRepliesObservable = this._observe(replyToCri).pipe(tap((value) => this.cancelIfUnexpected(value)), multicast(this.requestRepliesSubject));
|
|
550
|
+
this.requestRepliesSubscription = this.requestRepliesObservable.connect();
|
|
551
|
+
}
|
|
552
|
+
let serverSignaledCompletion = false;
|
|
553
|
+
let replyDestinationReset = false;
|
|
554
|
+
const correlationId = uuidv42();
|
|
555
|
+
this.activeCorrelationIds.add(correlationId);
|
|
556
|
+
subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
|
|
557
|
+
const defaultMessagesSubscription = this.requestRepliesObservable.pipe(filter((value) => {
|
|
558
|
+
return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
|
|
559
|
+
})).subscribe({
|
|
560
|
+
next(value) {
|
|
561
|
+
if (value.hasHeader("control" /* CONTROL_HEADER */)) {
|
|
562
|
+
if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
|
|
407
563
|
serverSignaledCompletion = true;
|
|
408
|
-
|
|
564
|
+
if (value.data.isPresent() || !sendControlEvents) {
|
|
565
|
+
subscriber.next(value);
|
|
566
|
+
}
|
|
567
|
+
subscriber.complete();
|
|
409
568
|
} else {
|
|
410
|
-
subscriber.
|
|
569
|
+
subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
|
|
411
570
|
}
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
subscriber.error(
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
subscriber.complete();
|
|
571
|
+
} else if (value.hasHeader("error" /* ERROR_HEADER */)) {
|
|
572
|
+
serverSignaledCompletion = true;
|
|
573
|
+
subscriber.error(RpcError.fromEvent(value));
|
|
574
|
+
} else {
|
|
575
|
+
subscriber.next(value);
|
|
418
576
|
}
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
577
|
+
},
|
|
578
|
+
error(err) {
|
|
579
|
+
replyDestinationReset = true;
|
|
580
|
+
subscriber.error(err);
|
|
581
|
+
},
|
|
582
|
+
complete() {
|
|
583
|
+
subscriber.complete();
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
subscriber.add(defaultMessagesSubscription);
|
|
587
|
+
event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
|
|
588
|
+
event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
589
|
+
this.send(event);
|
|
590
|
+
subscriber.add(() => {
|
|
591
|
+
if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
|
|
592
|
+
try {
|
|
593
|
+
this.sendCancel(event.cri, correlationId);
|
|
594
|
+
} catch (e) {
|
|
595
|
+
this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
|
|
431
596
|
}
|
|
432
|
-
}
|
|
597
|
+
}
|
|
433
598
|
});
|
|
434
|
-
}
|
|
435
|
-
return throwError(() => this.createSendUnavailableError());
|
|
436
|
-
}
|
|
599
|
+
});
|
|
437
600
|
}
|
|
438
601
|
listen(_serverInfo) {
|
|
439
602
|
return Promise.reject("Not implemented");
|
|
@@ -441,10 +604,6 @@ class EventBus {
|
|
|
441
604
|
observe(cri) {
|
|
442
605
|
return this._observe(cri);
|
|
443
606
|
}
|
|
444
|
-
cleanup() {
|
|
445
|
-
this.resetRequestReplies("Connection disconnected");
|
|
446
|
-
this.serverInfo = null;
|
|
447
|
-
}
|
|
448
607
|
cancelIfUnexpected(value) {
|
|
449
608
|
const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
|
|
450
609
|
if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
|
|
@@ -455,13 +614,19 @@ class EventBus {
|
|
|
455
614
|
return;
|
|
456
615
|
}
|
|
457
616
|
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);
|
|
617
|
+
this.sendCancel(originCri, correlationId);
|
|
462
618
|
this.recentlyReaped.add(correlationId);
|
|
463
619
|
setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
|
|
464
|
-
} catch {
|
|
620
|
+
} catch (e) {
|
|
621
|
+
this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
sendCancel(cri, correlationId) {
|
|
625
|
+
const cancelEvent = new Event(cri);
|
|
626
|
+
cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
|
|
627
|
+
cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
|
|
628
|
+
cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
|
|
629
|
+
this.send(cancelEvent);
|
|
465
630
|
}
|
|
466
631
|
resetRequestReplies(reason) {
|
|
467
632
|
if (this.requestRepliesSubject != null) {
|
|
@@ -476,29 +641,167 @@ class EventBus {
|
|
|
476
641
|
}
|
|
477
642
|
}
|
|
478
643
|
createSendUnavailableError() {
|
|
479
|
-
let ret
|
|
644
|
+
let ret;
|
|
480
645
|
if (this.stompConnectionManager.maxConnectionAttemptsReached) {
|
|
481
646
|
ret = "Max connection attempts reached event bus is not available";
|
|
647
|
+
} else if (this.stompConnectionManager.active) {
|
|
648
|
+
ret = "The event bus is not connected to the server";
|
|
649
|
+
} else {
|
|
650
|
+
ret = "You must call connect on the event bus before sending any request";
|
|
482
651
|
}
|
|
483
652
|
return new Error(ret);
|
|
484
653
|
}
|
|
485
654
|
_observe(cri) {
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
headers.set(prop, message.headers[prop]);
|
|
495
|
-
}
|
|
655
|
+
return this.stompConnectionManager.rxStomp.watch(cri).pipe(map((message) => {
|
|
656
|
+
const headers = new Map;
|
|
657
|
+
let destination = "";
|
|
658
|
+
for (const prop of Object.keys(message.headers)) {
|
|
659
|
+
if (prop === "destination") {
|
|
660
|
+
destination = message.headers[prop];
|
|
661
|
+
} else {
|
|
662
|
+
headers.set(prop, message.headers[prop]);
|
|
496
663
|
}
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
}
|
|
500
|
-
|
|
664
|
+
}
|
|
665
|
+
return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
|
|
666
|
+
}));
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// packages/core/src/api/security/ChainedCredentialsResolver.ts
|
|
671
|
+
class ChainedCredentialsResolver {
|
|
672
|
+
name;
|
|
673
|
+
resolvers;
|
|
674
|
+
constructor(...resolvers) {
|
|
675
|
+
this.resolvers = resolvers;
|
|
676
|
+
this.name = `ChainedCredentialsResolver(${resolvers.map((r) => r.name).join(" -> ")})`;
|
|
677
|
+
}
|
|
678
|
+
async resolve(server) {
|
|
679
|
+
for (const resolver of this.resolvers) {
|
|
680
|
+
const resolved = await resolver.resolve(server);
|
|
681
|
+
if (resolved !== null) {
|
|
682
|
+
return resolved;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return null;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// packages/core/src/api/security/BasicCredentialsResolver.ts
|
|
690
|
+
class BasicCredentialsResolver {
|
|
691
|
+
name = "BasicCredentialsResolver";
|
|
692
|
+
credentials;
|
|
693
|
+
constructor(clientId, clientSecret, organizationId, applicationId) {
|
|
694
|
+
const authHeaders = { clientId, clientSecret };
|
|
695
|
+
if (organizationId != null)
|
|
696
|
+
authHeaders.organizationId = organizationId;
|
|
697
|
+
if (applicationId != null)
|
|
698
|
+
authHeaders.applicationId = applicationId;
|
|
699
|
+
this.credentials = { authHeaders, organizationId, applicationId };
|
|
700
|
+
}
|
|
701
|
+
async resolve(_server) {
|
|
702
|
+
return this.credentials;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// packages/core/src/api/security/BearerCredentialsResolver.ts
|
|
707
|
+
class BearerCredentialsResolver {
|
|
708
|
+
name = "BearerCredentialsResolver";
|
|
709
|
+
token;
|
|
710
|
+
constructor(token) {
|
|
711
|
+
this.token = token;
|
|
712
|
+
}
|
|
713
|
+
async resolve(_server) {
|
|
714
|
+
const token = typeof this.token === "function" ? await this.token() : this.token;
|
|
715
|
+
return { authHeaders: { Authorization: `Bearer ${token}` } };
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// packages/core/src/api/security/EnvCredentialsResolver.ts
|
|
720
|
+
class EnvCredentialsResolver {
|
|
721
|
+
name = "EnvCredentialsResolver";
|
|
722
|
+
async resolve(server) {
|
|
723
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
724
|
+
let ret = null;
|
|
725
|
+
if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
|
|
726
|
+
ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
|
|
727
|
+
} else if (env?.KINOTIC_TOKEN) {
|
|
728
|
+
ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
|
|
501
729
|
}
|
|
730
|
+
return ret;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// packages/core/src/api/security/SessionCredentialsResolver.ts
|
|
735
|
+
class SessionCredentialsResolver {
|
|
736
|
+
name = "SessionCredentialsResolver";
|
|
737
|
+
async resolve(_server) {
|
|
738
|
+
return typeof document !== "undefined" ? {} : null;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// packages/core/src/internal/api/Util.ts
|
|
743
|
+
var DEFAULT_PORT = 58503;
|
|
744
|
+
var DEFAULT_HOST = "api.kinotic.ai";
|
|
745
|
+
|
|
746
|
+
class Util {
|
|
747
|
+
static createReplyEvent(incomingHeaders, headers, body) {
|
|
748
|
+
if (!incomingHeaders) {
|
|
749
|
+
throw new Error("incomingHeaders cannot be null");
|
|
750
|
+
}
|
|
751
|
+
const replyCRI = incomingHeaders.get("reply-to" /* REPLY_TO_HEADER */);
|
|
752
|
+
if (!replyCRI || replyCRI.trim() === "") {
|
|
753
|
+
throw new Error("No reply-to header found, cannot create outgoing message");
|
|
754
|
+
}
|
|
755
|
+
const newHeaders = new Map;
|
|
756
|
+
for (const [key, value] of incomingHeaders) {
|
|
757
|
+
if (key.startsWith("__")) {
|
|
758
|
+
newHeaders.set(key, value);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (headers) {
|
|
762
|
+
for (const [key, value] of headers) {
|
|
763
|
+
newHeaders.set(key, value);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return new Event(replyCRI, newHeaders, body || undefined);
|
|
767
|
+
}
|
|
768
|
+
static resolveConnectOptions(options) {
|
|
769
|
+
const opts = options ?? {};
|
|
770
|
+
const server = opts.server ?? {};
|
|
771
|
+
const env = typeof process !== "undefined" ? process.env : undefined;
|
|
772
|
+
const location = typeof window !== "undefined" ? window.location : undefined;
|
|
773
|
+
let host = server.host ?? env?.KINOTIC_SERVER_HOST;
|
|
774
|
+
const hostFromLocation = host == null && location != null;
|
|
775
|
+
const hostDefaulted = host == null && location == null;
|
|
776
|
+
if (host == null) {
|
|
777
|
+
host = location?.hostname ?? DEFAULT_HOST;
|
|
778
|
+
}
|
|
779
|
+
let useSSL = server.useSSL;
|
|
780
|
+
if (useSSL == null) {
|
|
781
|
+
if (env?.KINOTIC_SERVER_USE_SSL != null) {
|
|
782
|
+
useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
|
|
783
|
+
} else if (hostFromLocation) {
|
|
784
|
+
useSSL = location.protocol === "https:";
|
|
785
|
+
} else {
|
|
786
|
+
useSSL = hostDefaulted;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
let port = server.port;
|
|
790
|
+
if (port === undefined) {
|
|
791
|
+
if (env?.KINOTIC_SERVER_PORT != null) {
|
|
792
|
+
port = Number(env.KINOTIC_SERVER_PORT);
|
|
793
|
+
} else if (hostFromLocation) {
|
|
794
|
+
port = location.port ? Number(location.port) : null;
|
|
795
|
+
} else {
|
|
796
|
+
port = useSSL ? null : DEFAULT_PORT;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return {
|
|
800
|
+
...opts,
|
|
801
|
+
server: { host, port, useSSL },
|
|
802
|
+
sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
|
|
803
|
+
credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
|
|
804
|
+
};
|
|
502
805
|
}
|
|
503
806
|
}
|
|
504
807
|
|
|
@@ -691,22 +994,14 @@ class JsonArgumentResolver {
|
|
|
691
994
|
// packages/core/src/internal/api/ReturnValueConverter.ts
|
|
692
995
|
class BasicReturnValueConverter {
|
|
693
996
|
convert(incomingMetadata, returnValue) {
|
|
694
|
-
|
|
997
|
+
const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
|
|
998
|
+
return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
|
|
695
999
|
}
|
|
696
1000
|
}
|
|
697
1001
|
|
|
698
|
-
// packages/core/src/internal/api/
|
|
699
|
-
import
|
|
700
|
-
|
|
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
|
-
}
|
|
1002
|
+
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
1003
|
+
import { isObservable } from "rxjs";
|
|
1004
|
+
import { finalize } from "rxjs/operators";
|
|
710
1005
|
|
|
711
1006
|
// packages/core/src/api/ServiceIdentifier.ts
|
|
712
1007
|
class ServiceIdentifier {
|
|
@@ -743,6 +1038,9 @@ class ServiceIdentifier {
|
|
|
743
1038
|
}
|
|
744
1039
|
return this._cri;
|
|
745
1040
|
}
|
|
1041
|
+
unscopedCri() {
|
|
1042
|
+
return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
|
|
1043
|
+
}
|
|
746
1044
|
}
|
|
747
1045
|
|
|
748
1046
|
// packages/core/src/api/ZoneUtil.ts
|
|
@@ -762,6 +1060,7 @@ function validateLabel(label) {
|
|
|
762
1060
|
|
|
763
1061
|
// packages/core/src/api/KinoticDecorators.ts
|
|
764
1062
|
var scopeFunctions = new WeakSet;
|
|
1063
|
+
var scopeOptionalFunctions = new WeakSet;
|
|
765
1064
|
var versionRegistry = new WeakMap;
|
|
766
1065
|
var zonesRegistry = new WeakMap;
|
|
767
1066
|
var advertisedRegistry = new WeakMap;
|
|
@@ -799,6 +1098,23 @@ function resolveScope(instance) {
|
|
|
799
1098
|
function Scope(value, _context) {
|
|
800
1099
|
scopeFunctions.add(value);
|
|
801
1100
|
}
|
|
1101
|
+
function ScopeOptional(value, _context) {
|
|
1102
|
+
scopeOptionalFunctions.add(value);
|
|
1103
|
+
}
|
|
1104
|
+
function scopeOptionalMethodNames(instance) {
|
|
1105
|
+
const ret = new Set;
|
|
1106
|
+
let proto = Object.getPrototypeOf(instance);
|
|
1107
|
+
while (proto && proto !== Object.prototype) {
|
|
1108
|
+
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
1109
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
1110
|
+
if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
|
|
1111
|
+
ret.add(key);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
proto = Object.getPrototypeOf(proto);
|
|
1115
|
+
}
|
|
1116
|
+
return ret;
|
|
1117
|
+
}
|
|
802
1118
|
function Version(version) {
|
|
803
1119
|
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
|
|
804
1120
|
throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
|
|
@@ -861,6 +1177,93 @@ function Publish(namespace, name, advertise = false) {
|
|
|
861
1177
|
};
|
|
862
1178
|
}
|
|
863
1179
|
|
|
1180
|
+
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
1181
|
+
import opentelemetry, { context as context2, propagation as propagation2, trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
|
|
1182
|
+
// packages/core/package.json
|
|
1183
|
+
var package_default = {
|
|
1184
|
+
name: "@kinotic-ai/core",
|
|
1185
|
+
version: "5.0.0-beta.11",
|
|
1186
|
+
type: "module",
|
|
1187
|
+
files: [
|
|
1188
|
+
"dist"
|
|
1189
|
+
],
|
|
1190
|
+
module: "./dist/index.js",
|
|
1191
|
+
main: "./dist/index.cjs",
|
|
1192
|
+
types: "./dist/index.d.ts",
|
|
1193
|
+
exports: {
|
|
1194
|
+
".": {
|
|
1195
|
+
import: {
|
|
1196
|
+
types: "./dist/index.d.ts",
|
|
1197
|
+
default: "./dist/index.js"
|
|
1198
|
+
},
|
|
1199
|
+
require: {
|
|
1200
|
+
types: "./dist/index.d.cts",
|
|
1201
|
+
default: "./dist/index.cjs"
|
|
1202
|
+
}
|
|
1203
|
+
},
|
|
1204
|
+
"./node": {
|
|
1205
|
+
import: {
|
|
1206
|
+
types: "./dist/node/index.d.ts",
|
|
1207
|
+
default: "./dist/node/index.js"
|
|
1208
|
+
},
|
|
1209
|
+
require: {
|
|
1210
|
+
types: "./dist/node/index.d.cts",
|
|
1211
|
+
default: "./dist/node/index.cjs"
|
|
1212
|
+
}
|
|
1213
|
+
},
|
|
1214
|
+
"./package.json": "./package.json"
|
|
1215
|
+
},
|
|
1216
|
+
homepage: "https://github.com/kinotic-ai/kinotic",
|
|
1217
|
+
repository: {
|
|
1218
|
+
type: "git",
|
|
1219
|
+
url: "git+https://github.com/kinotic-ai/kinotic.git",
|
|
1220
|
+
directory: "kinotic-js/workspace/packages/core"
|
|
1221
|
+
},
|
|
1222
|
+
license: "Elastic License 2.0",
|
|
1223
|
+
publishConfig: {
|
|
1224
|
+
access: "public"
|
|
1225
|
+
},
|
|
1226
|
+
scripts: {
|
|
1227
|
+
"type-check": "tsc --noEmit",
|
|
1228
|
+
test: "vitest run",
|
|
1229
|
+
coverage: "vitest run --coverage",
|
|
1230
|
+
"ui-test": "vitest --ui --coverage.enabled=true --mode development"
|
|
1231
|
+
},
|
|
1232
|
+
devDependencies: {
|
|
1233
|
+
"@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
|
|
1234
|
+
"@opentelemetry/resources": "^2.10.0",
|
|
1235
|
+
"@opentelemetry/sdk-metrics": "^2.10.0",
|
|
1236
|
+
"@opentelemetry/sdk-node": "^0.221.0",
|
|
1237
|
+
"@opentelemetry/sdk-trace-node": "^2.10.0",
|
|
1238
|
+
"@types/debug": "^4.1.13",
|
|
1239
|
+
"@types/node": "^25.6.0",
|
|
1240
|
+
"@types/ws": "^8.18.0",
|
|
1241
|
+
"@vitest/coverage-v8": "^4.1.4",
|
|
1242
|
+
"@vitest/runner": "^4.1.4",
|
|
1243
|
+
"@vitest/ui": "^4.1.4",
|
|
1244
|
+
allure: "^3.14.3",
|
|
1245
|
+
"allure-vitest": "^3.10.2",
|
|
1246
|
+
dotenv: "^17.4.1",
|
|
1247
|
+
"properties-file": "^4.0.0",
|
|
1248
|
+
testcontainers: "^11.14.0",
|
|
1249
|
+
tslib: "^2.8.1",
|
|
1250
|
+
typescript: "^6.0.2",
|
|
1251
|
+
vitest: "^4.1.4"
|
|
1252
|
+
},
|
|
1253
|
+
dependencies: {
|
|
1254
|
+
"@opentelemetry/api": "^1.9.1",
|
|
1255
|
+
"@opentelemetry/semantic-conventions": "^1.40.0",
|
|
1256
|
+
"@stomp/rx-stomp": "^2.4.0",
|
|
1257
|
+
"@stomp/stompjs": "^7.3.0",
|
|
1258
|
+
debug: "^4.4.3",
|
|
1259
|
+
"p-tap": "^4.0.0",
|
|
1260
|
+
rxjs: "^7.8.2",
|
|
1261
|
+
"typescript-optional": "3.0.0-alpha.3",
|
|
1262
|
+
uuid: "^13.0.0",
|
|
1263
|
+
ws: "^8.21.0"
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
|
|
864
1267
|
// packages/core/src/internal/api/ServiceInvocationSupervisor.ts
|
|
865
1268
|
class ServiceInvocationSupervisor {
|
|
866
1269
|
log;
|
|
@@ -872,7 +1275,13 @@ class ServiceInvocationSupervisor {
|
|
|
872
1275
|
serviceIdentifier;
|
|
873
1276
|
serviceInstance;
|
|
874
1277
|
methodSubscription = null;
|
|
1278
|
+
unscopedSubscription = null;
|
|
1279
|
+
activeStreams = new Map;
|
|
1280
|
+
connectionLostSubscription = null;
|
|
1281
|
+
connectionGeneration = 0;
|
|
875
1282
|
methodMap;
|
|
1283
|
+
scopeOptionalMethods;
|
|
1284
|
+
tracer;
|
|
876
1285
|
constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
|
|
877
1286
|
if (!serviceIdentifier)
|
|
878
1287
|
throw new Error("ServiceIdentifier must not be null");
|
|
@@ -886,10 +1295,12 @@ class ServiceInvocationSupervisor {
|
|
|
886
1295
|
this.serviceInstance = serviceInstance;
|
|
887
1296
|
this._eventBus = eventBusService;
|
|
888
1297
|
this.interceptorProvider = interceptorProvider;
|
|
889
|
-
this.log = options.logger || createDebugLogger("
|
|
1298
|
+
this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
|
|
890
1299
|
this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
|
|
891
1300
|
this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
|
|
892
1301
|
this.methodMap = this.buildMethodMap(serviceInstance);
|
|
1302
|
+
this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
|
|
1303
|
+
this.tracer = opentelemetry.trace.getTracer(package_default.name, package_default.version);
|
|
893
1304
|
}
|
|
894
1305
|
isActive() {
|
|
895
1306
|
return this.active;
|
|
@@ -909,7 +1320,22 @@ class ServiceInvocationSupervisor {
|
|
|
909
1320
|
}
|
|
910
1321
|
this.active = true;
|
|
911
1322
|
const criBase = this.serviceIdentifier.cri().baseResource();
|
|
912
|
-
this.methodSubscription = this.
|
|
1323
|
+
this.methodSubscription = this.subscribeAt(criBase);
|
|
1324
|
+
this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
|
|
1325
|
+
if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
|
|
1326
|
+
const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
|
|
1327
|
+
this.unscopedSubscription = this.subscribeAt(unscopedBase);
|
|
1328
|
+
this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
|
|
1329
|
+
}
|
|
1330
|
+
this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
|
|
1331
|
+
this.connectionGeneration++;
|
|
1332
|
+
for (const stream of this.activeStreams.values()) {
|
|
1333
|
+
stream.subscription.unsubscribe();
|
|
1334
|
+
}
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
subscribeAt(criBase) {
|
|
1338
|
+
return this._eventBus.observe(criBase).subscribe({
|
|
913
1339
|
next: async (event) => {
|
|
914
1340
|
await this.processEvent(event);
|
|
915
1341
|
},
|
|
@@ -922,7 +1348,6 @@ class ServiceInvocationSupervisor {
|
|
|
922
1348
|
this.active = false;
|
|
923
1349
|
}
|
|
924
1350
|
});
|
|
925
|
-
this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
|
|
926
1351
|
}
|
|
927
1352
|
stop() {
|
|
928
1353
|
if (!this.active) {
|
|
@@ -931,6 +1356,15 @@ class ServiceInvocationSupervisor {
|
|
|
931
1356
|
this.active = false;
|
|
932
1357
|
this.methodSubscription?.unsubscribe();
|
|
933
1358
|
this.methodSubscription = null;
|
|
1359
|
+
this.unscopedSubscription?.unsubscribe();
|
|
1360
|
+
this.unscopedSubscription = null;
|
|
1361
|
+
this.connectionLostSubscription?.unsubscribe();
|
|
1362
|
+
this.connectionLostSubscription = null;
|
|
1363
|
+
const serviceName = this.serviceIdentifier.qualifiedName();
|
|
1364
|
+
for (const stream of this.activeStreams.values()) {
|
|
1365
|
+
this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
|
|
1366
|
+
stream.subscription.unsubscribe();
|
|
1367
|
+
}
|
|
934
1368
|
this.log.info("ServiceInvocationSupervisor stopped");
|
|
935
1369
|
}
|
|
936
1370
|
buildMethodMap(serviceInstance) {
|
|
@@ -970,10 +1404,19 @@ class ServiceInvocationSupervisor {
|
|
|
970
1404
|
if (!correlationId) {
|
|
971
1405
|
throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
|
|
972
1406
|
}
|
|
973
|
-
|
|
1407
|
+
const control = event.getHeader("control" /* CONTROL_HEADER */);
|
|
1408
|
+
this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
|
|
1409
|
+
const stream = this.activeStreams.get(correlationId);
|
|
1410
|
+
if (stream) {
|
|
1411
|
+
stream.subscription.unsubscribe();
|
|
1412
|
+
if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
|
|
1413
|
+
throw new Error(`Unknown control header value ${control}`);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
974
1416
|
}
|
|
975
1417
|
async processInvocationRequest(event) {
|
|
976
|
-
const
|
|
1418
|
+
const incomingCri = createCRI(event.cri);
|
|
1419
|
+
const path = incomingCri.path();
|
|
977
1420
|
if (!path) {
|
|
978
1421
|
throw new Error("The methodId must not be blank");
|
|
979
1422
|
}
|
|
@@ -981,49 +1424,163 @@ class ServiceInvocationSupervisor {
|
|
|
981
1424
|
if (!handlerMethod) {
|
|
982
1425
|
throw new Error(`No method resolved for methodId ${path}`);
|
|
983
1426
|
}
|
|
1427
|
+
if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
|
|
1428
|
+
throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
|
|
1429
|
+
}
|
|
984
1430
|
const methodName = path;
|
|
985
|
-
const
|
|
986
|
-
const
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1431
|
+
const span = this.startInvocationSpan(event, methodName);
|
|
1432
|
+
const generation = this.connectionGeneration;
|
|
1433
|
+
try {
|
|
1434
|
+
const args = this.argumentResolver.resolveArguments(event);
|
|
1435
|
+
const injectContext = receivesContext(this.serviceInstance, methodName);
|
|
1436
|
+
let serviceContext = {};
|
|
1437
|
+
const interceptor = this.interceptorProvider();
|
|
1438
|
+
if (interceptor) {
|
|
1439
|
+
try {
|
|
1440
|
+
serviceContext = await interceptor.intercept(event, serviceContext);
|
|
1441
|
+
} catch (e) {
|
|
1442
|
+
this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
|
|
1443
|
+
if (this.replyOwed(generation)) {
|
|
1444
|
+
this.handleException(event, new Error("Internal server error"));
|
|
1445
|
+
}
|
|
1446
|
+
this.failSpan(span, e);
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
if (injectContext) {
|
|
1451
|
+
args.push(serviceContext);
|
|
1452
|
+
}
|
|
1453
|
+
const expectedArgsCount = handlerMethod.length;
|
|
1454
|
+
if (args.length !== expectedArgsCount) {
|
|
1455
|
+
throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
|
|
1456
|
+
}
|
|
1457
|
+
let result;
|
|
990
1458
|
try {
|
|
991
|
-
|
|
1459
|
+
result = context2.with(trace.setSpan(context2.active(), span), () => handlerMethod(...args));
|
|
1460
|
+
if (result instanceof Promise) {
|
|
1461
|
+
result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
|
|
1462
|
+
this.failInvocation(event, e, span, generation);
|
|
1463
|
+
});
|
|
1464
|
+
} else {
|
|
1465
|
+
this.processMethodInvocationResult(event, result, span, generation);
|
|
1466
|
+
}
|
|
992
1467
|
} catch (e) {
|
|
993
|
-
this.
|
|
994
|
-
this.handleException(event, new Error("Internal server error"));
|
|
995
|
-
return;
|
|
1468
|
+
this.failInvocation(event, e, span, generation);
|
|
996
1469
|
}
|
|
1470
|
+
} catch (e) {
|
|
1471
|
+
this.failSpan(span, e);
|
|
1472
|
+
throw e;
|
|
997
1473
|
}
|
|
998
|
-
|
|
999
|
-
|
|
1474
|
+
}
|
|
1475
|
+
startInvocationSpan(event, methodName) {
|
|
1476
|
+
const carrier = {};
|
|
1477
|
+
for (const [key, value] of event.headers.entries()) {
|
|
1478
|
+
carrier[key] = value;
|
|
1000
1479
|
}
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
|
|
1480
|
+
const serviceName = this.serviceIdentifier.qualifiedName();
|
|
1481
|
+
return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
|
|
1482
|
+
kind: SpanKind.SERVER,
|
|
1483
|
+
attributes: {
|
|
1484
|
+
"rpc.system": "kinotic",
|
|
1485
|
+
"rpc.service": serviceName,
|
|
1486
|
+
"rpc.method": methodName
|
|
1487
|
+
}
|
|
1488
|
+
}, propagation2.extract(context2.active(), carrier));
|
|
1489
|
+
}
|
|
1490
|
+
failSpan(span, error) {
|
|
1491
|
+
span.recordException(error);
|
|
1492
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1493
|
+
span.end();
|
|
1494
|
+
}
|
|
1495
|
+
replyOwed(generation) {
|
|
1496
|
+
return generation === this.connectionGeneration;
|
|
1497
|
+
}
|
|
1498
|
+
failInvocation(event, error, span, generation) {
|
|
1499
|
+
if (this.replyOwed(generation)) {
|
|
1500
|
+
this.handleException(event, error);
|
|
1004
1501
|
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1502
|
+
this.failSpan(span, error);
|
|
1503
|
+
}
|
|
1504
|
+
processMethodInvocationResult(event, result, span, generation) {
|
|
1505
|
+
if (!this.replyOwed(generation)) {
|
|
1506
|
+
span.end();
|
|
1507
|
+
} else if (isObservable(result)) {
|
|
1508
|
+
this.streamResult(event, result, span);
|
|
1509
|
+
} else {
|
|
1510
|
+
const reply = this.returnValueConverter.convert(event.headers, result);
|
|
1511
|
+
reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
|
|
1512
|
+
this.sendReply(reply);
|
|
1513
|
+
span.end();
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
streamResult(event, stream, span) {
|
|
1517
|
+
const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
|
|
1518
|
+
if (!correlationId) {
|
|
1519
|
+
throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
|
|
1520
|
+
}
|
|
1521
|
+
let subscription = null;
|
|
1522
|
+
let failed = false;
|
|
1523
|
+
subscription = stream.pipe(finalize(() => {
|
|
1524
|
+
this.activeStreams.delete(correlationId);
|
|
1525
|
+
span.end();
|
|
1526
|
+
})).subscribe({
|
|
1527
|
+
next: (value) => {
|
|
1528
|
+
if (failed) {
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
try {
|
|
1532
|
+
const reply = this.returnValueConverter.convert(event.headers, value);
|
|
1533
|
+
reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
|
|
1534
|
+
this.sendReply(reply);
|
|
1535
|
+
} catch (e) {
|
|
1536
|
+
failed = true;
|
|
1537
|
+
this.handleException(event, e);
|
|
1538
|
+
span.recordException(e);
|
|
1539
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1540
|
+
subscription?.unsubscribe();
|
|
1541
|
+
}
|
|
1542
|
+
},
|
|
1543
|
+
error: (error) => {
|
|
1544
|
+
if (failed) {
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
this.handleException(event, error);
|
|
1548
|
+
span.recordException(error);
|
|
1549
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
1550
|
+
},
|
|
1551
|
+
complete: () => {
|
|
1552
|
+
if (failed) {
|
|
1553
|
+
return;
|
|
1554
|
+
}
|
|
1555
|
+
this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
|
|
1012
1556
|
}
|
|
1013
|
-
}
|
|
1014
|
-
|
|
1557
|
+
});
|
|
1558
|
+
if (failed) {
|
|
1559
|
+
subscription.unsubscribe();
|
|
1560
|
+
}
|
|
1561
|
+
if (!subscription.closed) {
|
|
1562
|
+
this.activeStreams.set(correlationId, { request: event, subscription });
|
|
1015
1563
|
}
|
|
1016
1564
|
}
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1565
|
+
sendReply(event) {
|
|
1566
|
+
try {
|
|
1567
|
+
this._eventBus.send(event);
|
|
1568
|
+
} catch (e) {
|
|
1569
|
+
this.log.warn(`Could not send reply to ${event.cri}`, e);
|
|
1570
|
+
}
|
|
1020
1571
|
}
|
|
1021
1572
|
handleException(event, error) {
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1573
|
+
try {
|
|
1574
|
+
const errorMessage = error?.message || "Unknown error";
|
|
1575
|
+
const exceptionName = error instanceof Error ? error.constructor.name : "Error";
|
|
1576
|
+
const errorEvent = Util.createReplyEvent(event.headers, new Map([
|
|
1577
|
+
["error" /* ERROR_HEADER */, errorMessage],
|
|
1578
|
+
["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
|
|
1579
|
+
]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
|
|
1580
|
+
this.sendReply(errorEvent);
|
|
1581
|
+
} catch (e) {
|
|
1582
|
+
this.log.warn(`Could not build the error reply for ${event.cri}`, e);
|
|
1583
|
+
}
|
|
1027
1584
|
}
|
|
1028
1585
|
validateReplyTo(event) {
|
|
1029
1586
|
const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
|
|
@@ -1044,89 +1601,12 @@ class ServiceInvocationSupervisor {
|
|
|
1044
1601
|
}
|
|
1045
1602
|
|
|
1046
1603
|
// packages/core/src/api/ServiceRegistry.ts
|
|
1047
|
-
import
|
|
1604
|
+
import opentelemetry2, { SpanKind as SpanKind2, SpanStatusCode as SpanStatusCode2 } from "@opentelemetry/api";
|
|
1048
1605
|
import {
|
|
1049
1606
|
ATTR_SERVER_ADDRESS,
|
|
1050
1607
|
ATTR_SERVER_PORT
|
|
1051
1608
|
} from "@opentelemetry/semantic-conventions";
|
|
1052
1609
|
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.1",
|
|
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
1610
|
class JsonEventFactory {
|
|
1131
1611
|
create(cri, args) {
|
|
1132
1612
|
const event = new Event(cri);
|
|
@@ -1165,7 +1645,7 @@ class ServiceRegistry {
|
|
|
1165
1645
|
_eventBus;
|
|
1166
1646
|
supervisors = new Map;
|
|
1167
1647
|
contextInterceptor = null;
|
|
1168
|
-
debugLogger = debug3("
|
|
1648
|
+
debugLogger = debug3("kinotic:serviceRegistry");
|
|
1169
1649
|
constructor(eventBus) {
|
|
1170
1650
|
this._eventBus = eventBus;
|
|
1171
1651
|
}
|
|
@@ -1215,16 +1695,16 @@ class ServiceProxy {
|
|
|
1215
1695
|
}
|
|
1216
1696
|
this.serviceIdentifier = serviceIdentifier;
|
|
1217
1697
|
this.serviceRegistry = serviceRegistry;
|
|
1218
|
-
this.tracer =
|
|
1698
|
+
this.tracer = opentelemetry2.trace.getTracer(package_default.name, package_default.version);
|
|
1219
1699
|
}
|
|
1220
1700
|
invoke(methodIdentifier, args, scope, eventFactory) {
|
|
1221
1701
|
return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
|
|
1222
|
-
kind:
|
|
1702
|
+
kind: SpanKind2.CLIENT
|
|
1223
1703
|
}, async (span) => {
|
|
1224
1704
|
if (scope) {
|
|
1225
|
-
span.setAttribute("
|
|
1705
|
+
span.setAttribute("kinotic.scope", scope);
|
|
1226
1706
|
}
|
|
1227
|
-
span.setAttribute("rpc.system", "
|
|
1707
|
+
span.setAttribute("rpc.system", "kinotic");
|
|
1228
1708
|
span.setAttribute("rpc.service", this.serviceIdentifier);
|
|
1229
1709
|
span.setAttribute("rpc.method", methodIdentifier);
|
|
1230
1710
|
return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(first()).toPromise().then(async (value) => {
|
|
@@ -1232,7 +1712,7 @@ class ServiceProxy {
|
|
|
1232
1712
|
return value;
|
|
1233
1713
|
}, async (ex) => {
|
|
1234
1714
|
span.recordException(ex);
|
|
1235
|
-
span.setStatus({ code:
|
|
1715
|
+
span.setStatus({ code: SpanStatusCode2.ERROR });
|
|
1236
1716
|
span.end();
|
|
1237
1717
|
throw ex;
|
|
1238
1718
|
});
|
|
@@ -1248,7 +1728,7 @@ class ServiceProxy {
|
|
|
1248
1728
|
eventFactoryToUse = eventFactory;
|
|
1249
1729
|
}
|
|
1250
1730
|
let eventBusToUse = this.serviceRegistry.eventBus;
|
|
1251
|
-
const span =
|
|
1731
|
+
const span = opentelemetry2.trace.getActiveSpan();
|
|
1252
1732
|
if (span) {
|
|
1253
1733
|
span.setAttribute(ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
|
|
1254
1734
|
span.setAttribute(ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
|
|
@@ -1290,8 +1770,8 @@ class KinoticSingleton {
|
|
|
1290
1770
|
this._eventBus = eventBus;
|
|
1291
1771
|
this.serviceRegistry.eventBus = eventBus;
|
|
1292
1772
|
}
|
|
1293
|
-
connect(
|
|
1294
|
-
return this._eventBus.connect(
|
|
1773
|
+
connect(options) {
|
|
1774
|
+
return this._eventBus.connect(Util.resolveConnectOptions(options));
|
|
1295
1775
|
}
|
|
1296
1776
|
disconnect(force) {
|
|
1297
1777
|
return this._eventBus.disconnect(force);
|
|
@@ -1412,6 +1892,9 @@ class CrudServiceProxy {
|
|
|
1412
1892
|
deleteById(id) {
|
|
1413
1893
|
return this.serviceProxy.invoke("deleteById", [id]);
|
|
1414
1894
|
}
|
|
1895
|
+
deleteByIdSync(id) {
|
|
1896
|
+
return this.serviceProxy.invoke("deleteByIdSync", [id]);
|
|
1897
|
+
}
|
|
1415
1898
|
async findAll(pageable) {
|
|
1416
1899
|
const page = await this.findAllSinglePage(pageable);
|
|
1417
1900
|
return new FindAllIterablePage(pageable, page, this);
|
|
@@ -1534,41 +2017,6 @@ class Order {
|
|
|
1534
2017
|
class Sort {
|
|
1535
2018
|
orders = [];
|
|
1536
2019
|
}
|
|
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
2020
|
// packages/core/src/api/security/ConnectedInfo.ts
|
|
1573
2021
|
class ConnectedInfo {
|
|
1574
2022
|
replyToId;
|
|
@@ -1585,18 +2033,23 @@ class ParticipantConstants {
|
|
|
1585
2033
|
export {
|
|
1586
2034
|
validateZone,
|
|
1587
2035
|
validateLabel,
|
|
2036
|
+
scopeOptionalMethodNames,
|
|
1588
2037
|
receivesContext,
|
|
1589
2038
|
isAdvertised,
|
|
1590
2039
|
createCRI,
|
|
1591
|
-
|
|
2040
|
+
buildServerUrl,
|
|
2041
|
+
buildBrokerUrl,
|
|
1592
2042
|
Zone,
|
|
1593
2043
|
Version,
|
|
1594
2044
|
TextEventFactory,
|
|
1595
2045
|
Sort,
|
|
1596
2046
|
SessionKeepAliveMode,
|
|
2047
|
+
SessionCredentialsResolver,
|
|
1597
2048
|
ServiceRegistry,
|
|
1598
2049
|
ServerInfo,
|
|
2050
|
+
ScopeOptional,
|
|
1599
2051
|
Scope,
|
|
2052
|
+
RpcError,
|
|
1600
2053
|
Publish,
|
|
1601
2054
|
ParticipantConstants,
|
|
1602
2055
|
Pageable,
|
|
@@ -1610,6 +2063,7 @@ export {
|
|
|
1610
2063
|
EventConstants,
|
|
1611
2064
|
EventBus,
|
|
1612
2065
|
Event,
|
|
2066
|
+
EnvCredentialsResolver,
|
|
1613
2067
|
Direction,
|
|
1614
2068
|
DefaultCRI,
|
|
1615
2069
|
DataSourceUtils,
|
|
@@ -1617,9 +2071,9 @@ export {
|
|
|
1617
2071
|
CrudServiceProxyFactory,
|
|
1618
2072
|
CrudServiceProxy,
|
|
1619
2073
|
Context,
|
|
1620
|
-
ConnectionInfo,
|
|
1621
2074
|
ConnectedInfo,
|
|
1622
|
-
|
|
1623
|
-
|
|
2075
|
+
ChainedCredentialsResolver,
|
|
2076
|
+
BearerCredentialsResolver,
|
|
2077
|
+
BasicCredentialsResolver,
|
|
1624
2078
|
AbstractIterablePage
|
|
1625
2079
|
};
|