arvo-event-handler 3.0.7 → 3.0.10

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 (43) hide show
  1. package/dist/ArvoEventHandler/index.d.ts +3 -4
  2. package/dist/ArvoEventHandler/index.js +53 -71
  3. package/dist/ArvoEventHandler/types.d.ts +3 -2
  4. package/dist/ArvoMachine/createMachine.d.ts +1 -1
  5. package/dist/ArvoMachine/createMachine.js +1 -1
  6. package/dist/ArvoOrchestrationUtils/createEmitableEvent.d.ts +30 -0
  7. package/dist/ArvoOrchestrationUtils/createEmitableEvent.js +160 -0
  8. package/dist/ArvoOrchestrationUtils/error.d.ts +18 -0
  9. package/dist/{ArvoOrchestrator → ArvoOrchestrationUtils}/error.js +14 -9
  10. package/dist/ArvoOrchestrationUtils/handlerErrors.d.ts +36 -0
  11. package/dist/ArvoOrchestrationUtils/handlerErrors.js +183 -0
  12. package/dist/ArvoOrchestrationUtils/orchestrationExecutionState.d.ts +11 -0
  13. package/dist/ArvoOrchestrationUtils/orchestrationExecutionState.js +7 -0
  14. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/acquireLockWithValidation.d.ts +8 -0
  15. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/acquireLockWithValidation.js +69 -0
  16. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/index.d.ts +42 -0
  17. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/index.js +221 -0
  18. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/validateAndParseSubject.d.ts +7 -0
  19. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/validateAndParseSubject.js +25 -0
  20. package/dist/ArvoOrchestrationUtils/servicesValidation.d.ts +22 -0
  21. package/dist/ArvoOrchestrationUtils/servicesValidation.js +56 -0
  22. package/dist/ArvoOrchestrationUtils/types.d.ts +7 -0
  23. package/dist/ArvoOrchestrationUtils/types.js +9 -0
  24. package/dist/ArvoOrchestrator/factory.d.ts +2 -2
  25. package/dist/ArvoOrchestrator/factory.js +15 -1
  26. package/dist/ArvoOrchestrator/index.d.ts +5 -20
  27. package/dist/ArvoOrchestrator/index.js +94 -471
  28. package/dist/ArvoOrchestrator/types.d.ts +19 -21
  29. package/dist/ArvoResumable/factory.d.ts +4 -2
  30. package/dist/ArvoResumable/factory.js +6 -25
  31. package/dist/ArvoResumable/index.d.ts +9 -21
  32. package/dist/ArvoResumable/index.js +82 -422
  33. package/dist/ArvoResumable/types.d.ts +5 -4
  34. package/dist/IArvoEventHandler/index.d.ts +1 -2
  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 +12 -11
  40. package/dist/index.js +24 -21
  41. package/dist/types.d.ts +8 -0
  42. package/package.json +2 -2
  43. package/dist/ArvoOrchestrator/error.d.ts +0 -16
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ 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);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ 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;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.handleOrchestrationErrors = exports.createSystemErrorEvents = void 0;
51
+ var api_1 = require("@opentelemetry/api");
52
+ var arvo_core_1 = require("arvo-core");
53
+ var ArvoDomain_1 = require("../ArvoDomain");
54
+ var errors_1 = require("../errors");
55
+ var utils_1 = require("../utils");
56
+ var types_1 = require("./types");
57
+ /**
58
+ * Creates system error events
59
+ */
60
+ var createSystemErrorEvents = function (_a) {
61
+ var _b, _c, _d, _e;
62
+ var error = _a.error, event = _a.event, otelHeaders = _a.otelHeaders, orchestrationParentSubject = _a.orchestrationParentSubject, initEventId = _a.initEventId, selfContract = _a.selfContract, systemErrorDomain = _a.systemErrorDomain, executionunits = _a.executionunits, source = _a.source, domain = _a.domain, handlerType = _a.handlerType;
63
+ // In case of none transaction errors like errors from
64
+ // the machine or the event creation etc, the are workflow
65
+ // error and shuold be handled by the workflow. Then are
66
+ // called system error and must be sent
67
+ // to the initiator. In as good of a format as possible
68
+ var parsedEventSubject = null;
69
+ try {
70
+ parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject);
71
+ }
72
+ catch (e) {
73
+ (0, arvo_core_1.logToSpan)({
74
+ level: 'WARNING',
75
+ message: "Unable to parse event subject: ".concat(e.message),
76
+ });
77
+ }
78
+ var domainSets = new Set(systemErrorDomain
79
+ ? systemErrorDomain.map(function (item) {
80
+ return (0, ArvoDomain_1.resolveEventDomain)({
81
+ domainToResolve: item,
82
+ handlerSelfContract: selfContract,
83
+ eventContract: selfContract,
84
+ triggeringEvent: event,
85
+ });
86
+ })
87
+ : [event.domain, domain, null]);
88
+ var result = [];
89
+ for (var _i = 0, _f = Array.from(domainSets); _i < _f.length; _i++) {
90
+ var _dom = _f[_i];
91
+ var factoryBuilder = handlerType === 'handler' ? arvo_core_1.createArvoEventFactory : arvo_core_1.createArvoOrchestratorEventFactory;
92
+ result.push(factoryBuilder(selfContract).systemError({
93
+ source: source,
94
+ // If the initiator of the workflow exist then match the
95
+ // subject so that it can incorporate it in its state. If
96
+ // parent does not exist then this is the root workflow so
97
+ // use its own subject
98
+ subject: orchestrationParentSubject !== null && orchestrationParentSubject !== void 0 ? orchestrationParentSubject : event.subject,
99
+ // The system error must always go back to
100
+ // the source which initiated it
101
+ to: (_b = parsedEventSubject === null || parsedEventSubject === void 0 ? void 0 : parsedEventSubject.execution.initiator) !== null && _b !== void 0 ? _b : event.source,
102
+ error: error,
103
+ traceparent: (_c = otelHeaders.traceparent) !== null && _c !== void 0 ? _c : undefined,
104
+ tracestate: (_d = otelHeaders.tracestate) !== null && _d !== void 0 ? _d : undefined,
105
+ accesscontrol: (_e = event.accesscontrol) !== null && _e !== void 0 ? _e : undefined,
106
+ executionunits: executionunits,
107
+ // If there is initEventID then use that.
108
+ // Otherwise, use event id. If the error is in init event
109
+ // then it will be the same as initEventId. Otherwise,
110
+ // we still would know what cause this error
111
+ parentid: initEventId !== null && initEventId !== void 0 ? initEventId : event.id,
112
+ domain: _dom,
113
+ }));
114
+ }
115
+ return result;
116
+ };
117
+ exports.createSystemErrorEvents = createSystemErrorEvents;
118
+ var handleOrchestrationErrors = function (_handlerType, param, span) { return __awaiter(void 0, void 0, void 0, function () {
119
+ var handlerType, error, errorEvents, _i, _a, _b, errEvtIdx, errEvt, _c, _d, _e, key, value;
120
+ return __generator(this, function (_f) {
121
+ switch (_f.label) {
122
+ case 0:
123
+ handlerType = types_1.ArvoOrchestrationHandlerMap[_handlerType];
124
+ error = (0, utils_1.isError)(param.error)
125
+ ? param.error
126
+ : new errors_1.ExecutionViolation("Non-Error object thrown during machine execution: ".concat(typeof param.error, ". This indicates a serious implementation flaw."));
127
+ (0, arvo_core_1.exceptionToSpan)(error, span);
128
+ span.setStatus({
129
+ code: api_1.SpanStatusCode.ERROR,
130
+ message: error.message,
131
+ });
132
+ // Don't persist state on a violation
133
+ //
134
+ // A violation means that there is something
135
+ // wrong in the state persitance or it is a
136
+ // error which will be handled outside the
137
+ // Arvo mechanism. So, it makes sense that it
138
+ // does not impact the state. The violations
139
+ // can be used to trigger retries as well
140
+ if ((0, arvo_core_1.isViolationError)(error)) {
141
+ (0, arvo_core_1.logToSpan)({
142
+ level: 'CRITICAL',
143
+ message: "".concat(handlerType || 'Arvo orchestration handler', " violation error: ").concat(error.message),
144
+ });
145
+ return [2 /*return*/, {
146
+ errorToThrow: error,
147
+ events: null,
148
+ }];
149
+ }
150
+ return [4 /*yield*/, param.syncEventResource
151
+ .persistState(param.event, {
152
+ executionStatus: 'failure',
153
+ subject: param.event.subject,
154
+ error: param.error,
155
+ }, null, span)
156
+ .catch(function (e) {
157
+ (0, arvo_core_1.logToSpan)({
158
+ level: 'CRITICAL',
159
+ message: "Error in orchestrator persisting the failure state: ".concat(e.message),
160
+ });
161
+ })];
162
+ case 1:
163
+ _f.sent();
164
+ (0, arvo_core_1.logToSpan)({
165
+ level: 'ERROR',
166
+ message: "".concat(handlerType || 'Arvo orchestration handler', " execution failed: ").concat(error.message),
167
+ });
168
+ errorEvents = (0, exports.createSystemErrorEvents)(__assign(__assign({}, param), { error: error }));
169
+ for (_i = 0, _a = Object.entries(errorEvents); _i < _a.length; _i++) {
170
+ _b = _a[_i], errEvtIdx = _b[0], errEvt = _b[1];
171
+ for (_c = 0, _d = Object.entries(errEvt.otelAttributes); _c < _d.length; _c++) {
172
+ _e = _d[_c], key = _e[0], value = _e[1];
173
+ span.setAttribute("emittables.".concat(errEvtIdx, ".").concat(key), value);
174
+ }
175
+ }
176
+ return [2 /*return*/, {
177
+ errorToThrow: null,
178
+ events: errorEvents,
179
+ }];
180
+ }
181
+ });
182
+ }); };
183
+ exports.handleOrchestrationErrors = handleOrchestrationErrors;
@@ -0,0 +1,11 @@
1
+ export declare const OrchestrationExecutionStatus: {
2
+ readonly FAILURE: "failure";
3
+ readonly NORMAL: "normal";
4
+ };
5
+ export type OrchestrationExecutionMemoryRecord<T extends Record<string, unknown>> = (T & {
6
+ executionStatus: typeof OrchestrationExecutionStatus.NORMAL;
7
+ }) | (Partial<T> & {
8
+ executionStatus: typeof OrchestrationExecutionStatus.FAILURE;
9
+ error: Error;
10
+ subject: string;
11
+ });
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OrchestrationExecutionStatus = void 0;
4
+ exports.OrchestrationExecutionStatus = {
5
+ FAILURE: 'failure',
6
+ NORMAL: 'normal',
7
+ };
@@ -0,0 +1,8 @@
1
+ import type { Span } from '@opentelemetry/api';
2
+ import { type ArvoEvent } from 'arvo-core';
3
+ import type { SyncEventResource } from '../../SyncEventResource';
4
+ import type { AcquiredLockStatusType } from '../../SyncEventResource/types';
5
+ /**
6
+ * Handles lock acquisition with proper error handling
7
+ */
8
+ export declare const acquireLockWithValidation: (syncEventResource: SyncEventResource<Record<string, any>>, event: ArvoEvent, span: Span) => Promise<AcquiredLockStatusType>;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ 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);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ 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;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.acquireLockWithValidation = void 0;
40
+ var arvo_core_1 = require("arvo-core");
41
+ var error_1 = require("../error");
42
+ /**
43
+ * Handles lock acquisition with proper error handling
44
+ */
45
+ var acquireLockWithValidation = function (syncEventResource, event, span) { return __awaiter(void 0, void 0, void 0, function () {
46
+ var acquiredLock;
47
+ return __generator(this, function (_a) {
48
+ switch (_a.label) {
49
+ case 0: return [4 /*yield*/, syncEventResource.acquireLock(event, span)];
50
+ case 1:
51
+ acquiredLock = _a.sent();
52
+ if (acquiredLock === 'NOT_ACQUIRED') {
53
+ throw new error_1.TransactionViolation({
54
+ cause: error_1.TransactionViolationCause.LOCK_UNACQUIRED,
55
+ message: 'Lock acquisition denied - Unable to obtain exclusive access to event processing',
56
+ initiatingEvent: event,
57
+ });
58
+ }
59
+ if (acquiredLock === 'ACQUIRED') {
60
+ (0, arvo_core_1.logToSpan)({
61
+ level: 'INFO',
62
+ message: "This execution acquired lock at resource '".concat(event.subject, "'"),
63
+ }, span);
64
+ }
65
+ return [2 /*return*/, acquiredLock];
66
+ }
67
+ });
68
+ }); };
69
+ exports.acquireLockWithValidation = acquireLockWithValidation;
@@ -0,0 +1,42 @@
1
+ import { type Span } from '@opentelemetry/api';
2
+ import { type ArvoEvent, type ArvoOrchestrationSubjectContent, type ArvoOrchestratorContract, type ArvoSemanticVersion, type OpenTelemetryHeaders, type VersionedArvoContract } from 'arvo-core';
3
+ import type IArvoEventHandler from '../../IArvoEventHandler';
4
+ import type { SyncEventResource } from '../../SyncEventResource';
5
+ import type { ArvoEventHandlerOpenTelemetryOptions, ArvoEventHandlerOtelSpanOptions } from '../../types';
6
+ import type { OrchestrationExecutionMemoryRecord } from '../orchestrationExecutionState';
7
+ import type { ArvoOrchestrationHandlerType } from '../types';
8
+ export type OrchestrationExecutionContext<TState extends OrchestrationExecutionMemoryRecord<Record<string, any>>> = {
9
+ event: ArvoEvent;
10
+ opentelemetry: ArvoEventHandlerOpenTelemetryOptions;
11
+ source: string;
12
+ syncEventResource: SyncEventResource<TState>;
13
+ executionunits: number;
14
+ systemErrorDomain?: (string | null)[];
15
+ selfContract: VersionedArvoContract<ArvoOrchestratorContract, ArvoSemanticVersion>;
16
+ domain: string | null;
17
+ _handlerType: ArvoOrchestrationHandlerType;
18
+ spanOptions: ArvoEventHandlerOtelSpanOptions & {
19
+ spanName: NonNullable<ArvoEventHandlerOtelSpanOptions['spanName']>;
20
+ };
21
+ };
22
+ export type CoreExecutionFn<TState extends OrchestrationExecutionMemoryRecord<Record<string, any>>> = (params: {
23
+ span: any;
24
+ otelHeaders: OpenTelemetryHeaders;
25
+ orchestrationParentSubject: string | null;
26
+ initEventId: string;
27
+ parsedEventSubject: ArvoOrchestrationSubjectContent;
28
+ state: TState | null;
29
+ _handlerType: ArvoOrchestrationHandlerType;
30
+ }) => Promise<{
31
+ emittables: ArvoEvent[];
32
+ newState: TState;
33
+ }>;
34
+ export declare const returnEventsWithLogging: (param: Awaited<ReturnType<IArvoEventHandler["execute"]>>, span: Span) => Awaited<ReturnType<IArvoEventHandler["execute"]>>;
35
+ /**
36
+ * Wraps orchestration execution with common infrastructure:
37
+ * - OpenTelemetry span management
38
+ * - Lock acquisition and release
39
+ * - State management
40
+ * - Error handling and system error generation
41
+ */
42
+ export declare const executeWithOrchestrationWrapper: <TState extends OrchestrationExecutionMemoryRecord<Record<string, any>>>({ event, opentelemetry, spanOptions, source, syncEventResource, executionunits, systemErrorDomain, selfContract, domain, _handlerType, }: OrchestrationExecutionContext<TState>, coreExecutionFn: CoreExecutionFn<TState>) => Promise<Awaited<ReturnType<IArvoEventHandler["execute"]>>>;
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ 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);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ 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;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.executeWithOrchestrationWrapper = exports.returnEventsWithLogging = void 0;
51
+ var api_1 = require("@opentelemetry/api");
52
+ var arvo_core_1 = require("arvo-core");
53
+ var utils_1 = require("../../utils");
54
+ var handlerErrors_1 = require("../handlerErrors");
55
+ var acquireLockWithValidation_1 = require("./acquireLockWithValidation");
56
+ var validateAndParseSubject_1 = require("./validateAndParseSubject");
57
+ var returnEventsWithLogging = function (param, span) {
58
+ var _a, _b;
59
+ (0, arvo_core_1.logToSpan)({
60
+ level: 'INFO',
61
+ message: "Execution completed with issues and emitted ".concat((_b = (_a = param.events) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0, " events"),
62
+ }, span);
63
+ return param;
64
+ };
65
+ exports.returnEventsWithLogging = returnEventsWithLogging;
66
+ /**
67
+ * Wraps orchestration execution with common infrastructure:
68
+ * - OpenTelemetry span management
69
+ * - Lock acquisition and release
70
+ * - State management
71
+ * - Error handling and system error generation
72
+ */
73
+ var executeWithOrchestrationWrapper = function (_a, coreExecutionFn_1) { return __awaiter(void 0, [_a, coreExecutionFn_1], void 0, function (_b, coreExecutionFn) {
74
+ var otelConfig;
75
+ var event = _b.event, opentelemetry = _b.opentelemetry, spanOptions = _b.spanOptions, source = _b.source, syncEventResource = _b.syncEventResource, executionunits = _b.executionunits, systemErrorDomain = _b.systemErrorDomain, selfContract = _b.selfContract, domain = _b.domain, _handlerType = _b._handlerType;
76
+ return __generator(this, function (_c) {
77
+ switch (_c.label) {
78
+ case 0:
79
+ otelConfig = (0, utils_1.createEventHandlerTelemetryConfig)(spanOptions.spanName({ selfContractUri: selfContract.uri, consumedEvent: event }), spanOptions, opentelemetry, event);
80
+ return [4 /*yield*/, arvo_core_1.ArvoOpenTelemetry.getInstance().startActiveSpan(__assign(__assign({}, otelConfig), { fn: function (span) { return __awaiter(void 0, void 0, void 0, function () {
81
+ var _i, _a, _b, key, value, otelHeaders, orchestrationParentSubject, initEventId, acquiredLock, parsedEventSubject, state, _c, emittables, newState, i, _d, _e, _f, key, value, error_1, _g, errorToThrow, errorEvents;
82
+ var _h, _j, _k, _l;
83
+ return __generator(this, function (_m) {
84
+ switch (_m.label) {
85
+ case 0:
86
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
87
+ span.setAttribute('arvo.handler.execution.type', _handlerType);
88
+ span.setAttribute('arvo.handler.execution.status', 'normal');
89
+ for (_i = 0, _a = Object.entries(event.otelAttributes); _i < _a.length; _i++) {
90
+ _b = _a[_i], key = _b[0], value = _b[1];
91
+ span.setAttribute("consumable.0.".concat(key), value);
92
+ }
93
+ (0, arvo_core_1.logToSpan)({
94
+ level: 'INFO',
95
+ message: "Starting execution for ".concat(event.type, " on subject ").concat(event.subject),
96
+ }, span);
97
+ otelHeaders = (0, arvo_core_1.currentOpenTelemetryHeaders)();
98
+ orchestrationParentSubject = null;
99
+ initEventId = null;
100
+ acquiredLock = null;
101
+ _m.label = 1;
102
+ case 1:
103
+ _m.trys.push([1, 6, 8, 10]);
104
+ parsedEventSubject = (0, validateAndParseSubject_1.validateAndParseSubject)(event, source, syncEventResource, span, 'orchestrator');
105
+ if (!parsedEventSubject) {
106
+ return [2 /*return*/, (0, exports.returnEventsWithLogging)({ events: [] }, span)];
107
+ }
108
+ return [4 /*yield*/, (0, acquireLockWithValidation_1.acquireLockWithValidation)(syncEventResource, event, span)];
109
+ case 2:
110
+ // Lock acquisition
111
+ acquiredLock = _m.sent();
112
+ return [4 /*yield*/, syncEventResource.acquireState(event, span)];
113
+ case 3:
114
+ state = _m.sent();
115
+ if ((state === null || state === void 0 ? void 0 : state.executionStatus) === 'failure') {
116
+ span.setAttribute('arvo.handler.execution.status', state.executionStatus);
117
+ (0, arvo_core_1.logToSpan)({
118
+ level: 'WARNING',
119
+ message: "The orchestration has failed in a previous event. Ignoring event id: ".concat(event.id, " with event subject: ").concat(event.subject),
120
+ }, span);
121
+ span.setStatus({
122
+ code: api_1.SpanStatusCode.ERROR,
123
+ message: "The orchestration has failed in a previous event. Ignoring event id: ".concat(event.id, " with event subject: ").concat(event.subject),
124
+ });
125
+ return [2 /*return*/, (0, exports.returnEventsWithLogging)({ events: [] }, span)];
126
+ }
127
+ orchestrationParentSubject = (_h = state === null || state === void 0 ? void 0 : state.parentSubject) !== null && _h !== void 0 ? _h : null;
128
+ initEventId = (_j = state === null || state === void 0 ? void 0 : state.initEventId) !== null && _j !== void 0 ? _j : null;
129
+ if (!state) {
130
+ (0, arvo_core_1.logToSpan)({
131
+ level: 'INFO',
132
+ message: "Initializing new execution state for subject: ".concat(event.subject),
133
+ });
134
+ if (event.type !== source) {
135
+ (0, arvo_core_1.logToSpan)({
136
+ level: 'WARNING',
137
+ message: "Invalid initialization event detected. Expected type '".concat(source, "' but received '").concat(event.type, "'."),
138
+ });
139
+ return [2 /*return*/, (0, exports.returnEventsWithLogging)({ events: [] }, span)];
140
+ }
141
+ }
142
+ else {
143
+ (0, arvo_core_1.logToSpan)({
144
+ level: 'INFO',
145
+ message: "Resuming execution with existing state for subject: ".concat(event.subject),
146
+ });
147
+ }
148
+ // Extract parent subject from init event if applicable
149
+ if (event.type === source) {
150
+ orchestrationParentSubject = (_l = (_k = event === null || event === void 0 ? void 0 : event.data) === null || _k === void 0 ? void 0 : _k.parentSubject$$) !== null && _l !== void 0 ? _l : null;
151
+ }
152
+ return [4 /*yield*/, coreExecutionFn({
153
+ span: span,
154
+ otelHeaders: otelHeaders,
155
+ orchestrationParentSubject: orchestrationParentSubject,
156
+ initEventId: initEventId !== null && initEventId !== void 0 ? initEventId : event.id,
157
+ parsedEventSubject: parsedEventSubject,
158
+ state: state,
159
+ _handlerType: _handlerType,
160
+ })];
161
+ case 4:
162
+ _c = _m.sent(), emittables = _c.emittables, newState = _c.newState;
163
+ // Add OpenTelemetry attributes for emitted events
164
+ for (i = 0; i < emittables.length; i++) {
165
+ for (_d = 0, _e = Object.entries(emittables[i].otelAttributes); _d < _e.length; _d++) {
166
+ _f = _e[_d], key = _f[0], value = _f[1];
167
+ span.setAttribute("emittables.".concat(i, ".").concat(key), value);
168
+ }
169
+ }
170
+ // Persist state
171
+ return [4 /*yield*/, syncEventResource.persistState(event, newState, state, span)];
172
+ case 5:
173
+ // Persist state
174
+ _m.sent();
175
+ (0, arvo_core_1.logToSpan)({
176
+ level: 'INFO',
177
+ message: "State update persisted in memory for subject ".concat(event.subject),
178
+ });
179
+ (0, arvo_core_1.logToSpan)({
180
+ level: 'INFO',
181
+ message: "Execution successfully completed and emitted ".concat(emittables.length, " events"),
182
+ });
183
+ return [2 /*return*/, (0, exports.returnEventsWithLogging)({ events: emittables }, span)];
184
+ case 6:
185
+ error_1 = _m.sent();
186
+ span.setAttribute('arvo.handler.execution.status', 'failure');
187
+ return [4 /*yield*/, (0, handlerErrors_1.handleOrchestrationErrors)(_handlerType, {
188
+ error: error_1,
189
+ event: event,
190
+ otelHeaders: otelHeaders,
191
+ orchestrationParentSubject: orchestrationParentSubject,
192
+ initEventId: initEventId,
193
+ selfContract: selfContract,
194
+ systemErrorDomain: systemErrorDomain,
195
+ executionunits: executionunits,
196
+ source: source,
197
+ domain: domain,
198
+ syncEventResource: syncEventResource,
199
+ handlerType: _handlerType,
200
+ }, span)];
201
+ case 7:
202
+ _g = _m.sent(), errorToThrow = _g.errorToThrow, errorEvents = _g.events;
203
+ if (errorToThrow)
204
+ throw errorToThrow;
205
+ return [2 /*return*/, {
206
+ events: errorEvents,
207
+ }];
208
+ case 8: return [4 /*yield*/, syncEventResource.releaseLock(event, acquiredLock, span)];
209
+ case 9:
210
+ _m.sent();
211
+ span.end();
212
+ return [7 /*endfinally*/];
213
+ case 10: return [2 /*return*/];
214
+ }
215
+ });
216
+ }); } }))];
217
+ case 1: return [2 /*return*/, _c.sent()];
218
+ }
219
+ });
220
+ }); };
221
+ exports.executeWithOrchestrationWrapper = executeWithOrchestrationWrapper;
@@ -0,0 +1,7 @@
1
+ import type { Span } from '@opentelemetry/api';
2
+ import { type ArvoEvent, type ArvoOrchestrationSubjectContent } from 'arvo-core';
3
+ import type { SyncEventResource } from '../../SyncEventResource';
4
+ /**
5
+ * Validates and parses orchestration subject
6
+ */
7
+ export declare const validateAndParseSubject: (event: ArvoEvent, expectedSource: string, syncEventResource: SyncEventResource<any>, span: Span, handlerType: "orchestrator" | "resumable") => ArvoOrchestrationSubjectContent | null;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateAndParseSubject = void 0;
4
+ var arvo_core_1 = require("arvo-core");
5
+ /**
6
+ * Validates and parses orchestration subject
7
+ */
8
+ var validateAndParseSubject = function (event, expectedSource, syncEventResource, span, handlerType) {
9
+ var _a;
10
+ syncEventResource.validateEventSubject(event, span);
11
+ var parsedEventSubject = arvo_core_1.ArvoOrchestrationSubject.parse(event.subject);
12
+ span.setAttributes((_a = {},
13
+ _a["arvo.parsed.subject.".concat(handlerType, ".name")] = parsedEventSubject.orchestrator.name,
14
+ _a["arvo.parsed.subject.".concat(handlerType, ".version")] = parsedEventSubject.orchestrator.version,
15
+ _a));
16
+ if (parsedEventSubject.orchestrator.name !== expectedSource) {
17
+ (0, arvo_core_1.logToSpan)({
18
+ level: 'WARNING',
19
+ message: "Event subject mismatch - expected '".concat(expectedSource, "' but got '").concat(parsedEventSubject.orchestrator.name, "'"),
20
+ }, span);
21
+ return null;
22
+ }
23
+ return parsedEventSubject;
24
+ };
25
+ exports.validateAndParseSubject = validateAndParseSubject;
@@ -0,0 +1,22 @@
1
+ import type { ArvoContract, VersionedArvoContract } from 'arvo-core';
2
+ import { type ArvoOrchestrationHandlerType } from './types';
3
+ /**
4
+ * Validates that all service contracts in a collection have unique URIs.
5
+ *
6
+ * Iterates through the provided contracts and checks if any URI appears more than once.
7
+ * Multiple versions of the same contract (with the same URI) are not allowed.
8
+ *
9
+ * @param contracts - A record mapping contract keys to their respective ArvoContract objects
10
+ * @returns An object with a boolean result indicating if all contracts are unique, and the error keys if not
11
+ */
12
+ export declare const areServiceContractsUnique: (contracts: Record<string, ArvoContract | VersionedArvoContract<any, any>>) => {
13
+ result: false;
14
+ keys: [string, string];
15
+ contractUri: string;
16
+ } | {
17
+ result: true;
18
+ };
19
+ export declare const servicesValidation: (contracts: {
20
+ self: ArvoContract | VersionedArvoContract<any, any>;
21
+ services: Record<string, VersionedArvoContract<any, any>>;
22
+ }, _handlerType: ArvoOrchestrationHandlerType) => void;