@contractspec/lib.observability 1.56.1 → 1.58.0

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 (73) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/anomaly/alert-manager.d.ts +17 -0
  3. package/dist/anomaly/alert-manager.js +24 -0
  4. package/dist/anomaly/anomaly-detector.d.ts +22 -0
  5. package/dist/anomaly/anomaly-detector.js +102 -0
  6. package/dist/anomaly/baseline-calculator.d.ts +23 -0
  7. package/dist/anomaly/baseline-calculator.js +40 -0
  8. package/dist/anomaly/root-cause-analyzer.d.ts +19 -0
  9. package/dist/anomaly/root-cause-analyzer.js +32 -0
  10. package/dist/index.d.ts +16 -0
  11. package/dist/index.js +1078 -0
  12. package/dist/intent/aggregator.d.ts +57 -0
  13. package/dist/intent/aggregator.js +110 -0
  14. package/dist/intent/detector.d.ts +28 -0
  15. package/dist/intent/detector.js +133 -0
  16. package/dist/logging/index.d.ts +17 -0
  17. package/dist/logging/index.js +42 -0
  18. package/dist/metrics/index.d.ts +12 -0
  19. package/dist/metrics/index.js +31 -0
  20. package/dist/node/anomaly/alert-manager.js +23 -0
  21. package/dist/node/anomaly/anomaly-detector.js +101 -0
  22. package/dist/node/anomaly/baseline-calculator.js +39 -0
  23. package/dist/node/anomaly/root-cause-analyzer.js +31 -0
  24. package/dist/node/index.js +1077 -0
  25. package/dist/node/intent/aggregator.js +109 -0
  26. package/dist/node/intent/detector.js +132 -0
  27. package/dist/node/logging/index.js +41 -0
  28. package/dist/node/metrics/index.js +30 -0
  29. package/dist/node/pipeline/evolution-pipeline.js +299 -0
  30. package/dist/node/pipeline/lifecycle-pipeline.js +85 -0
  31. package/dist/node/telemetry/posthog-baseline-reader.js +308 -0
  32. package/dist/node/telemetry/posthog-telemetry.js +60 -0
  33. package/dist/node/tracing/index.js +52 -0
  34. package/dist/node/tracing/middleware.js +150 -0
  35. package/dist/pipeline/evolution-pipeline.d.ts +36 -0
  36. package/dist/pipeline/evolution-pipeline.js +300 -0
  37. package/dist/pipeline/lifecycle-pipeline.d.ts +40 -0
  38. package/dist/pipeline/lifecycle-pipeline.js +86 -0
  39. package/dist/telemetry/posthog-baseline-reader.d.ts +27 -0
  40. package/dist/telemetry/posthog-baseline-reader.js +309 -0
  41. package/dist/telemetry/posthog-telemetry.d.ts +15 -0
  42. package/dist/telemetry/posthog-telemetry.js +61 -0
  43. package/dist/tracing/index.d.ts +5 -0
  44. package/dist/tracing/index.js +53 -0
  45. package/dist/tracing/middleware.d.ts +15 -0
  46. package/dist/tracing/middleware.js +151 -0
  47. package/package.json +140 -39
  48. package/dist/anomaly/alert-manager.d.mts +0 -21
  49. package/dist/anomaly/alert-manager.mjs +0 -23
  50. package/dist/anomaly/anomaly-detector.d.mts +0 -26
  51. package/dist/anomaly/anomaly-detector.mjs +0 -58
  52. package/dist/anomaly/baseline-calculator.d.mts +0 -26
  53. package/dist/anomaly/baseline-calculator.mjs +0 -37
  54. package/dist/anomaly/root-cause-analyzer.d.mts +0 -23
  55. package/dist/anomaly/root-cause-analyzer.mjs +0 -27
  56. package/dist/index.d.mts +0 -13
  57. package/dist/index.mjs +0 -14
  58. package/dist/intent/aggregator.d.mts +0 -60
  59. package/dist/intent/aggregator.mjs +0 -98
  60. package/dist/intent/detector.d.mts +0 -32
  61. package/dist/intent/detector.mjs +0 -122
  62. package/dist/logging/index.d.mts +0 -20
  63. package/dist/logging/index.mjs +0 -40
  64. package/dist/metrics/index.d.mts +0 -17
  65. package/dist/metrics/index.mjs +0 -26
  66. package/dist/pipeline/evolution-pipeline.d.mts +0 -40
  67. package/dist/pipeline/evolution-pipeline.mjs +0 -66
  68. package/dist/pipeline/lifecycle-pipeline.d.mts +0 -44
  69. package/dist/pipeline/lifecycle-pipeline.mjs +0 -73
  70. package/dist/tracing/index.d.mts +0 -9
  71. package/dist/tracing/index.mjs +0 -47
  72. package/dist/tracing/middleware.d.mts +0 -19
  73. package/dist/tracing/middleware.mjs +0 -80
