UNPKG

arvo-event-handler

Version:

Type-safe event handler system with versioning, telemetry, and contract validation for distributed Arvo event-driven architectures, featuring routing and multi-handler support.

699 lines (698 loc) 48.4 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ArvoResumable = void 0; var api_1 = require("@opentelemetry/api"); var arvo_core_1 = require("arvo-core"); var error_1 = require("../ArvoOrchestrator/error"); var index_1 = require("../SyncEventResource/index"); var index_2 = require("../utils/index"); var AbstractArvoEventHandler_1 = __importDefault(require("../AbstractArvoEventHandler")); var errors_1 = require("../errors"); var ArvoDomain_1 = require("../ArvoDomain"); /** * ArvoResumable - A stateful orchestration handler for managing distributed workflows * * ArvoResumable provides a handler-based approach to workflow orchestration that prioritizes * explicit control and simplicity over declarative abstractions. It excels at straightforward * request-response patterns and linear workflows while maintaining full type safety and * contract validation throughout the execution lifecycle. * * This class addresses fundamental issues in event-driven architecture including: * - Contract management with runtime validation and type safety * - Graduated complexity allowing simple workflows to remain simple * - Unified event handling across initialization and service responses * - Explicit state management without hidden abstractions * * Key capabilities: * - Handler-based workflow orchestration with explicit state control * - Contract-driven event validation with runtime schema enforcement * - Distributed resource locking for transaction safety * - Comprehensive OpenTelemetry integration for observability * - Automatic error handling with system error event generation * - Support for orchestrator chaining and nested workflow patterns * - Domain-based event routing and organization * * Unlike state machine approaches, ArvoResumable uses imperative handler functions * that provide direct control over workflow logic. This makes debugging easier and * reduces the learning curve for teams familiar with traditional programming patterns. * * @see {@link createArvoResumable} Factory function for creating instances * @see {@link ArvoResumableHandler} Handler interface documentation * @see {@link ArvoResumableState} State structure documentation */ var ArvoResumable = /** @class */ (function (_super) { __extends(ArvoResumable, _super); function ArvoResumable(param) { var _a; var _this = _super.call(this) || this; _this.systemErrorDomain = []; _this.executionunits = param.executionunits; _this.source = param.contracts.self.type; _this.syncEventResource = new index_1.SyncEventResource(param.memory, (_a = param.requiresResourceLocking) !== null && _a !== void 0 ? _a : true); _this.contracts = param.contracts; _this.handler = param.handler; _this.systemErrorDomain = param.systemErrorDomain; return _this; } Object.defineProperty(ArvoResumable.prototype, "requiresResourceLocking", { get: function () { return this.syncEventResource.requiresResourceLocking; }, enumerable: false, configurable: true }); Object.defineProperty(ArvoResumable.prototype, "memory", { get: function () { return this.syncEventResource.memory; }, enumerable: false, configurable: true }); Object.defineProperty(ArvoResumable.prototype, "domain", { get: function () { return this.contracts.self.domain; }, enumerable: false, configurable: true }); ArvoResumable.prototype.validateInput = function (event) { var _a; var resolvedContract = null; var contractType; var parsedEventDataSchema = arvo_core_1.EventDataschemaUtil.parse(event); if (!parsedEventDataSchema) { throw new errors_1.ExecutionViolation("Event dataschema resolution failed: Unable to parse dataschema='".concat(event.dataschema, "' for event(id='").concat(event.id, "', type='").concat(event.type, "'). This makes the event opaque and does not allow contract resolution")); } if (event.type === this.contracts.self.type) { contractType = 'self'; resolvedContract = this.contracts.self.version(parsedEventDataSchema.version); } else { contractType = 'service'; for (var _i = 0, _b = Object.values(this.contracts.services); _i < _b.length; _i++) { var contract = _b[_i]; if (resolvedContract) break; for (var _c = 0, _d = __spreadArray(__spreadArray([], contract.emitList, true), [contract.systemError], false); _c < _d.length; _c++) { var emitType = _d[_c]; if (resolvedContract) break; if (event.type === emitType.type) { resolvedContract = contract; } } } } if (!resolvedContract) { throw new errors_1.ConfigViolation("Contract resolution failed: No matching contract found for event (id='".concat(event.id, "', type='").concat(event.type, "')")); } (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Dataschema resolved: ".concat(event.dataschema, " matches contract(uri='").concat(resolvedContract.uri, "', version='").concat(resolvedContract.version, "')"), }); if (parsedEventDataSchema.uri !== resolvedContract.uri) { 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, "')")); } if (!(0, arvo_core_1.isWildCardArvoSematicVersion)(parsedEventDataSchema.version) && parsedEventDataSchema.version !== resolvedContract.version) { throw new Error("Contract version mismatch: ".concat(contractType, " Contract(version='").concat(resolvedContract.version, "', type='").concat(resolvedContract.accepts.type, "', uri=").concat(resolvedContract.uri, ") does not match Event(dataschema='").concat(event.dataschema, "', type='").concat(event.type, "')")); } var validationSchema = contractType === 'self' ? resolvedContract.accepts.schema : ((_a = resolvedContract.emits[event.type]) !== null && _a !== void 0 ? _a : resolvedContract.systemError.schema); validationSchema.parse(event.data); return { contractType: contractType }; }; /** * Creates emittable event from execution result * @param event - Source event to emit * @param otelHeaders - OpenTelemetry headers * @param orchestrationParentSubject - Parent orchestration subject * @param sourceEvent - Original triggering event * @param selfVersionedContract - The self versioned contract * @param initEventId - The id of the event which initiated the orchestration in the first place * @param _domain - The domain of the event. * * @throws {ContractViolation} On schema/contract mismatch * @throws {ExecutionViolation} On invalid parentSubject$$ format */ ArvoResumable.prototype.createEmittableEvent = function (event, otelHeaders, orchestrationParentSubject, sourceEvent, selfVersionedContract, initEventId, _domain) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Creating emittable event: ".concat(event.type), }); var serviceContract = Object.fromEntries(Object.values(this.contracts.services).map(function (item) { return [item.accepts.type, item]; })); var schema = null; var contract = null; var subject = sourceEvent.subject; var parentId = sourceEvent.id; var domain = (0, ArvoDomain_1.resolveEventDomain)({ domainToResolve: _domain, handlerSelfContract: selfVersionedContract, eventContract: null, triggeringEvent: sourceEvent, }); if (event.type === selfVersionedContract.metadata.completeEventType) { (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Creating event for machine workflow completion: ".concat(event.type), }); contract = selfVersionedContract; schema = selfVersionedContract.emits[selfVersionedContract.metadata.completeEventType]; subject = orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : sourceEvent.subject; parentId = initEventId; domain = (0, ArvoDomain_1.resolveEventDomain)({ domainToResolve: _domain, handlerSelfContract: selfVersionedContract, eventContract: selfVersionedContract, triggeringEvent: sourceEvent, }); } else if (serviceContract[event.type]) { (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Creating service event for external system: ".concat(event.type), }); contract = serviceContract[event.type]; schema = serviceContract[event.type].accepts.schema; domain = (0, ArvoDomain_1.resolveEventDomain)({ domainToResolve: _domain, handlerSelfContract: selfVersionedContract, eventContract: contract, triggeringEvent: sourceEvent, }); // If the event is to call another orchestrator then, extract the parent subject // passed to it and then form an new subject. This allows for event chaining // between orchestrators if (contract.metadata.contractType === 'ArvoOrchestratorContract') { if (event.data.parentSubject$$) { try { arvo_core_1.ArvoOrchestrationSubject.parse(event.data.parentSubject$$); } catch (_m) { 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.")); } } try { if (event.data.parentSubject$$) { subject = arvo_core_1.ArvoOrchestrationSubject.from({ orchestator: contract.accepts.type, version: contract.version, subject: event.data.parentSubject$$, domain: domain !== null && domain !== void 0 ? domain : null, meta: { redirectto: (_b = event.redirectto) !== null && _b !== void 0 ? _b : this.source, }, }); } else { subject = arvo_core_1.ArvoOrchestrationSubject.new({ version: contract.version, orchestator: contract.accepts.type, initiator: this.source, domain: domain !== null && domain !== void 0 ? domain : undefined, meta: { redirectto: (_c = event.redirectto) !== null && _c !== void 0 ? _c : this.source, }, }); } } catch (error) { // This is a execution violation because it indicates faulty parent subject // or some fundamental error with subject creation which must be not be propagated // any further and investigated manually. 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)); } } } var finalDataschema = event.dataschema; var finalData = event.data; // finally if the contract and the schema are available // then use them to validate the event. Otherwise just use // the data from the incoming event which is raw and created // by the machine if (contract && schema) { try { finalData = schema.parse(event.data); finalDataschema = arvo_core_1.EventDataschemaUtil.create(contract); } catch (error) { 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)); } } // Create the event var emittableEvent = (0, arvo_core_1.createArvoEvent)({ source: this.source, type: event.type, subject: subject, dataschema: finalDataschema !== null && finalDataschema !== void 0 ? finalDataschema : undefined, data: finalData, to: (_d = event.to) !== null && _d !== void 0 ? _d : event.type, accesscontrol: (_f = (_e = event.accesscontrol) !== null && _e !== void 0 ? _e : sourceEvent.accesscontrol) !== null && _f !== void 0 ? _f : undefined, // The orchestrator/ resumable does not respect redirectto from the source event redirectto: (_g = event.redirectto) !== null && _g !== void 0 ? _g : this.source, executionunits: (_h = event.executionunits) !== null && _h !== void 0 ? _h : this.executionunits, traceparent: (_j = otelHeaders.traceparent) !== null && _j !== void 0 ? _j : undefined, tracestate: (_k = otelHeaders.tracestate) !== null && _k !== void 0 ? _k : undefined, parentid: parentId, domain: domain !== null && domain !== void 0 ? domain : undefined, }, (_l = event.__extensions) !== null && _l !== void 0 ? _l : {}); (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Event created successfully: ".concat(emittableEvent.type), }); return emittableEvent; }; /** * Executes the orchestration workflow for an incoming event * * @param event - The triggering event to process * @param opentelemetry - OpenTelemetry configuration for trace inheritance * * @returns Object containing domained events * * @throws {TransactionViolation} When distributed lock acquisition fails * @throws {ConfigViolation} When handler resolution or contract validation fails * @throws {ContractViolation} When event schema validation fails * @throws {ExecutionViolation} When workflow execution encounters critical errors */ ArvoResumable.prototype.execute = function (event, opentelemetry) { return __awaiter(this, void 0, void 0, function () { var _a; var _this = this; return __generator(this, function (_b) { return [2 /*return*/, arvo_core_1.ArvoOpenTelemetry.getInstance().startActiveSpan({ name: "Resumable<".concat(this.contracts.self.uri, ">@<").concat(event.type, ">"), spanOptions: { kind: api_1.SpanKind.PRODUCER, 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) { var key = _a[0], value = _a[1]; return ["to_process.0.".concat(key), value]; }))), }, context: opentelemetry.inheritFrom === 'EVENT' ? { inheritFrom: 'TRACE_HEADERS', traceHeaders: { traceparent: event.traceparent, tracestate: event.tracestate, }, } : { inheritFrom: 'CONTEXT', context: api_1.context.active(), }, disableSpanManagement: true, fn: function (span) { return __awaiter(_this, void 0, void 0, function () { 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; var _this = this; var _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12; return __generator(this, function (_13) { switch (_13.label) { case 0: (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Resumable function starting execution for ".concat(event.type, " on subject ").concat(event.subject), }); otelHeaders = (0, arvo_core_1.currentOpenTelemetryHeaders)(); orchestrationParentSubject = null; acquiredLock = null; initEventId = null; _13.label = 1; case 1: _13.trys.push([1, 6, 7, 9]); /////////////////////////////////////////////////////////////// // Subject resolution, handler resolution and input validation /////////////// // //////////////////////////////////////////////// this.syncEventResource.validateEventSubject(event); parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject); span.setAttributes({ 'arvo.parsed.subject.orchestrator.name': parsedEventSubject.orchestrator.name, 'arvo.parsed.subject.orchestrator.version': parsedEventSubject.orchestrator.version, }); // The wrong source is not a big violation. May be some routing went wrong. So just ignore the event if (parsedEventSubject.orchestrator.name !== this.source) { (0, arvo_core_1.logToSpan)({ level: 'WARNING', 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."), }); (0, arvo_core_1.logToSpan)({ level: 'INFO', message: 'Orchestration executed with issues and emitted 0 events', }); return [2 /*return*/, { events: [], allEventDomains: [], domainedEvents: { all: [], }, }]; } (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Resolving machine for event ".concat(event.type), }); // Handler not found means that the handler is not defined which is not allowed and a critical bug if (!this.handler[parsedEventSubject.orchestrator.version]) { throw new errors_1.ConfigViolation("Handler resolution failed: No handler found matching orchestrator name='".concat(parsedEventSubject.orchestrator.name, "' and version='").concat(parsedEventSubject.orchestrator.version, "'.")); } (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Input validation started for event ".concat(event.type), }); contractType = this.validateInput(event).contractType; return [4 /*yield*/, this.syncEventResource.acquireLock(event)]; case 2: /////////////////////////////////////////////////////////////// // State locking, acquiry and handler exection /////////////////////////////////////////////////////////////// acquiredLock = _13.sent(); if (acquiredLock === 'NOT_ACQUIRED') { throw new error_1.TransactionViolation({ cause: error_1.TransactionViolationCause.LOCK_UNACQUIRED, message: 'Lock acquisition denied - Unable to obtain exclusive access to event processing', initiatingEvent: event, }); } if (acquiredLock === 'ACQUIRED') { (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "This execution acquired lock at resource '".concat(event.subject, "'"), }); } return [4 /*yield*/, this.syncEventResource.acquireState(event)]; case 3: state = _13.sent(); orchestrationParentSubject = (_r = state === null || state === void 0 ? void 0 : state.parentSubject) !== null && _r !== void 0 ? _r : null; initEventId = (_s = state === null || state === void 0 ? void 0 : state.initEventId) !== null && _s !== void 0 ? _s : event.id; if ((state === null || state === void 0 ? void 0 : state.status) === 'done') { (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "The resumable has already reached the terminal state. Ignoring event(id=".concat(event.id, ")"), }); return [2 /*return*/, { events: [], }]; } if (!state) { (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Initializing new execution state for subject: ".concat(event.subject), }); if (event.type !== this.source) { (0, arvo_core_1.logToSpan)({ level: 'WARNING', 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."), }); return [2 /*return*/, { events: [], }]; } } else { (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Resuming execution with existing state for subject: ".concat(event.subject), }); } // In case the event is the init event then // extract the parent subject from it and assume // it to be the orchestration parent subject if (event.type === this.source) { 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; } // This is not persisted until handling. The reason is that if the event // is causing a fault then what is the point of persisting it if (event.parentid && ((_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]) && 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])) { state.events.expected[event.parentid].push(event.toJSON()); } eventTypeToExpectedEvent = {}; 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++) { _b = _a[_i], _ = _b[0], eventList = _b[1]; for (_c = 0, eventList_1 = eventList; _c < eventList_1.length; _c++) { _evt = eventList_1[_c]; if (!eventTypeToExpectedEvent[_evt.type]) { eventTypeToExpectedEvent[_evt.type] = []; } eventTypeToExpectedEvent[_evt.type].push(_evt); } } handler = this.handler[parsedEventSubject.orchestrator.version]; return [4 /*yield*/, handler({ span: span, context: (_1 = state === null || state === void 0 ? void 0 : state.state$$) !== null && _1 !== void 0 ? _1 : null, metadata: state !== null && state !== void 0 ? state : null, collectedEvents: eventTypeToExpectedEvent, domain: { event: event.domain, self: this.contracts.self.domain, }, input: contractType === 'self' ? event.toJSON() : null, service: contractType === 'service' ? event.toJSON() : null, contracts: { self: this.contracts.self.version(parsedEventSubject.orchestrator.version), services: this.contracts.services, }, })]; case 4: executionResult = _13.sent(); emittables = []; for (_d = 0, _e = __spreadArray(__spreadArray([], ((executionResult === null || executionResult === void 0 ? void 0 : executionResult.output) ? [ { data: executionResult.output, type: this.contracts.self.metadata.completeEventType, to: (_3 = (_2 = parsedEventSubject.meta) === null || _2 === void 0 ? void 0 : _2.redirectto) !== null && _3 !== void 0 ? _3 : parsedEventSubject.execution.initiator, domain: orchestrationParentSubject ? [arvo_core_1.ArvoOrchestrationSubject.parse(orchestrationParentSubject).execution.domain] : [null], }, ] : []), true), ((_4 = executionResult === null || executionResult === void 0 ? void 0 : executionResult.services) !== null && _4 !== void 0 ? _4 : []), true); _d < _e.length; _d++) { item = _e[_d]; createdDomain = new Set(null); for (_f = 0, _g = Array.from(new Set((_5 = item.domain) !== null && _5 !== void 0 ? _5 : [null])); _f < _g.length; _f++) { _dom = _g[_f]; evt = this.createEmittableEvent(item, otelHeaders, orchestrationParentSubject, event, this.contracts.self.version(parsedEventSubject.orchestrator.version), initEventId, _dom); // Making sure the raw event broadcast is actually unique as the // domain resolution (especially for symbolic) can only happen // in the createEmittableEvent if (createdDomain.has(evt.domain)) continue; createdDomain.add(evt.domain); emittables.push(evt); for (_h = 0, _j = Object.entries(emittables[emittables.length - 1].otelAttributes); _h < _j.length; _h++) { _k = _j[_h], key = _k[0], value = _k[1]; span.setAttribute("to_emit.".concat(emittables.length - 1, ".").concat(key), value); } } } (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Resumable execution completed. Generated events: ".concat(emittables.length), }); eventTrackingState = { consumed: event.toJSON(), expected: emittables.length ? Object.fromEntries(emittables.map(function (item) { return [item.id, []]; })) : ((_6 = state === null || state === void 0 ? void 0 : state.events.expected) !== null && _6 !== void 0 ? _6 : null), produced: emittables.map(function (item) { return item.toJSON(); }), }; // Write to the memory return [4 /*yield*/, this.syncEventResource.persistState(event, { status: (executionResult === null || executionResult === void 0 ? void 0 : executionResult.output) ? 'done' : 'active', initEventId: initEventId, parentSubject: orchestrationParentSubject, subject: event.subject, events: eventTrackingState, 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, }, state, span)]; case 5: // Write to the memory _13.sent(); (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "State update persisted in memory for subject ".concat(event.subject), }); (0, arvo_core_1.logToSpan)({ level: 'INFO', message: "Resumable successfully executed and emitted ".concat(emittables.length, " events"), }); return [2 /*return*/, { events: emittables }]; case 6: error_2 = _13.sent(); e = (0, index_2.isError)(error_2) ? error_2 : new errors_1.ExecutionViolation("Non-Error object thrown during machine execution: ".concat(typeof error_2, ". This indicates a serious implementation flaw.")); (0, arvo_core_1.exceptionToSpan)(e); span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e.message, }); // For any violation errors bubble them up to the // called of the function so that they can // be handled gracefully if (e.name.includes('ViolationError')) { (0, arvo_core_1.logToSpan)({ level: 'CRITICAL', message: "Resumable violation error: ".concat(e.message), }); throw e; } (0, arvo_core_1.logToSpan)({ level: 'ERROR', message: "Resumable execution failed: ".concat(e.message), }); parsedEventSubject = null; try { parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject); } catch (e) { (0, arvo_core_1.logToSpan)({ level: 'WARNING', message: "Unable to parse event subject: ".concat(e.message), }); } result = []; for (_l = 0, _m = Array.from(new Set(this.systemErrorDomain ? this.systemErrorDomain.map(function (item) { return (0, ArvoDomain_1.resolveEventDomain)({ domainToResolve: item, handlerSelfContract: _this.contracts.self.version('latest'), eventContract: _this.contracts.self.version('latest'), triggeringEvent: event, }); }) : [event.domain, this.domain, null])); _l < _m.length; _l++) { _dom = _m[_l]; result.push((0, arvo_core_1.createArvoOrchestratorEventFactory)(this.contracts.self.version('latest')).systemError({ source: this.source, // If the initiator of the workflow exist then match the // subject so that it can incorporate it in its state. If // parent does not exist then this is the root workflow so // use its own subject subject: orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : event.subject, // The system error must always go back to // the source which initiated it to: (_9 = parsedEventSubject === null || parsedEventSubject === void 0 ? void 0 : parsedEventSubject.execution.initiator) !== null && _9 !== void 0 ? _9 : event.source, error: e, traceparent: (_10 = otelHeaders.traceparent) !== null && _10 !== void 0 ? _10 : undefined, tracestate: (_11 = otelHeaders.tracestate) !== null && _11 !== void 0 ? _11 : undefined, accesscontrol: (_12 = event.accesscontrol) !== null && _12 !== void 0 ? _12 : undefined, executionunits: this.executionunits, // If there is initEventID then use that. // Otherwise, use event id. If the error is in init event // then it will be the same as initEventId. Otherwise, // we still would know what cause this error parentid: initEventId !== null && initEventId !== void 0 ? initEventId : event.id, domain: _dom, })); for (_o = 0, _p = Object.entries(result[result.length - 1].otelAttributes); _o < _p.length; _o++) { _q = _p[_o], key = _q[0], value = _q[1]; span.setAttribute("to_emit.".concat(result.length - 1, ".").concat(key), value); } } return [2 /*return*/, { events: result, }]; case 7: return [4 /*yield*/, this.syncEventResource.releaseLock(event, acquiredLock, span)]; case 8: _13.sent(); span.end(); return [7 /*endfinally*/]; case 9: return [2 /*return*/]; } }); }); }, })]; }); }); }; Object.defineProperty(ArvoResumable.prototype, "systemErrorSchema", { get: function () { return this.contracts.self.systemError; }, enumerable: false, configurable: true }); return ArvoResumable; }(AbstractArvoEventHandler_1.default)); exports.ArvoResumable = ArvoResumable;