arvo-event-handler 3.0.6 → 3.0.8

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.
Files changed (46) hide show
  1. package/dist/ArvoEventHandler/helpers.d.ts +2 -2
  2. package/dist/ArvoEventHandler/index.d.ts +4 -4
  3. package/dist/ArvoEventHandler/index.js +13 -34
  4. package/dist/ArvoEventHandler/types.d.ts +5 -3
  5. package/dist/ArvoMachine/createMachine.d.ts +4 -2
  6. package/dist/ArvoMachine/createMachine.js +1 -1
  7. package/dist/ArvoMachine/types.d.ts +5 -1
  8. package/dist/ArvoOrchestrationUtils/createEmitableEvent.d.ts +30 -0
  9. package/dist/ArvoOrchestrationUtils/createEmitableEvent.js +160 -0
  10. package/dist/ArvoOrchestrationUtils/error.d.ts +18 -0
  11. package/dist/{ArvoOrchestrator → ArvoOrchestrationUtils}/error.js +14 -9
  12. package/dist/ArvoOrchestrationUtils/handlerErrors.d.ts +35 -0
  13. package/dist/ArvoOrchestrationUtils/handlerErrors.js +184 -0
  14. package/dist/ArvoOrchestrationUtils/orchestrationExecutionState.d.ts +11 -0
  15. package/dist/ArvoOrchestrationUtils/orchestrationExecutionState.js +7 -0
  16. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/acquireLockWithValidation.d.ts +8 -0
  17. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/acquireLockWithValidation.js +69 -0
  18. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/index.d.ts +40 -0
  19. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/index.js +228 -0
  20. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/validateAndParseSubject.d.ts +7 -0
  21. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/validateAndParseSubject.js +25 -0
  22. package/dist/ArvoOrchestrationUtils/types.d.ts +1 -0
  23. package/dist/ArvoOrchestrationUtils/types.js +2 -0
  24. package/dist/ArvoOrchestrator/factory.js +13 -0
  25. package/dist/ArvoOrchestrator/index.d.ts +5 -21
  26. package/dist/ArvoOrchestrator/index.js +93 -505
  27. package/dist/ArvoOrchestrator/types.d.ts +5 -4
  28. package/dist/ArvoResumable/factory.d.ts +2 -2
  29. package/dist/ArvoResumable/factory.js +1 -1
  30. package/dist/ArvoResumable/index.d.ts +6 -20
  31. package/dist/ArvoResumable/index.js +85 -462
  32. package/dist/ArvoResumable/types.d.ts +8 -5
  33. package/dist/IArvoEventHandler/index.d.ts +36 -0
  34. package/dist/IArvoEventHandler/index.js +2 -0
  35. package/dist/MachineExecutionEngine/index.d.ts +1 -1
  36. package/dist/MachineRegistry/index.d.ts +1 -1
  37. package/dist/SyncEventResource/index.d.ts +1 -1
  38. package/dist/SyncEventResource/index.js +1 -1
  39. package/dist/index.d.ts +14 -13
  40. package/dist/index.js +24 -23
  41. package/dist/types.d.ts +2 -2
  42. package/dist/utils/SimpleEventBroker/helper.d.ts +2 -2
  43. package/package.json +5 -4
  44. package/dist/AbstractArvoEventHandler/index.d.ts +0 -91
  45. package/dist/AbstractArvoEventHandler/index.js +0 -18
  46. package/dist/ArvoOrchestrator/error.d.ts +0 -16
@@ -1,30 +1,4 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -61,25 +35,18 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
61
35
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
36
  }
63
37
  };
64
- var __importDefault = (this && this.__importDefault) || function (mod) {
65
- return (mod && mod.__esModule) ? mod : { "default": mod };
66
- };
67
38
  Object.defineProperty(exports, "__esModule", { value: true });
68
39
  exports.ArvoOrchestrator = void 0;
69
- var api_1 = require("@opentelemetry/api");
70
40
  var arvo_core_1 = require("arvo-core");
71
- var utils_1 = require("../utils");
72
- var error_1 = require("./error");
41
+ var createEmitableEvent_1 = require("../ArvoOrchestrationUtils/createEmitableEvent");
42
+ var orchestrationExecutionWrapper_1 = require("../ArvoOrchestrationUtils/orchestrationExecutionWrapper");
73
43
  var SyncEventResource_1 = require("../SyncEventResource");
74
- var AbstractArvoEventHandler_1 = __importDefault(require("../AbstractArvoEventHandler"));
75
44
  var errors_1 = require("../errors");
