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