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) {
@@ -70,19 +44,13 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
70
44
  }
71
45
  return to.concat(ar || Array.prototype.slice.call(from));
72
46
  };
73
- var __importDefault = (this && this.__importDefault) || function (mod) {
74
- return (mod && mod.__esModule) ? mod : { "default": mod };
75
- };
76
47
  Object.defineProperty(exports, "__esModule", { value: true });
77
48
  exports.ArvoResumable = void 0;
78
- var api_1 = require("@opentelemetry/api");
79
49
  var arvo_core_1 = require("arvo-core");
80
- var error_1 = require("../ArvoOrchestrator/error");
50
+ var createEmitableEvent_1 = require("../ArvoOrchestrationUtils/createEmitableEvent");
51
+ var orchestrationExecutionWrapper_1 = require("../ArvoOrchestrationUtils/orchestrationExecutionWrapper");
81
52
  var index_1 = require("../SyncEventResource/index");
82
- var index_2 = require("../utils/index");
83
- var AbstractArvoEventHandler_1 = __importDefault(require("../AbstractArvoEventHandler"));
84
53
  var errors_1 = require("../errors");
85
- var ArvoDomain_1 = require("../ArvoDomain");
86
54
  /**
87
55
  * ArvoResumable - A stateful orchestration handler for managing distributed workflows
88
56
  *
@@ -114,19 +82,16 @@ var ArvoDomain_1 = require("../ArvoDomain");
114
82
  * @see {@link ArvoResumableHandler} Handler interface documentation
115
83
  * @see {@link ArvoResumableState} State structure documentation
116
84
  */
