@colabo-flow/s-go 0.4.0 → 1.0.0
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/CHANGELOG.md +83 -0
- package/dist/cjs/index.js +1800 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/esm/index.js +1749 -0
- package/dist/esm/index.js.map +7 -0
- package/dist/types/demo/config.d.ts +10 -0
- package/dist/types/demo/create-client.d.ts +1 -0
- package/dist/types/demo/create-host.d.ts +7 -0
- package/dist/types/demo/create-orchestrator.d.ts +1 -0
- package/dist/types/demo/send.d.ts +1 -0
- package/dist/types/index.d.ts +13 -0
- package/dist/types/jest.config.d.ts +3 -0
- package/dist/types/lib/client/index.d.ts +4 -0
- package/dist/types/lib/flowchestrator/index.d.ts +1 -0
- package/dist/types/lib/flowchestrator/store/flow.store.d.ts +57 -0
- package/dist/types/lib/flowchestrator/store/flow.store.test.d.ts +1 -0
- package/dist/types/lib/flowchestrator/store/flowFlowchestrator.store.test.d.ts +1 -0
- package/dist/types/lib/flowchestrator/store/flowchestrator.store.d.ts +82 -0
- package/dist/types/lib/flowchestrator/store/index.d.ts +42 -0
- package/dist/types/lib/host/index.d.ts +7 -0
- package/dist/types/lib/host/omnipresentTasks.d.ts +13 -0
- package/dist/types/lib/host/vos.d.ts +4 -0
- package/dist/types/lib/operators.d.ts +5 -0
- package/dist/types/lib/orchestrator/index.d.ts +2 -0
- package/dist/types/lib/params.d.ts +1 -0
- package/dist/types/lib/uuid_fix.d.ts +15 -0
- package/dist/types/lib/vos.d.ts +205 -0
- package/dist/types/vitest.config.d.ts +2 -0
- package/package.json +73 -13
|
@@ -0,0 +1,1800 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
EColaboFlowGoMsgType: () => EColaboFlowGoMsgType,
|
|
34
|
+
EProgrammingLanguageSupported: () => EProgrammingLanguageSupported,
|
|
35
|
+
ETaskExecute_Progress_Status: () => ETaskExecute_Progress_Status,
|
|
36
|
+
HEARTBEAT_TIME: () => HEARTBEAT_TIME,
|
|
37
|
+
__getPackagePath: () => __getPackagePath,
|
|
38
|
+
clientClose: () => clientClose,
|
|
39
|
+
clientExecuteTask: () => clientExecuteTask,
|
|
40
|
+
clientRun: () => clientRun,
|
|
41
|
+
hostRegisterTask: () => hostRegisterTask,
|
|
42
|
+
hostRegisterTaskExecutor: () => hostRegisterTaskExecutor,
|
|
43
|
+
hostRun: () => hostRun,
|
|
44
|
+
hostSetTitles: () => hostSetTitles,
|
|
45
|
+
orchestratorRun: () => orchestratorRun,
|
|
46
|
+
useFlowFlowchestratorStore: () => useFlowFlowchestratorStore,
|
|
47
|
+
useGlobalStore: () => useGlobalStore
|
|
48
|
+
});
|
|
49
|
+
module.exports = __toCommonJS(index_exports);
|
|
50
|
+
|
|
51
|
+
// lib/client/index.ts
|
|
52
|
+
var import_amqplib = require("amqplib");
|
|
53
|
+
var import_chalk = __toESM(require("chalk"), 1);
|
|
54
|
+
|
|
55
|
+
// lib/uuid_fix.ts
|
|
56
|
+
var TypeMismatchError = class extends Error {
|
|
57
|
+
};
|
|
58
|
+
var QuotaExceededError = class extends Error {
|
|
59
|
+
};
|
|
60
|
+
var __DEV__ = true;
|
|
61
|
+
var warned = false;
|
|
62
|
+
function insecureRandomValues(array) {
|
|
63
|
+
if (!warned) {
|
|
64
|
+
console.warn("WARNING: Using an insecure random number generator, as there is no support for crypto.getRandomValues in node native and we do not need it anyway for unique IDs in ColaboFlow messaging identification");
|
|
65
|
+
warned = true;
|
|
66
|
+
}
|
|
67
|
+
for (let i = 0, r; i < array.length; i++) {
|
|
68
|
+
if ((i & 3) === 0) r = Math.random() * 4294967296;
|
|
69
|
+
array[i] = r >>> ((i & 3) << 3) & 255;
|
|
70
|
+
}
|
|
71
|
+
return array;
|
|
72
|
+
}
|
|
73
|
+
function getRandomValues(array) {
|
|
74
|
+
if (!(array instanceof Int8Array || array instanceof Uint8Array || array instanceof Int16Array || array instanceof Uint16Array || array instanceof Int32Array || array instanceof Uint32Array || array instanceof Uint8ClampedArray)) {
|
|
75
|
+
throw new TypeMismatchError("Expected an integer array");
|
|
76
|
+
}
|
|
77
|
+
if (array.byteLength > 65536) {
|
|
78
|
+
throw new QuotaExceededError("Can only request a maximum of 65536 bytes");
|
|
79
|
+
}
|
|
80
|
+
if (__DEV__) {
|
|
81
|
+
if (typeof global["nativeCallSyncHook"] === "undefined") {
|
|
82
|
+
return insecureRandomValues(array);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return array;
|
|
86
|
+
}
|
|
87
|
+
if (typeof global.crypto !== "object") {
|
|
88
|
+
global.crypto = {};
|
|
89
|
+
}
|
|
90
|
+
if (typeof global.crypto.getRandomValues !== "function") {
|
|
91
|
+
global.crypto.getRandomValues = getRandomValues;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// lib/operators.ts
|
|
95
|
+
var import_uuid = require("uuid");
|
|
96
|
+
var createGoMsg = (sender, type) => {
|
|
97
|
+
const msg = {
|
|
98
|
+
id: `ColaboFlow-msg:${(0, import_uuid.v1)()}`,
|
|
99
|
+
requestId: `ColaboFlow-request:${(0, import_uuid.v1)()}`,
|
|
100
|
+
sender,
|
|
101
|
+
proxies: [],
|
|
102
|
+
msgReplyChainIds: [],
|
|
103
|
+
type
|
|
104
|
+
};
|
|
105
|
+
return msg;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// lib/vos.ts
|
|
109
|
+
var EColaboFlowGoMsgType = /* @__PURE__ */ ((EColaboFlowGoMsgType2) => {
|
|
110
|
+
EColaboFlowGoMsgType2["TASK_EXECUTE_REQUEST"] = "TASK_EXECUTE_REQUEST";
|
|
111
|
+
EColaboFlowGoMsgType2["TASK_EXECUTE_PROGRESS"] = "TASK_EXECUTE_PROGRESS";
|
|
112
|
+
EColaboFlowGoMsgType2["TASK_EXECUTE_RESPONSE"] = "TASK_EXECUTE_RESPONSE";
|
|
113
|
+
EColaboFlowGoMsgType2["TASK_INSTANCES_REPORT__REQUEST"] = "TASK_INSTANCES_REPORT__REQUEST";
|
|
114
|
+
EColaboFlowGoMsgType2["TASK_INSTANCES_REPORT__RESPONSE"] = "TASK_INSTANCES_REPORT__RESPONSE";
|
|
115
|
+
EColaboFlowGoMsgType2["HEARTBEAT"] = "HEARTBEAT";
|
|
116
|
+
return EColaboFlowGoMsgType2;
|
|
117
|
+
})(EColaboFlowGoMsgType || {});
|
|
118
|
+
var HEARTBEAT_TIME = 3e3;
|
|
119
|
+
var EProgrammingLanguageSupported = /* @__PURE__ */ ((EProgrammingLanguageSupported2) => {
|
|
120
|
+
EProgrammingLanguageSupported2["JAVASCRIPT"] = "JAVASCRIPT";
|
|
121
|
+
EProgrammingLanguageSupported2["PYTHON"] = "PYTHON";
|
|
122
|
+
EProgrammingLanguageSupported2["NATIVE"] = "NATIVE";
|
|
123
|
+
return EProgrammingLanguageSupported2;
|
|
124
|
+
})(EProgrammingLanguageSupported || {});
|
|
125
|
+
var ETaskExecute_Progress_Status = /* @__PURE__ */ ((ETaskExecute_Progress_Status2) => {
|
|
126
|
+
ETaskExecute_Progress_Status2["INITIALIZED"] = "INITIALIZED";
|
|
127
|
+
return ETaskExecute_Progress_Status2;
|
|
128
|
+
})(ETaskExecute_Progress_Status || {});
|
|
129
|
+
|
|
130
|
+
// lib/client/index.ts
|
|
131
|
+
var MINIMUM_FRAME_MAX = 8192;
|
|
132
|
+
var isAmqpDebugEnabled = () => {
|
|
133
|
+
const debugRaw = process.env.COLABO_FLOW_AMQP_DEBUG || "";
|
|
134
|
+
return debugRaw === "1" || debugRaw.toLowerCase() === "true";
|
|
135
|
+
};
|
|
136
|
+
var parsePositiveInt = (rawValue, fallback) => {
|
|
137
|
+
if (!rawValue) return fallback;
|
|
138
|
+
const parsed = Number.parseInt(rawValue, 10);
|
|
139
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
140
|
+
};
|
|
141
|
+
var formatError = (err) => {
|
|
142
|
+
if (!(err instanceof Error)) return String(err);
|
|
143
|
+
const errorExtended = err;
|
|
144
|
+
const meta = [
|
|
145
|
+
errorExtended.code ? `code=${errorExtended.code}` : "",
|
|
146
|
+
errorExtended.errno !== void 0 ? `errno=${errorExtended.errno}` : "",
|
|
147
|
+
errorExtended.syscall ? `syscall=${errorExtended.syscall}` : "",
|
|
148
|
+
errorExtended.address ? `address=${errorExtended.address}` : "",
|
|
149
|
+
errorExtended.port !== void 0 ? `port=${errorExtended.port}` : ""
|
|
150
|
+
].filter(Boolean).join(", ");
|
|
151
|
+
return meta ? `${err.message} (${meta})` : err.message;
|
|
152
|
+
};
|
|
153
|
+
var logAmqpUrlDetails = (client, urlRaw) => {
|
|
154
|
+
try {
|
|
155
|
+
const parsed = new URL(urlRaw);
|
|
156
|
+
const vhostRaw = parsed.pathname || "/";
|
|
157
|
+
const vhostDecoded = decodeURIComponent(vhostRaw);
|
|
158
|
+
const heartbeatQuery = parsed.searchParams.get("heartbeat") || "(broker default)";
|
|
159
|
+
const frameMaxQuery = parsed.searchParams.get("frameMax") || "(amqplib default)";
|
|
160
|
+
console.log(`${client.appNameText} AMQP URL details: protocol=${parsed.protocol}, host=${parsed.hostname}, port=${parsed.port || "5672"}, vhostRaw="${vhostRaw}", vhostDecoded="${vhostDecoded}", heartbeat=${heartbeatQuery}, frameMax=${frameMaxQuery}`);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
console.warn(`${client.appNameText} Could not parse AMQP URL "${urlRaw}": ${formatError(err)}`);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
var getEffectiveAmqpUrl = (client, urlRaw) => {
|
|
166
|
+
try {
|
|
167
|
+
const parsed = new URL(urlRaw);
|
|
168
|
+
const defaultFrameMax = parsePositiveInt(process.env.COLABO_FLOW_AMQP_FRAME_MAX, 131072);
|
|
169
|
+
const frameMaxConfiguredRaw = parsed.searchParams.get("frameMax") || void 0;
|
|
170
|
+
let frameMax = parsePositiveInt(frameMaxConfiguredRaw, defaultFrameMax);
|
|
171
|
+
if (frameMax < MINIMUM_FRAME_MAX) {
|
|
172
|
+
console.warn(`${client.appNameText} frameMax=${frameMax} is too low; forcing frameMax=${MINIMUM_FRAME_MAX}`);
|
|
173
|
+
frameMax = MINIMUM_FRAME_MAX;
|
|
174
|
+
}
|
|
175
|
+
parsed.searchParams.set("frameMax", String(frameMax));
|
|
176
|
+
return parsed.toString();
|
|
177
|
+
} catch {
|
|
178
|
+
return urlRaw;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
var getConnectSocketOptions = (connectionName) => {
|
|
182
|
+
return {
|
|
183
|
+
noDelay: true,
|
|
184
|
+
keepAlive: true,
|
|
185
|
+
keepAliveDelay: parsePositiveInt(process.env.COLABO_FLOW_AMQP_KEEPALIVE_DELAY_MS, 1e3),
|
|
186
|
+
timeout: parsePositiveInt(process.env.COLABO_FLOW_AMQP_CONNECT_TIMEOUT_MS, 1e4),
|
|
187
|
+
clientProperties: {
|
|
188
|
+
connection_name: connectionName
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
};
|
|
192
|
+
var attachConnectionDebugHandlers = (client) => {
|
|
193
|
+
if (!client.connection) return;
|
|
194
|
+
client.connection.on("error", (err) => {
|
|
195
|
+
console.error(`${client.appNameText} AMQP connection error: ${formatError(err)}`);
|
|
196
|
+
});
|
|
197
|
+
client.connection.on("close", () => {
|
|
198
|
+
console.warn(`${client.appNameText} AMQP connection closed`);
|
|
199
|
+
});
|
|
200
|
+
client.connection.on("blocked", (reason) => {
|
|
201
|
+
console.warn(`${client.appNameText} AMQP connection blocked: ${String(reason)}`);
|
|
202
|
+
});
|
|
203
|
+
client.connection.on("unblocked", () => {
|
|
204
|
+
console.warn(`${client.appNameText} AMQP connection unblocked`);
|
|
205
|
+
});
|
|
206
|
+
client.connection.on("frameError", (err) => {
|
|
207
|
+
console.error(`${client.appNameText} AMQP frameError: ${formatError(err)}`);
|
|
208
|
+
});
|
|
209
|
+
const maybeSocket = client.connection?.connection?.stream;
|
|
210
|
+
if (maybeSocket && isAmqpDebugEnabled()) {
|
|
211
|
+
maybeSocket.on("error", (err) => {
|
|
212
|
+
console.error(`${client.appNameText} AMQP socket error: ${formatError(err)}`);
|
|
213
|
+
});
|
|
214
|
+
maybeSocket.on("close", (hadError) => {
|
|
215
|
+
console.warn(`${client.appNameText} AMQP socket close (hadError=${hadError})`);
|
|
216
|
+
});
|
|
217
|
+
maybeSocket.on("end", () => {
|
|
218
|
+
console.warn(`${client.appNameText} AMQP socket end`);
|
|
219
|
+
});
|
|
220
|
+
maybeSocket.on("timeout", () => {
|
|
221
|
+
console.warn(`${client.appNameText} AMQP socket timeout`);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
var attachChannelDebugHandlers = (client) => {
|
|
226
|
+
if (!client.channel) return;
|
|
227
|
+
client.channel.on("error", (err) => {
|
|
228
|
+
console.error(`${client.appNameText} AMQP channel error: ${formatError(err)}`);
|
|
229
|
+
});
|
|
230
|
+
client.channel.on("close", () => {
|
|
231
|
+
console.warn(`${client.appNameText} AMQP channel closed`);
|
|
232
|
+
});
|
|
233
|
+
client.channel.on("return", (msg) => {
|
|
234
|
+
if (isAmqpDebugEnabled()) {
|
|
235
|
+
console.warn(`${client.appNameText} AMQP channel returned a message: ${JSON.stringify(msg)}`);
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
client.channel.on("drain", () => {
|
|
239
|
+
if (isAmqpDebugEnabled()) {
|
|
240
|
+
console.log(`${client.appNameText} AMQP channel drain`);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
var clientRun = async (client) => {
|
|
245
|
+
process.title = `ColaboFlow.Go.Client-${client.clientName}`;
|
|
246
|
+
client.appNameText = `[${import_chalk.default.red.bold("Colabo")}${import_chalk.default.blue.bold("Flow")}${import_chalk.default.green.bold(".Go")}-${import_chalk.default.green.yellow(client.clientName)}]`;
|
|
247
|
+
console.log(`${client.appNameText} Connecting to the ColaboFlow orchestrator: ${import_chalk.default.greenBright(client.amqpUrl)}`);
|
|
248
|
+
const effectiveAmqpUrl = getEffectiveAmqpUrl(client, client.amqpUrl);
|
|
249
|
+
if (effectiveAmqpUrl !== client.amqpUrl) {
|
|
250
|
+
console.log(`${client.appNameText} Effective AMQP URL: ${import_chalk.default.greenBright(effectiveAmqpUrl)}`);
|
|
251
|
+
}
|
|
252
|
+
logAmqpUrlDetails(client, effectiveAmqpUrl);
|
|
253
|
+
const connectionName = `${client.clientName}-pid-${process.pid}`;
|
|
254
|
+
const socketOptions = getConnectSocketOptions(connectionName);
|
|
255
|
+
if (isAmqpDebugEnabled()) {
|
|
256
|
+
console.log(`${client.appNameText} AMQP socket options: ${JSON.stringify(socketOptions)}`);
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
client.connection = await (0, import_amqplib.connect)(effectiveAmqpUrl, socketOptions);
|
|
260
|
+
} catch (err) {
|
|
261
|
+
console.error(`${client.appNameText} Error connecting to the "${import_chalk.default.greenBright(effectiveAmqpUrl)}" ColaboFlow orchestrator: ${formatError(err)}`);
|
|
262
|
+
if (isAmqpDebugEnabled() && err instanceof Error && err.stack) {
|
|
263
|
+
console.error(`${client.appNameText} connect stack: ${err.stack}`);
|
|
264
|
+
}
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
attachConnectionDebugHandlers(client);
|
|
268
|
+
try {
|
|
269
|
+
client.channel = await client.connection.createChannel();
|
|
270
|
+
} catch (err) {
|
|
271
|
+
console.error(`${client.appNameText} Error creating the channel: ${formatError(err)}`);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
attachChannelDebugHandlers(client);
|
|
275
|
+
};
|
|
276
|
+
var clientExecuteTask = async (client, taskId, taskInput, options) => {
|
|
277
|
+
const promise = new Promise(async (resolve, reject) => {
|
|
278
|
+
if (!client.channel) {
|
|
279
|
+
reject(new Error(`${client.appNameText} Client channel is not initialized. Call clientRun(...) first.`));
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const taskExecuteResponseQueue = `client-task_execute_response-${(0, import_uuid.v1)()}`;
|
|
283
|
+
const msgTaskRequest = {
|
|
284
|
+
...createGoMsg(client.clientName, "TASK_EXECUTE_REQUEST" /* TASK_EXECUTE_REQUEST */),
|
|
285
|
+
replyTo: taskExecuteResponseQueue,
|
|
286
|
+
extension: {
|
|
287
|
+
taskId,
|
|
288
|
+
taskInput,
|
|
289
|
+
options
|
|
290
|
+
},
|
|
291
|
+
msg: `run a "${taskId}" task`
|
|
292
|
+
};
|
|
293
|
+
const msgTaskRequestStr = JSON.stringify(msgTaskRequest);
|
|
294
|
+
const responseMaxChars = 200;
|
|
295
|
+
const msgTaskRequestStrShort = msgTaskRequestStr.length > responseMaxChars ? msgTaskRequestStr.substring(0, responseMaxChars / 2) + " [...] " + msgTaskRequestStr.substring(msgTaskRequestStr.length - responseMaxChars / 2) : msgTaskRequestStr;
|
|
296
|
+
console.log(`${client.appNameText} Sending task request [queue: "${import_chalk.default.blueBright(client.queueOrchestrator)}"] (reduced to ${responseMaxChars} chars): ${msgTaskRequestStrShort}`);
|
|
297
|
+
try {
|
|
298
|
+
client.channel.sendToQueue(client.queueOrchestrator, Buffer.from(JSON.stringify(msgTaskRequest)));
|
|
299
|
+
} catch (err) {
|
|
300
|
+
reject(new Error(`${client.appNameText} Failed sending TASK_EXECUTE_REQUEST to "${client.queueOrchestrator}": ${formatError(err)}`));
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
await client.channel.assertQueue(taskExecuteResponseQueue, {
|
|
305
|
+
exclusive: true
|
|
306
|
+
});
|
|
307
|
+
} catch (err) {
|
|
308
|
+
reject(new Error(`${client.appNameText} Failed creating reply queue "${taskExecuteResponseQueue}": ${formatError(err)}`));
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
client.channel.consume(
|
|
312
|
+
taskExecuteResponseQueue,
|
|
313
|
+
function(msgOrchestratorRes) {
|
|
314
|
+
if (!msgOrchestratorRes) {
|
|
315
|
+
reject(new Error(`${client.appNameText} Consumer for "${taskExecuteResponseQueue}" cancelled by broker`));
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
let msgOrchestratorResObj;
|
|
319
|
+
try {
|
|
320
|
+
msgOrchestratorResObj = JSON.parse(msgOrchestratorRes.content.toString());
|
|
321
|
+
} catch (err) {
|
|
322
|
+
reject(new Error(`${client.appNameText} Error parsing response message: ${formatError(err)}`));
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const msgOrchestratorResObjExtension = msgOrchestratorResObj.extension;
|
|
326
|
+
resolve(msgOrchestratorResObjExtension.taskOutput);
|
|
327
|
+
},
|
|
328
|
+
{
|
|
329
|
+
noAck: true
|
|
330
|
+
}
|
|
331
|
+
).catch((err) => {
|
|
332
|
+
reject(new Error(`${client.appNameText} Failed starting consumer on "${taskExecuteResponseQueue}": ${formatError(err)}`));
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
return promise;
|
|
336
|
+
};
|
|
337
|
+
var clientClose = async (client) => {
|
|
338
|
+
const promise = new Promise((resolve, reject) => {
|
|
339
|
+
setTimeout(async () => {
|
|
340
|
+
console.log(`${client.appNameText} Closing the ${import_chalk.default.bold.italic("channel")} to the ColaboFlow orchestrator...`);
|
|
341
|
+
try {
|
|
342
|
+
if (client.channel) {
|
|
343
|
+
await client.channel.close();
|
|
344
|
+
}
|
|
345
|
+
console.log(`${client.appNameText} Closing the ${import_chalk.default.bold.italic("connection")} to the ColaboFlow orchestrator...`);
|
|
346
|
+
if (client.connection) {
|
|
347
|
+
await client.connection.close();
|
|
348
|
+
}
|
|
349
|
+
resolve(true);
|
|
350
|
+
} catch (err) {
|
|
351
|
+
reject(new Error(`${client.appNameText} Error while closing client resources: ${formatError(err)}`));
|
|
352
|
+
}
|
|
353
|
+
}, 500);
|
|
354
|
+
});
|
|
355
|
+
return promise;
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// lib/orchestrator/index.ts
|
|
359
|
+
var import_amqplib2 = require("amqplib");
|
|
360
|
+
var import_chalk2 = __toESM(require("chalk"), 1);
|
|
361
|
+
var import_i_verify = require("@colabo-utils/i-verify");
|
|
362
|
+
process.title = "ColaboFlow.Go.Orchestrator";
|
|
363
|
+
var appNameText = `[${import_chalk2.default.red.bold("Colabo")}${import_chalk2.default.blue.bold("Flow")}${import_chalk2.default.green.bold(".Go")}${import_chalk2.default.green.yellow(".Orchestrator")}]`;
|
|
364
|
+
var isAmqpDebugEnabled2 = () => {
|
|
365
|
+
const debugRaw = process.env.COLABO_FLOW_AMQP_DEBUG || "";
|
|
366
|
+
return debugRaw === "1" || debugRaw.toLowerCase() === "true";
|
|
367
|
+
};
|
|
368
|
+
var parsePositiveInt2 = (rawValue, fallback) => {
|
|
369
|
+
if (!rawValue) return fallback;
|
|
370
|
+
const parsed = Number.parseInt(rawValue, 10);
|
|
371
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
372
|
+
};
|
|
373
|
+
var MINIMUM_FRAME_MAX2 = 8192;
|
|
374
|
+
var formatError2 = (err) => {
|
|
375
|
+
if (!(err instanceof Error)) return String(err);
|
|
376
|
+
const errorExtended = err;
|
|
377
|
+
const meta = [
|
|
378
|
+
errorExtended.code ? `code=${errorExtended.code}` : "",
|
|
379
|
+
errorExtended.errno !== void 0 ? `errno=${errorExtended.errno}` : "",
|
|
380
|
+
errorExtended.syscall ? `syscall=${errorExtended.syscall}` : "",
|
|
381
|
+
errorExtended.address ? `address=${errorExtended.address}` : "",
|
|
382
|
+
errorExtended.port !== void 0 ? `port=${errorExtended.port}` : ""
|
|
383
|
+
].filter(Boolean).join(", ");
|
|
384
|
+
return meta ? `${err.message} (${meta})` : err.message;
|
|
385
|
+
};
|
|
386
|
+
var logAmqpUrlDetails2 = (urlRaw) => {
|
|
387
|
+
try {
|
|
388
|
+
const parsed = new URL(urlRaw);
|
|
389
|
+
const vhostRaw = parsed.pathname || "/";
|
|
390
|
+
const vhostDecoded = decodeURIComponent(vhostRaw);
|
|
391
|
+
const heartbeatQuery = parsed.searchParams.get("heartbeat") || "(broker default)";
|
|
392
|
+
const frameMaxQuery = parsed.searchParams.get("frameMax") || "(amqplib default)";
|
|
393
|
+
console.log(`${appNameText} AMQP URL details: protocol=${parsed.protocol}, host=${parsed.hostname}, port=${parsed.port || "5672"}, vhostRaw="${vhostRaw}", vhostDecoded="${vhostDecoded}", heartbeat=${heartbeatQuery}, frameMax=${frameMaxQuery}`);
|
|
394
|
+
} catch (err) {
|
|
395
|
+
console.warn(`${appNameText} Could not parse AMQP URL "${urlRaw}": ${formatError2(err)}`);
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
var getEffectiveAmqpUrl2 = (urlRaw) => {
|
|
399
|
+
try {
|
|
400
|
+
const parsed = new URL(urlRaw);
|
|
401
|
+
const defaultFrameMax = parsePositiveInt2(process.env.COLABO_FLOW_AMQP_FRAME_MAX, 131072);
|
|
402
|
+
const frameMaxConfiguredRaw = parsed.searchParams.get("frameMax") || void 0;
|
|
403
|
+
let frameMax = parsePositiveInt2(frameMaxConfiguredRaw, defaultFrameMax);
|
|
404
|
+
if (frameMax < MINIMUM_FRAME_MAX2) {
|
|
405
|
+
console.warn(`${appNameText} frameMax=${frameMax} is too low; forcing frameMax=${MINIMUM_FRAME_MAX2}`);
|
|
406
|
+
frameMax = MINIMUM_FRAME_MAX2;
|
|
407
|
+
}
|
|
408
|
+
parsed.searchParams.set("frameMax", String(frameMax));
|
|
409
|
+
return parsed.toString();
|
|
410
|
+
} catch {
|
|
411
|
+
return urlRaw;
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
var attachConnectionDebugHandlers2 = (connection) => {
|
|
415
|
+
connection.on("error", (err) => {
|
|
416
|
+
console.error(`${appNameText} AMQP connection error: ${formatError2(err)}`);
|
|
417
|
+
});
|
|
418
|
+
connection.on("close", () => {
|
|
419
|
+
console.warn(`${appNameText} AMQP connection closed`);
|
|
420
|
+
});
|
|
421
|
+
connection.on("blocked", (reason) => {
|
|
422
|
+
console.warn(`${appNameText} AMQP connection blocked: ${String(reason)}`);
|
|
423
|
+
});
|
|
424
|
+
connection.on("unblocked", () => {
|
|
425
|
+
console.warn(`${appNameText} AMQP connection unblocked`);
|
|
426
|
+
});
|
|
427
|
+
connection.on("frameError", (err) => {
|
|
428
|
+
console.error(`${appNameText} AMQP frameError: ${formatError2(err)}`);
|
|
429
|
+
});
|
|
430
|
+
const maybeSocket = connection?.connection?.stream;
|
|
431
|
+
if (maybeSocket && isAmqpDebugEnabled2()) {
|
|
432
|
+
maybeSocket.on("error", (err) => {
|
|
433
|
+
console.error(`${appNameText} AMQP socket error: ${formatError2(err)}`);
|
|
434
|
+
});
|
|
435
|
+
maybeSocket.on("close", (hadError) => {
|
|
436
|
+
console.warn(`${appNameText} AMQP socket close (hadError=${hadError})`);
|
|
437
|
+
});
|
|
438
|
+
maybeSocket.on("end", () => {
|
|
439
|
+
console.warn(`${appNameText} AMQP socket end`);
|
|
440
|
+
});
|
|
441
|
+
maybeSocket.on("timeout", () => {
|
|
442
|
+
console.warn(`${appNameText} AMQP socket timeout`);
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
var attachChannelDebugHandlers2 = (channelName, channel) => {
|
|
447
|
+
channel.on("error", (err) => {
|
|
448
|
+
console.error(`${appNameText} AMQP channel "${channelName}" error: ${formatError2(err)}`);
|
|
449
|
+
});
|
|
450
|
+
channel.on("close", () => {
|
|
451
|
+
console.warn(`${appNameText} AMQP channel "${channelName}" closed`);
|
|
452
|
+
});
|
|
453
|
+
channel.on("return", (msg) => {
|
|
454
|
+
if (isAmqpDebugEnabled2()) {
|
|
455
|
+
console.warn(`${appNameText} AMQP channel "${channelName}" returned a message: ${JSON.stringify(msg)}`);
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
channel.on("drain", () => {
|
|
459
|
+
if (isAmqpDebugEnabled2()) {
|
|
460
|
+
console.log(`${appNameText} AMQP channel "${channelName}" drain`);
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
};
|
|
464
|
+
var getConnectSocketOptions2 = (connectionName) => {
|
|
465
|
+
return {
|
|
466
|
+
noDelay: true,
|
|
467
|
+
keepAlive: true,
|
|
468
|
+
keepAliveDelay: parsePositiveInt2(process.env.COLABO_FLOW_AMQP_KEEPALIVE_DELAY_MS, 1e3),
|
|
469
|
+
timeout: parsePositiveInt2(process.env.COLABO_FLOW_AMQP_CONNECT_TIMEOUT_MS, 1e4),
|
|
470
|
+
clientProperties: {
|
|
471
|
+
connection_name: connectionName
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
};
|
|
475
|
+
var asyncProcessColaboFlowMsg_TaskExecute = async (orchestrator, msgClientReqObj) => {
|
|
476
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
477
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
478
|
+
const msgClientReqExtension = msgClientReqObj.extension;
|
|
479
|
+
const taskId = msgClientReqExtension.taskId;
|
|
480
|
+
console.log(`${appNameText} Executing task taskId: "${import_chalk2.default.blueBright(taskId)}"`);
|
|
481
|
+
const taskExecuteResponseQueue = `orchestrator-task_execute_response-${(0, import_uuid.v1)()}`;
|
|
482
|
+
const hostsForTaskId = orchestrator.hostsForTaskIds[taskId];
|
|
483
|
+
if (!hostsForTaskId || hostsForTaskId.length <= 0) {
|
|
484
|
+
console.error(`${appNameText} Error, there is no host implementing the task: "${taskId}"`);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
let hostName = void 0;
|
|
488
|
+
if (msgClientReqExtension?.options?.hosts?.hostNames) {
|
|
489
|
+
console.info(`${appNameText} Client requested for the task "${taskId}" to be executed across one of the following hostNames: ${msgClientReqExtension?.options?.hosts?.hostNames}.`);
|
|
490
|
+
for (const hostNameTemp of msgClientReqExtension.options.hosts.hostNames) {
|
|
491
|
+
if (hostsForTaskId.indexOf(hostNameTemp) >= 0) {
|
|
492
|
+
hostName = hostNameTemp;
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (!hostName) {
|
|
497
|
+
if (msgClientReqExtension.options.hosts.runOnlyOnEnlistedHosts) {
|
|
498
|
+
console.error(`${appNameText} Error, there is no host implementing the task: "${taskId}" that matches the requested hosts hostNames: ${msgClientReqExtension.options.hosts.hostNames}`);
|
|
499
|
+
return;
|
|
500
|
+
} else {
|
|
501
|
+
hostName = hostsForTaskId[0];
|
|
502
|
+
console.info(`${appNameText} There is no host implementing the task: "${taskId}" that matches the requested hosts hostNames: ${msgClientReqExtension.options.hosts.hostNames}. Instead using the first availabile host: ${hostName}`);
|
|
503
|
+
}
|
|
504
|
+
} else {
|
|
505
|
+
console.info(`${appNameText} We found the host implementing the task: "${taskId}" that matches the requested hosts hostNames: ${hostName}.`);
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
hostName = hostsForTaskId[0];
|
|
509
|
+
console.info(`${appNameText} There are no preferences for a host implementing the task: "${taskId}" Using the first available host: ${hostName}.`);
|
|
510
|
+
}
|
|
511
|
+
const hostData = orchestrator.hosts[hostName];
|
|
512
|
+
console.log(`${appNameText} Delivering the task "${import_chalk2.default.blueBright(taskId)}" to host "${import_chalk2.default.blueBright(hostName)}" via queue "${import_chalk2.default.blueBright(hostData.queueHost)}" and listening for the response on the queue: "${import_chalk2.default.blueBright(taskExecuteResponseQueue)}"`);
|
|
513
|
+
const msgHostObjRequest = {
|
|
514
|
+
...createGoMsg(orchestrator.orchestratorName, "TASK_EXECUTE_REQUEST" /* TASK_EXECUTE_REQUEST */),
|
|
515
|
+
replyTo: taskExecuteResponseQueue,
|
|
516
|
+
extension: msgClientReqExtension,
|
|
517
|
+
msg: msgClientReqObj.msg
|
|
518
|
+
};
|
|
519
|
+
console.log(`${appNameText} Creating the task execution response queue: "${import_chalk2.default.blueBright(taskExecuteResponseQueue)}" ...`);
|
|
520
|
+
await orchestrator.hostsChannel.assertQueue(taskExecuteResponseQueue, {
|
|
521
|
+
exclusive: true
|
|
522
|
+
});
|
|
523
|
+
orchestrator.hostsChannel.consume(
|
|
524
|
+
taskExecuteResponseQueue,
|
|
525
|
+
function(msgHostRes) {
|
|
526
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
527
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
528
|
+
console.log(`${appNameText} Task Execution reply on the queue: "${import_chalk2.default.blueBright(taskExecuteResponseQueue)}" for the taskId: "${import_chalk2.default.blueBright(taskId)}"`);
|
|
529
|
+
(0, import_i_verify.assert)(msgHostRes, `msgHostRes is not defined`);
|
|
530
|
+
let msgHostResObj;
|
|
531
|
+
try {
|
|
532
|
+
msgHostResObj = JSON.parse(msgHostRes.content.toString());
|
|
533
|
+
} catch (err) {
|
|
534
|
+
console.error(`${appNameText} Error parsing host response message: ${formatError2(err)} | raw=${msgHostRes.content.toString()}`);
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
switch (msgHostResObj.type) {
|
|
538
|
+
case "TASK_EXECUTE_PROGRESS" /* TASK_EXECUTE_PROGRESS */:
|
|
539
|
+
const msgHostProgressObjExtension = msgHostResObj.extension;
|
|
540
|
+
console.log(`${appNameText} Task Execution PROGRESS: ${JSON.stringify(msgHostProgressObjExtension)}`);
|
|
541
|
+
break;
|
|
542
|
+
case "TASK_EXECUTE_RESPONSE" /* TASK_EXECUTE_RESPONSE */:
|
|
543
|
+
const msgHostResObjExtension = msgHostResObj.extension;
|
|
544
|
+
const executionResponse = JSON.stringify(msgHostResObjExtension.taskOutput);
|
|
545
|
+
const responseMaxChars = 200;
|
|
546
|
+
const executionResponseShort = executionResponse.length > responseMaxChars ? executionResponse.substring(0, responseMaxChars / 2) + " [...] " + executionResponse.substring(executionResponse.length - responseMaxChars / 2) : executionResponse;
|
|
547
|
+
console.log(`${appNameText} Task Execution RESPONSE (reduced to ${responseMaxChars} chars): ${executionResponseShort}`);
|
|
548
|
+
if (!msgClientReqObj.replyTo) {
|
|
549
|
+
console.error(`${appNameText} replyTo is missing in the msgClientReqObj [msgClientReqObj.id: "${import_chalk2.default.blueBright(msgClientReqObj.id)}"]`);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const queueReplyTo = msgClientReqObj.replyTo;
|
|
553
|
+
const msgClientRes = {
|
|
554
|
+
...createGoMsg(orchestrator.orchestratorName, "TASK_EXECUTE_RESPONSE" /* TASK_EXECUTE_RESPONSE */),
|
|
555
|
+
requestId: msgClientReqObj.requestId,
|
|
556
|
+
msgReplyChainIds: [msgClientReqObj.id],
|
|
557
|
+
extension: msgHostResObjExtension,
|
|
558
|
+
msg: `Host with tasks`
|
|
559
|
+
};
|
|
560
|
+
console.log(`${appNameText} Sending the task Execution response back to the client "${import_chalk2.default.blueBright(msgClientReqObj.sender)}" through queue: "${import_chalk2.default.blueBright(queueReplyTo)}"`);
|
|
561
|
+
try {
|
|
562
|
+
orchestrator.clientsChannel.sendToQueue(queueReplyTo, Buffer.from(JSON.stringify(msgClientRes)));
|
|
563
|
+
} catch (err) {
|
|
564
|
+
console.error(`${appNameText} Failed to send TASK_EXECUTE_RESPONSE to client queue "${queueReplyTo}": ${formatError2(err)}`);
|
|
565
|
+
}
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
},
|
|
569
|
+
{
|
|
570
|
+
// check if it is good to have it
|
|
571
|
+
noAck: true
|
|
572
|
+
}
|
|
573
|
+
);
|
|
574
|
+
console.log(`${appNameText} Listening on the queue: "${import_chalk2.default.blueBright(taskExecuteResponseQueue)}" for the execution response for the task "${import_chalk2.default.blueBright(taskId)}"`);
|
|
575
|
+
try {
|
|
576
|
+
orchestrator.hostsChannel.sendToQueue(hostData.queueHost, Buffer.from(JSON.stringify(msgHostObjRequest)));
|
|
577
|
+
} catch (err) {
|
|
578
|
+
console.error(`${appNameText} Failed to send TASK_EXECUTE_REQUEST to host queue "${hostData.queueHost}": ${formatError2(err)}`);
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
var asyncProcessColaboFlowMsg_Heartbeat = async (orchestrator, msgObj) => {
|
|
582
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
583
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
584
|
+
const msgExtension = msgObj.extension;
|
|
585
|
+
const hostName = msgObj.sender;
|
|
586
|
+
if (!(hostName in orchestrator.hosts)) {
|
|
587
|
+
console.log(`${appNameText} Discovered a new host: "${import_chalk2.default.blueBright(hostName)}" with the tasks available: ${import_chalk2.default.blueBright(JSON.stringify(msgExtension.taskIds))}`);
|
|
588
|
+
orchestrator.hosts[hostName] = {
|
|
589
|
+
hostName,
|
|
590
|
+
queueHost: msgExtension.queueHost,
|
|
591
|
+
// we make it empty as we want to populate it properly in the next section
|
|
592
|
+
taskIdsAvailable: [],
|
|
593
|
+
taskInstanceIds: []
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
const hostData = orchestrator.hosts[hostName];
|
|
597
|
+
const tasksRemoved = hostData.taskIdsAvailable.filter((newTaskId) => msgExtension.taskIds.indexOf(newTaskId) < 0);
|
|
598
|
+
if (tasksRemoved.length) console.log(`${appNameText} The host: "${import_chalk2.default.blueBright(hostName)}" doesn't offers anymore the following tasks: ${import_chalk2.default.blueBright(JSON.stringify(tasksRemoved))}`);
|
|
599
|
+
for (const taskId of tasksRemoved) {
|
|
600
|
+
const hostsForTheTaskId = orchestrator.hostsForTaskIds[taskId];
|
|
601
|
+
if (!Array.isArray(hostsForTheTaskId)) return;
|
|
602
|
+
var hostIndex = hostsForTheTaskId.indexOf(hostName);
|
|
603
|
+
if (hostIndex !== -1) {
|
|
604
|
+
hostsForTheTaskId.splice(hostIndex, 1);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
const tasksAdded = msgExtension.taskIds.filter((newTaskId) => hostData.taskIdsAvailable.indexOf(newTaskId) < 0);
|
|
608
|
+
if (tasksAdded.length) console.log(`${appNameText} The host: "${import_chalk2.default.blueBright(hostName)}" offers now the additional tasks: ${import_chalk2.default.blueBright(JSON.stringify(tasksAdded))}`);
|
|
609
|
+
hostData.taskIdsAvailable = msgExtension.taskIds;
|
|
610
|
+
for (const taskId of tasksAdded) {
|
|
611
|
+
if (!orchestrator.hostsForTaskIds[taskId]) orchestrator.hostsForTaskIds[taskId] = [];
|
|
612
|
+
if (orchestrator.hostsForTaskIds[taskId].indexOf(hostName) < 0) {
|
|
613
|
+
orchestrator.hostsForTaskIds[taskId].push(hostName);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (orchestrator.reportsConfig.showHeartbeatMsgs && msgExtension.id % orchestrator.reportsConfig.showHeartbeatMsgs == 0) {
|
|
617
|
+
console.log(`${appNameText} Received heartbeat: hostName: "${import_chalk2.default.blueBright(hostName)}", id: ${msgExtension.id}`);
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
var listenOnClientRequests = async (orchestrator) => {
|
|
621
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
622
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
623
|
+
console.log(`${appNameText} Listening on the orchestrator queue: "${import_chalk2.default.blueBright(orchestrator.queueOrchestrator)}"`);
|
|
624
|
+
console.log(`${appNameText} [*] Waiting for orchestrator messages. To exit press "${import_chalk2.default.blueBright("CTRL+C")}"`);
|
|
625
|
+
orchestrator.clientsChannel.consume(orchestrator.queueOrchestrator, (msg) => {
|
|
626
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
627
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
628
|
+
if (msg !== null) {
|
|
629
|
+
let msgObj;
|
|
630
|
+
try {
|
|
631
|
+
msgObj = JSON.parse(msg.content.toString());
|
|
632
|
+
console.log(`${appNameText} msgObj.sender: "${import_chalk2.default.blueBright(msgObj.sender)}", msgObj.msg: "${import_chalk2.default.blueBright(msgObj.msg)}"`);
|
|
633
|
+
switch (msgObj.type) {
|
|
634
|
+
case "TASK_EXECUTE_REQUEST" /* TASK_EXECUTE_REQUEST */:
|
|
635
|
+
void asyncProcessColaboFlowMsg_TaskExecute(orchestrator, msgObj).catch((err) => {
|
|
636
|
+
console.error(`${appNameText} Error while processing TASK_EXECUTE_REQUEST: ${formatError2(err)}`);
|
|
637
|
+
});
|
|
638
|
+
break;
|
|
639
|
+
}
|
|
640
|
+
} catch (err) {
|
|
641
|
+
console.error(`${appNameText} Error parsing client message: ${formatError2(err)} | raw=${msg.content.toString()}`);
|
|
642
|
+
}
|
|
643
|
+
orchestrator.clientsChannel.ack(msg);
|
|
644
|
+
} else {
|
|
645
|
+
console.log("${appNameText} Consumer cancelled by server");
|
|
646
|
+
}
|
|
647
|
+
});
|
|
648
|
+
};
|
|
649
|
+
var listenOnHeartbeatMessages = async (orchestrator) => {
|
|
650
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
651
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
652
|
+
orchestrator.clientsChannel.ackAll();
|
|
653
|
+
console.log(`${appNameText} Listening on the heartbeat queue: "${import_chalk2.default.blueBright(orchestrator.queueHostHeartbeat)}"`);
|
|
654
|
+
console.log(`${appNameText} [*] Waiting for heartbeat messages. To exit press "${import_chalk2.default.blueBright("CTRL+C")}"`);
|
|
655
|
+
orchestrator.clientsChannel.consume(orchestrator.queueHostHeartbeat, (msg) => {
|
|
656
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
657
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
658
|
+
if (msg !== null) {
|
|
659
|
+
let msgObj;
|
|
660
|
+
try {
|
|
661
|
+
msgObj = JSON.parse(msg.content.toString());
|
|
662
|
+
switch (msgObj.type) {
|
|
663
|
+
case "HEARTBEAT" /* HEARTBEAT */:
|
|
664
|
+
void asyncProcessColaboFlowMsg_Heartbeat(orchestrator, msgObj).catch((err) => {
|
|
665
|
+
console.error(`${appNameText} Error while processing HEARTBEAT: ${formatError2(err)}`);
|
|
666
|
+
});
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
} catch (err) {
|
|
670
|
+
console.error(`${appNameText} Error parsing heartbeat message: ${formatError2(err)} | raw=${msg.content.toString()}`);
|
|
671
|
+
}
|
|
672
|
+
orchestrator.clientsChannel.ack(msg);
|
|
673
|
+
} else {
|
|
674
|
+
console.log("${appNameText} Consumer cancelled by server");
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
};
|
|
678
|
+
var orchestratorRun = async (orchestrator) => {
|
|
679
|
+
console.log(`${appNameText} Connecting to the server: ${import_chalk2.default.greenBright(orchestrator.amqpUrl)}`);
|
|
680
|
+
const effectiveAmqpUrl = getEffectiveAmqpUrl2(orchestrator.amqpUrl);
|
|
681
|
+
if (effectiveAmqpUrl !== orchestrator.amqpUrl) {
|
|
682
|
+
console.log(`${appNameText} Effective AMQP URL: ${import_chalk2.default.greenBright(effectiveAmqpUrl)}`);
|
|
683
|
+
}
|
|
684
|
+
logAmqpUrlDetails2(effectiveAmqpUrl);
|
|
685
|
+
let colaboFlowOrchestratorConnection;
|
|
686
|
+
const connectionName = `${orchestrator.orchestratorName}-pid-${process.pid}`;
|
|
687
|
+
const socketOptions = getConnectSocketOptions2(connectionName);
|
|
688
|
+
if (isAmqpDebugEnabled2()) {
|
|
689
|
+
console.log(`${appNameText} AMQP socket options: ${JSON.stringify(socketOptions)}`);
|
|
690
|
+
}
|
|
691
|
+
try {
|
|
692
|
+
colaboFlowOrchestratorConnection = await (0, import_amqplib2.connect)(effectiveAmqpUrl, socketOptions);
|
|
693
|
+
} catch (err) {
|
|
694
|
+
console.error(`Error connecting to the "${import_chalk2.default.greenBright(effectiveAmqpUrl)}" server: ${formatError2(err)}`);
|
|
695
|
+
if (isAmqpDebugEnabled2() && err instanceof Error && err.stack) {
|
|
696
|
+
console.error(`${appNameText} connect stack: ${err.stack}`);
|
|
697
|
+
}
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
attachConnectionDebugHandlers2(colaboFlowOrchestratorConnection);
|
|
701
|
+
console.log(`${appNameText} Opening the ${import_chalk2.default.bold.italic("clients")} channel`);
|
|
702
|
+
try {
|
|
703
|
+
orchestrator.clientsChannel = await colaboFlowOrchestratorConnection.createChannel();
|
|
704
|
+
} catch (err) {
|
|
705
|
+
console.error(`Error creating the ${import_chalk2.default.greenBright("clients")} queue: ${formatError2(err)}`);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
attachChannelDebugHandlers2("clients", orchestrator.clientsChannel);
|
|
709
|
+
console.log(`${appNameText} Opening the ${import_chalk2.default.bold.italic("hosts")} channel`);
|
|
710
|
+
try {
|
|
711
|
+
orchestrator.hostsChannel = await colaboFlowOrchestratorConnection.createChannel();
|
|
712
|
+
} catch (err) {
|
|
713
|
+
console.error(`Error creating the ${import_chalk2.default.greenBright("hosts")} queue: ${formatError2(err)}`);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
attachChannelDebugHandlers2("hosts", orchestrator.hostsChannel);
|
|
717
|
+
(0, import_i_verify.assert)(orchestrator.hostsChannel, `orchestrator.hostsChannel is not defined`);
|
|
718
|
+
(0, import_i_verify.assert)(orchestrator.clientsChannel, `orchestrator.clientsChannel is not defined`);
|
|
719
|
+
console.log(`${appNameText} Opening the ${import_chalk2.default.bold.italic("orchestrator")} queue as a listener: ${import_chalk2.default.greenBright(orchestrator.queueOrchestrator)}`);
|
|
720
|
+
await orchestrator.clientsChannel.assertQueue(orchestrator.queueOrchestrator, {
|
|
721
|
+
durable: true,
|
|
722
|
+
exclusive: false,
|
|
723
|
+
autoDelete: false
|
|
724
|
+
});
|
|
725
|
+
console.log(`${appNameText} Opening the ${import_chalk2.default.bold.italic("heartbeat")} queue as a listener: ${import_chalk2.default.greenBright(orchestrator.queueHostHeartbeat)}`);
|
|
726
|
+
await orchestrator.hostsChannel.assertQueue(orchestrator.queueHostHeartbeat, {
|
|
727
|
+
durable: true,
|
|
728
|
+
exclusive: false,
|
|
729
|
+
autoDelete: false
|
|
730
|
+
});
|
|
731
|
+
console.log(`${appNameText} ${import_chalk2.default.blueBright("Delaying")} listening on clients to give time for hosts to register (to avoid task execution request errors due to no hosts that implement tasks (executors)) )`);
|
|
732
|
+
setTimeout(() => listenOnClientRequests(orchestrator), 2 * HEARTBEAT_TIME);
|
|
733
|
+
listenOnHeartbeatMessages(orchestrator);
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
// lib/host/index.ts
|
|
737
|
+
var import_amqplib3 = require("amqplib");
|
|
738
|
+
var import_chalk3 = __toESM(require("chalk"), 1);
|
|
739
|
+
var import_i_core2 = require("@colabo-flow/i-core");
|
|
740
|
+
|
|
741
|
+
// lib/host/omnipresentTasks.ts
|
|
742
|
+
var import_i_core = require("@colabo-flow/i-core");
|
|
743
|
+
var addOmnipresentTasks = async (host, hostRegisterTaskExecutor2, hostRegisterTask2) => {
|
|
744
|
+
const echoPing = (input) => {
|
|
745
|
+
console.log(`${host.appNameText} [echoPing] Pinged with the input: ${JSON.stringify(input)}`);
|
|
746
|
+
const output = {
|
|
747
|
+
input,
|
|
748
|
+
timeDateNow: Date.now(),
|
|
749
|
+
// https://nodejs.org/api/perf_hooks.html#performancenow
|
|
750
|
+
timePerformance: performance.now(),
|
|
751
|
+
// https://timestamp.online/article/how-to-get-current-date-and-time-in-javascript
|
|
752
|
+
timeHuman: (/* @__PURE__ */ new Date()).toISOString(),
|
|
753
|
+
hostname: host.hostname,
|
|
754
|
+
queueHost: host.queueHost
|
|
755
|
+
};
|
|
756
|
+
return output;
|
|
757
|
+
};
|
|
758
|
+
const executorEchoPing = {
|
|
759
|
+
id: "colabo.flow.echoPing",
|
|
760
|
+
description: "(Node.js) Used for testing worker availability. Returns the sender message in addition with the local metadata",
|
|
761
|
+
environment: import_i_core.EExecutingEnvironment.ISOMORPHIC,
|
|
762
|
+
reference: {
|
|
763
|
+
method: echoPing
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
const taskEchoPing = {
|
|
767
|
+
id: "colabo.flow.echoPing",
|
|
768
|
+
type: import_i_core.EFlowTaskType.SCRIPT,
|
|
769
|
+
executorRef: {
|
|
770
|
+
environment: import_i_core.EExecutingEnvironment.ISOMORPHIC,
|
|
771
|
+
id: executorEchoPing.id
|
|
772
|
+
},
|
|
773
|
+
placeType: import_i_core.EFlowPlaceType.TASK,
|
|
774
|
+
inputs: [],
|
|
775
|
+
outputs: [],
|
|
776
|
+
inoutputs: []
|
|
777
|
+
};
|
|
778
|
+
console.log(`${host.appNameText} Adding echoPing task executor and task`);
|
|
779
|
+
hostRegisterTaskExecutor2(host, executorEchoPing);
|
|
780
|
+
hostRegisterTask2(host, taskEchoPing);
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
// lib/host/index.ts
|
|
784
|
+
var LANGUAGE = "JAVASCRIPT" /* JAVASCRIPT */;
|
|
785
|
+
var MINIMUM_FRAME_MAX3 = 8192;
|
|
786
|
+
var isAmqpDebugEnabled3 = () => {
|
|
787
|
+
const debugRaw = process.env.COLABO_FLOW_AMQP_DEBUG || "";
|
|
788
|
+
return debugRaw === "1" || debugRaw.toLowerCase() === "true";
|
|
789
|
+
};
|
|
790
|
+
var parsePositiveInt3 = (rawValue, fallback) => {
|
|
791
|
+
if (!rawValue) return fallback;
|
|
792
|
+
const parsed = Number.parseInt(rawValue, 10);
|
|
793
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
794
|
+
};
|
|
795
|
+
var formatError3 = (err) => {
|
|
796
|
+
if (!(err instanceof Error)) return String(err);
|
|
797
|
+
const errorExtended = err;
|
|
798
|
+
const meta = [
|
|
799
|
+
errorExtended.code ? `code=${errorExtended.code}` : "",
|
|
800
|
+
errorExtended.errno !== void 0 ? `errno=${errorExtended.errno}` : "",
|
|
801
|
+
errorExtended.syscall ? `syscall=${errorExtended.syscall}` : "",
|
|
802
|
+
errorExtended.address ? `address=${errorExtended.address}` : "",
|
|
803
|
+
errorExtended.port !== void 0 ? `port=${errorExtended.port}` : ""
|
|
804
|
+
].filter(Boolean).join(", ");
|
|
805
|
+
const msg = meta ? `${err.message} (${meta})` : err.message;
|
|
806
|
+
return err.stack ? `${msg}
|
|
807
|
+
${err.stack}` : msg;
|
|
808
|
+
};
|
|
809
|
+
var logAmqpUrlDetails3 = (host, urlRaw) => {
|
|
810
|
+
try {
|
|
811
|
+
const parsed = new URL(urlRaw);
|
|
812
|
+
const vhostRaw = parsed.pathname || "/";
|
|
813
|
+
const vhostDecoded = decodeURIComponent(vhostRaw);
|
|
814
|
+
const heartbeatQuery = parsed.searchParams.get("heartbeat") || "(broker default)";
|
|
815
|
+
const frameMaxQuery = parsed.searchParams.get("frameMax") || "(amqplib default)";
|
|
816
|
+
console.log(`${host.appNameText} AMQP URL details: protocol=${parsed.protocol}, host=${parsed.hostname}, port=${parsed.port || "5672"}, vhostRaw="${vhostRaw}", vhostDecoded="${vhostDecoded}", heartbeat=${heartbeatQuery}, frameMax=${frameMaxQuery}`);
|
|
817
|
+
} catch (err) {
|
|
818
|
+
console.warn(`${host.appNameText} Could not parse AMQP URL "${urlRaw}": ${formatError3(err)}`);
|
|
819
|
+
}
|
|
820
|
+
};
|
|
821
|
+
var getEffectiveAmqpUrl3 = (host, urlRaw) => {
|
|
822
|
+
try {
|
|
823
|
+
const parsed = new URL(urlRaw);
|
|
824
|
+
const defaultFrameMax = parsePositiveInt3(process.env.COLABO_FLOW_AMQP_FRAME_MAX, 131072);
|
|
825
|
+
const frameMaxConfiguredRaw = parsed.searchParams.get("frameMax") || void 0;
|
|
826
|
+
let frameMax = parsePositiveInt3(frameMaxConfiguredRaw, defaultFrameMax);
|
|
827
|
+
if (frameMax < MINIMUM_FRAME_MAX3) {
|
|
828
|
+
console.warn(`${host.appNameText} frameMax=${frameMax} is too low; forcing frameMax=${MINIMUM_FRAME_MAX3}`);
|
|
829
|
+
frameMax = MINIMUM_FRAME_MAX3;
|
|
830
|
+
}
|
|
831
|
+
parsed.searchParams.set("frameMax", String(frameMax));
|
|
832
|
+
return parsed.toString();
|
|
833
|
+
} catch {
|
|
834
|
+
return urlRaw;
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
var getConnectSocketOptions3 = (connectionName) => {
|
|
838
|
+
return {
|
|
839
|
+
noDelay: true,
|
|
840
|
+
keepAlive: true,
|
|
841
|
+
keepAliveDelay: parsePositiveInt3(process.env.COLABO_FLOW_AMQP_KEEPALIVE_DELAY_MS, 1e3),
|
|
842
|
+
timeout: parsePositiveInt3(process.env.COLABO_FLOW_AMQP_CONNECT_TIMEOUT_MS, 1e4),
|
|
843
|
+
clientProperties: {
|
|
844
|
+
connection_name: connectionName
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
};
|
|
848
|
+
var attachConnectionDebugHandlers3 = (host, connection) => {
|
|
849
|
+
connection.on("error", (err) => {
|
|
850
|
+
console.error(`${host.appNameText} AMQP connection error: ${formatError3(err)}`);
|
|
851
|
+
});
|
|
852
|
+
connection.on("close", () => {
|
|
853
|
+
console.warn(`${host.appNameText} AMQP connection closed`);
|
|
854
|
+
});
|
|
855
|
+
connection.on("blocked", (reason) => {
|
|
856
|
+
console.warn(`${host.appNameText} AMQP connection blocked: ${String(reason)}`);
|
|
857
|
+
});
|
|
858
|
+
connection.on("unblocked", () => {
|
|
859
|
+
console.warn(`${host.appNameText} AMQP connection unblocked`);
|
|
860
|
+
});
|
|
861
|
+
connection.on("frameError", (err) => {
|
|
862
|
+
console.error(`${host.appNameText} AMQP frameError: ${formatError3(err)}`);
|
|
863
|
+
});
|
|
864
|
+
const maybeSocket = connection?.connection?.stream;
|
|
865
|
+
if (maybeSocket && isAmqpDebugEnabled3()) {
|
|
866
|
+
maybeSocket.on("error", (err) => {
|
|
867
|
+
console.error(`${host.appNameText} AMQP socket error: ${formatError3(err)}`);
|
|
868
|
+
});
|
|
869
|
+
maybeSocket.on("close", (hadError) => {
|
|
870
|
+
console.warn(`${host.appNameText} AMQP socket close (hadError=${hadError})`);
|
|
871
|
+
});
|
|
872
|
+
maybeSocket.on("end", () => {
|
|
873
|
+
console.warn(`${host.appNameText} AMQP socket end`);
|
|
874
|
+
});
|
|
875
|
+
maybeSocket.on("timeout", () => {
|
|
876
|
+
console.warn(`${host.appNameText} AMQP socket timeout`);
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
var attachChannelDebugHandlers3 = (host, channelName, channel) => {
|
|
881
|
+
channel.on("error", (err) => {
|
|
882
|
+
console.error(`${host.appNameText} AMQP channel "${channelName}" error: ${formatError3(err)}`);
|
|
883
|
+
});
|
|
884
|
+
channel.on("close", () => {
|
|
885
|
+
console.warn(`${host.appNameText} AMQP channel "${channelName}" closed`);
|
|
886
|
+
});
|
|
887
|
+
channel.on("return", (msg) => {
|
|
888
|
+
if (isAmqpDebugEnabled3()) {
|
|
889
|
+
console.warn(`${host.appNameText} AMQP channel "${channelName}" returned a message: ${JSON.stringify(msg)}`);
|
|
890
|
+
}
|
|
891
|
+
});
|
|
892
|
+
channel.on("drain", () => {
|
|
893
|
+
if (isAmqpDebugEnabled3()) {
|
|
894
|
+
console.log(`${host.appNameText} AMQP channel "${channelName}" drain`);
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
};
|
|
898
|
+
var hostSetTitles = (host) => {
|
|
899
|
+
process.title = `ColaboFlow.Go-${host.hostname}`;
|
|
900
|
+
host.appNameText = `[${import_chalk3.default.red.bold("Colabo")}${import_chalk3.default.blue.bold("Flow")}${import_chalk3.default.green.bold(".Go")}-${import_chalk3.default.green.yellow(host.hostname)}]`;
|
|
901
|
+
};
|
|
902
|
+
var hostRegisterTaskExecutor = (host, executor) => {
|
|
903
|
+
console.log(`${host.appNameText} Registering task executor, executor.id "${import_chalk3.default.greenBright(executor.id)}"`);
|
|
904
|
+
host.taskExecutorsAvailable[executor.id] = executor;
|
|
905
|
+
};
|
|
906
|
+
var getTaskExecutor = (host, executorId) => {
|
|
907
|
+
return host.taskExecutorsAvailable[executorId];
|
|
908
|
+
};
|
|
909
|
+
var hostRegisterTask = (host, task) => {
|
|
910
|
+
host.tasksAvailable[task.id] = task;
|
|
911
|
+
console.log(`${host.appNameText} Registered task with task.id "${import_chalk3.default.greenBright(task.id)}"`);
|
|
912
|
+
};
|
|
913
|
+
var connectToServer = async (host) => {
|
|
914
|
+
console.log(`${host.appNameText} Connecting to the server: ${import_chalk3.default.greenBright(host.amqpUrl)}`);
|
|
915
|
+
const effectiveAmqpUrl = getEffectiveAmqpUrl3(host, host.amqpUrl);
|
|
916
|
+
if (effectiveAmqpUrl !== host.amqpUrl) {
|
|
917
|
+
console.log(`${host.appNameText} Effective AMQP URL: ${import_chalk3.default.greenBright(effectiveAmqpUrl)}`);
|
|
918
|
+
}
|
|
919
|
+
logAmqpUrlDetails3(host, effectiveAmqpUrl);
|
|
920
|
+
let colaboFlowOrchestratorConnection;
|
|
921
|
+
const connectionName = `${host.hostname}-pid-${process.pid}`;
|
|
922
|
+
const socketOptions = getConnectSocketOptions3(connectionName);
|
|
923
|
+
if (isAmqpDebugEnabled3()) {
|
|
924
|
+
console.log(`${host.appNameText} AMQP socket options: ${JSON.stringify(socketOptions)}`);
|
|
925
|
+
}
|
|
926
|
+
try {
|
|
927
|
+
colaboFlowOrchestratorConnection = await (0, import_amqplib3.connect)(effectiveAmqpUrl, socketOptions);
|
|
928
|
+
host.connection = colaboFlowOrchestratorConnection;
|
|
929
|
+
attachConnectionDebugHandlers3(host, colaboFlowOrchestratorConnection);
|
|
930
|
+
return colaboFlowOrchestratorConnection;
|
|
931
|
+
} catch (err) {
|
|
932
|
+
console.error(`Error connecting to the "${import_chalk3.default.greenBright(effectiveAmqpUrl)}" server: ${formatError3(err)}`);
|
|
933
|
+
if (isAmqpDebugEnabled3() && err instanceof Error && err.stack) {
|
|
934
|
+
console.error(`${host.appNameText} connect stack: ${err.stack}`);
|
|
935
|
+
}
|
|
936
|
+
throw err;
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
var connectToHost = async (host, colaboFlowOrchestratorConnection) => {
|
|
940
|
+
console.log(`${host.appNameText} Opening the ${import_chalk3.default.bold.italic("node host")} channel as a listener (consumer): ${import_chalk3.default.greenBright(host.queueHost)}`);
|
|
941
|
+
let chHost;
|
|
942
|
+
try {
|
|
943
|
+
chHost = await colaboFlowOrchestratorConnection.createChannel();
|
|
944
|
+
attachChannelDebugHandlers3(host, "host-listener", chHost);
|
|
945
|
+
return chHost;
|
|
946
|
+
} catch (err) {
|
|
947
|
+
console.error(`${host.appNameText} Error creating the "${import_chalk3.default.greenBright(host.queueHost)}" queue: ${formatError3(err)}`);
|
|
948
|
+
throw err;
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
var connectToOrchestratorHeartbeat = async (host, colaboFlowOrchestratorConnection) => {
|
|
952
|
+
console.log(`${host.appNameText} Opening the ${import_chalk3.default.bold.italic("orchestrator heartbeat")} channel as a produced (emitter): ${import_chalk3.default.greenBright(host.queueHostHeartbeat)}`);
|
|
953
|
+
try {
|
|
954
|
+
const chHostHeartbeat = await colaboFlowOrchestratorConnection.createChannel();
|
|
955
|
+
host.chHostHeartbeat = chHostHeartbeat;
|
|
956
|
+
attachChannelDebugHandlers3(host, "host-heartbeat", chHostHeartbeat);
|
|
957
|
+
return chHostHeartbeat;
|
|
958
|
+
} catch (err) {
|
|
959
|
+
console.error(`${host.appNameText} Error creating the "${import_chalk3.default.greenBright(host.queueHostHeartbeat)}" queue: ${formatError3(err)}`);
|
|
960
|
+
throw err;
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
var heartbeatId = 0;
|
|
964
|
+
var sendHeartbeatToHost = async (host) => {
|
|
965
|
+
if (!host.chHostHeartbeat) {
|
|
966
|
+
console.error(`${host.appNameText} [sendHeartbeatToHost] Error: channel host.chHostHeartbeat is not existing`);
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
const heartbeat = {
|
|
970
|
+
...createGoMsg(host.hostname, "HEARTBEAT" /* HEARTBEAT */),
|
|
971
|
+
extension: {
|
|
972
|
+
id: heartbeatId++,
|
|
973
|
+
queueHost: host.queueHost,
|
|
974
|
+
language: "JAVASCRIPT" /* JAVASCRIPT */,
|
|
975
|
+
taskIds: Object.keys(host.taskExecutorsAvailable)
|
|
976
|
+
},
|
|
977
|
+
msg: `node host with tasks: ${JSON.stringify(Object.keys(host.taskExecutorsAvailable))}`
|
|
978
|
+
};
|
|
979
|
+
if (host.reportsConfig.showHeartbeatMsgs && heartbeat.extension.id % host.reportsConfig.showHeartbeatMsgs == 0) {
|
|
980
|
+
console.log(`${host.appNameText} Sending heartbeat [${heartbeat.extension.id}] [from "${import_chalk3.default.blueBright(host.hostname)}" queue: "${import_chalk3.default.blueBright(host.queueHostHeartbeat)}"]`);
|
|
981
|
+
}
|
|
982
|
+
try {
|
|
983
|
+
host.chHostHeartbeat.sendToQueue(host.queueHostHeartbeat, Buffer.from(JSON.stringify(heartbeat)));
|
|
984
|
+
} catch (err) {
|
|
985
|
+
console.error(`${host.appNameText} [sendHeartbeatToHost] Failed to send heartbeat: ${formatError3(err)}`);
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
var asyncProcessColaboFlowMsg_TaskExecute2 = async (host, msgOrchestratorReqObj) => {
|
|
989
|
+
if (!host.chHostHeartbeat) {
|
|
990
|
+
console.error(`${host.appNameText} [sendHeartbeatToHost] Error: channel host.chHostHeartbeat is not existing`);
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
const msgOrchestratorTaskExecuteReqObjExtension = msgOrchestratorReqObj.extension;
|
|
994
|
+
const taskId = msgOrchestratorTaskExecuteReqObjExtension.taskId;
|
|
995
|
+
const taskInput = msgOrchestratorTaskExecuteReqObjExtension.taskInput;
|
|
996
|
+
const queueReplyTo = msgOrchestratorReqObj.replyTo ?? host.queueHostHeartbeat;
|
|
997
|
+
if (host.reportsConfig.showExecutionMsgs) {
|
|
998
|
+
console.log(`${host.appNameText} [asyncProcessColaboFlowMsg_TaskExecute] Got a task to execute [and return over the RPC-reply queue: "${import_chalk3.default.blueBright(queueReplyTo)}"]: taskId: ${taskId}`);
|
|
999
|
+
}
|
|
1000
|
+
const task = host.tasksAvailable[taskId];
|
|
1001
|
+
if (!task) {
|
|
1002
|
+
console.error(`${host.appNameText} [asyncProcessColaboFlowMsg_TaskExecute] task is missing for the id: ${taskId}`);
|
|
1003
|
+
}
|
|
1004
|
+
console.log(`${host.appNameText} [asyncProcessColaboFlowMsg_TaskExecute] Executing id: ${import_chalk3.default.blueBright(taskId)}, task.description: ${task.description}`);
|
|
1005
|
+
const taskInstanceId = `taskId:lang-${LANGUAGE}:host-${host.hostname}:${(0, import_uuid.v1)()}`;
|
|
1006
|
+
const taskInstance = (0, import_i_core2.createTaskInstanceForTaskWithoutFlow)(task);
|
|
1007
|
+
taskInstance.id = taskInstanceId;
|
|
1008
|
+
host.taskInstances[taskId] = taskInstance;
|
|
1009
|
+
host.runningTaskInstancesInfos[taskId] = {
|
|
1010
|
+
id: taskInstanceId,
|
|
1011
|
+
taskInstance
|
|
1012
|
+
};
|
|
1013
|
+
if (typeof task.executorRef?.id === "undefined") {
|
|
1014
|
+
console.error(`Executor ID is not provided for the task: ${taskId}`);
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
const taskExecutor = getTaskExecutor(host, task.executorRef?.id);
|
|
1018
|
+
const msgTaskExecutionProgress = {
|
|
1019
|
+
...createGoMsg(host.hostname, "TASK_EXECUTE_PROGRESS" /* TASK_EXECUTE_PROGRESS */),
|
|
1020
|
+
requestId: msgOrchestratorReqObj.requestId,
|
|
1021
|
+
msgReplyChainIds: [msgOrchestratorReqObj.id],
|
|
1022
|
+
extension: {
|
|
1023
|
+
taskInstanceId,
|
|
1024
|
+
status: "INITIALIZED" /* INITIALIZED */,
|
|
1025
|
+
progress: 0
|
|
1026
|
+
},
|
|
1027
|
+
msg: `Returning task execution for the taskId: '${taskId}' over queue: '${queueReplyTo}'}`
|
|
1028
|
+
};
|
|
1029
|
+
if (host.reportsConfig.showExecutionMsgs) {
|
|
1030
|
+
console.log(`${host.appNameText} Sending PROGRESS to the task execution requester (orchestrator) [queue: "${import_chalk3.default.blueBright(queueReplyTo)}"]: ${JSON.stringify(msgTaskExecutionProgress)}`);
|
|
1031
|
+
}
|
|
1032
|
+
try {
|
|
1033
|
+
host.chHostHeartbeat.sendToQueue(queueReplyTo, Buffer.from(JSON.stringify(msgTaskExecutionProgress)));
|
|
1034
|
+
} catch (err) {
|
|
1035
|
+
console.error(`${host.appNameText} Failed sending TASK_EXECUTE_PROGRESS to queue "${queueReplyTo}": ${formatError3(err)}`);
|
|
1036
|
+
}
|
|
1037
|
+
const taskOutput = await taskExecutor.reference?.method(taskInput);
|
|
1038
|
+
const taskOutputStr = JSON.stringify(taskOutput);
|
|
1039
|
+
const responseMaxChars = 200;
|
|
1040
|
+
const taskOutputStrShort = taskOutputStr.length > responseMaxChars ? taskOutputStr.substring(0, responseMaxChars / 2) + " [...] " + taskOutputStr.substring(taskOutputStr.length - responseMaxChars / 2) : taskOutputStr;
|
|
1041
|
+
console.log(`${host.appNameText} [asyncProcessColaboFlowMsg_TaskExecute] task executed. Result is (reduced to ${responseMaxChars} chars): ${import_chalk3.default.blueBright(taskOutputStrShort)}`);
|
|
1042
|
+
const msgTaskExecutionReply = {
|
|
1043
|
+
...createGoMsg(host.hostname, "TASK_EXECUTE_RESPONSE" /* TASK_EXECUTE_RESPONSE */),
|
|
1044
|
+
requestId: msgOrchestratorReqObj.requestId,
|
|
1045
|
+
msgReplyChainIds: [msgOrchestratorReqObj.id],
|
|
1046
|
+
extension: {
|
|
1047
|
+
taskOutput
|
|
1048
|
+
},
|
|
1049
|
+
msg: `Returning task execution for the taskId: '${taskId}' over queue: '${queueReplyTo}'}`
|
|
1050
|
+
};
|
|
1051
|
+
const msgTaskExecutionReplyStr = JSON.stringify(msgTaskExecutionReply);
|
|
1052
|
+
const msgTaskExecutionReplyStrShort = msgTaskExecutionReplyStr.length > responseMaxChars ? msgTaskExecutionReplyStr.substring(0, responseMaxChars / 2) + " [...] " + msgTaskExecutionReplyStr.substring(msgTaskExecutionReplyStr.length - responseMaxChars / 2) : msgTaskExecutionReplyStr;
|
|
1053
|
+
if (host.reportsConfig.showExecutionMsgs) {
|
|
1054
|
+
console.log(`${host.appNameText} Sending RESPONSE to the task execution requester (orchestrator) [queue: "${import_chalk3.default.blueBright(queueReplyTo)}"]: (reduced to ${responseMaxChars} chars) ${msgTaskExecutionReplyStrShort}`);
|
|
1055
|
+
}
|
|
1056
|
+
try {
|
|
1057
|
+
host.chHostHeartbeat.sendToQueue(queueReplyTo, Buffer.from(msgTaskExecutionReplyStr));
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
console.error(`${host.appNameText} Failed sending TASK_EXECUTE_RESPONSE to queue "${queueReplyTo}": ${formatError3(err)}`);
|
|
1060
|
+
}
|
|
1061
|
+
};
|
|
1062
|
+
var processColaboFlowMsg_TaskInstancesReport = (host, msgObj) => {
|
|
1063
|
+
if (!host.chHostHeartbeat) {
|
|
1064
|
+
console.error(`${host.appNameText} [sendHeartbeatToHost] Error: channel host.chHostHeartbeat is not existing`);
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
const msgExtension = msgObj.extension;
|
|
1068
|
+
const reportFinalizedTaskInstances = msgExtension.reportFinalizedTaskInstances;
|
|
1069
|
+
const reportRunningTaskInstances = msgExtension.reportRunningTaskInstances;
|
|
1070
|
+
console.log(`${host.appNameText} [processColaboFlowMsg_TaskInstancesReport] Sending task instances report to the requester: ${import_chalk3.default.blueBright(msgObj.sender)}`);
|
|
1071
|
+
const tasksInstanceInfos = {};
|
|
1072
|
+
if (reportRunningTaskInstances) {
|
|
1073
|
+
Object.assign(tasksInstanceInfos, host.runningTaskInstancesInfos);
|
|
1074
|
+
}
|
|
1075
|
+
if (reportFinalizedTaskInstances) {
|
|
1076
|
+
Object.assign(tasksInstanceInfos, host.finalizedTaskInstancesInfos);
|
|
1077
|
+
}
|
|
1078
|
+
const msgReply = {
|
|
1079
|
+
...createGoMsg(host.hostname, "TASK_INSTANCES_REPORT__RESPONSE" /* TASK_INSTANCES_REPORT__RESPONSE */),
|
|
1080
|
+
requestId: msgObj.requestId,
|
|
1081
|
+
msgReplyChainIds: [msgObj.id],
|
|
1082
|
+
extension: {
|
|
1083
|
+
tasksInstanceInfos
|
|
1084
|
+
},
|
|
1085
|
+
msg: `node host with tasks: ${JSON.stringify(Object.keys(host.taskExecutorsAvailable))}`
|
|
1086
|
+
};
|
|
1087
|
+
const queueReplyTo = msgObj.replyTo ?? host.queueHostHeartbeat;
|
|
1088
|
+
if (host.reportsConfig.showReportsMsgs) {
|
|
1089
|
+
console.log(`${host.appNameText} Sending response to the task instances report [queue: "${import_chalk3.default.blueBright(queueReplyTo)}"]: ${JSON.stringify(msgReply)}`);
|
|
1090
|
+
}
|
|
1091
|
+
try {
|
|
1092
|
+
host.chHostHeartbeat.sendToQueue(queueReplyTo, Buffer.from(JSON.stringify(msgReply)));
|
|
1093
|
+
} catch (err) {
|
|
1094
|
+
console.error(`${host.appNameText} Failed sending TASK_INSTANCES_REPORT__RESPONSE to queue "${queueReplyTo}": ${formatError3(err)}`);
|
|
1095
|
+
}
|
|
1096
|
+
};
|
|
1097
|
+
var hostRun = async (host) => {
|
|
1098
|
+
process.title = `ColaboFlow.Go-${host.hostname}`;
|
|
1099
|
+
addOmnipresentTasks(host, hostRegisterTaskExecutor, hostRegisterTask);
|
|
1100
|
+
const colaboFlowOrchestratorConnection = await connectToServer(host);
|
|
1101
|
+
const chHost = await connectToHost(host, colaboFlowOrchestratorConnection);
|
|
1102
|
+
await connectToOrchestratorHeartbeat(host, colaboFlowOrchestratorConnection);
|
|
1103
|
+
console.log(`${host.appNameText} Hosting tasks: "${import_chalk3.default.greenBright(Object.keys(host.tasksAvailable).toString())}"`);
|
|
1104
|
+
setInterval(() => {
|
|
1105
|
+
sendHeartbeatToHost(host);
|
|
1106
|
+
}, HEARTBEAT_TIME);
|
|
1107
|
+
console.log(`${host.appNameText} Listening on the queue: "${import_chalk3.default.blueBright(host.queueHost)}"`);
|
|
1108
|
+
await chHost.assertQueue(host.queueHost, {
|
|
1109
|
+
exclusive: true
|
|
1110
|
+
});
|
|
1111
|
+
console.log(`${host.appNameText} [*] Waiting for messages in %s. To exit press "${import_chalk3.default.blueBright("CTRL+C")}"`);
|
|
1112
|
+
chHost.consume(host.queueHost, async (msg) => {
|
|
1113
|
+
if (msg !== null) {
|
|
1114
|
+
chHost.ack(msg);
|
|
1115
|
+
let msgObj;
|
|
1116
|
+
try {
|
|
1117
|
+
msgObj = JSON.parse(msg.content.toString());
|
|
1118
|
+
const msgObjStr = JSON.stringify(msgObj);
|
|
1119
|
+
const responseMaxChars = 200;
|
|
1120
|
+
const msgObjStrShort = msgObjStr.length > responseMaxChars ? msgObjStr.substring(0, responseMaxChars / 2) + " [...] " + msgObjStr.substring(msgObjStr.length - responseMaxChars / 2) : msgObjStr;
|
|
1121
|
+
console.log(`${host.appNameText} Received (reduced to ${responseMaxChars} chars): "${import_chalk3.default.blueBright(msgObjStrShort)}"`);
|
|
1122
|
+
console.log(`${host.appNameText} msgObj.sender: "${import_chalk3.default.blueBright(msgObj.sender)}", msgObj.type: "${import_chalk3.default.blueBright(msgObj.type)}, msgObj.msg: "${import_chalk3.default.blueBright(msgObj.msg)}"`);
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
console.error(`${host.appNameText} Error parsing the message: ${formatError3(err)} | raw=${msg.content.toString()}`);
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
try {
|
|
1128
|
+
switch (msgObj.type) {
|
|
1129
|
+
case "TASK_EXECUTE_REQUEST" /* TASK_EXECUTE_REQUEST */:
|
|
1130
|
+
await asyncProcessColaboFlowMsg_TaskExecute2(host, msgObj);
|
|
1131
|
+
break;
|
|
1132
|
+
case "TASK_INSTANCES_REPORT__REQUEST" /* TASK_INSTANCES_REPORT__REQUEST */:
|
|
1133
|
+
processColaboFlowMsg_TaskInstancesReport(host, msgObj);
|
|
1134
|
+
break;
|
|
1135
|
+
}
|
|
1136
|
+
} catch (err) {
|
|
1137
|
+
console.error(`${host.appNameText} Error while processing message type "${msgObj.type}": ${formatError3(err)}`);
|
|
1138
|
+
}
|
|
1139
|
+
} else {
|
|
1140
|
+
console.log("${host.appNameText} Consumer cancelled by server");
|
|
1141
|
+
}
|
|
1142
|
+
});
|
|
1143
|
+
};
|
|
1144
|
+
|
|
1145
|
+
// index.ts
|
|
1146
|
+
var import_i_register = require("@colabo-utils/i-register");
|
|
1147
|
+
|
|
1148
|
+
// lib/flowchestrator/store/flowchestrator.store.ts
|
|
1149
|
+
var import_chalk4 = __toESM(require("chalk"), 1);
|
|
1150
|
+
var import_i_core3 = require("@colabo-flow/i-core");
|
|
1151
|
+
var import_i_store = require("@colabo-utils/i-store");
|
|
1152
|
+
var import_i_core4 = require("@colabo-knalledge/i-core");
|
|
1153
|
+
var import_i_verify2 = require("@colabo-utils/i-verify");
|
|
1154
|
+
var import_i_core5 = require("@colabo-flow/i-core");
|
|
1155
|
+
var DEBUG = true;
|
|
1156
|
+
var DEBUG_VERBOSE = true;
|
|
1157
|
+
var appNameText2 = "ColaboFlow.Go.FlowCheStrator.Store";
|
|
1158
|
+
var _store;
|
|
1159
|
+
var useFlowFlowchestratorStore = (flowStoreProtected) => {
|
|
1160
|
+
const _appNameText = flowStoreProtected.appNameText;
|
|
1161
|
+
appNameText2 = `${_appNameText}:[${import_chalk4.default.bold.yellow("STORE")}]`;
|
|
1162
|
+
if (!_store) {
|
|
1163
|
+
_store = (0, import_i_store.createBaseStore)((set, _get) => {
|
|
1164
|
+
const get = () => {
|
|
1165
|
+
return _get();
|
|
1166
|
+
};
|
|
1167
|
+
const storeObj = {
|
|
1168
|
+
// state
|
|
1169
|
+
// ========================
|
|
1170
|
+
flowInstanceObservers: [],
|
|
1171
|
+
flowInstanceContexts: {},
|
|
1172
|
+
flowInstancesContainer: {},
|
|
1173
|
+
// mutations
|
|
1174
|
+
// ========================
|
|
1175
|
+
addFlowInstance: (payload) => {
|
|
1176
|
+
const { flowInstanceContexts, flowInstancesContainer } = get();
|
|
1177
|
+
flowInstanceContexts[payload.flowInstance.id] = {
|
|
1178
|
+
visualTaskContainers: {}
|
|
1179
|
+
};
|
|
1180
|
+
const flowInstanceContainer = {
|
|
1181
|
+
flowInstance: payload.flowInstance,
|
|
1182
|
+
flowInstanceEngine: payload.flowEngine,
|
|
1183
|
+
isFlowStarted: false,
|
|
1184
|
+
flowInput: payload.flowInput
|
|
1185
|
+
};
|
|
1186
|
+
flowInstancesContainer[payload.flowInstance.id] = flowInstanceContainer;
|
|
1187
|
+
},
|
|
1188
|
+
removeFlowInstance: (payload) => {
|
|
1189
|
+
const { flowInstancesContainer, flowInstanceContexts } = get();
|
|
1190
|
+
if (DEBUG) console.log(`${appNameText2}:[removeFlowInstance] removing flow instance with ID: ${payload.flowInstanceId}`);
|
|
1191
|
+
delete flowInstancesContainer[payload.flowInstanceId];
|
|
1192
|
+
delete flowInstanceContexts[payload.flowInstanceId];
|
|
1193
|
+
},
|
|
1194
|
+
updateFlowInstanceId: (payload) => {
|
|
1195
|
+
const { flowInstancesContainer, flowInstanceContexts } = get();
|
|
1196
|
+
flowInstancesContainer[payload.flowInstanceIdNew] = flowInstancesContainer[payload.flowInstanceIdCurrent];
|
|
1197
|
+
delete flowInstancesContainer[payload.flowInstanceIdCurrent];
|
|
1198
|
+
flowInstancesContainer[payload.flowInstanceIdNew].flowInstance.id = payload.flowInstanceIdNew;
|
|
1199
|
+
flowInstanceContexts[payload.flowInstanceIdNew] = flowInstanceContexts[payload.flowInstanceIdCurrent];
|
|
1200
|
+
delete flowInstanceContexts[payload.flowInstanceIdCurrent];
|
|
1201
|
+
},
|
|
1202
|
+
// actions
|
|
1203
|
+
// ========================
|
|
1204
|
+
loadFlowInstances: async (flowId, flowInstanceNodeId, statuses) => {
|
|
1205
|
+
if (DEBUG) console.log(`${appNameText2}:[loadFlowInstances] loading flow instances...`);
|
|
1206
|
+
const request = {
|
|
1207
|
+
type: import_i_core4.KEDGE_API_TYPE.INDEX_COLABO_API,
|
|
1208
|
+
paramsDetailed: {
|
|
1209
|
+
type: {
|
|
1210
|
+
path: "type",
|
|
1211
|
+
value: import_i_core3.KFlowTypes.FLOW_INSTANCE
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
if (flowId) {
|
|
1216
|
+
request.paramsDetailed ??= {};
|
|
1217
|
+
request.paramsDetailed["flowId"] = {
|
|
1218
|
+
path: "dataContent.flowId",
|
|
1219
|
+
value: flowId
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
if (flowInstanceNodeId) {
|
|
1223
|
+
request.paramsDetailed ??= {};
|
|
1224
|
+
request.paramsDetailed["flowInstanceNodeId"] = {
|
|
1225
|
+
path: "_id",
|
|
1226
|
+
value: flowInstanceNodeId
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
if (statuses) {
|
|
1230
|
+
const statusesStrArray = statuses.map((status) => status.toString());
|
|
1231
|
+
request.paramsDetailed ??= {};
|
|
1232
|
+
request.paramsDetailed["statuses"] = {
|
|
1233
|
+
path: "dataContent.executionStatus.status",
|
|
1234
|
+
value: statusesStrArray,
|
|
1235
|
+
props: {
|
|
1236
|
+
type: import_i_core4.EApiRequestParamType.IN
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
const flowInstanceKNodes = await flowStoreProtected.kNodeService.getVosWithColaboApi(request);
|
|
1241
|
+
if (!flowInstanceKNodes) {
|
|
1242
|
+
throw new Error("persisted Flow instances not retrieved from store");
|
|
1243
|
+
}
|
|
1244
|
+
if (DEBUG) console.log(`${appNameText2}:[loadFlowInstances] flow instances retrieved (packed) from store with IDs ${flowInstanceKNodes.map((kNode) => kNode._id)}`);
|
|
1245
|
+
const flowInstances = await Promise.all(flowInstanceKNodes.map(async (flowInstanceKNode) => {
|
|
1246
|
+
const flowInstance = (0, import_i_core3.flowInstanceUnpack)(flowInstanceKNode);
|
|
1247
|
+
if (DEBUG) console.log(`${appNameText2}:[loadFlowInstances] flow instance unpacked: ${JSON.stringify(flowInstance, null, 4)}`);
|
|
1248
|
+
for (const tokenKnodeId of flowInstanceKNode?.dataContent?.tokenKnodeIds ?? []) {
|
|
1249
|
+
const tokenKNode = await flowStoreProtected.kNodeService.getById(tokenKnodeId);
|
|
1250
|
+
if (!tokenKNode) {
|
|
1251
|
+
throw new Error(`Token not found, tokenKnodeId: ${tokenKnodeId}`);
|
|
1252
|
+
}
|
|
1253
|
+
const token = (0, import_i_core5.tokenUnpack)(tokenKNode);
|
|
1254
|
+
if (DEBUG_VERBOSE) console.log(`${appNameText2}:[loadFlowInstances] token unpacked: ID ${token.id}`);
|
|
1255
|
+
flowInstance.tokens.push(token);
|
|
1256
|
+
}
|
|
1257
|
+
return flowInstance;
|
|
1258
|
+
}));
|
|
1259
|
+
if (DEBUG) console.log(`${appNameText2}:[loadFlowInstances] flow instances unpacked`);
|
|
1260
|
+
for (const flowInstance of flowInstances) {
|
|
1261
|
+
if (DEBUG) console.log(`${appNameText2}:[loadFlowInstances] adding flow instance with ID ${flowInstance.id} to the in-memory store`);
|
|
1262
|
+
const flow = await flowStoreProtected.getDomainStore().loadFlow(flowInstance.flowId);
|
|
1263
|
+
if (DEBUG_VERBOSE) console.log(`${appNameText2}:[loadFlowInstances] flow with ID ${flow.id} loaded from the store: ${JSON.stringify(flow, null, 4)}`);
|
|
1264
|
+
const flowEngine = new import_i_core3.FlowInstanceEngine(flow, flowInstance);
|
|
1265
|
+
const payloadFlowInstanceAdd = {
|
|
1266
|
+
flowInstance,
|
|
1267
|
+
flowEngine,
|
|
1268
|
+
// TODO: we should understand what to do with flowInput, where it is persisted and how to depersist it
|
|
1269
|
+
flowInput: void 0
|
|
1270
|
+
};
|
|
1271
|
+
get().addFlowInstance(payloadFlowInstanceAdd);
|
|
1272
|
+
}
|
|
1273
|
+
if (DEBUG_VERBOSE) console.log(`${appNameText2}:[loadInstances] flow instances loaded: ${JSON.stringify(flowInstances, null, 4)}`);
|
|
1274
|
+
return flowInstances;
|
|
1275
|
+
},
|
|
1276
|
+
createFlowInstance: async (payload) => {
|
|
1277
|
+
if (DEBUG) console.log(`${appNameText2}:[createFlowInstance] starting...`);
|
|
1278
|
+
const flow = payload.flow;
|
|
1279
|
+
const flowEngine = new import_i_core3.FlowInstanceEngine(flow, void 0, { createEntitiesIds: true, flowInstancePartial: payload.flowInstancePartial });
|
|
1280
|
+
const flowInstance = await flowEngine.asyncGetFlowInstance();
|
|
1281
|
+
if (DEBUG) console.log(`${appNameText2}:[createFlowInstance] flow instance created: ${JSON.stringify(flowInstance, null, 4)}`);
|
|
1282
|
+
const processNewFlowInstance_payload = {
|
|
1283
|
+
flow,
|
|
1284
|
+
flowInstance
|
|
1285
|
+
};
|
|
1286
|
+
const { flowInstanceObservers } = get();
|
|
1287
|
+
for (const observer of flowInstanceObservers) {
|
|
1288
|
+
if (DEBUG) console.log(`[FlowActions.FLOW_INSTANCE_CREATE] running flow instance observer, observer.name = ${observer.name}`);
|
|
1289
|
+
if (observer.asyncNewFlowInstanceProcessor) {
|
|
1290
|
+
await observer.asyncNewFlowInstanceProcessor(processNewFlowInstance_payload);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
const payloadFlowInstanceAdd = { flowInstance, flowEngine, flowInput: payload.flowInput };
|
|
1294
|
+
get().addFlowInstance(payloadFlowInstanceAdd);
|
|
1295
|
+
return flowInstance;
|
|
1296
|
+
},
|
|
1297
|
+
deleteFlowInstance: async (payload) => {
|
|
1298
|
+
if (DEBUG) console.log(`${appNameText2}:[deleteFlowInstance] deleting flow instance with ID: ${payload.flowInstanceId}`);
|
|
1299
|
+
const { flowInstancesContainer, removeFlowInstance } = get();
|
|
1300
|
+
removeFlowInstance({ flowInstanceId: payload.flowInstanceId });
|
|
1301
|
+
flowStoreProtected.kNodeService.destroy(payload.flowInstanceId);
|
|
1302
|
+
if (DEBUG) console.log(`${appNameText2}:[deleteFlowInstance] flow instance with ID ${payload.flowInstanceId} deleted from the in-memory and persistent store`);
|
|
1303
|
+
},
|
|
1304
|
+
persistFlowInstance: async (payload) => {
|
|
1305
|
+
const flowInstanceId = payload.flowInstanceId;
|
|
1306
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] persisting flow instance with ID: ${flowInstanceId}`);
|
|
1307
|
+
const { flowInstanceContexts, flowInstancesContainer } = get();
|
|
1308
|
+
const flowInstanceContainer = flowInstancesContainer[flowInstanceId];
|
|
1309
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1310
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] persisting flow instance with ID: ${flowInstance.id}: ${JSON.stringify(flowInstance, null, 4)}`);
|
|
1311
|
+
const flowInstanceKNode = (0, import_i_core3.flowInstancePack)(flowInstance);
|
|
1312
|
+
if (flowInstanceKNode._id?.startsWith(import_i_core4.KnAllEdge_EntityEphemeralIdPrefix)) flowInstanceKNode._id = void 0;
|
|
1313
|
+
if (flowInstanceKNode._id) {
|
|
1314
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] flow instance with ID ${flowInstance.id} already exists, updating it...`);
|
|
1315
|
+
const updateRequest = {
|
|
1316
|
+
type: import_i_core4.KNODE_API_TYPE.UPDATE_COLABO_API,
|
|
1317
|
+
paramsDetailed: {
|
|
1318
|
+
id: {
|
|
1319
|
+
path: "_id",
|
|
1320
|
+
value: flowInstance.id
|
|
1321
|
+
}
|
|
1322
|
+
},
|
|
1323
|
+
data: flowInstanceKNode
|
|
1324
|
+
};
|
|
1325
|
+
const kNodeFromServer = await flowStoreProtected.kNodeService.updateSingleWithColaboApi(updateRequest);
|
|
1326
|
+
if (!kNodeFromServer) {
|
|
1327
|
+
throw new Error("Flow instance not updated");
|
|
1328
|
+
}
|
|
1329
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] flow instance updated with flow knode ID: ${kNodeFromServer._id}: ${JSON.stringify(kNodeFromServer, null, 4)}`);
|
|
1330
|
+
} else {
|
|
1331
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] flow instance with ID ${flowInstance.id} does not exist, creating it...`);
|
|
1332
|
+
const createResult = await flowStoreProtected.kNodeService.create(flowInstanceKNode);
|
|
1333
|
+
if (!createResult || createResult.length !== 1) {
|
|
1334
|
+
throw new Error("Flow instance not created");
|
|
1335
|
+
}
|
|
1336
|
+
const kNodeFromServer = createResult[0];
|
|
1337
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] flow instance persisted with flow knode ID: ${kNodeFromServer._id}: ${JSON.stringify(kNodeFromServer, null, 4)}`);
|
|
1338
|
+
get().updateFlowInstanceId({
|
|
1339
|
+
flowInstanceIdCurrent: flowInstance.id,
|
|
1340
|
+
flowInstanceIdNew: kNodeFromServer._id
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
return flowInstance;
|
|
1344
|
+
},
|
|
1345
|
+
depersistFlowInstance: async (payload) => {
|
|
1346
|
+
const flowInstanceKnodeId = payload.flowInstanceId;
|
|
1347
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] depersisting flow instance from kNode with ID: ${flowInstanceKnodeId}`);
|
|
1348
|
+
const flowInstanceKNode = await flowStoreProtected.kNodeService.getById(flowInstanceKnodeId);
|
|
1349
|
+
if (!flowInstanceKNode) {
|
|
1350
|
+
throw new Error("persisted Flow instance not retrieved from store");
|
|
1351
|
+
}
|
|
1352
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] flow instance retrieved (packed) from store with ID ${flowInstanceKNode._id}: ${JSON.stringify(flowInstanceKNode, null, 4)}`);
|
|
1353
|
+
const flowInstance = (0, import_i_core3.flowInstanceUnpack)(flowInstanceKNode);
|
|
1354
|
+
for (const tokenKnodeId of flowInstanceKNode?.dataContent?.tokenKnodeIds ?? []) {
|
|
1355
|
+
const tokenKNode = await flowStoreProtected.kNodeService.getById(tokenKnodeId);
|
|
1356
|
+
if (!tokenKNode) {
|
|
1357
|
+
throw new Error(`Token not found, tokenKnodeId: ${tokenKnodeId}`);
|
|
1358
|
+
}
|
|
1359
|
+
const token = (0, import_i_core5.tokenUnpack)(tokenKNode);
|
|
1360
|
+
flowInstance.tokens.push(token);
|
|
1361
|
+
}
|
|
1362
|
+
if (DEBUG) console.log(`${appNameText2}:[persistFlowInstance] flow instance unpacked from kNode with ID ${flowInstanceKNode._id}: ${JSON.stringify(flowInstance, null, 4)}`);
|
|
1363
|
+
const flow = await flowStoreProtected.getDomainStore().loadFlow(flowInstance.flowId);
|
|
1364
|
+
const flowInstanceEngine = new import_i_core3.FlowInstanceEngine(flow);
|
|
1365
|
+
const processNewFlowInstance_payload = {
|
|
1366
|
+
flow,
|
|
1367
|
+
flowInstance
|
|
1368
|
+
};
|
|
1369
|
+
const { flowInstanceObservers } = get();
|
|
1370
|
+
for (const observer of flowInstanceObservers) {
|
|
1371
|
+
if (DEBUG) console.log(`[FlowActions.FLOW_INSTANCE_CREATE] running flow instance observer, observer.name = ${observer.name}`);
|
|
1372
|
+
if (observer.asyncNewFlowInstanceProcessor) {
|
|
1373
|
+
await observer.asyncNewFlowInstanceProcessor(processNewFlowInstance_payload);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
const flowInput = void 0;
|
|
1377
|
+
const payloadFlowInstanceAdd = { flowInstance, flowEngine: flowInstanceEngine, flowInput };
|
|
1378
|
+
get().addFlowInstance(payloadFlowInstanceAdd);
|
|
1379
|
+
return flowInstance;
|
|
1380
|
+
},
|
|
1381
|
+
executeFlowInstance: async (payload) => {
|
|
1382
|
+
},
|
|
1383
|
+
setFlowInstanceStatus: async (payload) => {
|
|
1384
|
+
const flowInstanceKnodeId = payload.flowInstanceKnodeId;
|
|
1385
|
+
if (DEBUG) console.log(`${appNameText2}:[setFlowInstanceStatus] setting flow instance status to ${payload.status} for flow instance with ID: ${flowInstanceKnodeId}`);
|
|
1386
|
+
const { flowInstancesContainer, depersistFlowInstance } = get();
|
|
1387
|
+
if (!(payload.flowInstanceKnodeId in flowInstancesContainer)) {
|
|
1388
|
+
console.info(`${appNameText2}:[getAgentTokenForFlowInstance] flow instance with ID ${payload.flowInstanceKnodeId} not found in the in-memory store. Retrieving it from the persistent store...`);
|
|
1389
|
+
await depersistFlowInstance({ flowInstanceId: payload.flowInstanceKnodeId });
|
|
1390
|
+
}
|
|
1391
|
+
const flowInstanceContainer = flowInstancesContainer[payload.flowInstanceKnodeId];
|
|
1392
|
+
if (!flowInstanceContainer) {
|
|
1393
|
+
const errorMsg = `Flow instance with ID ${payload.flowInstanceKnodeId} not found in the in-memory store after trying to depersist it.`;
|
|
1394
|
+
console.error(`${appNameText2}:[getAgentTokenForFlowInstance] ${errorMsg}`);
|
|
1395
|
+
return Promise.reject(new Error(errorMsg));
|
|
1396
|
+
}
|
|
1397
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1398
|
+
console.log(`${appNameText2}:[setFlowInstanceStatus] flow instance with ID ${flowInstance.id} found in the in-memory store: ${JSON.stringify(flowInstance, null, 4)}`);
|
|
1399
|
+
flowInstance.executionStatus.status = payload.status;
|
|
1400
|
+
get().persistFlowInstance({ flowInstanceId: flowInstance.id });
|
|
1401
|
+
return flowInstance.executionStatus.status;
|
|
1402
|
+
},
|
|
1403
|
+
joinAgentToFlowInstance: async (payload) => {
|
|
1404
|
+
const { flowInstanceContexts, flowInstancesContainer, depersistFlowInstance } = get();
|
|
1405
|
+
if (!(payload.flowInstanceKnodeId in flowInstancesContainer)) {
|
|
1406
|
+
console.info(`${appNameText2}:[joinFlowInstance] flow instance with ID ${payload.flowInstanceKnodeId} not found in the in-memory store. Retrieving it from the persistent store...`);
|
|
1407
|
+
await depersistFlowInstance({ flowInstanceId: payload.flowInstanceKnodeId });
|
|
1408
|
+
}
|
|
1409
|
+
const flowInstanceContainer = flowInstancesContainer[payload.flowInstanceKnodeId];
|
|
1410
|
+
if (!flowInstanceContainer) {
|
|
1411
|
+
const errorMsg = `Flow instance with ID ${payload.flowInstanceKnodeId} not found in the in-memory store after trying to depersist it.`;
|
|
1412
|
+
console.error(`${appNameText2}:[joinFlowInstance] ${errorMsg}`);
|
|
1413
|
+
return Promise.reject(new Error(errorMsg));
|
|
1414
|
+
}
|
|
1415
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1416
|
+
const flowEngine = flowInstanceContainer.flowInstanceEngine;
|
|
1417
|
+
const flow = await flowEngine.asyncGetFlow();
|
|
1418
|
+
let place;
|
|
1419
|
+
if (payload.placeId) {
|
|
1420
|
+
place = (0, import_i_core3.findPlaceByIdInFlow)(flow, payload.placeId);
|
|
1421
|
+
(0, import_i_verify2.assert)(place, `Flow place with ID ${payload.placeId} not found in flow with ID ${flow.id}`);
|
|
1422
|
+
} else {
|
|
1423
|
+
const startEvent = (0, import_i_core3.getStartEventInFlow)(flow);
|
|
1424
|
+
(0, import_i_verify2.assert)(startEvent, `Flow start event not found in flow with ID ${flow.id}`);
|
|
1425
|
+
place = startEvent;
|
|
1426
|
+
}
|
|
1427
|
+
const token = flowEngine.createTokenInPlace(place, payload.whoAmI, payload.agentType, void 0, payload.flowInstanceKnodeId);
|
|
1428
|
+
if (DEBUG) console.log(`${appNameText2}:[joinFlowInstance] created token: ${token.id} in place: ${place.id}`);
|
|
1429
|
+
const tokenKNode = (0, import_i_core5.tokenPack)(token);
|
|
1430
|
+
console.log(`${appNameText2}:[joinFlowInstance] tokenKNode: ${JSON.stringify(tokenKNode, null, 4)}`);
|
|
1431
|
+
const createResult = await flowStoreProtected.kNodeService.create(tokenKNode);
|
|
1432
|
+
if (!createResult || createResult.length !== 1) {
|
|
1433
|
+
throw new Error("Token not created");
|
|
1434
|
+
}
|
|
1435
|
+
const kNodeFromServer = createResult[0];
|
|
1436
|
+
if (DEBUG) console.log(`${appNameText2}:[joinFlowInstance] token persisted with flow knode ID: ${kNodeFromServer._id}: ${JSON.stringify(kNodeFromServer, null, 4)}`);
|
|
1437
|
+
token.id = kNodeFromServer._id;
|
|
1438
|
+
flowInstance.tokens.push(token);
|
|
1439
|
+
const flowInstanceKnodeId = get().persistFlowInstance({ flowInstanceId: flowInstance.id });
|
|
1440
|
+
if (DEBUG) console.log(`${appNameText2}:[joinFlowInstance] flow instance persisted with flow knode ID: ${flowInstanceKnodeId}: ${JSON.stringify(flowInstance, null, 4)}`);
|
|
1441
|
+
return kNodeFromServer._id;
|
|
1442
|
+
},
|
|
1443
|
+
getAgentTokenForFlowInstance: async (payload) => {
|
|
1444
|
+
const { flowInstanceContexts, flowInstancesContainer, depersistFlowInstance } = get();
|
|
1445
|
+
if (DEBUG) console.log(`${appNameText2}:[getAgentTokenForFlowInstance] starting...`);
|
|
1446
|
+
if (DEBUG) console.log(`${appNameText2}:[getAgentTokenForFlowInstance] flowInstanceKnodeId: ${payload.flowInstanceId}, whoAmI: ${payload.whoAmI}`);
|
|
1447
|
+
if (!(payload.flowInstanceId in flowInstancesContainer)) {
|
|
1448
|
+
console.info(`${appNameText2}:[getAgentTokenForFlowInstance] flow instance with ID ${payload.flowInstanceId} not found in the in-memory store. Retrieving it from the persistent store...`);
|
|
1449
|
+
await depersistFlowInstance({ flowInstanceId: payload.flowInstanceId });
|
|
1450
|
+
}
|
|
1451
|
+
const flowInstanceContainer = flowInstancesContainer[payload.flowInstanceId];
|
|
1452
|
+
if (!flowInstanceContainer) {
|
|
1453
|
+
const errorMsg = `Flow instance with ID ${payload.flowInstanceId} not found in the in-memory store after trying to depersist it.`;
|
|
1454
|
+
console.error(`${appNameText2}:[getAgentTokenForFlowInstance] ${errorMsg}`);
|
|
1455
|
+
return Promise.reject(new Error(errorMsg));
|
|
1456
|
+
}
|
|
1457
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1458
|
+
const token = flowInstance.tokens.find((token2) => token2.whoAmI === payload.whoAmI);
|
|
1459
|
+
if (token) {
|
|
1460
|
+
if (DEBUG) console.log(`${appNameText2}:[getAgentTokenForFlowInstance] token found in flow instance with ID ${flowInstance.id}: ${JSON.stringify(token, null, 4)}`);
|
|
1461
|
+
return token;
|
|
1462
|
+
} else {
|
|
1463
|
+
if (DEBUG) console.log(`${appNameText2}:[getAgentTokenForFlowInstance] token not found in flow instance with ID ${flowInstance.id}`);
|
|
1464
|
+
return void 0;
|
|
1465
|
+
}
|
|
1466
|
+
},
|
|
1467
|
+
loadToken: async (tokenKnodeId) => {
|
|
1468
|
+
if (DEBUG) console.log(`${appNameText2}:[loadToken] loading token with ID: ${tokenKnodeId}`);
|
|
1469
|
+
const tokenKNode = await flowStoreProtected.kNodeService.getById(tokenKnodeId);
|
|
1470
|
+
if (!tokenKNode) {
|
|
1471
|
+
throw new Error("Token not found");
|
|
1472
|
+
}
|
|
1473
|
+
if (DEBUG) console.log(`${appNameText2}:[loadToken] token retrieved from store with ID: ${tokenKNode._id}: ${JSON.stringify(tokenKNode, null, 4)}`);
|
|
1474
|
+
const token = (0, import_i_core5.tokenUnpack)(tokenKNode);
|
|
1475
|
+
if (DEBUG) console.log(`${appNameText2}:[loadToken] token unpacked from kNode with ID: ${tokenKNode._id}: ${JSON.stringify(token, null, 4)}`);
|
|
1476
|
+
return token;
|
|
1477
|
+
},
|
|
1478
|
+
loadTokens: async (payload) => {
|
|
1479
|
+
const { flowInstanceContexts, flowInstancesContainer, depersistFlowInstance } = get();
|
|
1480
|
+
if (!(payload.flowInstanceKnodeId in flowInstancesContainer)) {
|
|
1481
|
+
console.info(`${appNameText2}:[joinFlowInstance] flow instance with ID ${payload.flowInstanceKnodeId} not found in the in-memory store. Retrieving it from the persistent store...`);
|
|
1482
|
+
await depersistFlowInstance({ flowInstanceId: payload.flowInstanceKnodeId });
|
|
1483
|
+
}
|
|
1484
|
+
const flowInstanceContainer = flowInstancesContainer[payload.flowInstanceKnodeId];
|
|
1485
|
+
if (!flowInstanceContainer) {
|
|
1486
|
+
const errorMsg = `Flow instance with ID ${payload.flowInstanceKnodeId} not found in the in-memory store after trying to depersist it.`;
|
|
1487
|
+
console.error(`${appNameText2}:[joinFlowInstance] ${errorMsg}`);
|
|
1488
|
+
return Promise.reject(new Error(errorMsg));
|
|
1489
|
+
}
|
|
1490
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1491
|
+
const tokens = flowInstance.tokens;
|
|
1492
|
+
const tokensReduced = tokens.map((token) => {
|
|
1493
|
+
const tokenReduced = {
|
|
1494
|
+
id: token.id,
|
|
1495
|
+
whoAmI: token.whoAmI,
|
|
1496
|
+
agentType: token.agentType,
|
|
1497
|
+
placeId: token.placeId,
|
|
1498
|
+
dataEntryReferencesNo: token.dataEntryReferences.length
|
|
1499
|
+
};
|
|
1500
|
+
return tokenReduced;
|
|
1501
|
+
});
|
|
1502
|
+
if (DEBUG) console.log(`${appNameText2}:[loadTokens] tokens loaded from flow instance with ID ${flowInstance.id}: ${JSON.stringify(tokensReduced, null, 4)}`);
|
|
1503
|
+
return tokens;
|
|
1504
|
+
},
|
|
1505
|
+
moveToken: async (payload) => {
|
|
1506
|
+
const tokenId = payload.tokenId;
|
|
1507
|
+
const tokenTemp = await get().loadToken(tokenId);
|
|
1508
|
+
const flowInstanceId = tokenTemp.flowInstanceId;
|
|
1509
|
+
const { flowInstanceContexts, flowInstancesContainer, depersistFlowInstance } = get();
|
|
1510
|
+
if (!(flowInstanceId in flowInstancesContainer)) {
|
|
1511
|
+
console.info(`${appNameText2}:[joinFlowInstance] flow instance with ID ${flowInstanceId} not found in the in-memory store. Retrieving it from the persistent store...`);
|
|
1512
|
+
await depersistFlowInstance({ flowInstanceId });
|
|
1513
|
+
}
|
|
1514
|
+
const flowInstanceContainer = flowInstancesContainer[flowInstanceId];
|
|
1515
|
+
if (!flowInstanceContainer) {
|
|
1516
|
+
const errorMsg = `Flow instance with ID ${flowInstanceId} not found in the in-memory store after trying to depersist it.`;
|
|
1517
|
+
console.error(`${appNameText2}:[joinFlowInstance] ${errorMsg}`);
|
|
1518
|
+
return Promise.reject(new Error(errorMsg));
|
|
1519
|
+
}
|
|
1520
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1521
|
+
const flowEngine = flowInstanceContainer.flowInstanceEngine;
|
|
1522
|
+
const flow = await flowEngine.asyncGetFlow();
|
|
1523
|
+
const tokens = flowInstance.tokens;
|
|
1524
|
+
const token = tokens.find((token2) => token2.id === payload.tokenId);
|
|
1525
|
+
if (!token) {
|
|
1526
|
+
const errorMsg = `Token with ID ${payload.tokenId} not found in flow instance with ID ${flowInstance.id}.`;
|
|
1527
|
+
console.error(`${appNameText2}:[moveToken] ${errorMsg}`);
|
|
1528
|
+
return Promise.reject(new Error(errorMsg));
|
|
1529
|
+
}
|
|
1530
|
+
const newPlaceId = payload.placeId;
|
|
1531
|
+
const place = (0, import_i_core3.findPlaceByIdInFlow)(flow, newPlaceId);
|
|
1532
|
+
if (!place) {
|
|
1533
|
+
const errorMsg = `Place with ID ${newPlaceId} not found in flow with ID ${flow.id}.`;
|
|
1534
|
+
console.error(`${appNameText2}:[moveToken] ${errorMsg}`);
|
|
1535
|
+
return Promise.reject(new Error(errorMsg));
|
|
1536
|
+
}
|
|
1537
|
+
token.placeId = newPlaceId;
|
|
1538
|
+
const tokenKNode = (0, import_i_core5.tokenPack)(token);
|
|
1539
|
+
const updateRequest = {
|
|
1540
|
+
type: import_i_core4.KNODE_API_TYPE.UPDATE_COLABO_API,
|
|
1541
|
+
paramsDetailed: {
|
|
1542
|
+
id: {
|
|
1543
|
+
path: "_id",
|
|
1544
|
+
value: token.id
|
|
1545
|
+
}
|
|
1546
|
+
},
|
|
1547
|
+
data: tokenKNode
|
|
1548
|
+
};
|
|
1549
|
+
const kNodeFromServer = await flowStoreProtected.kNodeService.updateSingleWithColaboApi(updateRequest);
|
|
1550
|
+
if (!kNodeFromServer) {
|
|
1551
|
+
throw new Error("Token not updated");
|
|
1552
|
+
}
|
|
1553
|
+
if (DEBUG) console.log(`${appNameText2}:[moveToken] token moved in flow instance with ID ${flowInstance.id} to placeId: ${newPlaceId}`);
|
|
1554
|
+
return token;
|
|
1555
|
+
},
|
|
1556
|
+
moveAllTokens: async (payload) => {
|
|
1557
|
+
const { flowInstanceContexts, flowInstancesContainer, depersistFlowInstance } = get();
|
|
1558
|
+
if (DEBUG) console.log(`${appNameText2}:[moveAllTokens] starting...`);
|
|
1559
|
+
if (DEBUG) console.log(`${appNameText2}:[moveAllTokens] flowInstanceId: ${payload.flowInstanceId}, placeId: ${payload.placeId}`);
|
|
1560
|
+
if (!(payload.flowInstanceId in flowInstancesContainer)) {
|
|
1561
|
+
console.info(`${appNameText2}:[moveAllTokens] flow instance with ID ${payload.flowInstanceId} not found in the in-memory store. Retrieving it from the persistent store...`);
|
|
1562
|
+
await depersistFlowInstance({ flowInstanceId: payload.flowInstanceId });
|
|
1563
|
+
}
|
|
1564
|
+
const flowInstanceContainer = flowInstancesContainer[payload.flowInstanceId];
|
|
1565
|
+
if (!flowInstanceContainer) {
|
|
1566
|
+
const errorMsg = `Flow instance with ID ${payload.flowInstanceId} not found in the in-memory store after trying to depersist it.`;
|
|
1567
|
+
console.error(`${appNameText2}:[moveAllTokens] ${errorMsg}`);
|
|
1568
|
+
return Promise.reject(new Error(errorMsg));
|
|
1569
|
+
}
|
|
1570
|
+
const flowInstance = flowInstanceContainer.flowInstance;
|
|
1571
|
+
const flowEngine = flowInstanceContainer.flowInstanceEngine;
|
|
1572
|
+
const flow = await flowEngine.asyncGetFlow();
|
|
1573
|
+
const tokens = flowInstance.tokens;
|
|
1574
|
+
for (const token of tokens) {
|
|
1575
|
+
const newPlaceId = payload.placeId;
|
|
1576
|
+
const place = (0, import_i_core3.findPlaceByIdInFlow)(flow, newPlaceId);
|
|
1577
|
+
if (!place) {
|
|
1578
|
+
const errorMsg = `Place with ID ${newPlaceId} not found in flow with ID ${flow.id}.`;
|
|
1579
|
+
console.error(`${appNameText2}:[moveAllTokens] ${errorMsg}`);
|
|
1580
|
+
return Promise.reject(new Error(errorMsg));
|
|
1581
|
+
}
|
|
1582
|
+
token.placeId = newPlaceId;
|
|
1583
|
+
const tokenKNode = (0, import_i_core5.tokenPack)(token);
|
|
1584
|
+
const updateRequest = {
|
|
1585
|
+
type: import_i_core4.KNODE_API_TYPE.UPDATE_COLABO_API,
|
|
1586
|
+
paramsDetailed: {
|
|
1587
|
+
id: {
|
|
1588
|
+
path: "_id",
|
|
1589
|
+
value: token.id
|
|
1590
|
+
}
|
|
1591
|
+
},
|
|
1592
|
+
data: tokenKNode
|
|
1593
|
+
};
|
|
1594
|
+
const kNodeFromServer = await flowStoreProtected.kNodeService.updateSingleWithColaboApi(updateRequest);
|
|
1595
|
+
if (!kNodeFromServer) {
|
|
1596
|
+
throw new Error("Token not updated");
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
return tokens;
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
return storeObj;
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
const storeState = _store.getState();
|
|
1606
|
+
return storeState;
|
|
1607
|
+
};
|
|
1608
|
+
|
|
1609
|
+
// lib/flowchestrator/store/flow.store.ts
|
|
1610
|
+
var import_chalk5 = __toESM(require("chalk"), 1);
|
|
1611
|
+
var import_i_core_services = require("@colabo-knalledge/i-core-services");
|
|
1612
|
+
var import_i_core6 = require("@colabo-knalledge/i-core");
|
|
1613
|
+
var import_i_core7 = require("@colabo-flow/i-core");
|
|
1614
|
+
var import_i_store2 = require("@colabo-utils/i-store");
|
|
1615
|
+
var import_i_verify3 = require("@colabo-utils/i-verify");
|
|
1616
|
+
var DEBUG2 = true;
|
|
1617
|
+
var DEBUG_VERBOSE2 = false;
|
|
1618
|
+
var appNameText3 = "ColaboFlow.Go.Store";
|
|
1619
|
+
var _store2;
|
|
1620
|
+
var defaultKNodeServiceSingleton;
|
|
1621
|
+
function getDefaultKNodeService() {
|
|
1622
|
+
if (!defaultKNodeServiceSingleton) {
|
|
1623
|
+
defaultKNodeServiceSingleton = new import_i_core_services.ColaboKnAllEdgeNodeServiceExtended(
|
|
1624
|
+
null,
|
|
1625
|
+
null
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1628
|
+
return defaultKNodeServiceSingleton;
|
|
1629
|
+
}
|
|
1630
|
+
var useFlowStore = (options) => {
|
|
1631
|
+
const { appNameText: _appNameText, kNodeService: injectedKNodeService } = options;
|
|
1632
|
+
appNameText3 = `${_appNameText}:[${import_chalk5.default.bold.yellow("STORE")}]`;
|
|
1633
|
+
if (!_store2) {
|
|
1634
|
+
if (!options.kNodeService && !options.useDefaultKNodeService) {
|
|
1635
|
+
throw new Error(
|
|
1636
|
+
`${appNameText3} useFlowStore: Missing kNodeService and useDefaultKNodeService not set`
|
|
1637
|
+
);
|
|
1638
|
+
}
|
|
1639
|
+
const kNodeService = options.useDefaultKNodeService ? getDefaultKNodeService() : options.kNodeService;
|
|
1640
|
+
(0, import_i_verify3.assert)(kNodeService, "[] KNode service is not initialized");
|
|
1641
|
+
const _getDomainStore = () => {
|
|
1642
|
+
(0, import_i_verify3.assert)(_store2, `${appNameText3} Flow Store is not initialized`);
|
|
1643
|
+
return _store2?.getState();
|
|
1644
|
+
};
|
|
1645
|
+
const flowStoreProtected = {
|
|
1646
|
+
appNameText: _appNameText,
|
|
1647
|
+
kNodeService,
|
|
1648
|
+
getDomainStore: _getDomainStore
|
|
1649
|
+
};
|
|
1650
|
+
_store2 = (0, import_i_store2.createBaseStore)((set, _get) => {
|
|
1651
|
+
const get = () => {
|
|
1652
|
+
return _get();
|
|
1653
|
+
};
|
|
1654
|
+
const storeObj = {
|
|
1655
|
+
// state
|
|
1656
|
+
// ========================
|
|
1657
|
+
flows: {},
|
|
1658
|
+
// modules
|
|
1659
|
+
// ========================
|
|
1660
|
+
modules: {
|
|
1661
|
+
flowchestrator: useFlowFlowchestratorStore(flowStoreProtected)
|
|
1662
|
+
},
|
|
1663
|
+
// mutations
|
|
1664
|
+
// ========================
|
|
1665
|
+
getFlow: (flowId) => {
|
|
1666
|
+
if (DEBUG2) console.log(`${appNameText3}:[getFlow] Getting flow: ${flowId}`);
|
|
1667
|
+
const { flows } = get();
|
|
1668
|
+
if (DEBUG2) console.log(`${appNameText3}:[getFlow] store.flows: ${Object.keys(flows)}`);
|
|
1669
|
+
const flow = flows[flowId];
|
|
1670
|
+
if (DEBUG2) console.log(`${appNameText3}:[getFlow] Flow found: ${flow ? flow.id : "undefined"}`);
|
|
1671
|
+
return flow;
|
|
1672
|
+
},
|
|
1673
|
+
addFlow: (flow) => {
|
|
1674
|
+
if (DEBUG2) console.log(`${appNameText3}:[addFlow] Adding flow: ${flow.id}`);
|
|
1675
|
+
set((state) => ({
|
|
1676
|
+
flows: {
|
|
1677
|
+
...state.flows,
|
|
1678
|
+
[flow.id]: flow
|
|
1679
|
+
}
|
|
1680
|
+
}));
|
|
1681
|
+
const { flows } = get();
|
|
1682
|
+
if (DEBUG2) console.log(`${appNameText3}:[addFlow] store.flows: ${Object.keys(flows)}`);
|
|
1683
|
+
if (DEBUG2) console.log(`${appNameText3}:[addFlow] Flow added: ${flow.id}`);
|
|
1684
|
+
},
|
|
1685
|
+
// actions
|
|
1686
|
+
// ========================
|
|
1687
|
+
loadFlow: async (flowId) => {
|
|
1688
|
+
if (DEBUG2) console.log(`${appNameText3}:[loadFlow] Loading flow: ${flowId}`);
|
|
1689
|
+
const flowKNode = await kNodeService.getById(flowId);
|
|
1690
|
+
if (DEBUG_VERBOSE2) console.log(`${appNameText3} flowKNode: ${JSON.stringify(flowKNode, null, 4)}`);
|
|
1691
|
+
const flow = (0, import_i_core7.flowUnpack)(flowKNode);
|
|
1692
|
+
if (DEBUG_VERBOSE2) console.log(`${appNameText3} flow: ${JSON.stringify(flow, null, 4)}`);
|
|
1693
|
+
if (DEBUG2) console.log(`${appNameText3}:[loadFlow] Flow loaded: ${flow.id}`);
|
|
1694
|
+
get().addFlow(flow);
|
|
1695
|
+
return flow;
|
|
1696
|
+
},
|
|
1697
|
+
loadFlows: async () => {
|
|
1698
|
+
if (DEBUG2) console.log(`${appNameText3}:[loadFlows] Loading flows`);
|
|
1699
|
+
const request = {
|
|
1700
|
+
type: import_i_core6.KEDGE_API_TYPE.INDEX_COLABO_API,
|
|
1701
|
+
paramsDetailed: {
|
|
1702
|
+
type: {
|
|
1703
|
+
path: "type",
|
|
1704
|
+
value: import_i_core7.KFlowTypes.FLOW
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
const flowsKNode = await kNodeService.getVosWithColaboApi(request);
|
|
1709
|
+
const flows = flowsKNode.map((flowKNode) => {
|
|
1710
|
+
const flow = (0, import_i_core7.flowUnpack)(flowKNode);
|
|
1711
|
+
return flow;
|
|
1712
|
+
});
|
|
1713
|
+
const flowNames = flows.map((flow) => flow.name ?? flow.id);
|
|
1714
|
+
if (DEBUG2) console.log(`${appNameText3}:[loadFlows] Flows loaded: ${JSON.stringify(flowNames, null, 4)}`);
|
|
1715
|
+
flows.forEach(
|
|
1716
|
+
(flow) => {
|
|
1717
|
+
get().addFlow(flow);
|
|
1718
|
+
}
|
|
1719
|
+
);
|
|
1720
|
+
if (DEBUG2) console.log(`${appNameText3}:[loadFlows] Flows added to the in-memory store`);
|
|
1721
|
+
return flows;
|
|
1722
|
+
}
|
|
1723
|
+
};
|
|
1724
|
+
return storeObj;
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
const storeState = _store2.getState();
|
|
1728
|
+
return storeState;
|
|
1729
|
+
};
|
|
1730
|
+
|
|
1731
|
+
// lib/flowchestrator/store/index.ts
|
|
1732
|
+
var import_i_store3 = require("@colabo-utils/i-store");
|
|
1733
|
+
var import_i_core_services2 = require("@colabo-knalledge/i-core-services");
|
|
1734
|
+
var _store3;
|
|
1735
|
+
var defaultKNodeServiceSingleton2;
|
|
1736
|
+
function getDefaultKNodeService2() {
|
|
1737
|
+
if (!defaultKNodeServiceSingleton2) {
|
|
1738
|
+
defaultKNodeServiceSingleton2 = new import_i_core_services2.ColaboKnAllEdgeNodeServiceExtended(
|
|
1739
|
+
null,
|
|
1740
|
+
null
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
return defaultKNodeServiceSingleton2;
|
|
1744
|
+
}
|
|
1745
|
+
var useGlobalStore = (options) => {
|
|
1746
|
+
if (!_store3) {
|
|
1747
|
+
const useFlowStoreOptions = {
|
|
1748
|
+
appNameText: options.appNameText,
|
|
1749
|
+
kNodeService: options.kNodeService ? options.kNodeService : getDefaultKNodeService2(),
|
|
1750
|
+
useDefaultKNodeService: options.useDefaultKNodeService
|
|
1751
|
+
};
|
|
1752
|
+
_store3 = (0, import_i_store3.createBaseStore)((set, _get) => {
|
|
1753
|
+
const get = () => {
|
|
1754
|
+
return _get();
|
|
1755
|
+
};
|
|
1756
|
+
const storeObj = {
|
|
1757
|
+
// state
|
|
1758
|
+
// ========================
|
|
1759
|
+
appVersion: "1.0.0",
|
|
1760
|
+
// modules
|
|
1761
|
+
// ========================
|
|
1762
|
+
modules: {
|
|
1763
|
+
flow: useFlowStore(useFlowStoreOptions)
|
|
1764
|
+
// documents: useDocumentStore(),
|
|
1765
|
+
}
|
|
1766
|
+
// mutations
|
|
1767
|
+
// ========================
|
|
1768
|
+
// actions
|
|
1769
|
+
// ========================
|
|
1770
|
+
};
|
|
1771
|
+
return storeObj;
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
const storeState = _store3.getState();
|
|
1775
|
+
return storeState;
|
|
1776
|
+
};
|
|
1777
|
+
|
|
1778
|
+
// index.ts
|
|
1779
|
+
var __getPackagePath = () => {
|
|
1780
|
+
return (0, import_i_register.getPackagePath_ToBeInvited)();
|
|
1781
|
+
};
|
|
1782
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1783
|
+
0 && (module.exports = {
|
|
1784
|
+
EColaboFlowGoMsgType,
|
|
1785
|
+
EProgrammingLanguageSupported,
|
|
1786
|
+
ETaskExecute_Progress_Status,
|
|
1787
|
+
HEARTBEAT_TIME,
|
|
1788
|
+
__getPackagePath,
|
|
1789
|
+
clientClose,
|
|
1790
|
+
clientExecuteTask,
|
|
1791
|
+
clientRun,
|
|
1792
|
+
hostRegisterTask,
|
|
1793
|
+
hostRegisterTaskExecutor,
|
|
1794
|
+
hostRun,
|
|
1795
|
+
hostSetTitles,
|
|
1796
|
+
orchestratorRun,
|
|
1797
|
+
useFlowFlowchestratorStore,
|
|
1798
|
+
useGlobalStore
|
|
1799
|
+
});
|
|
1800
|
+
//# sourceMappingURL=index.js.map
|