@usearazzo/runner 1.0.1-alpha.34 → 1.0.1-alpha.35

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 (44) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +6 -1
  3. package/dist/arazzo-runner.browser.js +687 -317
  4. package/dist/arazzo-runner.browser.min.js +1 -1
  5. package/package.json +52 -7
  6. package/src/errors/ExecutionError.cjs +2 -0
  7. package/src/errors/ExecutionError.mjs +2 -0
  8. package/src/executor/OpenAPIOperationExecutor.cjs +58 -47
  9. package/src/executor/OpenAPIOperationExecutor.mjs +58 -47
  10. package/src/executor/WorkflowExecutor.cjs +302 -160
  11. package/src/executor/WorkflowExecutor.mjs +302 -160
  12. package/src/index.cjs +14 -0
  13. package/src/index.mjs +2 -0
  14. package/src/observability/EventChannel.cjs +30 -20
  15. package/src/observability/EventChannel.mjs +30 -23
  16. package/src/observability/Redactor.cjs +7 -5
  17. package/src/observability/Redactor.mjs +7 -5
  18. package/src/observability/combineObservers.cjs +18 -0
  19. package/src/observability/combineObservers.mjs +12 -0
  20. package/src/observability/instrument.cjs +159 -0
  21. package/src/observability/instrument.mjs +144 -0
  22. package/src/observability/logging/LoggingObserver.cjs +177 -0
  23. package/src/observability/logging/LoggingObserver.mjs +172 -0
  24. package/src/observability/logging/index.cjs +13 -0
  25. package/src/observability/logging/index.mjs +1 -0
  26. package/src/observability/opentelemetry/ArazzoRunnerInstrumentation.cjs +321 -0
  27. package/src/observability/opentelemetry/ArazzoRunnerInstrumentation.mjs +313 -0
  28. package/src/observability/opentelemetry/index.cjs +13 -0
  29. package/src/observability/opentelemetry/index.mjs +1 -0
  30. package/src/observability/stream/EventStream.cjs +112 -0
  31. package/src/observability/stream/EventStream.mjs +107 -0
  32. package/src/observability/stream/index.cjs +13 -0
  33. package/src/observability/stream/index.mjs +1 -0
  34. package/src/registry/DocumentRegistry.cjs +14 -9
  35. package/src/registry/DocumentRegistry.mjs +14 -9
  36. package/src/version.cjs +9 -0
  37. package/src/version.mjs +3 -0
  38. package/types/observability/logging/LoggingObserver.d.ts +82 -0
  39. package/types/observability/logging/index.d.ts +2 -0
  40. package/types/observability/opentelemetry/ArazzoRunnerInstrumentation.d.ts +84 -0
  41. package/types/observability/opentelemetry/index.d.ts +2 -0
  42. package/types/observability/stream/EventStream.d.ts +68 -0
  43. package/types/observability/stream/index.d.ts +2 -0
  44. package/types/runner.d.ts +131 -34
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _apidomCore = require("@speclynx/apidom-core");
8
+ var _runner = require("@usearazzo/runner");
9
+ /**
10
+ * The level a log record is written at. Every common logger has these four.
11
+ * @public
12
+ */
13
+
14
+ /**
15
+ * One log record, made from one event.
16
+ * @public
17
+ */
18
+
19
+ /**
20
+ * Writes one log record to the logger of your choice. Loggers disagree on
21
+ * argument order, so this is where a record is handed over the way yours
22
+ * expects: `logger[level](fields, message)` for pino or bunyan,
23
+ * `logger.log(level, message, fields)` for winston,
24
+ * `console[level](message, fields)` for the console.
25
+ * @public
26
+ */
27
+
28
+ /**
29
+ * Options for {@link loggingObserver}.
30
+ * @public
31
+ */
32
+
33
+ /**
34
+ * The default level: `info` for the boundaries of workflows and steps, `warn`
35
+ * for a failed step, `error` for a failed workflow or a step that threw, and
36
+ * `debug` for the decisions and machinery under them.
37
+ */
38
+ const defaultLevel = event => {
39
+ switch (event.type) {
40
+ case 'workflow:start':
41
+ case 'step:start':
42
+ return 'info';
43
+ case 'workflow:settled':
44
+ // a transferred workflow did not fail itself: its target reports its own outcome
45
+ return event.status === 'failed' ? 'error' : 'info';
46
+ case 'step:settled':
47
+ if (event.error !== undefined) return 'error';
48
+ return event.successful ? 'info' : 'warn';
49
+ default:
50
+ return 'debug';
51
+ }
52
+ };
53
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
54
+
55
+ // what a settled event threw, after its message
56
+ const thrown = event => {
57
+ if (event.error === undefined) return '';
58
+ return `: ${event.error instanceof Error ? event.error.message : String(event.error)}`;
59
+ };
60
+ const message = event => {
61
+ switch (event.type) {
62
+ case 'workflow:start':
63
+ return `workflow ${event.workflowId} started${event.via === 'root' ? '' : ` (${event.via})`}`;
64
+ case 'workflow:settled':
65
+ return `workflow ${event.workflowId} ${event.status}${thrown(event)}`;
66
+ case 'workflow:normalize:start':
67
+ return `workflow ${event.workflowId} normalizing`;
68
+ case 'workflow:normalize:settled':
69
+ return `workflow ${event.workflowId} normalized`;
70
+ case 'dependency:start':
71
+ return `dependency ${event.dependency.workflowId} of ${event.workflowId} started`;
72
+ case 'dependency:settled':
73
+ return `dependency ${event.dependency.workflowId} of ${event.workflowId} ${event.memoized ? 'already ' : ''}${event.settledStatus}`;
74
+ case 'step:start':
75
+ return `step ${event.stepId} started`;
76
+ case 'step:attempt':
77
+ return `step ${event.stepId} attempt ${event.attempt}`;
78
+ case 'criterion:evaluated':
79
+ {
80
+ const {
81
+ condition,
82
+ met,
83
+ diagnostic
84
+ } = event.criterion;
85
+ const outcome = met ? 'met' : 'not met';
86
+ return `step ${event.stepId} criterion ${condition} ${outcome}${diagnostic === undefined ? '' : `: ${diagnostic.message}`}`;
87
+ }
88
+ case 'action:selected':
89
+ return event.action === undefined ? `step ${event.stepId} matched no action (${event.transition.kind})` : `step ${event.stepId} selected action ${String((0, _apidomCore.toValue)(event.action.name))} (${event.transition.kind})`;
90
+ case 'retry:wait':
91
+ return `step ${event.stepId} waits ${event.delayMs} ms before attempt ${event.attempt + 1}`;
92
+ case 'retry:reference:start':
93
+ return `step ${event.stepId} retry reference ${event.kind} ${event.id} started`;
94
+ case 'retry:reference:settled':
95
+ return `step ${event.stepId} retry reference ${event.kind} ${event.id} ${event.successful ? 'succeeded' : 'failed'}`;
96
+ case 'step:settled':
97
+ return `step ${event.stepId} ${event.successful ? 'succeeded' : 'failed'} after ${plural(event.attempts, 'attempt')}${thrown(event)}`;
98
+ case 'document:load:start':
99
+ return `loading document ${event.uri}`;
100
+ case 'document:load:settled':
101
+ return `loaded document ${event.uri}`;
102
+ case 'openapi:operation:normalize:start':
103
+ return `operation ${operationName(event)} normalizing`;
104
+ case 'openapi:operation:normalize:settled':
105
+ return `operation ${operationName(event)} normalized`;
106
+ case 'openapi:operation:assembled':
107
+ return `operation ${operationName(event)} assembled`;
108
+ case 'openapi:operation:request:start':
109
+ return `${event.request.method} ${event.request.url}`;
110
+ case 'openapi:operation:request:settled':
111
+ return `operation ${operationName(event)} responded ${event.response.status} (${plural(event.response.size, 'byte')})`;
112
+ }
113
+ };
114
+ const operationName = event => event.operation.operationId ?? event.operation.jsonPointer;
115
+
116
+ /**
117
+ * The event as log fields: a selected action, the document's own element,
118
+ * becomes its `name` and `type`, so a logger does not serialize an element
119
+ * tree.
120
+ */
121
+ const fields = event => {
122
+ if (event.type !== 'action:selected' || event.action === undefined) return {
123
+ ...event
124
+ };
125
+ const {
126
+ action,
127
+ ...rest
128
+ } = event;
129
+ return {
130
+ ...rest,
131
+ action: {
132
+ name: (0, _apidomCore.toValue)(action.name),
133
+ type: (0, _apidomCore.toValue)(action.type)
134
+ }
135
+ };
136
+ };
137
+
138
+ /**
139
+ * An observer that writes every event as a log record through `log`, masked
140
+ * by a `Redactor` first.
141
+ *
142
+ * Events carry no level, so this adapter gives them one: `info` for workflows
143
+ * and steps starting and settling, `warn` for a failed step, `error` for a
144
+ * failed workflow or a step or workflow that threw, and `debug` for
145
+ * attempts, criteria, actions, retries,
146
+ * dependencies, document loads, normalization and requests. A workflow that
147
+ * transferred to another is `info`: the workflow it transferred to reports its
148
+ * own outcome. `levels` overrides it per event type.
149
+ *
150
+ * ```js
151
+ * import pino from 'pino';
152
+ * import { ArazzoRunner } from '@usearazzo/runner';
153
+ * import { loggingObserver } from '@usearazzo/runner/observability/logging';
154
+ *
155
+ * // the error of a step or workflow that threw, serialized as pino does `err`
156
+ * const logger = pino({ serializers: { error: pino.stdSerializers.err } });
157
+ * const runner = await ArazzoRunner.load(uri, {
158
+ * observer: loggingObserver(({ level, message, fields }) => logger[level](fields, message)),
159
+ * });
160
+ * ```
161
+ * @public
162
+ */
163
+ const loggingObserver = (log, options = {}) => {
164
+ const redactor = options.redactor ?? new _runner.Redactor();
165
+ const {
166
+ levels = {}
167
+ } = options;
168
+ return event => {
169
+ const masked = redactor.event(event);
170
+ log({
171
+ level: levels[masked.type] ?? defaultLevel(masked),
172
+ message: message(masked),
173
+ fields: fields(masked)
174
+ });
175
+ };
176
+ };
177
+ var _default = exports.default = loggingObserver;
@@ -0,0 +1,172 @@
1
+ import { toValue } from '@speclynx/apidom-core';
2
+ import { Redactor } from '@usearazzo/runner';
3
+
4
+ /**
5
+ * The level a log record is written at. Every common logger has these four.
6
+ * @public
7
+ */
8
+
9
+ /**
10
+ * One log record, made from one event.
11
+ * @public
12
+ */
13
+
14
+ /**
15
+ * Writes one log record to the logger of your choice. Loggers disagree on
16
+ * argument order, so this is where a record is handed over the way yours
17
+ * expects: `logger[level](fields, message)` for pino or bunyan,
18
+ * `logger.log(level, message, fields)` for winston,
19
+ * `console[level](message, fields)` for the console.
20
+ * @public
21
+ */
22
+
23
+ /**
24
+ * Options for {@link loggingObserver}.
25
+ * @public
26
+ */
27
+
28
+ /**
29
+ * The default level: `info` for the boundaries of workflows and steps, `warn`
30
+ * for a failed step, `error` for a failed workflow or a step that threw, and
31
+ * `debug` for the decisions and machinery under them.
32
+ */
33
+ const defaultLevel = event => {
34
+ switch (event.type) {
35
+ case 'workflow:start':
36
+ case 'step:start':
37
+ return 'info';
38
+ case 'workflow:settled':
39
+ // a transferred workflow did not fail itself: its target reports its own outcome
40
+ return event.status === 'failed' ? 'error' : 'info';
41
+ case 'step:settled':
42
+ if (event.error !== undefined) return 'error';
43
+ return event.successful ? 'info' : 'warn';
44
+ default:
45
+ return 'debug';
46
+ }
47
+ };
48
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
49
+
50
+ // what a settled event threw, after its message
51
+ const thrown = event => {
52
+ if (event.error === undefined) return '';
53
+ return `: ${event.error instanceof Error ? event.error.message : String(event.error)}`;
54
+ };
55
+ const message = event => {
56
+ switch (event.type) {
57
+ case 'workflow:start':
58
+ return `workflow ${event.workflowId} started${event.via === 'root' ? '' : ` (${event.via})`}`;
59
+ case 'workflow:settled':
60
+ return `workflow ${event.workflowId} ${event.status}${thrown(event)}`;
61
+ case 'workflow:normalize:start':
62
+ return `workflow ${event.workflowId} normalizing`;
63
+ case 'workflow:normalize:settled':
64
+ return `workflow ${event.workflowId} normalized`;
65
+ case 'dependency:start':
66
+ return `dependency ${event.dependency.workflowId} of ${event.workflowId} started`;
67
+ case 'dependency:settled':
68
+ return `dependency ${event.dependency.workflowId} of ${event.workflowId} ${event.memoized ? 'already ' : ''}${event.settledStatus}`;
69
+ case 'step:start':
70
+ return `step ${event.stepId} started`;
71
+ case 'step:attempt':
72
+ return `step ${event.stepId} attempt ${event.attempt}`;
73
+ case 'criterion:evaluated':
74
+ {
75
+ const {
76
+ condition,
77
+ met,
78
+ diagnostic
79
+ } = event.criterion;
80
+ const outcome = met ? 'met' : 'not met';
81
+ return `step ${event.stepId} criterion ${condition} ${outcome}${diagnostic === undefined ? '' : `: ${diagnostic.message}`}`;
82
+ }
83
+ case 'action:selected':
84
+ return event.action === undefined ? `step ${event.stepId} matched no action (${event.transition.kind})` : `step ${event.stepId} selected action ${String(toValue(event.action.name))} (${event.transition.kind})`;
85
+ case 'retry:wait':
86
+ return `step ${event.stepId} waits ${event.delayMs} ms before attempt ${event.attempt + 1}`;
87
+ case 'retry:reference:start':
88
+ return `step ${event.stepId} retry reference ${event.kind} ${event.id} started`;
89
+ case 'retry:reference:settled':
90
+ return `step ${event.stepId} retry reference ${event.kind} ${event.id} ${event.successful ? 'succeeded' : 'failed'}`;
91
+ case 'step:settled':
92
+ return `step ${event.stepId} ${event.successful ? 'succeeded' : 'failed'} after ${plural(event.attempts, 'attempt')}${thrown(event)}`;
93
+ case 'document:load:start':
94
+ return `loading document ${event.uri}`;
95
+ case 'document:load:settled':
96
+ return `loaded document ${event.uri}`;
97
+ case 'openapi:operation:normalize:start':
98
+ return `operation ${operationName(event)} normalizing`;
99
+ case 'openapi:operation:normalize:settled':
100
+ return `operation ${operationName(event)} normalized`;
101
+ case 'openapi:operation:assembled':
102
+ return `operation ${operationName(event)} assembled`;
103
+ case 'openapi:operation:request:start':
104
+ return `${event.request.method} ${event.request.url}`;
105
+ case 'openapi:operation:request:settled':
106
+ return `operation ${operationName(event)} responded ${event.response.status} (${plural(event.response.size, 'byte')})`;
107
+ }
108
+ };
109
+ const operationName = event => event.operation.operationId ?? event.operation.jsonPointer;
110
+
111
+ /**
112
+ * The event as log fields: a selected action, the document's own element,
113
+ * becomes its `name` and `type`, so a logger does not serialize an element
114
+ * tree.
115
+ */
116
+ const fields = event => {
117
+ if (event.type !== 'action:selected' || event.action === undefined) return {
118
+ ...event
119
+ };
120
+ const {
121
+ action,
122
+ ...rest
123
+ } = event;
124
+ return {
125
+ ...rest,
126
+ action: {
127
+ name: toValue(action.name),
128
+ type: toValue(action.type)
129
+ }
130
+ };
131
+ };
132
+
133
+ /**
134
+ * An observer that writes every event as a log record through `log`, masked
135
+ * by a `Redactor` first.
136
+ *
137
+ * Events carry no level, so this adapter gives them one: `info` for workflows
138
+ * and steps starting and settling, `warn` for a failed step, `error` for a
139
+ * failed workflow or a step or workflow that threw, and `debug` for
140
+ * attempts, criteria, actions, retries,
141
+ * dependencies, document loads, normalization and requests. A workflow that
142
+ * transferred to another is `info`: the workflow it transferred to reports its
143
+ * own outcome. `levels` overrides it per event type.
144
+ *
145
+ * ```js
146
+ * import pino from 'pino';
147
+ * import { ArazzoRunner } from '@usearazzo/runner';
148
+ * import { loggingObserver } from '@usearazzo/runner/observability/logging';
149
+ *
150
+ * // the error of a step or workflow that threw, serialized as pino does `err`
151
+ * const logger = pino({ serializers: { error: pino.stdSerializers.err } });
152
+ * const runner = await ArazzoRunner.load(uri, {
153
+ * observer: loggingObserver(({ level, message, fields }) => logger[level](fields, message)),
154
+ * });
155
+ * ```
156
+ * @public
157
+ */
158
+ const loggingObserver = (log, options = {}) => {
159
+ const redactor = options.redactor ?? new Redactor();
160
+ const {
161
+ levels = {}
162
+ } = options;
163
+ return event => {
164
+ const masked = redactor.event(event);
165
+ log({
166
+ level: levels[masked.type] ?? defaultLevel(masked),
167
+ message: message(masked),
168
+ fields: fields(masked)
169
+ });
170
+ };
171
+ };
172
+ export default loggingObserver;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ Object.defineProperty(exports, "loggingObserver", {
8
+ enumerable: true,
9
+ get: function () {
10
+ return _LoggingObserver.default;
11
+ }
12
+ });
13
+ var _LoggingObserver = _interopRequireDefault(require("./LoggingObserver.cjs"));
@@ -0,0 +1 @@
1
+ export { default as loggingObserver } from "./LoggingObserver.mjs";
@@ -0,0 +1,321 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.default = void 0;
8
+ var _api = require("@opentelemetry/api");
9
+ var _apidomCore = require("@speclynx/apidom-core");
10
+ var _runner = require("@usearazzo/runner");
11
+ var _version = _interopRequireDefault(require("../../version.cjs"));
12
+ /**
13
+ * Configuration of {@link ArazzoRunnerInstrumentation}, OpenTelemetry's
14
+ * `InstrumentationConfig`.
15
+ * @public
16
+ */
17
+
18
+ const NAME = '@usearazzo/runner';
19
+ const locationAttributes = ({
20
+ uri,
21
+ jsonPointer
22
+ }) => ({
23
+ 'arazzo.document.uri': uri,
24
+ ...(jsonPointer === undefined ? {} : {
25
+ 'arazzo.document.json_pointer': jsonPointer
26
+ })
27
+ });
28
+ const spanOf = operation => operation.kind === 'workflow' ? {
29
+ name: `workflow ${operation.workflowId}`,
30
+ attributes: {
31
+ 'arazzo.run.id': operation.runId,
32
+ 'arazzo.workflow.id': operation.workflowId,
33
+ 'arazzo.workflow.via': operation.via,
34
+ ...locationAttributes(operation.location)
35
+ }
36
+ } : {
37
+ name: `step ${operation.stepId}`,
38
+ attributes: {
39
+ 'arazzo.run.id': operation.runId,
40
+ 'arazzo.workflow.id': operation.workflowId,
41
+ 'arazzo.step.id': operation.stepId,
42
+ ...locationAttributes(operation.location)
43
+ }
44
+ };
45
+ const fail = (span, error) => {
46
+ if (error === undefined) {
47
+ span.setStatus({
48
+ code: _api.SpanStatusCode.ERROR
49
+ });
50
+ return;
51
+ }
52
+ span.recordException(error instanceof Error ? error : String(error));
53
+ span.setStatus({
54
+ code: _api.SpanStatusCode.ERROR,
55
+ ...(error instanceof Error ? {
56
+ message: error.message
57
+ } : {})
58
+ });
59
+ };
60
+
61
+ /**
62
+ * Traces every runner in the process with OpenTelemetry, as an OpenTelemetry
63
+ * instrumentation: list it with the others, and no runner needs wiring.
64
+ *
65
+ * ```js
66
+ * import { NodeSDK } from '@opentelemetry/sdk-node';
67
+ * import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
68
+ * import { ArazzoRunnerInstrumentation } from '@usearazzo/runner/observability/opentelemetry';
69
+ *
70
+ * new NodeSDK({
71
+ * instrumentations: [getNodeAutoInstrumentations(), new ArazzoRunnerInstrumentation()],
72
+ * }).start();
73
+ * ```
74
+ *
75
+ * In the browser, with the fetch instrumentation for the request spans:
76
+ *
77
+ * ```js
78
+ * import { BatchSpanProcessor, WebTracerProvider } from '@opentelemetry/sdk-trace-web';
79
+ * import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
80
+ * import { ZoneContextManager } from '@opentelemetry/context-zone';
81
+ * import { registerInstrumentations } from '@opentelemetry/instrumentation';
82
+ * import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
83
+ * import { ArazzoRunnerInstrumentation } from '@usearazzo/runner/observability/opentelemetry';
84
+ *
85
+ * const provider = new WebTracerProvider({
86
+ * spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter())],
87
+ * });
88
+ * provider.register({ contextManager: new ZoneContextManager() });
89
+ * registerInstrumentations({
90
+ * // propagateTraceHeaderCorsUrls: the cross-origin APIs that get a traceparent
91
+ * instrumentations: [
92
+ * new FetchInstrumentation({ propagateTraceHeaderCorsUrls: [/api\.example\.com/] }),
93
+ * new ArazzoRunnerInstrumentation(),
94
+ * ],
95
+ * });
96
+ * ```
97
+ *
98
+ * Each workflow invocation and each step is an `INTERNAL` span, the step's
99
+ * under its workflow's, a sub-workflow's and a retry reference's under the
100
+ * step that calls them, and a `dependsOn` workflow's or a transfer target's
101
+ * under the workflow that runs them. Attempts, criteria,
102
+ * selected actions, retry waits, retry references and the operations a step
103
+ * calls are events of the step's span, each named by the runner event it
104
+ * comes from (`step:attempt`, `criterion:evaluated`, `action:selected`, …). A step runs in its span's context, so
105
+ * the HTTP instrumentation of the client it sends with (undici for Node's
106
+ * `fetch`, `@opentelemetry/instrumentation-fetch` in the browser) nests its
107
+ * request spans under the step and propagates the trace into the API.
108
+ *
109
+ * In the browser, the workflow and step spans keep their tree with any
110
+ * context manager, but request spans nest under the step only where the
111
+ * context survives an `await`: zone.js loses it across a native one, so
112
+ * transpile `async`/`await` as OpenTelemetry's web instrumentation asks.
113
+ *
114
+ * Spans carry the identifiers and outcomes of the run, not its data: no
115
+ * inputs, outputs, criterion values or requests. A step or workflow that
116
+ * throws records the error, whose message can quote what the run saw.
117
+ * @public
118
+ */
119
+ class ArazzoRunnerInstrumentation {
120
+ instrumentationName = NAME;
121
+ instrumentationVersion = _version.default;
122
+ #config;
123
+ #tracer;
124
+ #remove;
125
+ // the operation each span traces: an event's active span is acted on only
126
+ // when it is this instrumentation's own
127
+ #operations = new WeakMap();
128
+ // the transition each step span's step last selected, which tells a failure
129
+ // the workflow handles from one that ends it
130
+ #transitions = new WeakMap();
131
+ // the spans each run has open, outermost first: a run's operations are
132
+ // sequential, so the innermost is the parent of the next
133
+ #runs = new Map();
134
+ constructor(config = {}) {
135
+ this.#config = {
136
+ ...config,
137
+ enabled: config.enabled ?? true
138
+ };
139
+ this.#tracer = _api.trace.getTracer(this.instrumentationName, this.instrumentationVersion);
140
+ if (this.#config.enabled) this.enable();
141
+ }
142
+
143
+ /** Starts tracing every runner in the process. */
144
+ enable() {
145
+ this.#remove ??= (0, _runner.instrument)({
146
+ wrap: this.#wrap,
147
+ observer: this.#observe
148
+ });
149
+ }
150
+
151
+ /** Stops tracing; runs in progress stop at their next workflow or step. */
152
+ disable() {
153
+ this.#remove?.();
154
+ this.#remove = undefined;
155
+ }
156
+ setTracerProvider(tracerProvider) {
157
+ this.#tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
158
+ }
159
+
160
+ /** Records no metrics. */
161
+ setMeterProvider() {}
162
+ setConfig(config) {
163
+ this.#config = {
164
+ ...config,
165
+ enabled: config.enabled ?? true
166
+ };
167
+ }
168
+ getConfig() {
169
+ return this.#config;
170
+ }
171
+
172
+ // the span of the operation, made the active context for everything it
173
+ // does. Its parent is the innermost span open in its run, so the run's tree
174
+ // holds with a context manager that loses context across a native await
175
+ // (zone.js in the browser); the run's root takes the active context
176
+ #wrap = async (operation, run) => {
177
+ const parent = this.#runs.get(operation.runId)?.at(-1);
178
+ const parentContext = parent === undefined ? _api.context.active() : _api.trace.setSpan(_api.context.active(), parent);
179
+ const {
180
+ name,
181
+ attributes
182
+ } = spanOf(operation);
183
+ const span = this.#tracer.startSpan(name, {
184
+ kind: _api.SpanKind.INTERNAL,
185
+ attributes
186
+ }, parentContext);
187
+ this.#operations.set(span, operation);
188
+ // registered once the span exists, so a failure to start one leaves nothing behind
189
+ const open = this.#runs.get(operation.runId) ?? [];
190
+ this.#runs.set(operation.runId, open);
191
+ open.push(span);
192
+ try {
193
+ await _api.context.with(_api.trace.setSpan(parentContext, span), run);
194
+ } finally {
195
+ // by identity: an operation settling out of order must not pop another's span
196
+ const index = open.lastIndexOf(span);
197
+ if (index !== -1) open.splice(index, 1);
198
+ if (open.length === 0) this.#runs.delete(operation.runId);
199
+ span.end();
200
+ }
201
+ };
202
+
203
+ // the span of the operation of `kind` the event belongs to: the innermost
204
+ // open in its run, read from the run rather than the active context for the
205
+ // same reason as the parents above
206
+ #active(event, kind) {
207
+ const span = event.runId === undefined ? undefined : this.#runs.get(event.runId)?.at(-1);
208
+ return span !== undefined && this.#operations.get(span)?.kind === kind ? span : undefined;
209
+ }
210
+ #observe = event => {
211
+ switch (event.type) {
212
+ case 'workflow:settled':
213
+ {
214
+ const span = this.#active(event, 'workflow');
215
+ if (span === undefined) return;
216
+ span.setAttributes({
217
+ 'arazzo.workflow.status': event.status,
218
+ 'arazzo.workflow.settled_status': event.settledStatus
219
+ });
220
+ // a transferred workflow did not fail itself: its target reports its own outcome
221
+ if (event.status === 'failed' || event.error !== undefined) fail(span, event.error);
222
+ return;
223
+ }
224
+ case 'step:settled':
225
+ {
226
+ const span = this.#active(event, 'step');
227
+ if (span === undefined) return;
228
+ span.setAttributes({
229
+ 'arazzo.step.attempts': event.attempts,
230
+ 'arazzo.step.successful': event.successful
231
+ });
232
+ // an error only when it threw or its failure ends the workflow (break):
233
+ // a failure an onFailure action handles (goto, end) is the workflow's
234
+ // design, not an error
235
+ const unhandled = !event.successful && this.#transitions.get(span) === 'break';
236
+ if (unhandled || event.error !== undefined) fail(span, event.error);
237
+ return;
238
+ }
239
+ case 'step:attempt':
240
+ this.#addEvent(event, event.type, {
241
+ 'arazzo.step.attempt': event.attempt
242
+ });
243
+ return;
244
+ case 'criterion:evaluated':
245
+ this.#addEvent(event, event.type, {
246
+ 'arazzo.step.attempt': event.attempt,
247
+ 'arazzo.criterion.kind': event.kind,
248
+ 'arazzo.criterion.condition': event.criterion.condition,
249
+ 'arazzo.criterion.met': event.criterion.met
250
+ });
251
+ return;
252
+ case 'action:selected':
253
+ {
254
+ const span = this.#active(event, 'step');
255
+ // the step's own decision, not that of a step a retry references
256
+ const step = span === undefined ? undefined : this.#operations.get(span);
257
+ if (span !== undefined && step?.stepId === event.stepId) {
258
+ this.#transitions.set(span, event.transition.kind);
259
+ }
260
+ this.#addEvent(event, event.type, {
261
+ 'arazzo.step.attempt': event.attempt,
262
+ 'arazzo.action.transition': event.transition.kind,
263
+ ...(event.action === undefined ? {} : {
264
+ 'arazzo.action.name': String((0, _apidomCore.toValue)(event.action.name))
265
+ })
266
+ });
267
+ return;
268
+ }
269
+ case 'retry:wait':
270
+ this.#addEvent(event, event.type, {
271
+ 'arazzo.step.attempt': event.attempt,
272
+ 'arazzo.retry.delay_ms': event.delayMs
273
+ });
274
+ return;
275
+ case 'retry:reference:start':
276
+ case 'retry:reference:settled':
277
+ this.#addEvent(event, event.type, {
278
+ 'arazzo.step.attempt': event.attempt,
279
+ 'arazzo.retry.reference.kind': event.kind,
280
+ 'arazzo.retry.reference.id': event.id,
281
+ ...(event.type === 'retry:reference:settled' ? {
282
+ 'arazzo.retry.reference.successful': event.successful
283
+ } : {})
284
+ });
285
+ return;
286
+ case 'openapi:operation:assembled':
287
+ {
288
+ // an operation executor used on its own runs for no step
289
+ if (event.step === undefined) return;
290
+ const {
291
+ documentURI,
292
+ jsonPointer,
293
+ operationId
294
+ } = event.operation;
295
+ this.#addEvent({
296
+ ...event.step,
297
+ runId: event.runId
298
+ }, event.type, {
299
+ 'arazzo.operation.document_uri': documentURI,
300
+ 'arazzo.operation.json_pointer': jsonPointer,
301
+ ...(operationId === undefined ? {} : {
302
+ 'arazzo.operation.id': operationId
303
+ })
304
+ });
305
+ return;
306
+ }
307
+ default:
308
+ return;
309
+ }
310
+ };
311
+
312
+ // an event of the step's span. It names its step, since a retry's stepId
313
+ // reference reports under the referenced step within the retrying step
314
+ #addEvent(event, name, attributes) {
315
+ this.#active(event, 'step')?.addEvent(name, {
316
+ 'arazzo.step.id': event.stepId,
317
+ ...attributes
318
+ });
319
+ }
320
+ }
321
+ var _default = exports.default = ArazzoRunnerInstrumentation;