iii-sdk 0.0.2-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,642 @@
1
+ //#region rolldown:runtime
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ const require_otel_worker_gauges = require('./otel-worker-gauges-bAp_yKcU.cjs');
29
+ let __opentelemetry_api = require("@opentelemetry/api");
30
+ let module$1 = require("module");
31
+ let os = require("os");
32
+ os = __toESM(os);
33
+ let ws = require("ws");
34
+ let node_async_hooks = require("node:async_hooks");
35
+ let __opentelemetry_api_logs = require("@opentelemetry/api-logs");
36
+
37
+ //#region src/iii-types.ts
38
+ let MessageType = /* @__PURE__ */ function(MessageType$1) {
39
+ MessageType$1["RegisterFunction"] = "registerfunction";
40
+ MessageType$1["UnregisterFunction"] = "unregisterfunction";
41
+ MessageType$1["RegisterService"] = "registerservice";
42
+ MessageType$1["InvokeFunction"] = "invokefunction";
43
+ MessageType$1["InvocationResult"] = "invocationresult";
44
+ MessageType$1["RegisterTriggerType"] = "registertriggertype";
45
+ MessageType$1["RegisterTrigger"] = "registertrigger";
46
+ MessageType$1["UnregisterTrigger"] = "unregistertrigger";
47
+ MessageType$1["UnregisterTriggerType"] = "unregistertriggertype";
48
+ MessageType$1["TriggerRegistrationResult"] = "triggerregistrationresult";
49
+ MessageType$1["WorkerRegistered"] = "workerregistered";
50
+ return MessageType$1;
51
+ }({});
52
+
53
+ //#endregion
54
+ //#region src/logger.ts
55
+ var Logger = class {
56
+ get otelLogger() {
57
+ if (!this._otelLogger) this._otelLogger = require_otel_worker_gauges.getLogger();
58
+ return this._otelLogger;
59
+ }
60
+ constructor(invoker, traceId, serviceName, spanId) {
61
+ this.invoker = invoker;
62
+ this.traceId = traceId;
63
+ this.serviceName = serviceName;
64
+ this.spanId = spanId;
65
+ this._otelLogger = null;
66
+ }
67
+ emit(message, severity, data) {
68
+ const attributes = {};
69
+ if (this.traceId) attributes.trace_id = this.traceId;
70
+ if (this.spanId) attributes.span_id = this.spanId;
71
+ if (this.serviceName) attributes["service.name"] = this.serviceName;
72
+ if (data !== void 0) attributes["log.data"] = typeof data === "string" ? data : require_otel_worker_gauges.safeStringify(data);
73
+ if (this.otelLogger) this.otelLogger.emit({
74
+ severityNumber: severity,
75
+ body: message,
76
+ attributes: Object.keys(attributes).length > 0 ? attributes : void 0
77
+ });
78
+ else switch (severity) {
79
+ case __opentelemetry_api_logs.SeverityNumber.DEBUG:
80
+ console.debug(message, data);
81
+ break;
82
+ case __opentelemetry_api_logs.SeverityNumber.INFO:
83
+ console.info(message, data);
84
+ break;
85
+ case __opentelemetry_api_logs.SeverityNumber.WARN:
86
+ console.warn(message, data);
87
+ break;
88
+ case __opentelemetry_api_logs.SeverityNumber.ERROR:
89
+ console.error(message, data);
90
+ break;
91
+ default: console.log(message, data);
92
+ }
93
+ }
94
+ info(message, data) {
95
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.INFO, data);
96
+ }
97
+ warn(message, data) {
98
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.WARN, data);
99
+ }
100
+ error(message, data) {
101
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.ERROR, data);
102
+ }
103
+ debug(message, data) {
104
+ this.emit(message, __opentelemetry_api_logs.SeverityNumber.DEBUG, data);
105
+ }
106
+ };
107
+
108
+ //#endregion
109
+ //#region src/context.ts
110
+ const globalStorage = new node_async_hooks.AsyncLocalStorage();
111
+ const withContext = async (fn, ctx) => {
112
+ const currentOtelContext = __opentelemetry_api.context.active();
113
+ return globalStorage.run(ctx, async () => {
114
+ return __opentelemetry_api.context.with(currentOtelContext, async () => await fn(ctx));
115
+ });
116
+ };
117
+ const getContext = () => {
118
+ const store = globalStorage.getStore();
119
+ if (store) return store;
120
+ return { logger: new Logger() };
121
+ };
122
+
123
+ //#endregion
124
+ //#region src/iii.ts
125
+ const { version: SDK_VERSION } = (0, module$1.createRequire)(require("url").pathToFileURL(__filename).href)("../package.json");
126
+ function getOsInfo() {
127
+ return `${os.platform()} ${os.release()} (${os.arch()})`;
128
+ }
129
+ function getDefaultWorkerName() {
130
+ return `${os.hostname()}:${process.pid}`;
131
+ }
132
+ var Sdk = class {
133
+ constructor(address, options) {
134
+ this.address = address;
135
+ this.functions = /* @__PURE__ */ new Map();
136
+ this.services = /* @__PURE__ */ new Map();
137
+ this.invocations = /* @__PURE__ */ new Map();
138
+ this.triggers = /* @__PURE__ */ new Map();
139
+ this.triggerTypes = /* @__PURE__ */ new Map();
140
+ this.functionsAvailableCallbacks = /* @__PURE__ */ new Set();
141
+ this.logCallbacks = /* @__PURE__ */ new Map();
142
+ this.messagesToSend = [];
143
+ this.reconnectAttempt = 0;
144
+ this.connectionState = "disconnected";
145
+ this.stateCallbacks = /* @__PURE__ */ new Set();
146
+ this.isShuttingDown = false;
147
+ this.registerTriggerType = (triggerType, handler) => {
148
+ this.sendMessage(MessageType.RegisterTriggerType, triggerType, true);
149
+ this.triggerTypes.set(triggerType.id, {
150
+ message: {
151
+ ...triggerType,
152
+ type: MessageType.RegisterTriggerType
153
+ },
154
+ handler
155
+ });
156
+ };
157
+ this.on = (event, callback) => {
158
+ this.ws?.on(event, callback);
159
+ };
160
+ this.unregisterTriggerType = (triggerType) => {
161
+ this.sendMessage(MessageType.UnregisterTriggerType, triggerType, true);
162
+ this.triggerTypes.delete(triggerType.id);
163
+ };
164
+ this.registerTrigger = (trigger) => {
165
+ const id = crypto.randomUUID();
166
+ this.sendMessage(MessageType.RegisterTrigger, {
167
+ ...trigger,
168
+ id
169
+ }, true);
170
+ this.triggers.set(id, {
171
+ ...trigger,
172
+ id,
173
+ type: MessageType.RegisterTrigger
174
+ });
175
+ return { unregister: () => {
176
+ this.sendMessage(MessageType.UnregisterTrigger, {
177
+ id,
178
+ trigger_type: MessageType.UnregisterTrigger
179
+ });
180
+ this.triggers.delete(id);
181
+ } };
182
+ };
183
+ this.registerFunction = (message, handler) => {
184
+ if (!message.id || message.id.trim() === "") throw new Error("id is required");
185
+ this.sendMessage(MessageType.RegisterFunction, message, true);
186
+ this.functions.set(message.id, {
187
+ message: {
188
+ ...message,
189
+ type: MessageType.RegisterFunction
190
+ },
191
+ handler: async (input, traceparent, baggage) => {
192
+ if (require_otel_worker_gauges.getTracer()) {
193
+ const parentContext = require_otel_worker_gauges.extractContext(traceparent, baggage);
194
+ return __opentelemetry_api.context.with(parentContext, () => require_otel_worker_gauges.withSpan(`invoke ${message.id}`, { kind: __opentelemetry_api.SpanKind.SERVER }, async (span) => {
195
+ const traceId = require_otel_worker_gauges.currentTraceId() ?? crypto.randomUUID();
196
+ const spanId = require_otel_worker_gauges.currentSpanId();
197
+ return withContext(async () => await handler(input), {
198
+ logger: new Logger(void 0, traceId, message.id, spanId),
199
+ trace: span
200
+ });
201
+ }));
202
+ }
203
+ return withContext(async () => await handler(input), { logger: new Logger(void 0, crypto.randomUUID(), message.id) });
204
+ }
205
+ });
206
+ return {
207
+ id: message.id,
208
+ unregister: () => {
209
+ this.sendMessage(MessageType.UnregisterFunction, { id: message.id }, true);
210
+ this.functions.delete(message.id);
211
+ }
212
+ };
213
+ };
214
+ this.registerService = (message) => {
215
+ this.sendMessage(MessageType.RegisterService, message, true);
216
+ this.services.set(message.id, {
217
+ ...message,
218
+ type: MessageType.RegisterService
219
+ });
220
+ };
221
+ this.call = async (function_id, data, timeoutMs) => {
222
+ const invocation_id = crypto.randomUUID();
223
+ const traceparent = require_otel_worker_gauges.injectTraceparent();
224
+ const baggage = require_otel_worker_gauges.injectBaggage();
225
+ const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
226
+ return new Promise((resolve, reject) => {
227
+ const timeout = setTimeout(() => {
228
+ if (this.invocations.get(invocation_id)) {
229
+ this.invocations.delete(invocation_id);
230
+ reject(/* @__PURE__ */ new Error(`Invocation timeout after ${effectiveTimeout}ms: ${function_id}`));
231
+ }
232
+ }, effectiveTimeout);
233
+ this.invocations.set(invocation_id, {
234
+ resolve: (result) => {
235
+ clearTimeout(timeout);
236
+ resolve(result);
237
+ },
238
+ reject: (error) => {
239
+ clearTimeout(timeout);
240
+ reject(error);
241
+ },
242
+ timeout
243
+ });
244
+ this.sendMessage(MessageType.InvokeFunction, {
245
+ invocation_id,
246
+ function_id,
247
+ data,
248
+ traceparent,
249
+ baggage
250
+ });
251
+ });
252
+ };
253
+ this.callVoid = (function_id, data) => {
254
+ const traceparent = require_otel_worker_gauges.injectTraceparent();
255
+ const baggage = require_otel_worker_gauges.injectBaggage();
256
+ this.sendMessage(MessageType.InvokeFunction, {
257
+ function_id,
258
+ data,
259
+ traceparent,
260
+ baggage
261
+ });
262
+ };
263
+ this.listFunctions = async () => {
264
+ return (await this.call(require_otel_worker_gauges.EngineFunctions.LIST_FUNCTIONS, {})).functions;
265
+ };
266
+ this.listWorkers = async () => {
267
+ return (await this.call(require_otel_worker_gauges.EngineFunctions.LIST_WORKERS, {})).workers;
268
+ };
269
+ this.createStream = (streamName, stream) => {
270
+ this.registerFunction({ id: `stream.get(${streamName})` }, stream.get.bind(stream));
271
+ this.registerFunction({ id: `stream.set(${streamName})` }, stream.set.bind(stream));
272
+ this.registerFunction({ id: `stream.delete(${streamName})` }, stream.delete.bind(stream));
273
+ this.registerFunction({ id: `stream.list(${streamName})` }, stream.list.bind(stream));
274
+ this.registerFunction({ id: `stream.list_groups(${streamName})` }, stream.listGroups.bind(stream));
275
+ };
276
+ this.onFunctionsAvailable = (callback) => {
277
+ this.functionsAvailableCallbacks.add(callback);
278
+ if (!this.functionsAvailableTrigger) {
279
+ if (!this.functionsAvailableFunctionPath) this.functionsAvailableFunctionPath = `engine.on_functions_available.${crypto.randomUUID()}`;
280
+ const function_id = this.functionsAvailableFunctionPath;
281
+ if (!this.functions.has(function_id)) this.registerFunction({ id: function_id }, async ({ functions }) => {
282
+ this.functionsAvailableCallbacks.forEach((handler) => {
283
+ handler(functions);
284
+ });
285
+ return null;
286
+ });
287
+ this.functionsAvailableTrigger = this.registerTrigger({
288
+ trigger_type: require_otel_worker_gauges.EngineTriggers.FUNCTIONS_AVAILABLE,
289
+ function_id,
290
+ config: {}
291
+ });
292
+ }
293
+ return () => {
294
+ this.functionsAvailableCallbacks.delete(callback);
295
+ if (this.functionsAvailableCallbacks.size === 0 && this.functionsAvailableTrigger) {
296
+ this.functionsAvailableTrigger.unregister();
297
+ this.functionsAvailableTrigger = void 0;
298
+ }
299
+ };
300
+ };
301
+ this.onLog = (callback, config) => {
302
+ const effectiveConfig = config ?? { level: "all" };
303
+ this.logCallbacks.set(callback, effectiveConfig);
304
+ if (!this.logTrigger) {
305
+ if (!this.logFunctionPath) this.logFunctionPath = `engine.on_log.${crypto.randomUUID()}`;
306
+ const function_id = this.logFunctionPath;
307
+ if (!this.functions.has(function_id)) this.registerFunction({ id: function_id }, async (log) => {
308
+ this.logCallbacks.forEach((cfg, handler) => {
309
+ try {
310
+ const minSeverity = this.severityTextToNumber(cfg.level ?? "all");
311
+ if (cfg.level === "all" || log.severity_number >= minSeverity) handler(log);
312
+ } catch (error) {
313
+ this.logError("Log callback handler threw an exception", error);
314
+ }
315
+ });
316
+ return null;
317
+ });
318
+ this.logTrigger = this.registerTrigger({
319
+ trigger_type: require_otel_worker_gauges.EngineTriggers.LOG,
320
+ function_id,
321
+ config: {
322
+ level: "all",
323
+ severity_min: 0
324
+ }
325
+ });
326
+ }
327
+ return () => {
328
+ this.logCallbacks.delete(callback);
329
+ if (this.logCallbacks.size === 0 && this.logTrigger) {
330
+ this.logTrigger.unregister();
331
+ this.logTrigger = void 0;
332
+ }
333
+ };
334
+ };
335
+ this.getConnectionState = () => {
336
+ return this.connectionState;
337
+ };
338
+ this.onConnectionStateChange = (callback) => {
339
+ this.stateCallbacks.add(callback);
340
+ callback(this.connectionState);
341
+ return () => this.stateCallbacks.delete(callback);
342
+ };
343
+ this.shutdown = async () => {
344
+ this.isShuttingDown = true;
345
+ this.stopMetricsReporting();
346
+ await require_otel_worker_gauges.shutdownOtel();
347
+ this.clearReconnectTimeout();
348
+ for (const [_id, invocation] of this.invocations) {
349
+ if (invocation.timeout) clearTimeout(invocation.timeout);
350
+ invocation.reject(/* @__PURE__ */ new Error("iii is shutting down"));
351
+ }
352
+ this.invocations.clear();
353
+ if (this.ws) {
354
+ this.ws.removeAllListeners();
355
+ this.ws.close();
356
+ this.ws = void 0;
357
+ }
358
+ this.stateCallbacks.clear();
359
+ this.setConnectionState("disconnected");
360
+ };
361
+ this.workerName = options?.workerName ?? getDefaultWorkerName();
362
+ this.metricsReportingEnabled = options?.enableMetricsReporting ?? true;
363
+ this.invocationTimeoutMs = options?.invocationTimeoutMs ?? require_otel_worker_gauges.DEFAULT_INVOCATION_TIMEOUT_MS;
364
+ this.reconnectionConfig = {
365
+ ...require_otel_worker_gauges.DEFAULT_BRIDGE_RECONNECTION_CONFIG,
366
+ ...options?.reconnectionConfig
367
+ };
368
+ if (options?.otel) require_otel_worker_gauges.initOtel({
369
+ ...options.otel,
370
+ engineWsUrl: this.address
371
+ });
372
+ this.connect();
373
+ }
374
+ registerWorkerMetadata() {
375
+ this.callVoid(require_otel_worker_gauges.EngineFunctions.REGISTER_WORKER, {
376
+ runtime: "node",
377
+ version: SDK_VERSION,
378
+ name: this.workerName,
379
+ os: getOsInfo()
380
+ });
381
+ }
382
+ setConnectionState(state) {
383
+ if (this.connectionState !== state) {
384
+ this.connectionState = state;
385
+ for (const callback of this.stateCallbacks) try {
386
+ callback(state);
387
+ } catch (error) {
388
+ this.logError("Error in connection state callback", error);
389
+ }
390
+ }
391
+ }
392
+ connect() {
393
+ if (this.isShuttingDown) return;
394
+ this.setConnectionState("connecting");
395
+ this.ws = new ws.WebSocket(this.address);
396
+ this.ws.on("open", this.onSocketOpen.bind(this));
397
+ this.ws.on("close", this.onSocketClose.bind(this));
398
+ this.ws.on("error", this.onSocketError.bind(this));
399
+ }
400
+ clearReconnectTimeout() {
401
+ if (this.reconnectTimeout) {
402
+ clearTimeout(this.reconnectTimeout);
403
+ this.reconnectTimeout = void 0;
404
+ }
405
+ }
406
+ scheduleReconnect() {
407
+ if (this.isShuttingDown) return;
408
+ const { maxRetries, initialDelayMs, backoffMultiplier, maxDelayMs, jitterFactor } = this.reconnectionConfig;
409
+ if (maxRetries !== -1 && this.reconnectAttempt >= maxRetries) {
410
+ this.setConnectionState("failed");
411
+ this.logError(`Max reconnection retries (${maxRetries}) reached, giving up`);
412
+ return;
413
+ }
414
+ if (this.reconnectTimeout) return;
415
+ const exponentialDelay = initialDelayMs * backoffMultiplier ** this.reconnectAttempt;
416
+ const cappedDelay = Math.min(exponentialDelay, maxDelayMs);
417
+ const jitter = cappedDelay * jitterFactor * (2 * Math.random() - 1);
418
+ const delay = Math.floor(cappedDelay + jitter);
419
+ this.setConnectionState("reconnecting");
420
+ console.debug(`[iii] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempt + 1})...`);
421
+ this.reconnectTimeout = setTimeout(() => {
422
+ this.reconnectTimeout = void 0;
423
+ this.reconnectAttempt++;
424
+ this.connect();
425
+ }, delay);
426
+ }
427
+ onSocketError(error) {
428
+ this.logError("WebSocket error", error);
429
+ }
430
+ startMetricsReporting() {
431
+ if (!this.metricsReportingEnabled || !this.workerId) return;
432
+ const meter = require_otel_worker_gauges.getMeter();
433
+ if (!meter) {
434
+ console.warn("[iii] Worker metrics disabled: OpenTelemetry not initialized. Call initOtel() with metricsEnabled: true before creating the iii.");
435
+ return;
436
+ }
437
+ require_otel_worker_gauges.registerWorkerGauges(meter, {
438
+ workerId: this.workerId,
439
+ workerName: this.workerName
440
+ });
441
+ }
442
+ stopMetricsReporting() {
443
+ require_otel_worker_gauges.stopWorkerGauges();
444
+ }
445
+ onSocketClose() {
446
+ this.ws?.removeAllListeners();
447
+ this.ws?.terminate();
448
+ this.ws = void 0;
449
+ this.setConnectionState("disconnected");
450
+ this.stopMetricsReporting();
451
+ this.scheduleReconnect();
452
+ }
453
+ onSocketOpen() {
454
+ this.clearReconnectTimeout();
455
+ this.reconnectAttempt = 0;
456
+ this.setConnectionState("connected");
457
+ this.ws?.on("message", this.onMessage.bind(this));
458
+ this.triggerTypes.forEach(({ message }) => {
459
+ this.sendMessage(MessageType.RegisterTriggerType, message, true);
460
+ });
461
+ this.services.forEach((service) => {
462
+ this.sendMessage(MessageType.RegisterService, service, true);
463
+ });
464
+ this.functions.forEach(({ message }) => {
465
+ this.sendMessage(MessageType.RegisterFunction, message, true);
466
+ });
467
+ this.triggers.forEach((trigger) => {
468
+ this.sendMessage(MessageType.RegisterTrigger, trigger, true);
469
+ });
470
+ const pending = this.messagesToSend;
471
+ this.messagesToSend = [];
472
+ for (const message of pending) {
473
+ if (message.type === MessageType.InvokeFunction && message.invocation_id && !this.invocations.has(message.invocation_id)) continue;
474
+ this.sendMessageRaw(JSON.stringify(message));
475
+ }
476
+ this.registerWorkerMetadata();
477
+ }
478
+ isOpen() {
479
+ return this.ws?.readyState === ws.WebSocket.OPEN;
480
+ }
481
+ sendMessageRaw(data) {
482
+ if (this.ws && this.isOpen()) try {
483
+ this.ws.send(data, (err) => {
484
+ if (err) this.logError("Failed to send message", err);
485
+ });
486
+ } catch (error) {
487
+ this.logError("Exception while sending message", error);
488
+ }
489
+ }
490
+ sendMessage(type, message, skipIfClosed = false) {
491
+ const fullMessage = {
492
+ ...message,
493
+ type
494
+ };
495
+ if (this.isOpen()) this.sendMessageRaw(JSON.stringify(fullMessage));
496
+ else if (!skipIfClosed) this.messagesToSend.push(fullMessage);
497
+ }
498
+ logError(message, error) {
499
+ const otelLogger = require_otel_worker_gauges.getLogger();
500
+ const errorMessage = error instanceof Error ? error.message : String(error ?? "");
501
+ if (otelLogger) otelLogger.emit({
502
+ severityNumber: __opentelemetry_api_logs.SeverityNumber.ERROR,
503
+ body: `[iii] ${message}${errorMessage ? `: ${errorMessage}` : ""}`
504
+ });
505
+ else console.error(`[iii] ${message}`, error ?? "");
506
+ }
507
+ severityTextToNumber(level) {
508
+ switch (level) {
509
+ case "trace": return 1;
510
+ case "debug": return 5;
511
+ case "info": return 9;
512
+ case "warn": return 13;
513
+ case "error": return 17;
514
+ case "fatal": return 21;
515
+ case "all": return 0;
516
+ default: return 0;
517
+ }
518
+ }
519
+ onInvocationResult(invocation_id, result, error) {
520
+ const invocation = this.invocations.get(invocation_id);
521
+ if (invocation) {
522
+ if (invocation.timeout) clearTimeout(invocation.timeout);
523
+ error ? invocation.reject(error) : invocation.resolve(result);
524
+ }
525
+ this.invocations.delete(invocation_id);
526
+ }
527
+ async onInvokeFunction(invocation_id, function_id, input, traceparent, baggage) {
528
+ const fn = this.functions.get(function_id);
529
+ const getResponseTraceparent = () => require_otel_worker_gauges.injectTraceparent() ?? traceparent;
530
+ const getResponseBaggage = () => require_otel_worker_gauges.injectBaggage() ?? baggage;
531
+ if (fn) {
532
+ if (!invocation_id) {
533
+ try {
534
+ await fn.handler(input, traceparent, baggage);
535
+ } catch (error) {
536
+ this.logError(`Error invoking function ${function_id}`, error);
537
+ }
538
+ return;
539
+ }
540
+ try {
541
+ const result = await fn.handler(input, traceparent, baggage);
542
+ this.sendMessage(MessageType.InvocationResult, {
543
+ invocation_id,
544
+ function_id,
545
+ result,
546
+ traceparent: getResponseTraceparent(),
547
+ baggage: getResponseBaggage()
548
+ });
549
+ } catch (error) {
550
+ this.sendMessage(MessageType.InvocationResult, {
551
+ invocation_id,
552
+ function_id,
553
+ error: {
554
+ code: "invocation_failed",
555
+ message: error.message
556
+ },
557
+ traceparent: getResponseTraceparent(),
558
+ baggage: getResponseBaggage()
559
+ });
560
+ }
561
+ } else this.sendMessage(MessageType.InvocationResult, {
562
+ invocation_id,
563
+ function_id,
564
+ error: {
565
+ code: "function_not_found",
566
+ message: "Function not found"
567
+ },
568
+ traceparent,
569
+ baggage
570
+ });
571
+ }
572
+ async onRegisterTrigger(message) {
573
+ const triggerTypeData = this.triggerTypes.get(message.trigger_type);
574
+ const { id, trigger_type, function_id, config } = message;
575
+ if (triggerTypeData) try {
576
+ await triggerTypeData.handler.registerTrigger({
577
+ id,
578
+ function_id,
579
+ config
580
+ });
581
+ this.sendMessage(MessageType.TriggerRegistrationResult, {
582
+ id,
583
+ trigger_type,
584
+ function_id
585
+ });
586
+ } catch (error) {
587
+ this.sendMessage(MessageType.TriggerRegistrationResult, {
588
+ id,
589
+ trigger_type,
590
+ function_id,
591
+ error: {
592
+ code: "trigger_registration_failed",
593
+ message: error.message
594
+ }
595
+ });
596
+ }
597
+ else this.sendMessage(MessageType.TriggerRegistrationResult, {
598
+ id,
599
+ trigger_type,
600
+ function_id,
601
+ error: {
602
+ code: "trigger_type_not_found",
603
+ message: "Trigger type not found"
604
+ }
605
+ });
606
+ }
607
+ onMessage(socketMessage) {
608
+ let type;
609
+ let message;
610
+ try {
611
+ const parsed = JSON.parse(socketMessage.toString());
612
+ type = parsed.type;
613
+ const { type: _, ...rest } = parsed;
614
+ message = rest;
615
+ } catch (error) {
616
+ this.logError("Failed to parse incoming message", error);
617
+ return;
618
+ }
619
+ if (type === MessageType.InvocationResult) {
620
+ const { invocation_id, result, error } = message;
621
+ this.onInvocationResult(invocation_id, result, error);
622
+ } else if (type === MessageType.InvokeFunction) {
623
+ const { invocation_id, function_id, data, traceparent, baggage } = message;
624
+ this.onInvokeFunction(invocation_id, function_id, data, traceparent, baggage);
625
+ } else if (type === MessageType.RegisterTrigger) this.onRegisterTrigger(message);
626
+ else if (type === MessageType.WorkerRegistered) {
627
+ const { worker_id } = message;
628
+ this.workerId = worker_id;
629
+ console.debug("[iii] Worker registered with ID:", worker_id);
630
+ this.startMetricsReporting();
631
+ }
632
+ }
633
+ };
634
+ const init = (address, options) => new Sdk(address, options);
635
+
636
+ //#endregion
637
+ exports.Logger = Logger;
638
+ exports.__toESM = __toESM;
639
+ exports.getContext = getContext;
640
+ exports.init = init;
641
+ exports.withContext = withContext;
642
+ //# sourceMappingURL=index.cjs.map