117
- var ArvoResumable = /** @class */ (function (_super) {
118
- __extends(ArvoResumable, _super);
85
+ var ArvoResumable = /** @class */ (function () {
119
86
  function ArvoResumable(param) {
120
87
  var _a;
121
- var _this = _super.call(this) || this;
122
- _this.systemErrorDomain = [];
123
- _this.executionunits = param.executionunits;
124
- _this.source = param.contracts.self.type;
125
- _this.syncEventResource = new index_1.SyncEventResource(param.memory, (_a = param.requiresResourceLocking) !== null && _a !== void 0 ? _a : true);
126
- _this.contracts = param.contracts;
127
- _this.handler = param.handler;
128
- _this.systemErrorDomain = param.systemErrorDomain;
129
- return _this;
88
+ this.systemErrorDomain = [];
89
+ this.executionunits = param.executionunits;
90
+ this.source = param.contracts.self.type;
91
+ this.syncEventResource = new index_1.SyncEventResource(param.memory, (_a = param.requiresResourceLocking) !== null && _a !== void 0 ? _a : true);
92
+ this.contracts = param.contracts;
93
+ this.handler = param.handler;
94
+ this.systemErrorDomain = param.systemErrorDomain;
130
95
  }
131
96
  Object.defineProperty(ArvoResumable.prototype, "requiresResourceLocking", {
132
97
  get: function () {
@@ -149,7 +114,7 @@ var ArvoResumable = /** @class */ (function (_super) {
149
114
  enumerable: false,
150
115
  configurable: true
151
116
  });
152
- ArvoResumable.prototype.validateInput = function (event) {
117
+ ArvoResumable.prototype.validateInput = function (event, span) {
153
118
  var _a;
154
119
  var resolvedContract = null;
155
120
  var contractType;
@@ -183,7 +148,7 @@ var ArvoResumable = /** @class */ (function (_super) {
183
148
  (0, arvo_core_1.logToSpan)({
184
149
  level: 'INFO',
185
150
  message: "Dataschema resolved: ".concat(event.dataschema, " matches contract(uri='").concat(resolvedContract.uri, "', version='").concat(resolvedContract.version, "')"),
186
- });
151
+ }, span);
187
152
  if (parsedEventDataSchema.uri !== resolvedContract.uri) {
188
153
  throw new Error("Contract URI mismatch: ".concat(contractType, " Contract(uri='").concat(resolvedContract.uri, "', type='").concat(resolvedContract.accepts.type, "') does not match Event(dataschema='").concat(event.dataschema, "', type='").concat(event.type, "')"));
189
154
  }
@@ -197,147 +162,6 @@ var ArvoResumable = /** @class */ (function (_super) {
197
162
  validationSchema.parse(event.data);
198
163
  return { contractType: contractType };
199
164
  };
200
- /**
201
- * Creates emittable event from execution result
202
- * @param event - Source event to emit
203
- * @param otelHeaders - OpenTelemetry headers
204
- * @param orchestrationParentSubject - Parent orchestration subject
205
- * @param sourceEvent - Original triggering event
206
- * @param selfVersionedContract - The self versioned contract
207
- * @param initEventId - The id of the event which initiated the orchestration in the first place
208
- * @param _domain - The domain of the event.
209
- *
210
- * @throws {ContractViolation} On schema/contract mismatch
211
- * @throws {ExecutionViolation} On invalid parentSubject$$ format
212
- */
213
- ArvoResumable.prototype.createEmittableEvent = function (event, otelHeaders, orchestrationParentSubject, sourceEvent, selfVersionedContract, initEventId, _domain) {
214
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
215
- (0, arvo_core_1.logToSpan)({
216
- level: 'INFO',
217
- message: "Creating emittable event: ".concat(event.type),
218
- });
219
- var serviceContract = Object.fromEntries(Object.values(this.contracts.services).map(function (item) { return [item.accepts.type, item]; }));
220
- var schema = null;
221
- var contract = null;
222
- var subject = sourceEvent.subject;
223
- var parentId = sourceEvent.id;
224
- var domain = (0, ArvoDomain_1.resolveEventDomain)({
225
- domainToResolve: _domain,
226
- handlerSelfContract: selfVersionedContract,
227
- eventContract: null,
228
- triggeringEvent: sourceEvent,
229
- });
230
- if (event.type === selfVersionedContract.metadata.completeEventType) {
231
- (0, arvo_core_1.logToSpan)({
232
- level: 'INFO',
233
- message: "Creating event for machine workflow completion: ".concat(event.type),
234
- });
235
- contract = selfVersionedContract;
236
- schema = selfVersionedContract.emits[selfVersionedContract.metadata.completeEventType];
237
- subject = orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : sourceEvent.subject;
238
- parentId = initEventId;
239
- domain = (0, ArvoDomain_1.resolveEventDomain)({
240
- domainToResolve: _domain,
241
- handlerSelfContract: selfVersionedContract,
242
- eventContract: selfVersionedContract,
243
- triggeringEvent: sourceEvent,
244
- });
245
- }
246
- else if (serviceContract[event.type]) {
247
- (0, arvo_core_1.logToSpan)({
248
- level: 'INFO',
249
- message: "Creating service event for external system: ".concat(event.type),
250
- });
251
- contract = serviceContract[event.type];
252
- schema = serviceContract[event.type].accepts.schema;
253
- domain = (0, ArvoDomain_1.resolveEventDomain)({
254
- domainToResolve: _domain,
255
- handlerSelfContract: selfVersionedContract,
256
- eventContract: contract,
257
- triggeringEvent: sourceEvent,
258
- });
259
- // If the event is to call another orchestrator then, extract the parent subject
260
- // passed to it and then form an new subject. This allows for event chaining
261
- // between orchestrators
262
- if (contract.metadata.contractType === 'ArvoOrchestratorContract') {
263
- if (event.data.parentSubject$$) {
264
- try {
265
- arvo_core_1.ArvoOrchestrationSubject.parse(event.data.parentSubject$$);
266
- }
267
- catch (_m) {
268
- 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."));
269
- }
270
- }
271
- try {
272
- if (event.data.parentSubject$$) {
273
- subject = arvo_core_1.ArvoOrchestrationSubject.from({
274
- orchestator: contract.accepts.type,
275
- version: contract.version,
276
- subject: event.data.parentSubject$$,
277
- domain: domain !== null && domain !== void 0 ? domain : null,
278
- meta: {
279
- redirectto: (_b = event.redirectto) !== null && _b !== void 0 ? _b : this.source,
280
- },
281
- });
282
- }
283
- else {
284
- subject = arvo_core_1.ArvoOrchestrationSubject.new({
285
- version: contract.version,
286
- orchestator: contract.accepts.type,
287
- initiator: this.source,
288
- domain: domain !== null && domain !== void 0 ? domain : undefined,
289
- meta: {
290
- redirectto: (_c = event.redirectto) !== null && _c !== void 0 ? _c : this.source,
291
- },
292
- });
293
- }
294
- }
295
- catch (error) {
296
- // This is a execution violation because it indicates faulty parent subject
297
- // or some fundamental error with subject creation which must be not be propagated
298
- // any further and investigated manually.
299
- 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));
300
- }
301
- }
302
- }
303
- var finalDataschema = event.dataschema;
304
- var finalData = event.data;
305
- // finally if the contract and the schema are available
306
- // then use them to validate the event. Otherwise just use
307
- // the data from the incoming event which is raw and created
308
- // by the machine
309
- if (contract && schema) {
310
- try {
311
- finalData = schema.parse(event.data);
312
- finalDataschema = arvo_core_1.EventDataschemaUtil.create(contract);
313
- }
314
- catch (error) {
315
- 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));
316
- }
317
- }
318
- // Create the event
319
- var emittableEvent = (0, arvo_core_1.createArvoEvent)({
320
- source: this.source,
321
- type: event.type,
322
- subject: subject,
323
- dataschema: finalDataschema !== null && finalDataschema !== void 0 ? finalDataschema : undefined,
324
- data: finalData,
325
- to: (_d = event.to) !== null && _d !== void 0 ? _d : event.type,
326
- accesscontrol: (_f = (_e = event.accesscontrol) !== null && _e !== void 0 ? _e : sourceEvent.accesscontrol) !== null && _f !== void 0 ? _f : undefined,
327
- // The orchestrator/ resumable does not respect redirectto from the source event
328
- redirectto: (_g = event.redirectto) !== null && _g !== void 0 ? _g : this.source,
329
- executionunits: (_h = event.executionunits) !== null && _h !== void 0 ? _h : this.executionunits,
330
- traceparent: (_j = otelHeaders.traceparent) !== null && _j !== void 0 ? _j : undefined,
331
- tracestate: (_k = otelHeaders.tracestate) !== null && _k !== void 0 ? _k : undefined,
332
- parentid: parentId,
333
- domain: domain !== null && domain !== void 0 ? domain : undefined,
334
- }, (_l = event.__extensions) !== null && _l !== void 0 ? _l : {});
335
- (0, arvo_core_1.logToSpan)({
336
- level: 'INFO',
337
- message: "Event created successfully: ".concat(emittableEvent.type),
338
- });
339
- return emittableEvent;
340
- };
341
165
  /**
342
166
  * Executes the orchestration workflow for an incoming event
343
167
  *
@@ -353,82 +177,31 @@ var ArvoResumable = /** @class */ (function (_super) {
353
177
  */
354
178
  ArvoResumable.prototype.execute = function (event, opentelemetry) {
355
179
  return __awaiter(this, void 0, void 0, function () {
356
- var _a;
357
180
  var _this = this;
358
- return __generator(this, function (_b) {
359
- return [2 /*return*/, arvo_core_1.ArvoOpenTelemetry.getInstance().startActiveSpan({
360
- name: "Resumable<".concat(this.contracts.self.uri, ">@<").concat(event.type, ">"),
361
- spanOptions: {
362
- kind: api_1.SpanKind.PRODUCER,
363
- 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) {
364
- var key = _a[0], value = _a[1];
365
- return ["to_process.0.".concat(key), value];
366
- }))),
367
- },
368
- context: opentelemetry.inheritFrom === 'EVENT'
369
- ? {
370
- inheritFrom: 'TRACE_HEADERS',
371
- traceHeaders: {
372
- traceparent: event.traceparent,
373
- tracestate: event.tracestate,
374
- },
375
- }
376
- : {
377
- inheritFrom: 'CONTEXT',
378
- context: api_1.context.active(),
379
- },
380
- disableSpanManagement: true,
381
- fn: function (span) { return __awaiter(_this, void 0, void 0, function () {
382
- var otelHeaders, orchestrationParentSubject, acquiredLock, initEventId, parsedEventSubject, contractType, state, eventTypeToExpectedEvent, _i, _a, _b, _, eventList, _c, eventList_1, _evt, handler, executionResult, emittables, _d, _e, item, createdDomain, _f, _g, _dom, evt, _h, _j, _k, key, value, eventTrackingState, error_2, e, parsedEventSubject, result, _l, _m, _dom, _o, _p, _q, key, value;
383
- var _this = this;
384
- var _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12;
385
- return __generator(this, function (_13) {
386
- switch (_13.label) {
181
+ return __generator(this, function (_a) {
182
+ switch (_a.label) {
183
+ case 0: return [4 /*yield*/, (0, orchestrationExecutionWrapper_1.executeWithOrchestrationWrapper)({
184
+ _handlerType: 'resumable',
185
+ event: event,
186
+ opentelemetry: opentelemetry,
187
+ spanName: "Resumable<".concat(this.contracts.self.uri, ">@<").concat(event.type, ">"),
188
+ source: this.source,
189
+ syncEventResource: this.syncEventResource,
190
+ executionunits: this.executionunits,
191
+ systemErrorDomain: this.systemErrorDomain,
192
+ selfContract: this.contracts.self.version('latest'),
193
+ domain: this.domain,
194
+ }, function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
195
+ var contractType, eventTypeToExpectedEvent, _i, _c, _d, _, eventList, _e, eventList_1, _evt, handler, versionedSelfContract, executionResult, rawEvents, emittables, eventTrackingState, newState;
196
+ var _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
197
+ var span = _b.span, otelHeaders = _b.otelHeaders, orchestrationParentSubject = _b.orchestrationParentSubject, initEventId = _b.initEventId, parsedEventSubject = _b.parsedEventSubject, state = _b.state;
198
+ return __generator(this, function (_v) {
199
+ switch (_v.label) {
387
200
  case 0:
388
201
  (0, arvo_core_1.logToSpan)({
389
202
  level: 'INFO',
390
- message: "Resumable function starting execution for ".concat(event.type, " on subject ").concat(event.subject),
391
- });
392
- otelHeaders = (0, arvo_core_1.currentOpenTelemetryHeaders)();
393
- orchestrationParentSubject = null;
394
- acquiredLock = null;
395
- initEventId = null;
396
- _13.label = 1;
397
- case 1:
398
- _13.trys.push([1, 6, 7, 9]);
399
- ///////////////////////////////////////////////////////////////
400
- // Subject resolution, handler resolution and input validation
401
- ///////////////
402
- // ////////////////////////////////////////////////
403
- this.syncEventResource.validateEventSubject(event);
404
- parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject);
405
- span.setAttributes({
406
- 'arvo.parsed.subject.orchestrator.name': parsedEventSubject.orchestrator.name,
407
- 'arvo.parsed.subject.orchestrator.version': parsedEventSubject.orchestrator.version,
408
- });
409
- // The wrong source is not a big violation. May be some routing went wrong. So just ignore the event
410
- if (parsedEventSubject.orchestrator.name !== this.source) {
411
- (0, arvo_core_1.logToSpan)({
412
- level: 'WARNING',
413
- 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."),
414
- });
415
- (0, arvo_core_1.logToSpan)({
416
- level: 'INFO',
417
- message: 'Orchestration executed with issues and emitted 0 events',
418
- });
419
- return [2 /*return*/, {
420
- events: [],
421
- allEventDomains: [],
422
- domainedEvents: {
423
- all: [],
424
- },
425
- }];
426
- }
427
- (0, arvo_core_1.logToSpan)({
428
- level: 'INFO',
429
- message: "Resolving machine for event ".concat(event.type),
430
- });
431
- // Handler not found means that the handler is not defined which is not allowed and a critical bug
203
+ message: "Resolving handler for event ".concat(event.type),
204
+ }, span);
432
205
  if (!this.handler[parsedEventSubject.orchestrator.version]) {
433
206
  throw new errors_1.ConfigViolation("Handler resolution failed: No handler found matching orchestrator name='".concat(parsedEventSubject.orchestrator.name, "' and version='").concat(parsedEventSubject.orchestrator.version, "'."));
434
207
  }
@@ -436,79 +209,28 @@ var ArvoResumable = /** @class */ (function (_super) {
436
209
  level: 'INFO',
437
210
  message: "Input validation started for event ".concat(event.type),
438
211
  });
439
- contractType = this.validateInput(event).contractType;
440
- return [4 /*yield*/, this.syncEventResource.acquireLock(event)];
441
- case 2:
442
- ///////////////////////////////////////////////////////////////
443
- // State locking, acquiry and handler exection
444
- ///////////////////////////////////////////////////////////////
445
- acquiredLock = _13.sent();
446
- if (acquiredLock === 'NOT_ACQUIRED') {
447
- throw new error_1.TransactionViolation({
448
- cause: error_1.TransactionViolationCause.LOCK_UNACQUIRED,
449
- message: 'Lock acquisition denied - Unable to obtain exclusive access to event processing',
450
- initiatingEvent: event,
451
- });
452
- }
453
- if (acquiredLock === 'ACQUIRED') {
454
- (0, arvo_core_1.logToSpan)({
455
- level: 'INFO',
456
- message: "This execution acquired lock at resource '".concat(event.subject, "'"),
457
- });
458
- }
459
- return [4 /*yield*/, this.syncEventResource.acquireState(event)];
460
- case 3:
461
- state = _13.sent();
462
- orchestrationParentSubject = (_r = state === null || state === void 0 ? void 0 : state.parentSubject) !== null && _r !== void 0 ? _r : null;
463
- initEventId = (_s = state === null || state === void 0 ? void 0 : state.initEventId) !== null && _s !== void 0 ? _s : event.id;
212
+ contractType = this.validateInput(event, span).contractType;
464
213
  if ((state === null || state === void 0 ? void 0 : state.status) === 'done') {
465
214
  (0, arvo_core_1.logToSpan)({
466
215
  level: 'INFO',
467
216
  message: "The resumable has already reached the terminal state. Ignoring event(id=".concat(event.id, ")"),
468
217
  });
469
218
  return [2 /*return*/, {
470
- events: [],
219
+ emittables: [],
220
+ newState: state,
471
221
  }];
472
222
  }
473
- if (!state) {
474
- (0, arvo_core_1.logToSpan)({
475
- level: 'INFO',
476
- message: "Initializing new execution state for subject: ".concat(event.subject),
477
- });
478
- if (event.type !== this.source) {
479
- (0, arvo_core_1.logToSpan)({
480
- level: 'WARNING',
481
- 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."),
482
- });
483
- return [2 /*return*/, {
484
- events: [],
485
- }];
486
- }
487
- }
488
- else {
489
- (0, arvo_core_1.logToSpan)({
490
- level: 'INFO',
491
- message: "Resuming execution with existing state for subject: ".concat(event.subject),
492
- });
493
- }
494
- // In case the event is the init event then
495
- // extract the parent subject from it and assume
496
- // it to be the orchestration parent subject
497
- if (event.type === this.source) {
498
- orchestrationParentSubject = (_u = (_t = event === null || event === void 0 ? void 0 : event.data) === null || _t === void 0 ? void 0 : _t.parentSubject$$) !== null && _u !== void 0 ? _u : null;
499
- }
500
- // This is not persisted until handling. The reason is that if the event
501
- // is causing a fault then what is the point of persisting it
223
+ // Track expected events
502
224
  if (event.parentid &&
503
- ((_w = (_v = state === null || state === void 0 ? void 0 : state.events) === null || _v === void 0 ? void 0 : _v.expected) === null || _w === void 0 ? void 0 : _w[event.parentid]) &&
504
- Array.isArray((_y = (_x = state === null || state === void 0 ? void 0 : state.events) === null || _x === void 0 ? void 0 : _x.expected) === null || _y === void 0 ? void 0 : _y[event.parentid])) {
225
+ ((_g = (_f = state === null || state === void 0 ? void 0 : state.events) === null || _f === void 0 ? void 0 : _f.expected) === null || _g === void 0 ? void 0 : _g[event.parentid]) &&
226
+ Array.isArray((_j = (_h = state === null || state === void 0 ? void 0 : state.events) === null || _h === void 0 ? void 0 : _h.expected) === null || _j === void 0 ? void 0 : _j[event.parentid])) {
505
227
  state.events.expected[event.parentid].push(event.toJSON());
506
228
  }
507
229
  eventTypeToExpectedEvent = {};
508
- for (_i = 0, _a = Object.entries((_0 = (_z = state === null || state === void 0 ? void 0 : state.events) === null || _z === void 0 ? void 0 : _z.expected) !== null && _0 !== void 0 ? _0 : {}); _i < _a.length; _i++) {
509
- _b = _a[_i], _ = _b[0], eventList = _b[1];
510
- for (_c = 0, eventList_1 = eventList; _c < eventList_1.length; _c++) {
511
- _evt = eventList_1[_c];
230
+ for (_i = 0, _c = Object.entries((_l = (_k = state === null || state === void 0 ? void 0 : state.events) === null || _k === void 0 ? void 0 : _k.expected) !== null && _l !== void 0 ? _l : {}); _i < _c.length; _i++) {
231
+ _d = _c[_i], _ = _d[0], eventList = _d[1];
232
+ for (_e = 0, eventList_1 = eventList; _e < eventList_1.length; _e++) {
233
+ _evt = eventList_1[_e];
512
234
  if (!eventTypeToExpectedEvent[_evt.type]) {
513
235
  eventTypeToExpectedEvent[_evt.type] = [];
514
236
  }
@@ -516,9 +238,10 @@ var ArvoResumable = /** @class */ (function (_super) {
516
238
  }
517
239
  }
518
240
  handler = this.handler[parsedEventSubject.orchestrator.version];
241
+ versionedSelfContract = this.contracts.self.version(parsedEventSubject.orchestrator.version);
519
242
  return [4 /*yield*/, handler({
520
243
  span: span,
521
- context: (_1 = state === null || state === void 0 ? void 0 : state.state$$) !== null && _1 !== void 0 ? _1 : null,
244
+ context: (_m = state === null || state === void 0 ? void 0 : state.state$$) !== null && _m !== void 0 ? _m : null,
522
245
  metadata: state !== null && state !== void 0 ? state : null,
523
246
  collectedEvents: eventTypeToExpectedEvent,
524
247
  domain: {
@@ -528,43 +251,35 @@ var ArvoResumable = /** @class */ (function (_super) {
528
251
  input: contractType === 'self' ? event.toJSON() : null,
529
252
  service: contractType === 'service' ? event.toJSON() : null,
530
253
  contracts: {
531
- self: this.contracts.self.version(parsedEventSubject.orchestrator.version),
254
+ self: versionedSelfContract,
532
255
  services: this.contracts.services,
533
256
  },
534
257
  })];
535
- case 4:
536
- executionResult = _13.sent();
537
- emittables = [];
538
- for (_d = 0, _e = __spreadArray(__spreadArray([], ((executionResult === null || executionResult === void 0 ? void 0 : executionResult.output)
539
- ? [
540
- {
541
- data: executionResult.output,
542
- type: this.contracts.self.metadata.completeEventType,
543
- to: (_3 = (_2 = parsedEventSubject.meta) === null || _2 === void 0 ? void 0 : _2.redirectto) !== null && _3 !== void 0 ? _3 : parsedEventSubject.execution.initiator,
544
- domain: orchestrationParentSubject
545
- ? [arvo_core_1.ArvoOrchestrationSubject.parse(orchestrationParentSubject).execution.domain]
546
- : [null],
547
- },
548
- ]
549
- : []), true), ((_4 = executionResult === null || executionResult === void 0 ? void 0 : executionResult.services) !== null && _4 !== void 0 ? _4 : []), true); _d < _e.length; _d++) {
550
- item = _e[_d];
551
- createdDomain = new Set(null);
552
- for (_f = 0, _g = Array.from(new Set((_5 = item.domain) !== null && _5 !== void 0 ? _5 : [null])); _f < _g.length; _f++) {
553
- _dom = _g[_f];
554
- evt = this.createEmittableEvent(item, otelHeaders, orchestrationParentSubject, event, this.contracts.self.version(parsedEventSubject.orchestrator.version), initEventId, _dom);
555
- // Making sure the raw event broadcast is actually unique as the
556
- // domain resolution (especially for symbolic) can only happen
557
- // in the createEmittableEvent
558
- if (createdDomain.has(evt.domain))
559
- continue;
560
- createdDomain.add(evt.domain);
561
- emittables.push(evt);
562
- for (_h = 0, _j = Object.entries(emittables[emittables.length - 1].otelAttributes); _h < _j.length; _h++) {
563
- _k = _j[_h], key = _k[0], value = _k[1];
564
- span.setAttribute("to_emit.".concat(emittables.length - 1, ".").concat(key), value);
565
- }
566
- }
258
+ case 1:
259
+ executionResult = _v.sent();
260
+ rawEvents = (_o = executionResult === null || executionResult === void 0 ? void 0 : executionResult.services) !== null && _o !== void 0 ? _o : [];
261
+ if (executionResult === null || executionResult === void 0 ? void 0 : executionResult.output) {
262
+ rawEvents.push({
263
+ id: executionResult.output.__id,
264
+ data: executionResult.output,
265
+ type: this.contracts.self.metadata.completeEventType,
266
+ to: (_q = (_p = parsedEventSubject.meta) === null || _p === void 0 ? void 0 : _p.redirectto) !== null && _q !== void 0 ? _q : parsedEventSubject.execution.initiator,
267
+ domain: orchestrationParentSubject
268
+ ? [arvo_core_1.ArvoOrchestrationSubject.parse(orchestrationParentSubject).execution.domain]
269
+ : [null],
270
+ });
567
271
  }
272
+ emittables = (0, createEmitableEvent_1.processRawEventsIntoEmittables)({
273
+ rawEvents: rawEvents,
274
+ otelHeaders: otelHeaders,
275
+ orchestrationParentSubject: orchestrationParentSubject,
276
+ sourceEvent: event,
277
+ selfContract: versionedSelfContract,
278
+ serviceContracts: this.contracts.services,
279
+ initEventId: initEventId,
280
+ executionunits: this.executionunits,
281
+ source: this.source,
282
+ }, span);
568
283
  (0, arvo_core_1.logToSpan)({
569
284
  level: 'INFO',
570
285
  message: "Resumable execution completed. Generated events: ".concat(emittables.length),
@@ -573,116 +288,24 @@ var ArvoResumable = /** @class */ (function (_super) {
573
288
  consumed: event.toJSON(),
574
289
  expected: emittables.length
575
290
  ? Object.fromEntries(emittables.map(function (item) { return [item.id, []]; }))
576
- : ((_6 = state === null || state === void 0 ? void 0 : state.events.expected) !== null && _6 !== void 0 ? _6 : null),
291
+ : ((_s = (_r = state === null || state === void 0 ? void 0 : state.events) === null || _r === void 0 ? void 0 : _r.expected) !== null && _s !== void 0 ? _s : null),
577
292
  produced: emittables.map(function (item) { return item.toJSON(); }),
578
293
  };
579
- // Write to the memory
580
- return [4 /*yield*/, this.syncEventResource.persistState(event, {
581
- status: (executionResult === null || executionResult === void 0 ? void 0 : executionResult.output) ? 'done' : 'active',
582
- initEventId: initEventId,
583
- parentSubject: orchestrationParentSubject,
584
- subject: event.subject,
585
- events: eventTrackingState,
586
- state$$: (_8 = (_7 = executionResult === null || executionResult === void 0 ? void 0 : executionResult.context) !== null && _7 !== void 0 ? _7 : state === null || state === void 0 ? void 0 : state.state$$) !== null && _8 !== void 0 ? _8 : null,
587
- }, state, span)];
588
- case 5:
589
- // Write to the memory
590
- _13.sent();
591
- (0, arvo_core_1.logToSpan)({
592
- level: 'INFO',
593
- message: "State update persisted in memory for subject ".concat(event.subject),
594
- });
595
- (0, arvo_core_1.logToSpan)({
596
- level: 'INFO',
597
- message: "Resumable successfully executed and emitted ".concat(emittables.length, " events"),
598
- });
599
- return [2 /*return*/, { events: emittables }];
600
- case 6:
601
- error_2 = _13.sent();
602
- e = (0, index_2.isError)(error_2)
603
- ? error_2
604
- : new errors_1.ExecutionViolation("Non-Error object thrown during machine execution: ".concat(typeof error_2, ". This indicates a serious implementation flaw."));
605
- (0, arvo_core_1.exceptionToSpan)(e);
606
- span.setStatus({
607
- code: api_1.SpanStatusCode.ERROR,
608
- message: e.message,
609
- });
610
- // For any violation errors bubble them up to the
611
- // called of the function so that they can
612
- // be handled gracefully
613
- if (e.name.includes('ViolationError')) {
614
- (0, arvo_core_1.logToSpan)({
615
- level: 'CRITICAL',
616
- message: "Resumable violation error: ".concat(e.message),
617
- });
618
- throw e;
619
- }
620
- (0, arvo_core_1.logToSpan)({
621
- level: 'ERROR',
622
- message: "Resumable execution failed: ".concat(e.message),
623
- });
624
- parsedEventSubject = null;
625
- try {
626
- parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject);
627
- }
628
- catch (e) {
629
- (0, arvo_core_1.logToSpan)({
630
- level: 'WARNING',
631
- message: "Unable to parse event subject: ".concat(e.message),
632
- });
633
- }
634
- result = [];
635
- for (_l = 0, _m = Array.from(new Set(this.systemErrorDomain
636
- ? this.systemErrorDomain.map(function (item) {
637
- return (0, ArvoDomain_1.resolveEventDomain)({
638
- domainToResolve: item,
639
- handlerSelfContract: _this.contracts.self.version('latest'),
640
- eventContract: _this.contracts.self.version('latest'),
641
- triggeringEvent: event,
642
- });
643
- })
644
- : [event.domain, this.domain, null])); _l < _m.length; _l++) {
645
- _dom = _m[_l];
646
- result.push((0, arvo_core_1.createArvoOrchestratorEventFactory)(this.contracts.self.version('latest')).systemError({
647
- source: this.source,
648
- // If the initiator of the workflow exist then match the
649
- // subject so that it can incorporate it in its state. If
650
- // parent does not exist then this is the root workflow so
651
- // use its own subject
652
- subject: orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : event.subject,
653
- // The system error must always go back to
654
- // the source which initiated it
655
- to: (_9 = parsedEventSubject === null || parsedEventSubject === void 0 ? void 0 : parsedEventSubject.execution.initiator) !== null && _9 !== void 0 ? _9 : event.source,
656
- error: e,
657
- traceparent: (_10 = otelHeaders.traceparent) !== null && _10 !== void 0 ? _10 : undefined,
658
- tracestate: (_11 = otelHeaders.tracestate) !== null && _11 !== void 0 ? _11 : undefined,
659
- accesscontrol: (_12 = event.accesscontrol) !== null && _12 !== void 0 ? _12 : undefined,
660
- executionunits: this.executionunits,
661
- // If there is initEventID then use that.
662
- // Otherwise, use event id. If the error is in init event
663
- // then it will be the same as initEventId. Otherwise,
664
- // we still would know what cause this error
665
- parentid: initEventId !== null && initEventId !== void 0 ? initEventId : event.id,
666
- domain: _dom,
667
- }));
668
- for (_o = 0, _p = Object.entries(result[result.length - 1].otelAttributes); _o < _p.length; _o++) {
669
- _q = _p[_o], key = _q[0], value = _q[1];
670
- span.setAttribute("to_emit.".concat(result.length - 1, ".").concat(key), value);
671
- }
672
- }
673
- return [2 /*return*/, {
674
- events: result,
675
- }];
676
- case 7: return [4 /*yield*/, this.syncEventResource.releaseLock(event, acquiredLock, span)];
677
- case 8:
678
- _13.sent();
679
- span.end();
680
- return [7 /*endfinally*/];
681
- case 9: return [2 /*return*/];
294
+ newState = {
295
+ executionStatus: 'normal',
296
+ status: (executionResult === null || executionResult === void 0 ? void 0 : executionResult.output) ? 'done' : 'active',
297
+ initEventId: initEventId,
298
+ parentSubject: orchestrationParentSubject,
299
+ subject: event.subject,
300
+ events: eventTrackingState,
301
+ state$$: (_u = (_t = executionResult === null || executionResult === void 0 ? void 0 : executionResult.context) !== null && _t !== void 0 ? _t : state === null || state === void 0 ? void 0 : state.state$$) !== null && _u !== void 0 ? _u : null,
302
+ };
303
+ return [2 /*return*/, { emittables: emittables, newState: newState }];
682
304
  }
683
305
  });
684
- }); },
685
- })];
306
+ }); })];
307
+ case 1: return [2 /*return*/, _a.sent()];
308
+ }
686
309
  });
687
310
  });
688
311
  };
@@ -694,5 +317,5 @@ var ArvoResumable = /** @class */ (function (_super) {
694
317
  configurable: true
695
318
  });
696
319
  return ArvoResumable;
697
- }(AbstractArvoEventHandler_1.default));
320
+ }());
698
321
  exports.ArvoResumable = ArvoResumable;