@criterionx/opentelemetry 0.3.5

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Tomas Maritano
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,197 @@
1
+ import { Decision, RunOptions, ProfileRegistry, Result, Engine } from '@criterionx/core';
2
+ import { Tracer, Meter } from '@opentelemetry/api';
3
+
4
+ /**
5
+ * Options for creating a traced engine
6
+ */
7
+ interface TracedEngineOptions {
8
+ /** OpenTelemetry Tracer instance */
9
+ tracer?: Tracer;
10
+ /** OpenTelemetry Meter instance for metrics */
11
+ meter?: Meter;
12
+ /** Include input data in span attributes (careful with PII) */
13
+ recordInput?: boolean;
14
+ /** Include output data in span attributes */
15
+ recordOutput?: boolean;
16
+ /** Include profile data in span attributes */
17
+ recordProfile?: boolean;
18
+ /** Custom span name prefix (default: "criterion") */
19
+ spanNamePrefix?: string;
20
+ }
21
+ /**
22
+ * Span attributes added to decision evaluation spans
23
+ */
24
+ interface DecisionSpanAttributes {
25
+ "criterion.decision.id": string;
26
+ "criterion.decision.version": string;
27
+ "criterion.status": string;
28
+ "criterion.matched_rule"?: string;
29
+ "criterion.rules_evaluated": number;
30
+ "criterion.profile_id"?: string;
31
+ "criterion.input"?: string;
32
+ "criterion.output"?: string;
33
+ "criterion.profile"?: string;
34
+ "criterion.error"?: string;
35
+ }
36
+ /**
37
+ * Metric names used by the instrumentation
38
+ */
39
+ declare const METRIC_NAMES: {
40
+ /** Counter for decision evaluations */
41
+ readonly EVALUATIONS: "criterion.evaluations";
42
+ /** Histogram for evaluation duration */
43
+ readonly DURATION: "criterion.duration";
44
+ /** Counter for matched rules */
45
+ readonly RULES_MATCHED: "criterion.rules.matched";
46
+ /** Counter for errors */
47
+ readonly ERRORS: "criterion.errors";
48
+ };
49
+ /**
50
+ * Metric label names
51
+ */
52
+ declare const METRIC_LABELS: {
53
+ readonly DECISION_ID: "decision_id";
54
+ readonly DECISION_VERSION: "decision_version";
55
+ readonly STATUS: "status";
56
+ readonly RULE_ID: "rule_id";
57
+ readonly ERROR_TYPE: "error_type";
58
+ };
59
+ /**
60
+ * Interface for a traced engine that wraps the base Engine
61
+ */
62
+ interface TracedEngine {
63
+ /** Run a decision with tracing */
64
+ run<TInput, TOutput, TProfile>(decision: Decision<TInput, TOutput, TProfile>, context: TInput, options: RunOptions<TProfile>, registry?: ProfileRegistry<TProfile>): Result<TOutput>;
65
+ /** Get the underlying engine */
66
+ getEngine(): Engine;
67
+ }
68
+
69
+ /**
70
+ * OpenTelemetry tracing for Criterion decision engine
71
+ *
72
+ * @example Basic usage
73
+ * ```typescript
74
+ * import { trace } from "@opentelemetry/api";
75
+ * import { createTracedEngine } from "@criterionx/opentelemetry";
76
+ *
77
+ * const tracedEngine = createTracedEngine({
78
+ * tracer: trace.getTracer("my-app"),
79
+ * });
80
+ *
81
+ * const result = tracedEngine.run(decision, input, { profile });
82
+ * // Automatically creates a span with decision metadata
83
+ * ```
84
+ */
85
+
86
+ /**
87
+ * Create a traced engine that wraps decision evaluation with OpenTelemetry spans
88
+ *
89
+ * @example With custom options
90
+ * ```typescript
91
+ * const tracedEngine = createTracedEngine({
92
+ * tracer: trace.getTracer("my-service", "1.0.0"),
93
+ * recordInput: true, // Include input in span (careful with PII)
94
+ * recordOutput: true, // Include output in span
95
+ * spanNamePrefix: "decisions",
96
+ * });
97
+ * ```
98
+ */
99
+ declare function createTracedEngine(options?: TracedEngineOptions): TracedEngine;
100
+ /**
101
+ * Wrap an existing engine with tracing capabilities
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { Engine } from "@criterionx/core";
106
+ * import { wrapEngine } from "@criterionx/opentelemetry";
107
+ *
108
+ * const engine = new Engine();
109
+ * const tracedEngine = wrapEngine(engine, {
110
+ * tracer: myTracer,
111
+ * });
112
+ * ```
113
+ */
114
+ declare function wrapEngine(engine: Engine, options?: TracedEngineOptions): TracedEngine;
115
+
116
+ /**
117
+ * OpenTelemetry metrics for Criterion decision engine
118
+ *
119
+ * @example Basic usage
120
+ * ```typescript
121
+ * import { metrics } from "@opentelemetry/api";
122
+ * import { createMetricsRecorder, recordEvaluation } from "@criterionx/opentelemetry";
123
+ *
124
+ * const recorder = createMetricsRecorder({
125
+ * meter: metrics.getMeter("my-app"),
126
+ * });
127
+ *
128
+ * // After running a decision
129
+ * recorder.recordEvaluation(decision, result, durationMs);
130
+ * ```
131
+ */
132
+
133
+ /**
134
+ * Options for creating a metrics recorder
135
+ */
136
+ interface MetricsRecorderOptions {
137
+ /** OpenTelemetry Meter instance */
138
+ meter?: Meter;
139
+ /** Metric name prefix (default: "criterion") */
140
+ prefix?: string;
141
+ }
142
+ /**
143
+ * Metrics recorder for decision evaluations
144
+ */
145
+ interface MetricsRecorder {
146
+ /** Record a decision evaluation */
147
+ recordEvaluation<TOutput>(decision: Decision<unknown, TOutput, unknown>, result: Result<TOutput>, durationMs: number): void;
148
+ }
149
+ /**
150
+ * Create a metrics recorder for decision evaluations
151
+ *
152
+ * Records:
153
+ * - `criterion.evaluations` (counter): Total evaluations by decision_id, status
154
+ * - `criterion.duration` (histogram): Evaluation duration in milliseconds
155
+ * - `criterion.rules.matched` (counter): Rule matches by decision_id, rule_id
156
+ * - `criterion.errors` (counter): Errors by decision_id, error_type
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * import { metrics } from "@opentelemetry/api";
161
+ * import { createMetricsRecorder } from "@criterionx/opentelemetry";
162
+ *
163
+ * const recorder = createMetricsRecorder({
164
+ * meter: metrics.getMeter("my-service"),
165
+ * });
166
+ *
167
+ * // Use with engine
168
+ * const start = performance.now();
169
+ * const result = engine.run(decision, input, { profile });
170
+ * const duration = performance.now() - start;
171
+ *
172
+ * recorder.recordEvaluation(decision, result, duration);
173
+ * ```
174
+ */
175
+ declare function createMetricsRecorder(options?: MetricsRecorderOptions): MetricsRecorder;
176
+ /**
177
+ * Create a metered engine that automatically records metrics
178
+ *
179
+ * Combines the base engine with automatic metrics recording.
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * import { createMeteredEngine } from "@criterionx/opentelemetry";
184
+ *
185
+ * const engine = createMeteredEngine({
186
+ * meter: metrics.getMeter("my-service"),
187
+ * });
188
+ *
189
+ * // Metrics are automatically recorded
190
+ * const result = engine.run(decision, input, { profile });
191
+ * ```
192
+ */
193
+ declare function createMeteredEngine(options?: MetricsRecorderOptions): {
194
+ run<TInput, TOutput, TProfile>(decision: Decision<TInput, TOutput, TProfile>, context: TInput, runOptions: RunOptions<TProfile>, registry?: ProfileRegistry<TProfile>): Result<TOutput>;
195
+ };
196
+
197
+ export { type DecisionSpanAttributes, METRIC_LABELS, METRIC_NAMES, type MetricsRecorder, type MetricsRecorderOptions, type TracedEngine, type TracedEngineOptions, createMeteredEngine, createMetricsRecorder, createTracedEngine, wrapEngine };
package/dist/index.js ADDED
@@ -0,0 +1,234 @@
1
+ // src/tracing.ts
2
+ import {
3
+ trace,
4
+ SpanKind,
5
+ SpanStatusCode
6
+ } from "@opentelemetry/api";
7
+ import { Engine } from "@criterionx/core";
8
+ var DEFAULT_SPAN_PREFIX = "criterion";
9
+ function createTracedEngine(options = {}) {
10
+ const {
11
+ tracer = trace.getTracer("@criterionx/opentelemetry"),
12
+ recordInput = false,
13
+ recordOutput = false,
14
+ recordProfile = false,
15
+ spanNamePrefix = DEFAULT_SPAN_PREFIX
16
+ } = options;
17
+ const engine = new Engine();
18
+ return {
19
+ run(decision, context, runOptions, registry) {
20
+ const spanName = `${spanNamePrefix}.${decision.id}`;
21
+ return tracer.startActiveSpan(spanName, { kind: SpanKind.INTERNAL }, (span) => {
22
+ const startTime = performance.now();
23
+ try {
24
+ span.setAttribute("criterion.decision.id", decision.id);
25
+ span.setAttribute("criterion.decision.version", decision.version);
26
+ if (recordInput) {
27
+ span.setAttribute("criterion.input", JSON.stringify(context));
28
+ }
29
+ if (typeof runOptions.profile === "string") {
30
+ span.setAttribute("criterion.profile_id", runOptions.profile);
31
+ } else if (recordProfile) {
32
+ span.setAttribute("criterion.profile", JSON.stringify(runOptions.profile));
33
+ }
34
+ const result = engine.run(decision, context, runOptions, registry);
35
+ span.setAttribute("criterion.status", result.status);
36
+ span.setAttribute("criterion.rules_evaluated", result.meta.evaluatedRules.length);
37
+ if (result.status === "OK" && result.meta.matchedRule) {
38
+ span.setAttribute("criterion.matched_rule", result.meta.matchedRule);
39
+ }
40
+ if (result.meta.profileId) {
41
+ span.setAttribute("criterion.profile_id", result.meta.profileId);
42
+ }
43
+ if (recordOutput && result.data) {
44
+ span.setAttribute("criterion.output", JSON.stringify(result.data));
45
+ }
46
+ if (result.status === "OK") {
47
+ span.setStatus({ code: SpanStatusCode.OK });
48
+ } else {
49
+ span.setStatus({
50
+ code: SpanStatusCode.ERROR,
51
+ message: result.meta.explanation
52
+ });
53
+ span.setAttribute("criterion.error", result.meta.explanation);
54
+ }
55
+ const duration = performance.now() - startTime;
56
+ span.setAttribute("criterion.duration_ms", duration);
57
+ return result;
58
+ } catch (error) {
59
+ const err = error instanceof Error ? error : new Error(String(error));
60
+ span.recordException(err);
61
+ span.setStatus({
62
+ code: SpanStatusCode.ERROR,
63
+ message: err.message
64
+ });
65
+ span.setAttribute("criterion.error", err.message);
66
+ throw error;
67
+ } finally {
68
+ span.end();
69
+ }
70
+ });
71
+ },
72
+ getEngine() {
73
+ return engine;
74
+ }
75
+ };
76
+ }
77
+ function wrapEngine(engine, options = {}) {
78
+ const {
79
+ tracer = trace.getTracer("@criterionx/opentelemetry"),
80
+ recordInput = false,
81
+ recordOutput = false,
82
+ recordProfile = false,
83
+ spanNamePrefix = DEFAULT_SPAN_PREFIX
84
+ } = options;
85
+ return {
86
+ run(decision, context, runOptions, registry) {
87
+ const spanName = `${spanNamePrefix}.${decision.id}`;
88
+ return tracer.startActiveSpan(spanName, { kind: SpanKind.INTERNAL }, (span) => {
89
+ const startTime = performance.now();
90
+ try {
91
+ span.setAttribute("criterion.decision.id", decision.id);
92
+ span.setAttribute("criterion.decision.version", decision.version);
93
+ if (recordInput) {
94
+ span.setAttribute("criterion.input", JSON.stringify(context));
95
+ }
96
+ if (typeof runOptions.profile === "string") {
97
+ span.setAttribute("criterion.profile_id", runOptions.profile);
98
+ } else if (recordProfile) {
99
+ span.setAttribute("criterion.profile", JSON.stringify(runOptions.profile));
100
+ }
101
+ const result = engine.run(decision, context, runOptions, registry);
102
+ span.setAttribute("criterion.status", result.status);
103
+ span.setAttribute("criterion.rules_evaluated", result.meta.evaluatedRules.length);
104
+ if (result.status === "OK" && result.meta.matchedRule) {
105
+ span.setAttribute("criterion.matched_rule", result.meta.matchedRule);
106
+ }
107
+ if (result.meta.profileId) {
108
+ span.setAttribute("criterion.profile_id", result.meta.profileId);
109
+ }
110
+ if (recordOutput && result.data) {
111
+ span.setAttribute("criterion.output", JSON.stringify(result.data));
112
+ }
113
+ if (result.status === "OK") {
114
+ span.setStatus({ code: SpanStatusCode.OK });
115
+ } else {
116
+ span.setStatus({
117
+ code: SpanStatusCode.ERROR,
118
+ message: result.meta.explanation
119
+ });
120
+ span.setAttribute("criterion.error", result.meta.explanation);
121
+ }
122
+ const duration = performance.now() - startTime;
123
+ span.setAttribute("criterion.duration_ms", duration);
124
+ return result;
125
+ } catch (error) {
126
+ const err = error instanceof Error ? error : new Error(String(error));
127
+ span.recordException(err);
128
+ span.setStatus({
129
+ code: SpanStatusCode.ERROR,
130
+ message: err.message
131
+ });
132
+ span.setAttribute("criterion.error", err.message);
133
+ throw error;
134
+ } finally {
135
+ span.end();
136
+ }
137
+ });
138
+ },
139
+ getEngine() {
140
+ return engine;
141
+ }
142
+ };
143
+ }
144
+
145
+ // src/metrics.ts
146
+ import { metrics } from "@opentelemetry/api";
147
+ import { Engine as Engine2 } from "@criterionx/core";
148
+
149
+ // src/types.ts
150
+ var METRIC_NAMES = {
151
+ /** Counter for decision evaluations */
152
+ EVALUATIONS: "criterion.evaluations",
153
+ /** Histogram for evaluation duration */
154
+ DURATION: "criterion.duration",
155
+ /** Counter for matched rules */
156
+ RULES_MATCHED: "criterion.rules.matched",
157
+ /** Counter for errors */
158
+ ERRORS: "criterion.errors"
159
+ };
160
+ var METRIC_LABELS = {
161
+ DECISION_ID: "decision_id",
162
+ DECISION_VERSION: "decision_version",
163
+ STATUS: "status",
164
+ RULE_ID: "rule_id",
165
+ ERROR_TYPE: "error_type"
166
+ };
167
+
168
+ // src/metrics.ts
169
+ function createMetricsRecorder(options = {}) {
170
+ const {
171
+ meter = metrics.getMeter("@criterionx/opentelemetry"),
172
+ prefix = "criterion"
173
+ } = options;
174
+ const evaluationsCounter = meter.createCounter(`${prefix}.evaluations`, {
175
+ description: "Total number of decision evaluations",
176
+ unit: "1"
177
+ });
178
+ const durationHistogram = meter.createHistogram(`${prefix}.duration`, {
179
+ description: "Decision evaluation duration",
180
+ unit: "ms"
181
+ });
182
+ const rulesMatchedCounter = meter.createCounter(`${prefix}.rules.matched`, {
183
+ description: "Number of rule matches by rule ID",
184
+ unit: "1"
185
+ });
186
+ const errorsCounter = meter.createCounter(`${prefix}.errors`, {
187
+ description: "Number of evaluation errors",
188
+ unit: "1"
189
+ });
190
+ return {
191
+ recordEvaluation(decision, result, durationMs) {
192
+ const labels = {
193
+ [METRIC_LABELS.DECISION_ID]: decision.id,
194
+ [METRIC_LABELS.DECISION_VERSION]: decision.version,
195
+ [METRIC_LABELS.STATUS]: result.status
196
+ };
197
+ evaluationsCounter.add(1, labels);
198
+ durationHistogram.record(durationMs, labels);
199
+ if (result.status === "OK" && result.meta.matchedRule) {
200
+ rulesMatchedCounter.add(1, {
201
+ [METRIC_LABELS.DECISION_ID]: decision.id,
202
+ [METRIC_LABELS.RULE_ID]: result.meta.matchedRule
203
+ });
204
+ }
205
+ if (result.status !== "OK") {
206
+ errorsCounter.add(1, {
207
+ [METRIC_LABELS.DECISION_ID]: decision.id,
208
+ [METRIC_LABELS.ERROR_TYPE]: result.status
209
+ });
210
+ }
211
+ }
212
+ };
213
+ }
214
+ function createMeteredEngine(options = {}) {
215
+ const engine = new Engine2();
216
+ const recorder = createMetricsRecorder(options);
217
+ return {
218
+ run(decision, context, runOptions, registry) {
219
+ const start = performance.now();
220
+ const result = engine.run(decision, context, runOptions, registry);
221
+ const duration = performance.now() - start;
222
+ recorder.recordEvaluation(decision, result, duration);
223
+ return result;
224
+ }
225
+ };
226
+ }
227
+ export {
228
+ METRIC_LABELS,
229
+ METRIC_NAMES,
230
+ createMeteredEngine,
231
+ createMetricsRecorder,
232
+ createTracedEngine,
233
+ wrapEngine
234
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@criterionx/opentelemetry",
3
+ "version": "0.3.5",
4
+ "description": "OpenTelemetry instrumentation for Criterion decision engine",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "dependencies": {
18
+ "@criterionx/core": "0.3.5"
19
+ },
20
+ "peerDependencies": {
21
+ "@opentelemetry/api": ">=1.0.0"
22
+ },
23
+ "devDependencies": {
24
+ "@opentelemetry/api": "^1.9.0",
25
+ "@opentelemetry/sdk-trace-base": "^1.29.0",
26
+ "@types/node": "^20.0.0",
27
+ "tsup": "^8.0.0",
28
+ "typescript": "^5.3.0",
29
+ "vitest": "^4.0.0",
30
+ "zod": "^3.23.0"
31
+ },
32
+ "keywords": [
33
+ "criterion",
34
+ "opentelemetry",
35
+ "tracing",
36
+ "metrics",
37
+ "observability",
38
+ "instrumentation"
39
+ ],
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/tomymaritano/criterionx.git",
44
+ "directory": "packages/opentelemetry"
45
+ },
46
+ "scripts": {
47
+ "build": "tsup src/index.ts --format esm --dts --clean",
48
+ "test": "vitest run",
49
+ "typecheck": "tsc --noEmit"
50
+ }
51
+ }