@@ -1,32 +0,0 @@
1
- import { AggregatedOperationMetrics, OperationSequence } from "./aggregator.mjs";
2
-
3
- //#region src/intent/detector.d.ts
4
- type IntentSignalType = 'latency-regression' | 'error-spike' | 'throughput-drop' | 'missing-workflow-step';
5
- interface IntentSignal {
6
- id: string;
7
- type: IntentSignalType;
8
- operation?: AggregatedOperationMetrics['operation'];
9
- confidence: number;
10
- description: string;
11
- metadata?: Record<string, unknown>;
12
- evidence: {
13
- type: 'metric' | 'sequence' | 'anomaly';
14
- description: string;
15
- data?: Record<string, unknown>;
16
- }[];
17
- }
18
- interface IntentDetectorOptions {
19
- errorRateThreshold?: number;
20
- latencyP99ThresholdMs?: number;
21
- throughputDropThreshold?: number;
22
- minSequenceLength?: number;
23
- }
24
- declare class IntentDetector {
25
- private readonly options;
26
- constructor(options?: IntentDetectorOptions);
27
- detectFromMetrics(current: AggregatedOperationMetrics[], previous?: AggregatedOperationMetrics[]): IntentSignal[];
28
- detectSequentialIntents(sequences: OperationSequence[]): IntentSignal[];
29
- }
30
- //#endregion
31
- export { IntentDetector, IntentDetectorOptions, IntentSignal, IntentSignalType };
32
- //# sourceMappingURL=detector.d.mts.map
@@ -1,122 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
-
3
- //#region src/intent/detector.ts
4
- const DEFAULTS = {
5
- errorRateThreshold: .05,
6
- latencyP99ThresholdMs: 750,
7
- throughputDropThreshold: .3,
8
- minSequenceLength: 3
9
- };
10
- var IntentDetector = class {
11
- options;
12
- constructor(options = {}) {
13
- this.options = {
14
- errorRateThreshold: options.errorRateThreshold ?? DEFAULTS.errorRateThreshold,
15
- latencyP99ThresholdMs: options.latencyP99ThresholdMs ?? DEFAULTS.latencyP99ThresholdMs,
16
- throughputDropThreshold: options.throughputDropThreshold ?? DEFAULTS.throughputDropThreshold,
17
- minSequenceLength: options.minSequenceLength ?? DEFAULTS.minSequenceLength
18
- };
19
- }
20
- detectFromMetrics(current, previous) {
21
- const signals = [];
22
- const baseline = new Map((previous ?? []).map((metric) => [`${metric.operation.name}.v${metric.operation.version}`, metric]));
23
- for (const metric of current) {
24
- if (metric.errorRate >= this.options.errorRateThreshold) {
25
- signals.push({
26
- id: randomUUID(),
27
- type: "error-spike",
28
- operation: metric.operation,
29
- confidence: Math.min(1, metric.errorRate / this.options.errorRateThreshold),
30
- description: `Error rate ${metric.errorRate.toFixed(2)} exceeded threshold`,
31
- metadata: {
32
- errorRate: metric.errorRate,
33
- topErrors: metric.topErrors
34
- },
35
- evidence: [{
36
- type: "metric",
37
- description: "error-rate",
38
- data: {
39
- errorRate: metric.errorRate,
40
- threshold: this.options.errorRateThreshold
41
- }
42
- }]
43
- });
44
- continue;
45
- }
46
- if (metric.p99LatencyMs >= this.options.latencyP99ThresholdMs) {
47
- signals.push({
48
- id: randomUUID(),
49
- type: "latency-regression",
50
- operation: metric.operation,
51
- confidence: Math.min(1, metric.p99LatencyMs / this.options.latencyP99ThresholdMs),
52
- description: `P99 latency ${metric.p99LatencyMs}ms exceeded threshold`,
53
- metadata: { p99LatencyMs: metric.p99LatencyMs },
54
- evidence: [{
55
- type: "metric",
56
- description: "p99-latency",
57
- data: {
58
- p99LatencyMs: metric.p99LatencyMs,
59
- threshold: this.options.latencyP99ThresholdMs
60
- }
61
- }]
62
- });
63
- continue;
64
- }
65
- const base = baseline.get(`${metric.operation.name}.v${metric.operation.version}`);
66
- if (base) {
67
- const drop = (base.totalCalls - metric.totalCalls) / Math.max(base.totalCalls, 1);
68
- if (drop >= this.options.throughputDropThreshold) signals.push({
69
- id: randomUUID(),
70
- type: "throughput-drop",
71
- operation: metric.operation,
72
- confidence: Math.min(1, drop / this.options.throughputDropThreshold),
73
- description: `Throughput dropped ${(drop * 100).toFixed(1)}% vs baseline`,
74
- metadata: {
75
- baselineCalls: base.totalCalls,
76
- currentCalls: metric.totalCalls
77
- },
78
- evidence: [{
79
- type: "metric",
80
- description: "throughput-drop",
81
- data: {
82
- baselineCalls: base.totalCalls,
83
- currentCalls: metric.totalCalls
84
- }
85
- }]
86
- });
87
- }
88
- }
89
- return signals;
90
- }
91
- detectSequentialIntents(sequences) {
92
- const signals = [];
93
- for (const sequence of sequences) {
94
- if (sequence.steps.length < this.options.minSequenceLength) continue;
95
- const description = sequence.steps.join(" → ");
96
- signals.push({
97
- id: randomUUID(),
98
- type: "missing-workflow-step",
99
- confidence: .6,
100
- description: `Repeated workflow detected: ${description}`,
101
- metadata: {
102
- steps: sequence.steps,
103
- tenantId: sequence.tenantId,
104
- occurrences: sequence.count
105
- },
106
- evidence: [{
107
- type: "sequence",
108
- description: "sequential-calls",
109
- data: {
110
- steps: sequence.steps,
111
- count: sequence.count
112
- }
113
- }]
114
- });
115
- }
116
- return signals;
117
- }
118
- };
119
-
120
- //#endregion
121
- export { IntentDetector };
122
- //# sourceMappingURL=detector.mjs.map
@@ -1,20 +0,0 @@
1
- //#region src/logging/index.d.ts
2
- type LogLevel = 'debug' | 'info' | 'warn' | 'error';
3
- interface LogEntry {
4
- level: LogLevel;
5
- message: string;
6
- [key: string]: unknown;
7
- }
8
- declare class Logger {
9
- private readonly serviceName;
10
- constructor(serviceName: string);
11
- private log;
12
- debug(message: string, meta?: Record<string, unknown>): void;
13
- info(message: string, meta?: Record<string, unknown>): void;
14
- warn(message: string, meta?: Record<string, unknown>): void;
15
- error(message: string, meta?: Record<string, unknown>): void;
16
- }
17
- declare const logger: Logger;
18
- //#endregion
19
- export { LogEntry, LogLevel, Logger, logger };
20
- //# sourceMappingURL=index.d.mts.map
@@ -1,40 +0,0 @@
1
- import { context, trace } from "@opentelemetry/api";
2
-
3
- //#region src/logging/index.ts
4
- var Logger = class {
5
- constructor(serviceName) {
6
- this.serviceName = serviceName;
7
- }
8
- log(level, message, meta = {}) {
9
- const span = trace.getSpan(context.active());
10
- const traceId = span?.spanContext().traceId;
11
- const spanId = span?.spanContext().spanId;
12
- const entry = {
13
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
14
- service: this.serviceName,
15
- level,
16
- message,
17
- traceId,
18
- spanId,
19
- ...meta
20
- };
21
- console.log(JSON.stringify(entry));
22
- }
23
- debug(message, meta) {
24
- this.log("debug", message, meta);
25
- }
26
- info(message, meta) {
27
- this.log("info", message, meta);
28
- }
29
- warn(message, meta) {
30
- this.log("warn", message, meta);
31
- }
32
- error(message, meta) {
33
- this.log("error", message, meta);
34
- }
35
- };
36
- const logger = new Logger(process.env.OTEL_SERVICE_NAME || "unknown-service");
37
-
38
- //#endregion
39
- export { Logger, logger };
40
- //# sourceMappingURL=index.mjs.map
@@ -1,17 +0,0 @@
1
- import * as _opentelemetry_api0 from "@opentelemetry/api";
2
- import { Counter, Histogram, Meter, UpDownCounter } from "@opentelemetry/api";
3
-
4
- //#region src/metrics/index.d.ts
5
- declare function getMeter(name?: string): Meter;
6
- declare function createCounter(name: string, description?: string, meterName?: string): Counter;
7
- declare function createUpDownCounter(name: string, description?: string, meterName?: string): UpDownCounter;
8
- declare function createHistogram(name: string, description?: string, meterName?: string): Histogram;
9
- declare const standardMetrics: {
10
- httpRequests: Counter<_opentelemetry_api0.Attributes>;
11
- httpDuration: Histogram<_opentelemetry_api0.Attributes>;
12
- operationErrors: Counter<_opentelemetry_api0.Attributes>;
13
- workflowDuration: Histogram<_opentelemetry_api0.Attributes>;
14
- };
15
- //#endregion
16
- export { createCounter, createHistogram, createUpDownCounter, getMeter, standardMetrics };
17
- //# sourceMappingURL=index.d.mts.map
@@ -1,26 +0,0 @@
1
- import { metrics } from "@opentelemetry/api";
2
-
3
- //#region src/metrics/index.ts
4
- const DEFAULT_METER_NAME = "@contractspec/lib.observability";
5
- function getMeter(name = DEFAULT_METER_NAME) {
6
- return metrics.getMeter(name);
7
- }
8
- function createCounter(name, description, meterName) {
9
- return getMeter(meterName).createCounter(name, { description });
10
- }
11
- function createUpDownCounter(name, description, meterName) {
12
- return getMeter(meterName).createUpDownCounter(name, { description });
13
- }
14
- function createHistogram(name, description, meterName) {
15
- return getMeter(meterName).createHistogram(name, { description });
16
- }
17
- const standardMetrics = {
18
- httpRequests: createCounter("http_requests_total", "Total HTTP requests"),
19
- httpDuration: createHistogram("http_request_duration_seconds", "HTTP request duration"),
20
- operationErrors: createCounter("operation_errors_total", "Total operation errors"),
21
- workflowDuration: createHistogram("workflow_duration_seconds", "Workflow execution duration")
22
- };
23
-
24
- //#endregion
25
- export { createCounter, createHistogram, createUpDownCounter, getMeter, standardMetrics };
26
- //# sourceMappingURL=index.mjs.map
@@ -1,40 +0,0 @@
1
- import { IntentAggregator, IntentAggregatorSnapshot, TelemetrySample } from "../intent/aggregator.mjs";
2
- import { IntentDetector, IntentSignal } from "../intent/detector.mjs";
3
- import { EventEmitter } from "node:events";
4
-
5
- //#region src/pipeline/evolution-pipeline.d.ts
6
- type EvolutionPipelineEvent = {
7
- type: 'intent.detected';
8
- payload: IntentSignal;
9
- } | {
10
- type: 'telemetry.window';
11
- payload: {
12
- sampleCount: number;
13
- };
14
- };
15
- interface EvolutionPipelineOptions {
16
- detector?: IntentDetector;
17
- aggregator?: IntentAggregator;
18
- emitter?: EventEmitter;
19
- onIntent?: (intent: IntentSignal) => Promise<void> | void;
20
- onSnapshot?: (snapshot: IntentAggregatorSnapshot) => Promise<void> | void;
21
- }
22
- declare class EvolutionPipeline {
23
- private readonly detector;
24
- private readonly aggregator;
25
- private readonly emitter;
26
- private readonly onIntent?;
27
- private readonly onSnapshot?;
28
- private timer?;
29
- private previousMetrics?;
30
- constructor(options?: EvolutionPipelineOptions);
31
- ingest(sample: TelemetrySample): void;
32
- on(listener: (event: EvolutionPipelineEvent) => void): void;
33
- start(intervalMs?: number): void;
34
- stop(): void;
35
- run(): Promise<void>;
36
- private emit;
37
- }
38
- //#endregion
39
- export { EvolutionPipeline, EvolutionPipelineEvent, EvolutionPipelineOptions };
40
- //# sourceMappingURL=evolution-pipeline.d.mts.map
@@ -1,66 +0,0 @@
1
- import { IntentAggregator } from "../intent/aggregator.mjs";
2
- import { IntentDetector } from "../intent/detector.mjs";
3
- import { EventEmitter } from "node:events";
4
-
5
- //#region src/pipeline/evolution-pipeline.ts
6
- var EvolutionPipeline = class {
7
- detector;
8
- aggregator;
9
- emitter;
10
- onIntent;
11
- onSnapshot;
12
- timer;
13
- previousMetrics;
14
- constructor(options = {}) {
15
- this.detector = options.detector ?? new IntentDetector();
16
- this.aggregator = options.aggregator ?? new IntentAggregator();
17
- this.emitter = options.emitter ?? new EventEmitter();
18
- this.onIntent = options.onIntent;
19
- this.onSnapshot = options.onSnapshot;
20
- }
21
- ingest(sample) {
22
- this.aggregator.add(sample);
23
- }
24
- on(listener) {
25
- this.emitter.on("event", listener);
26
- }
27
- start(intervalMs = 300 * 1e3) {
28
- this.stop();
29
- this.timer = setInterval(() => {
30
- this.run();
31
- }, intervalMs);
32
- }
33
- stop() {
34
- if (this.timer) {
35
- clearInterval(this.timer);
36
- this.timer = void 0;
37
- }
38
- }
39
- async run() {
40
- const snapshot = this.aggregator.flush();
41
- this.emit({
42
- type: "telemetry.window",
43
- payload: { sampleCount: snapshot.sampleCount }
44
- });
45
- if (this.onSnapshot) await this.onSnapshot(snapshot);
46
- if (!snapshot.sampleCount) return;
47
- const metricSignals = this.detector.detectFromMetrics(snapshot.metrics, this.previousMetrics);
48
- const sequenceSignals = this.detector.detectSequentialIntents(snapshot.sequences);
49
- this.previousMetrics = snapshot.metrics;
50
- const signals = [...metricSignals, ...sequenceSignals];
51
- for (const signal of signals) {
52
- if (this.onIntent) await this.onIntent(signal);
53
- this.emit({
54
- type: "intent.detected",
55
- payload: signal
56
- });
57
- }
58
- }
59
- emit(event) {
60
- this.emitter.emit("event", event);
61
- }
62
- };
63
-
64
- //#endregion
65
- export { EvolutionPipeline };
66
- //# sourceMappingURL=evolution-pipeline.mjs.map
@@ -1,44 +0,0 @@
1
- import { EventEmitter } from "node:events";
2
- import { LifecycleAssessment, LifecycleStage } from "@contractspec/lib.lifecycle";
3
-
4
- //#region src/pipeline/lifecycle-pipeline.d.ts
5
- type LifecyclePipelineEvent = {
6
- type: 'assessment.recorded';
7
- payload: {
8
- tenantId?: string;
9
- stage: LifecycleStage;
10
- };
11
- } | {
12
- type: 'stage.changed';
13
- payload: {
14
- tenantId?: string;
15
- previousStage?: LifecycleStage;
16
- nextStage: LifecycleStage;
17
- };
18
- } | {
19
- type: 'confidence.low';
20
- payload: {
21
- tenantId?: string;
22
- confidence: number;
23
- };
24
- };
25
- interface LifecycleKpiPipelineOptions {
26
- meterName?: string;
27
- emitter?: EventEmitter;
28
- lowConfidenceThreshold?: number;
29
- }
30
- declare class LifecycleKpiPipeline {
31
- private readonly assessmentCounter;
32
- private readonly confidenceHistogram;
33
- private readonly stageUpDownCounter;
34
- private readonly emitter;
35
- private readonly lowConfidenceThreshold;
36
- private readonly currentStageByTenant;
37
- constructor(options?: LifecycleKpiPipelineOptions);
38
- recordAssessment(assessment: LifecycleAssessment, tenantId?: string): void;
39
- on(listener: (event: LifecyclePipelineEvent) => void): void;
40
- private ensureStageCounters;
41
- }
42
- //#endregion
43
- export { LifecycleKpiPipeline, LifecycleKpiPipelineOptions, LifecyclePipelineEvent };
44
- //# sourceMappingURL=lifecycle-pipeline.d.mts.map
@@ -1,73 +0,0 @@
1
- import { createCounter, createHistogram, createUpDownCounter } from "../metrics/index.mjs";
2
- import { EventEmitter } from "node:events";
3
- import { getStageLabel } from "@contractspec/lib.lifecycle";
4
-
5
- //#region src/pipeline/lifecycle-pipeline.ts
6
- var LifecycleKpiPipeline = class {
7
- assessmentCounter;
8
- confidenceHistogram;
9
- stageUpDownCounter;
10
- emitter;
11
- lowConfidenceThreshold;
12
- currentStageByTenant = /* @__PURE__ */ new Map();
13
- constructor(options = {}) {
14
- const meterName = options.meterName ?? "@contractspec/lib.lifecycle-kpi";
15
- this.assessmentCounter = createCounter("lifecycle_assessments_total", "Total lifecycle assessments", meterName);
16
- this.confidenceHistogram = createHistogram("lifecycle_assessment_confidence", "Lifecycle assessment confidence distribution", meterName);
17
- this.stageUpDownCounter = createUpDownCounter("lifecycle_stage_tenants", "Current tenants per lifecycle stage", meterName);
18
- this.emitter = options.emitter ?? new EventEmitter();
19
- this.lowConfidenceThreshold = options.lowConfidenceThreshold ?? .4;
20
- }
21
- recordAssessment(assessment, tenantId) {
22
- const attributes = {
23
- stage: getStageLabel(assessment.stage),
24
- tenantId
25
- };
26
- this.assessmentCounter.add(1, attributes);
27
- this.confidenceHistogram.record(assessment.confidence, attributes);
28
- this.ensureStageCounters(assessment.stage, tenantId);
29
- this.emitter.emit("event", {
30
- type: "assessment.recorded",
31
- payload: {
32
- tenantId,
33
- stage: assessment.stage
34
- }
35
- });
36
- if (assessment.confidence < this.lowConfidenceThreshold) this.emitter.emit("event", {
37
- type: "confidence.low",
38
- payload: {
39
- tenantId,
40
- confidence: assessment.confidence
41
- }
42
- });
43
- }
44
- on(listener) {
45
- this.emitter.on("event", listener);
46
- }
47
- ensureStageCounters(stage, tenantId) {
48
- if (!tenantId) return;
49
- const previous = this.currentStageByTenant.get(tenantId);
50
- if (previous === stage) return;
51
- if (previous !== void 0) this.stageUpDownCounter.add(-1, {
52
- stage: getStageLabel(previous),
53
- tenantId
54
- });
55
- this.stageUpDownCounter.add(1, {
56
- stage: getStageLabel(stage),
57
- tenantId
58
- });
59
- this.currentStageByTenant.set(tenantId, stage);
60
- this.emitter.emit("event", {
61
- type: "stage.changed",
62
- payload: {
63
- tenantId,
64
- previousStage: previous,
65
- nextStage: stage
66
- }
67
- });
68
- }
69
- };
70
-
71
- //#endregion
72
- export { LifecycleKpiPipeline };
73
- //# sourceMappingURL=lifecycle-pipeline.mjs.map
@@ -1,9 +0,0 @@
1
- import { Span, Tracer } from "@opentelemetry/api";
2
-
3
- //#region src/tracing/index.d.ts
4
- declare function getTracer(name?: string): Tracer;
5
- declare function traceAsync<T>(name: string, fn: (span: Span) => Promise<T>, tracerName?: string): Promise<T>;
6
- declare function traceSync<T>(name: string, fn: (span: Span) => T, tracerName?: string): T;
7
- //#endregion
8
- export { getTracer, traceAsync, traceSync };
9
- //# sourceMappingURL=index.d.mts.map
@@ -1,47 +0,0 @@
1
- import { SpanStatusCode, trace } from "@opentelemetry/api";
2
-
3
- //#region src/tracing/index.ts
4
- const DEFAULT_TRACER_NAME = "@contractspec/lib.observability";
5
- function getTracer(name = DEFAULT_TRACER_NAME) {
6
- return trace.getTracer(name);
7
- }
8
- async function traceAsync(name, fn, tracerName) {
9
- return getTracer(tracerName).startActiveSpan(name, async (span) => {
10
- try {
11
- const result = await fn(span);
12
- span.setStatus({ code: SpanStatusCode.OK });
13
- return result;
14
- } catch (error) {
15
- span.recordException(error);
16
- span.setStatus({
17
- code: SpanStatusCode.ERROR,
18
- message: error instanceof Error ? error.message : String(error)
19
- });
20
- throw error;
21
- } finally {
22
- span.end();
23
- }
24
- });
25
- }
26
- function traceSync(name, fn, tracerName) {
27
- return getTracer(tracerName).startActiveSpan(name, (span) => {
28
- try {
29
- const result = fn(span);
30
- span.setStatus({ code: SpanStatusCode.OK });
31
- return result;
32
- } catch (error) {
33
- span.recordException(error);
34
- span.setStatus({
35
- code: SpanStatusCode.ERROR,
36
- message: error instanceof Error ? error.message : String(error)
37
- });
38
- throw error;
39
- } finally {
40
- span.end();
41
- }
42
- });
43
- }
44
-
45
- //#endregion
46
- export { getTracer, traceAsync, traceSync };
47
- //# sourceMappingURL=index.mjs.map
@@ -1,19 +0,0 @@
1
- import { TelemetrySample } from "../intent/aggregator.mjs";
2
-
3
- //#region src/tracing/middleware.d.ts
4
- interface TracingMiddlewareOptions {
5
- resolveOperation?: (input: {
6
- req: Request;
7
- res?: Response;
8
- }) => {
9
- name: string;
10
- version: string;
11
- } | undefined;
12
- onSample?: (sample: TelemetrySample) => void;
13
- tenantResolver?: (req: Request) => string | undefined;
14
- actorResolver?: (req: Request) => string | undefined;
15
- }
16
- declare function createTracingMiddleware(options?: TracingMiddlewareOptions): (req: Request, next: () => Promise<Response>) => Promise<Response>;
17
- //#endregion
18
- export { TracingMiddlewareOptions, createTracingMiddleware };
19
- //# sourceMappingURL=middleware.d.mts.map
@@ -1,80 +0,0 @@
1
- import { traceAsync } from "./index.mjs";
2
- import { standardMetrics } from "../metrics/index.mjs";
3
-
4
- //#region src/tracing/middleware.ts
5
- function createTracingMiddleware(options = {}) {
6
- return async (req, next) => {
7
- const method = req.method;
8
- const path = new URL(req.url).pathname;
9
- standardMetrics.httpRequests.add(1, {
10
- method,
11
- path
12
- });
13
- const startTime = performance.now();
14
- return traceAsync(`HTTP ${method} ${path}`, async (span) => {
15
- span.setAttribute("http.method", method);
16
- span.setAttribute("http.url", req.url);
17
- try {
18
- const response = await next();
19
- span.setAttribute("http.status_code", response.status);
20
- const duration = (performance.now() - startTime) / 1e3;
21
- standardMetrics.httpDuration.record(duration, {
22
- method,
23
- path,
24
- status: response.status.toString()
25
- });
26
- emitTelemetrySample({
27
- req,
28
- res: response,
29
- span,
30
- success: true,
31
- durationMs: duration * 1e3,
32
- options
33
- });
34
- return response;
35
- } catch (error) {
36
- standardMetrics.operationErrors.add(1, {
37
- method,
38
- path
39
- });
40
- emitTelemetrySample({
41
- req,
42
- span,
43
- success: false,
44
- durationMs: performance.now() - startTime,
45
- error,
46
- options
47
- });
48
- throw error;
49
- }
50
- });
51
- };
52
- }
53
- function emitTelemetrySample({ req, res, span, success, durationMs, error, options }) {
54
- if (!options.onSample || !options.resolveOperation) return;
55
- const operation = options.resolveOperation({
56
- req,
57
- res
58
- });
59
- if (!operation) return;
60
- const sample = {
61
- operation,
62
- durationMs,
63
- success,
64
- timestamp: /* @__PURE__ */ new Date(),
65
- errorCode: !success && error instanceof Error ? error.name : success ? void 0 : "unknown",
66
- tenantId: options.tenantResolver?.(req),
67
- actorId: options.actorResolver?.(req),
68
- traceId: span.spanContext().traceId,
69
- metadata: {
70
- method: req.method,
71
- path: new URL(req.url).pathname,
72
- status: res?.status
73
- }
74
- };
75
- options.onSample(sample);
76
- }
77
-
78
- //#endregion
79
- export { createTracingMiddleware };
80
- //# sourceMappingURL=middleware.mjs.map