76
- var ArvoDomain_1 = require("../ArvoDomain");
77
45
  /**
78
46
  * Orchestrates state machine execution and lifecycle management.
79
47
  * Handles machine resolution, state management, event processing and error handling.
80
48
  */
81
- var ArvoOrchestrator = /** @class */ (function (_super) {
82
- __extends(ArvoOrchestrator, _super);
49
+ var ArvoOrchestrator = /** @class */ (function () {
83
50
  /**
84
51
  * Creates a new orchestrator instance
85
52
  * @param params - Configuration parameters
@@ -87,26 +54,12 @@ var ArvoOrchestrator = /** @class */ (function (_super) {
87
54
  */
88
55
  function ArvoOrchestrator(_a) {
89
56
  var executionunits = _a.executionunits, memory = _a.memory, registry = _a.registry, executionEngine = _a.executionEngine, requiresResourceLocking = _a.requiresResourceLocking, systemErrorDomain = _a.systemErrorDomain;
90
- var _this = _super.call(this) || this;
91
- _this.systemErrorDomain = [];
92
- _this.executionunits = executionunits;
93
- var representativeMachine = registry.machines[0];
94
- var lastSeenVersions = [];
95
- for (var _i = 0, _b = registry.machines; _i < _b.length; _i++) {
96
- var machine = _b[_i];
97
- if (representativeMachine.source !== machine.source) {
98
- throw new Error("All the machines in the orchestrator must have type '".concat(representativeMachine.source, "'"));
99
- }
100
- if (lastSeenVersions.includes(machine.version)) {
101
- throw new Error("An orchestrator must have unique machine versions. Machine ID:".concat(machine.id, " has duplicate version ").concat(machine.version, "."));
102
- }
103
- lastSeenVersions.push(machine.version);
104
- }
105
- _this.registry = registry;
106
- _this.executionEngine = executionEngine;
107
- _this.syncEventResource = new SyncEventResource_1.SyncEventResource(memory, requiresResourceLocking);
108
- _this.systemErrorDomain = systemErrorDomain;
109
- return _this;
57
+ this.systemErrorDomain = [];
58
+ this.executionunits = executionunits;
59
+ this.registry = registry;
60
+ this.executionEngine = executionEngine;
61
+ this.syncEventResource = new SyncEventResource_1.SyncEventResource(memory, requiresResourceLocking);
62
+ this.systemErrorDomain = systemErrorDomain;
110
63
  }
111
64
  Object.defineProperty(ArvoOrchestrator.prototype, "source", {
112
65
  get: function () {
@@ -136,148 +89,6 @@ var ArvoOrchestrator = /** @class */ (function (_super) {
136
89
  enumerable: false,
137
90
  configurable: true
138
91
  });
139
- /**
140
- * Creates emittable event from execution result
141
- * @param event - Source event to emit
142
- * @param machine - Machine that generated event
143
- * @param otelHeaders - OpenTelemetry headers
144
- * @param orchestrationParentSubject - Parent orchestration subject
145
- * @param sourceEvent - Original triggering event
146
- * @param initEventId - The id of the event which initiated the orchestration in the first place
147
- * @param _domain - The domain of the event.
148
- *
149
- * @throws {ContractViolation} On schema/contract mismatch
150
- * @throws {ExecutionViolation} On invalid parentSubject$$ format
151
- */
152
- ArvoOrchestrator.prototype.createEmittableEvent = function (event, machine, otelHeaders, orchestrationParentSubject, sourceEvent, initEventId, _domain) {
153
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
154
- (0, arvo_core_1.logToSpan)({
155
- level: 'INFO',
156
- message: "Creating emittable event: ".concat(event.type),
157
- });
158
- var selfContract = machine.contracts.self;
159
- var serviceContract = Object.fromEntries(Object.values(machine.contracts.services).map(function (item) { return [item.accepts.type, item]; }));
160
- var schema = null;
161
- var contract = null;
162
- var subject = sourceEvent.subject;
163
- var parentId = sourceEvent.id;
164
- var domain = (0, ArvoDomain_1.resolveEventDomain)({
165
- domainToResolve: _domain,
166
- handlerSelfContract: selfContract,
167
- eventContract: null,
168
- triggeringEvent: sourceEvent,
169
- });
170
- if (event.type === selfContract.metadata.completeEventType) {
171
- (0, arvo_core_1.logToSpan)({
172
- level: 'INFO',
173
- message: "Creating event for machine workflow completion: ".concat(event.type),
174
- });
175
- contract = selfContract;
176
- schema = selfContract.emits[selfContract.metadata.completeEventType];
177
- subject = orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : sourceEvent.subject;
178
- parentId = initEventId;
179
- domain = (0, ArvoDomain_1.resolveEventDomain)({
180
- domainToResolve: _domain,
181
- handlerSelfContract: selfContract,
182
- eventContract: selfContract,
183
- triggeringEvent: sourceEvent,
184
- });
185
- }
186
- else if (serviceContract[event.type]) {
187
- (0, arvo_core_1.logToSpan)({
188
- level: 'INFO',
189
- message: "Creating service event for external system: ".concat(event.type),
190
- });
191
- contract = serviceContract[event.type];
192
- schema = serviceContract[event.type].accepts.schema;
193
- domain = (0, ArvoDomain_1.resolveEventDomain)({
194
- domainToResolve: _domain,
195
- handlerSelfContract: selfContract,
196
- eventContract: contract,
197
- triggeringEvent: sourceEvent,
198
- });
199
- // If the event is to call another orchestrator then, extract the parent subject
200
- // passed to it and then form an new subject. This allows for event chaining
201
- // between orchestrators
202
- if (contract.metadata.contractType === 'ArvoOrchestratorContract') {
203
- if (event.data.parentSubject$$) {
204
- try {
205
- arvo_core_1.ArvoOrchestrationSubject.parse(event.data.parentSubject$$);
206
- }
207
- catch (_m) {
208
- throw new errors_1.ExecutionViolation("Invalid parentSubject$$ for the event(type='".concat(event.type, "', uri='").concat((_a = event.dataschema) !== null && _a !== void 0 ? _a : arvo_core_1.EventDataschemaUtil.create(contract), "').It must be follow the ArvoOrchestrationSubject schema. The easiest way is to use the current orchestration subject by storing the subject via the context block in the machine definition."));
209
- }
210
- }
211
- try {
212
- if (event.data.parentSubject$$) {
213
- subject = arvo_core_1.ArvoOrchestrationSubject.from({
214
- orchestator: contract.accepts.type,
215
- version: contract.version,
216
- subject: event.data.parentSubject$$,
217
- domain: domain !== null && domain !== void 0 ? domain : null,
218
- meta: {
219
- redirectto: (_b = event.redirectto) !== null && _b !== void 0 ? _b : this.source,
220
- },
221
- });
222
- }
223
- else {
224
- subject = arvo_core_1.ArvoOrchestrationSubject.new({
225
- version: contract.version,
226
- orchestator: contract.accepts.type,
227
- initiator: this.source,
228
- domain: domain !== null && domain !== void 0 ? domain : undefined,
229
- meta: {
230
- redirectto: (_c = event.redirectto) !== null && _c !== void 0 ? _c : this.source,
231
- },
232
- });
233
- }
234
- }
235
- catch (error) {
236
- // This is a execution violation because it indicates faulty parent subject
237
- // or some fundamental error with subject creation which must be not be propagated
238
- // any further and investigated manually.
239
- throw new errors_1.ExecutionViolation("Orchestration subject creation failed due to invalid parameters - Event: ".concat(event.type, " - Check event emit parameters in the machine definition. ").concat(error === null || error === void 0 ? void 0 : error.message));
240
- }
241
- }
242
- }
243
- var finalDataschema = event.dataschema;
244
- var finalData = event.data;
245
- // finally if the contract and the schema are available
246
- // then use them to validate the event. Otherwise just use
247
- // the data from the incoming event which is raw and created
248
- // by the machine
249
- if (contract && schema) {
250
- try {
251
- finalData = schema.parse(event.data);
252
- finalDataschema = arvo_core_1.EventDataschemaUtil.create(contract);
253
- }
254
- catch (error) {
255
- throw new errors_1.ContractViolation("Invalid event data: Schema validation failed - Check emit parameters in machine definition.\nEvent type: ".concat(event.type, "\nDetails: ").concat(error.message));
256
- }
257
- }
258
- // Create the event
259
- var emittableEvent = (0, arvo_core_1.createArvoEvent)({
260
- source: this.source,
261
- type: event.type,
262
- subject: subject,
263
- dataschema: finalDataschema !== null && finalDataschema !== void 0 ? finalDataschema : undefined,
264
- data: finalData,
265
- to: (_d = event.to) !== null && _d !== void 0 ? _d : event.type,
266
- accesscontrol: (_f = (_e = event.accesscontrol) !== null && _e !== void 0 ? _e : sourceEvent.accesscontrol) !== null && _f !== void 0 ? _f : undefined,
267
- // The orchestrator does not respect redirectto from the source event
268
- redirectto: (_g = event.redirectto) !== null && _g !== void 0 ? _g : this.source,
269
- executionunits: (_h = event.executionunits) !== null && _h !== void 0 ? _h : this.executionunits,
270
- traceparent: (_j = otelHeaders.traceparent) !== null && _j !== void 0 ? _j : undefined,
271
- tracestate: (_k = otelHeaders.tracestate) !== null && _k !== void 0 ? _k : undefined,
272
- parentid: parentId,
273
- domain: domain !== null && domain !== void 0 ? domain : undefined,
274
- }, (_l = event.__extensions) !== null && _l !== void 0 ? _l : {});
275
- (0, arvo_core_1.logToSpan)({
276
- level: 'INFO',
277
- message: "Event created successfully: ".concat(emittableEvent.type),
278
- });
279
- return emittableEvent;
280
- };
281
92
  /**
282
93
  * Core orchestration method that executes state machines in response to events.
283
94
  *
@@ -292,317 +103,94 @@ var ArvoOrchestrator = /** @class */ (function (_super) {
292
103
  */
293
104
  ArvoOrchestrator.prototype.execute = function (event_1) {
294
105
  return __awaiter(this, arguments, void 0, function (event, opentelemetry) {
295
- var _a;
296
106
  var _this = this;
297
107
  if (opentelemetry === void 0) { opentelemetry = {
298
108
  inheritFrom: 'EVENT',
299
109
  }; }
300
- return __generator(this, function (_b) {
301
- switch (_b.label) {
302
- case 0: return [4 /*yield*/, arvo_core_1.ArvoOpenTelemetry.getInstance().startActiveSpan({
303
- name: "Orchestrator<".concat(this.registry.machines[0].contracts.self.uri, ">@<").concat(event.type, ">"),
304
- spanOptions: {
305
- kind: api_1.SpanKind.PRODUCER,
306
- attributes: __assign((_a = {}, _a[arvo_core_1.ArvoExecution.ATTR_SPAN_KIND] = arvo_core_1.ArvoExecutionSpanKind.ORCHESTRATOR, _a[arvo_core_1.OpenInference.ATTR_SPAN_KIND] = arvo_core_1.OpenInferenceSpanKind.CHAIN, _a), Object.fromEntries(Object.entries(event.otelAttributes).map(function (_a) {
307
- var key = _a[0], value = _a[1];
308
- return ["to_process.0.".concat(key), value];
309
- }))),
310
- },
311
- context: opentelemetry.inheritFrom === 'EVENT'
312
- ? {
313
- inheritFrom: 'TRACE_HEADERS',
314
- traceHeaders: {
315
- traceparent: event.traceparent,
316
- tracestate: event.tracestate,
317
- },
110
+ return __generator(this, function (_a) {
111
+ switch (_a.label) {
112
+ case 0: return [4 /*yield*/, (0, orchestrationExecutionWrapper_1.executeWithOrchestrationWrapper)({
113
+ _handlerType: 'orchestrator',
114
+ event: event,
115
+ opentelemetry: opentelemetry,
116
+ spanName: "Orchestrator<".concat(this.registry.machines[0].contracts.self.uri, ">@<").concat(event.type, ">"),
117
+ source: this.source,
118
+ syncEventResource: this.syncEventResource,
119
+ executionunits: this.executionunits,
120
+ systemErrorDomain: this.systemErrorDomain,
121
+ selfContract: this.registry.machines[0].contracts.self,
122
+ domain: this.domain,
123
+ }, function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
124
+ var machine, inputValidation, executionResult, rawMachineEmittedEvents, emittables, newState;
125
+ var _c, _d, _e, _f;
126
+ var span = _b.span, otelHeaders = _b.otelHeaders, orchestrationParentSubject = _b.orchestrationParentSubject, initEventId = _b.initEventId, parsedEventSubject = _b.parsedEventSubject, state = _b.state;
127
+ return __generator(this, function (_g) {
128
+ (0, arvo_core_1.logToSpan)({
129
+ level: 'INFO',
130
+ message: "Resolving machine for event ".concat(event.type),
131
+ }, span);
132
+ machine = this.registry.resolve(event, { inheritFrom: 'CONTEXT' });
133
+ if (!machine) {
134
+ throw new errors_1.ConfigViolation("Machine resolution failed: No machine found matching orchestrator name='".concat(parsedEventSubject.orchestrator.name, "' and version='").concat(parsedEventSubject.orchestrator.version, "'."));
135
+ }
136
+ (0, arvo_core_1.logToSpan)({
137
+ level: 'INFO',
138
+ message: "Input validation started for event ".concat(event.type, " on machine ").concat(machine.source),
139
+ }, span);
140
+ inputValidation = machine.validateInput(event);
141
+ if (inputValidation.type === 'CONTRACT_UNRESOLVED') {
142
+ throw new errors_1.ConfigViolation('Contract validation failed - Event does not match any registered contract schemas in the machine');
318
143
  }
319
- : {
320
- inheritFrom: 'CONTEXT',
321
- context: api_1.context.active(),
322
- },
323
- disableSpanManagement: true,
324
- fn: function (span) { return __awaiter(_this, void 0, void 0, function () {
325
- var otelHeaders, orchestrationParentSubject, initEventId, acquiredLock, parsedEventSubject, machine, _a, name_1, version, inputValidation, state, executionResult, rawMachineEmittedEvents, emittables, _i, rawMachineEmittedEvents_1, item, createdDomain, _b, _c, _dom, evt, _d, _e, _f, key, value, error_2, e, parsedEventSubject, result, _g, _h, _dom, _j, _k, _l, key, value;
326
- var _this = this;
327
- var _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
328
- return __generator(this, function (_0) {
329
- switch (_0.label) {
330
- case 0:
331
- (0, arvo_core_1.logToSpan)({
332
- level: 'INFO',
333
- message: "Orchestrator starting execution for ".concat(event.type, " on subject ").concat(event.subject),
334
- });
335
- otelHeaders = (0, arvo_core_1.currentOpenTelemetryHeaders)();
336
- orchestrationParentSubject = null;
337
- initEventId = null;
338
- acquiredLock = null;
339
- _0.label = 1;
340
- case 1:
341
- _0.trys.push([1, 5, 6, 8]);
342
- ///////////////////////////////////////////////////////////////
343
- // Subject resolution, machine resolution and input validation
344
- ///////////////////////////////////////////////////////////////
345
- this.syncEventResource.validateEventSubject(event, span);
346
- parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject);
347
- span.setAttributes({
348
- 'arvo.parsed.subject.orchestrator.name': parsedEventSubject.orchestrator.name,
349
- 'arvo.parsed.subject.orchestrator.version': parsedEventSubject.orchestrator.version,
350
- });
351
- // The wrong source is not a big violation. May be some routing went wrong. So just ignore
352
- if (parsedEventSubject.orchestrator.name !== this.source) {
353
- (0, arvo_core_1.logToSpan)({
354
- level: 'WARNING',
355
- message: "Event subject mismatch detected. Expected orchestrator '".concat(this.source, "' but subject indicates '").concat(parsedEventSubject.orchestrator.name, "'. This indicates either a routing error or a non-applicable event that can be safely ignored."),
356
- });
357
- (0, arvo_core_1.logToSpan)({
358
- level: 'INFO',
359
- message: 'Orchestration executed with issues and emitted 0 events',
360
- });
361
- return [2 /*return*/, {
362
- events: [],
363
- }];
364
- }
365
- (0, arvo_core_1.logToSpan)({
366
- level: 'INFO',
367
- message: "Resolving machine for event ".concat(event.type),
368
- });
369
- machine = this.registry.resolve(event, {
370
- inheritFrom: 'CONTEXT',
371
- });
372
- // Unable to find a machine is a big configuration bug and violation
373
- if (!machine) {
374
- _a = parsedEventSubject.orchestrator, name_1 = _a.name, version = _a.version;
375
- throw new errors_1.ConfigViolation("Machine resolution failed: No machine found matching orchestrator name='".concat(name_1, "' and version='").concat(version, "'."));
376
- }
377
- (0, arvo_core_1.logToSpan)({
378
- level: 'INFO',
379
- message: "Input validation started for event ".concat(event.type, " on machine ").concat(machine.source),
380
- });
381
- inputValidation = machine.validateInput(event);
382
- if (inputValidation.type === 'CONTRACT_UNRESOLVED') {
383
- // This is a configuration error because the contract was never
384
- // configured in the machine. That is why it was unresolved. It
385
- // signifies a problem in configration not the data or event flow
386
- throw new errors_1.ConfigViolation('Contract validation failed - Event does not match any registered contract schemas in the machine');
387
- }
388
- if (inputValidation.type === 'INVALID_DATA' || inputValidation.type === 'INVALID') {
389
- // This is a contract error becuase there is a configuration but
390
- // the event data received was invalid due to conflicting data
391
- // or event dataschema did not match the contract data schema. This
392
- // signifies an issue with event flow because unexpected events
393
- // are being received
394
- throw new errors_1.ContractViolation("Input validation failed - Event data does not meet contract requirements: ".concat(inputValidation.error.message));
395
- }
396
- return [4 /*yield*/, this.syncEventResource.acquireLock(event, span)];
397
- case 2:
398
- ///////////////////////////////////////////////////////////////
399
- // State locking, acquiry machine exection
400
- ///////////////////////////////////////////////////////////////
401
- acquiredLock = _0.sent();
402
- if (acquiredLock === 'NOT_ACQUIRED') {
403
- throw new error_1.TransactionViolation({
404
- cause: error_1.TransactionViolationCause.LOCK_UNACQUIRED,
405
- message: 'Lock acquisition denied - Unable to obtain exclusive access to event processing',
406
- initiatingEvent: event,
407
- });
408
- }
409
- if (acquiredLock === 'ACQUIRED') {
410
- (0, arvo_core_1.logToSpan)({
411
- level: 'INFO',
412
- message: "This execution acquired lock at resource '".concat(event.subject, "'"),
413
- });
414
- }
415
- return [4 /*yield*/, this.syncEventResource.acquireState(event, span)];
416
- case 3:
417
- state = _0.sent();
418
- orchestrationParentSubject = (_m = state === null || state === void 0 ? void 0 : state.parentSubject) !== null && _m !== void 0 ? _m : null;
419
- initEventId = (_o = state === null || state === void 0 ? void 0 : state.initEventId) !== null && _o !== void 0 ? _o : event.id;
420
- if (!state) {
421
- (0, arvo_core_1.logToSpan)({
422
- level: 'INFO',
423
- message: "Initializing new execution state for subject: ".concat(event.subject),
424
- });
425
- if (event.type !== this.source) {
426
- (0, arvo_core_1.logToSpan)({
427
- level: 'WARNING',
428
- message: "Invalid initialization event detected. Expected type '".concat(this.source, "' but received '").concat(event.type, "'. This may indicate an incorrectly routed event or a non-initialization event that can be safely ignored."),
429
- });
430
- return [2 /*return*/, {
431
- events: [],
432
- }];
433
- }
434
- }
435
- else {
436
- (0, arvo_core_1.logToSpan)({
437
- level: 'INFO',
438
- message: "Resuming execution with existing state for subject: ".concat(event.subject),
439
- });
440
- }
441
- // In case the event is the init event then
442
- // extract the parent subject from it and assume
443
- // it to be the orchestration parent subject
444
- if (event.type === this.source) {
445
- orchestrationParentSubject = (_q = (_p = event === null || event === void 0 ? void 0 : event.data) === null || _p === void 0 ? void 0 : _p.parentSubject$$) !== null && _q !== void 0 ? _q : null;
446
- }
447
- executionResult = this.executionEngine.execute({
448
- state: (_r = state === null || state === void 0 ? void 0 : state.state) !== null && _r !== void 0 ? _r : null,
449
- event: event,
450
- machine: machine,
451
- }, { inheritFrom: 'CONTEXT' });
452
- span.setAttribute('arvo.orchestration.status', executionResult.state.status);
453
- rawMachineEmittedEvents = executionResult.events;
454
- // In case execution of the machine has finished
455
- // and the final output has been created, then in
456
- // that case, make the raw event as the final output
457
- // is not even raw enough to be called an event yet
458
- if (executionResult.finalOutput) {
459
- rawMachineEmittedEvents.push({
460
- type: machine.contracts.self
461
- .metadata.completeEventType,
462
- data: executionResult.finalOutput,
463
- to: (_t = (_s = parsedEventSubject.meta) === null || _s === void 0 ? void 0 : _s.redirectto) !== null && _t !== void 0 ? _t : parsedEventSubject.execution.initiator,
464
- domain: orchestrationParentSubject
465
- ? [arvo_core_1.ArvoOrchestrationSubject.parse(orchestrationParentSubject).execution.domain]
466
- : [null],
467
- });
468
- }
469
- emittables = [];
470
- for (_i = 0, rawMachineEmittedEvents_1 = rawMachineEmittedEvents; _i < rawMachineEmittedEvents_1.length; _i++) {
471
- item = rawMachineEmittedEvents_1[_i];
472
- createdDomain = new Set();
473
- for (_b = 0, _c = Array.from(new Set((_u = item.domain) !== null && _u !== void 0 ? _u : [null])); _b < _c.length; _b++) {
474
- _dom = _c[_b];
475
- evt = this.createEmittableEvent(item, machine, otelHeaders, orchestrationParentSubject, event, initEventId, _dom);
476
- // Making sure the raw event broadcast is actually unique as the
477
- // domain resolution (especially for symbolic) can only happen
478
- // in the createEmittableEvent
479
- if (createdDomain.has(evt.domain))
480
- continue;
481
- createdDomain.add(evt.domain);
482
- emittables.push(evt);
483
- for (_d = 0, _e = Object.entries(emittables[emittables.length - 1].otelAttributes); _d < _e.length; _d++) {
484
- _f = _e[_d], key = _f[0], value = _f[1];
485
- span.setAttribute("to_emit.".concat(emittables.length - 1, ".").concat(key), value);
486
- }
487
- }
488
- }
489
- (0, arvo_core_1.logToSpan)({
490
- level: 'INFO',
491
- message: "Machine execution completed - Status: ".concat(executionResult.state.status, ", Generated events: ").concat(executionResult.events.length),
492
- });
493
- // Write to the memory
494
- return [4 /*yield*/, this.syncEventResource.persistState(event, {
495
- initEventId: initEventId,
496
- subject: event.subject,
497
- parentSubject: orchestrationParentSubject,
498
- status: executionResult.state.status,
499
- value: (_v = executionResult.state.value) !== null && _v !== void 0 ? _v : null,
500
- state: executionResult.state,
501
- events: {
502
- consumed: event.toJSON(),
503
- produced: emittables.map(function (item) { return item.toJSON(); }),
504
- },
505
- machineDefinition: JSON.stringify(machine.logic.config),
506
- }, state, span)];
507
- case 4:
508
- // Write to the memory
509
- _0.sent();
510
- (0, arvo_core_1.logToSpan)({
511
- level: 'INFO',
512
- message: "State update persisted in memory for subject ".concat(event.subject),
513
- });
514
- (0, arvo_core_1.logToSpan)({
515
- level: 'INFO',
516
- message: "Orchestration successfully executed and emitted ".concat(emittables.length, " events"),
517
- });
518
- return [2 /*return*/, { events: emittables }];
519
- case 5:
520
- error_2 = _0.sent();
521
- e = (0, utils_1.isError)(error_2)
522
- ? error_2
523
- : new errors_1.ExecutionViolation("Non-Error object thrown during machine execution: ".concat(typeof error_2, ". This indicates a serious implementation flaw."));
524
- (0, arvo_core_1.exceptionToSpan)(e);
525
- span.setStatus({
526
- code: api_1.SpanStatusCode.ERROR,
527
- message: e.message,
528
- });
529
- // For any violation errors bubble them up to the
530
- // called of the function so that they can
531
- // be handled gracefully
532
- if (e.name.includes('ViolationError')) {
533
- (0, arvo_core_1.logToSpan)({
534
- level: 'CRITICAL',
535
- message: "Orchestrator violation error: ".concat(e.message),
536
- });
537
- throw e;
538
- }
539
- (0, arvo_core_1.logToSpan)({
540
- level: 'ERROR',
541
- message: "Orchestrator execution failed: ".concat(e.message),
542
- });
543
- parsedEventSubject = null;
544
- try {
545
- parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject);
546
- }
547
- catch (e) {
548
- (0, arvo_core_1.logToSpan)({
549
- level: 'WARNING',
550
- message: "Unable to parse event subject: ".concat(e.message),
551
- });
552
- }
553
- result = [];
554
- for (_g = 0, _h = Array.from(new Set(this.systemErrorDomain
555
- ? this.systemErrorDomain.map(function (item) {
556
- return (0, ArvoDomain_1.resolveEventDomain)({
557
- domainToResolve: item,
558
- triggeringEvent: event,
559
- handlerSelfContract: _this.registry.machines[0].contracts.self,
560
- eventContract: _this.registry.machines[0].contracts.self,
561
- });
562
- })
563
- : [event.domain, this.domain, null])); _g < _h.length; _g++) {
564
- _dom = _h[_g];
565
- result.push((0, arvo_core_1.createArvoOrchestratorEventFactory)(this.registry.machines[0].contracts.self).systemError({
566
- source: this.source,
567
- // If the initiator of the workflow exist then match the
568
- // subject so that it can incorporate it in its state. If
569
- // parent does not exist then this is the root workflow so
570
- // use its own subject
571
- subject: orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : event.subject,
572
- // The system error must always go back to
573
- // the source which initiated it
574
- to: (_w = parsedEventSubject === null || parsedEventSubject === void 0 ? void 0 : parsedEventSubject.execution.initiator) !== null && _w !== void 0 ? _w : event.source,
575
- error: e,
576
- traceparent: (_x = otelHeaders.traceparent) !== null && _x !== void 0 ? _x : undefined,
577
- tracestate: (_y = otelHeaders.tracestate) !== null && _y !== void 0 ? _y : undefined,
578
- accesscontrol: (_z = event.accesscontrol) !== null && _z !== void 0 ? _z : undefined,
579
- executionunits: this.executionunits,
580
- // If there is initEventID then use that.
581
- // Otherwise, use event id. If the error is in init event
582
- // then it will be the same as initEventId. Otherwise,
583
- // we still would know what cause this error
584
- parentid: initEventId !== null && initEventId !== void 0 ? initEventId : event.id,
585
- domain: _dom,
586
- }));
587
- for (_j = 0, _k = Object.entries(result[result.length - 1].otelAttributes); _j < _k.length; _j++) {
588
- _l = _k[_j], key = _l[0], value = _l[1];
589
- span.setAttribute("to_emit.".concat(result.length - 1, ".").concat(key), value);
590
- }
591
- }
592
- return [2 /*return*/, {
593
- events: result,
594
- }];
595
- case 6: return [4 /*yield*/, this.syncEventResource.releaseLock(event, acquiredLock, span)];
596
- case 7:
597
- _0.sent();
598
- span.end();
599
- return [7 /*endfinally*/];
600
- case 8: return [2 /*return*/];
601
- }
602
- });
603
- }); },
604
- })];
605
- case 1: return [2 /*return*/, _b.sent()];
144
+ if (inputValidation.type === 'INVALID_DATA' || inputValidation.type === 'INVALID') {
145
+ throw new errors_1.ContractViolation("Input validation failed - Event data does not meet contract requirements: ".concat(inputValidation.error.message));
146
+ }
147
+ executionResult = this.executionEngine.execute({ state: (_c = state === null || state === void 0 ? void 0 : state.state) !== null && _c !== void 0 ? _c : null, event: event, machine: machine }, { inheritFrom: 'CONTEXT' });
148
+ span.setAttribute('arvo.orchestration.status', executionResult.state.status);
149
+ rawMachineEmittedEvents = executionResult.events;
150
+ if (executionResult.finalOutput) {
151
+ rawMachineEmittedEvents.push({
152
+ type: machine.contracts.self.metadata.completeEventType,
153
+ id: executionResult.finalOutput.__id,
154
+ data: executionResult.finalOutput,
155
+ to: (_e = (_d = parsedEventSubject.meta) === null || _d === void 0 ? void 0 : _d.redirectto) !== null && _e !== void 0 ? _e : parsedEventSubject.execution.initiator,
156
+ domain: orchestrationParentSubject
157
+ ? [arvo_core_1.ArvoOrchestrationSubject.parse(orchestrationParentSubject).execution.domain]
158
+ : [null],
159
+ });
160
+ }
161
+ emittables = (0, createEmitableEvent_1.processRawEventsIntoEmittables)({
162
+ rawEvents: rawMachineEmittedEvents,
163
+ otelHeaders: otelHeaders,
164
+ orchestrationParentSubject: orchestrationParentSubject,
165
+ sourceEvent: event,
166
+ selfContract: machine.contracts.self,
167
+ serviceContracts: machine.contracts.services,
168
+ initEventId: initEventId,
169
+ executionunits: this.executionunits,
170
+ source: this.source,
171
+ }, span);
172
+ (0, arvo_core_1.logToSpan)({
173
+ level: 'INFO',
174
+ message: "Machine execution completed - Status: ".concat(executionResult.state.status, ", Generated events: ").concat(emittables.length),
175
+ }, span);
176
+ newState = {
177
+ executionStatus: 'normal',
178
+ initEventId: initEventId,
179
+ subject: event.subject,
180
+ parentSubject: orchestrationParentSubject,
181
+ status: executionResult.state.status,
182
+ value: (_f = executionResult.state.value) !== null && _f !== void 0 ? _f : null,
183
+ state: executionResult.state,
184
+ events: {
185
+ consumed: event.toJSON(),
186
+ produced: emittables.map(function (item) { return item.toJSON(); }),
187
+ },
188
+ machineDefinition: JSON.stringify(machine.logic.config),
189
+ };
190
+ return [2 /*return*/, { emittables: emittables, newState: newState }];
191
+ });
192
+ }); })];
193
+ case 1: return [2 /*return*/, _a.sent()];
606
194
  }
607
195
  });
608
196
  });
@@ -621,5 +209,5 @@ var ArvoOrchestrator = /** @class */ (function (_super) {
621
209
  configurable: true
622
210
  });
623
211
  return ArvoOrchestrator;
624
- }(AbstractArvoEventHandler_1.default));
212
+ }());
625
213
  exports.ArvoOrchestrator = ArvoOrchestrator;