@contractspec/lib.observability 1.57.0 → 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.
- package/CHANGELOG.md +13 -0
- package/dist/anomaly/alert-manager.d.ts +17 -0
- package/dist/anomaly/alert-manager.js +24 -0
- package/dist/anomaly/anomaly-detector.d.ts +22 -0
- package/dist/anomaly/anomaly-detector.js +102 -0
- package/dist/anomaly/baseline-calculator.d.ts +23 -0
- package/dist/anomaly/baseline-calculator.js +40 -0
- package/dist/anomaly/root-cause-analyzer.d.ts +19 -0
- package/dist/anomaly/root-cause-analyzer.js +32 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +1078 -0
- package/dist/intent/aggregator.d.ts +57 -0
- package/dist/intent/aggregator.js +110 -0
- package/dist/intent/detector.d.ts +28 -0
- package/dist/intent/detector.js +133 -0
- package/dist/logging/index.d.ts +17 -0
- package/dist/logging/index.js +42 -0
- package/dist/metrics/index.d.ts +12 -0
- package/dist/metrics/index.js +31 -0
- package/dist/node/anomaly/alert-manager.js +23 -0
- package/dist/node/anomaly/anomaly-detector.js +101 -0
- package/dist/node/anomaly/baseline-calculator.js +39 -0
- package/dist/node/anomaly/root-cause-analyzer.js +31 -0
- package/dist/node/index.js +1077 -0
- package/dist/node/intent/aggregator.js +109 -0
- package/dist/node/intent/detector.js +132 -0
- package/dist/node/logging/index.js +41 -0
- package/dist/node/metrics/index.js +30 -0
- package/dist/node/pipeline/evolution-pipeline.js +299 -0
- package/dist/node/pipeline/lifecycle-pipeline.js +85 -0
- package/dist/node/telemetry/posthog-baseline-reader.js +308 -0
- package/dist/node/telemetry/posthog-telemetry.js +60 -0
- package/dist/node/tracing/index.js +52 -0
- package/dist/node/tracing/middleware.js +150 -0
- package/dist/pipeline/evolution-pipeline.d.ts +36 -0
- package/dist/pipeline/evolution-pipeline.js +300 -0
- package/dist/pipeline/lifecycle-pipeline.d.ts +40 -0
- package/dist/pipeline/lifecycle-pipeline.js +86 -0
- package/dist/telemetry/posthog-baseline-reader.d.ts +27 -0
- package/dist/telemetry/posthog-baseline-reader.js +309 -0
- package/dist/telemetry/posthog-telemetry.d.ts +15 -0
- package/dist/telemetry/posthog-telemetry.js +61 -0
- package/dist/tracing/index.d.ts +5 -0
- package/dist/tracing/index.js +53 -0
- package/dist/tracing/middleware.d.ts +15 -0
- package/dist/tracing/middleware.js +151 -0
- package/package.json +140 -43
- package/dist/anomaly/alert-manager.d.mts +0 -21
- package/dist/anomaly/alert-manager.mjs +0 -23
- package/dist/anomaly/anomaly-detector.d.mts +0 -26
- package/dist/anomaly/anomaly-detector.mjs +0 -58
- package/dist/anomaly/baseline-calculator.d.mts +0 -26
- package/dist/anomaly/baseline-calculator.mjs +0 -37
- package/dist/anomaly/root-cause-analyzer.d.mts +0 -23
- package/dist/anomaly/root-cause-analyzer.mjs +0 -27
- package/dist/index.d.mts +0 -15
- package/dist/index.mjs +0 -16
- package/dist/intent/aggregator.d.mts +0 -60
- package/dist/intent/aggregator.mjs +0 -98
- package/dist/intent/detector.d.mts +0 -32
- package/dist/intent/detector.mjs +0 -122
- package/dist/logging/index.d.mts +0 -20
- package/dist/logging/index.mjs +0 -40
- package/dist/metrics/index.d.mts +0 -17
- package/dist/metrics/index.mjs +0 -26
- package/dist/pipeline/evolution-pipeline.d.mts +0 -40
- package/dist/pipeline/evolution-pipeline.mjs +0 -66
- package/dist/pipeline/lifecycle-pipeline.d.mts +0 -44
- package/dist/pipeline/lifecycle-pipeline.mjs +0 -73
- package/dist/telemetry/posthog-baseline-reader.d.mts +0 -31
- package/dist/telemetry/posthog-baseline-reader.mjs +0 -266
- package/dist/telemetry/posthog-telemetry.d.mts +0 -19
- package/dist/telemetry/posthog-telemetry.mjs +0 -61
- package/dist/tracing/index.d.mts +0 -9
- package/dist/tracing/index.mjs +0 -47
- package/dist/tracing/middleware.d.mts +0 -19
- package/dist/tracing/middleware.mjs +0 -80
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/telemetry/posthog-baseline-reader.ts
|
|
3
|
+
class PosthogBaselineReader {
|
|
4
|
+
reader;
|
|
5
|
+
eventPrefix;
|
|
6
|
+
constructor(reader, options = {}) {
|
|
7
|
+
this.reader = reader;
|
|
8
|
+
this.eventPrefix = options.eventPrefix ?? "observability";
|
|
9
|
+
}
|
|
10
|
+
async readSamples(input) {
|
|
11
|
+
const result = await this.queryHogQL({
|
|
12
|
+
query: [
|
|
13
|
+
"select",
|
|
14
|
+
" properties.operation as operationName,",
|
|
15
|
+
" properties.version as version,",
|
|
16
|
+
" properties.durationMs as durationMs,",
|
|
17
|
+
" properties.success as success,",
|
|
18
|
+
" properties.errorCode as errorCode,",
|
|
19
|
+
" properties.tenantId as tenantId,",
|
|
20
|
+
" properties.traceId as traceId,",
|
|
21
|
+
" properties.metadata as metadata,",
|
|
22
|
+
" distinct_id as actorId,",
|
|
23
|
+
" timestamp as timestamp",
|
|
24
|
+
"from events",
|
|
25
|
+
`where ${buildOperationWhereClause(this.eventPrefix, input)}`,
|
|
26
|
+
"order by timestamp desc",
|
|
27
|
+
`limit ${input.limit ?? 1000}`
|
|
28
|
+
].join(`
|
|
29
|
+
`),
|
|
30
|
+
values: buildOperationValues(input)
|
|
31
|
+
});
|
|
32
|
+
return mapTelemetrySamples(result);
|
|
33
|
+
}
|
|
34
|
+
async readAggregatedMetrics(operation, windowDays = 7) {
|
|
35
|
+
const dateRange = buildWindowRange(windowDays);
|
|
36
|
+
const result = await this.queryHogQL({
|
|
37
|
+
query: [
|
|
38
|
+
"select",
|
|
39
|
+
" count() as totalCalls,",
|
|
40
|
+
" avg(properties.durationMs) as averageLatencyMs,",
|
|
41
|
+
" quantile(0.95)(properties.durationMs) as p95LatencyMs,",
|
|
42
|
+
" quantile(0.99)(properties.durationMs) as p99LatencyMs,",
|
|
43
|
+
" max(properties.durationMs) as maxLatencyMs,",
|
|
44
|
+
" sum(if(properties.success = 1, 1, 0)) as successCount,",
|
|
45
|
+
" sum(if(properties.success = 0, 1, 0)) as errorCount",
|
|
46
|
+
"from events",
|
|
47
|
+
`where ${buildOperationWhereClause(this.eventPrefix, {
|
|
48
|
+
operations: [operation],
|
|
49
|
+
dateRange
|
|
50
|
+
})}`
|
|
51
|
+
].join(`
|
|
52
|
+
`),
|
|
53
|
+
values: buildOperationValues({
|
|
54
|
+
operations: [operation],
|
|
55
|
+
dateRange
|
|
56
|
+
})
|
|
57
|
+
});
|
|
58
|
+
const stats = mapAggregatedMetrics(result, operation, dateRange);
|
|
59
|
+
if (!stats)
|
|
60
|
+
return null;
|
|
61
|
+
const topErrors = await this.readTopErrors(operation, dateRange);
|
|
62
|
+
return {
|
|
63
|
+
...stats,
|
|
64
|
+
topErrors
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
async readOperationSequences(dateRange) {
|
|
68
|
+
const result = await this.queryHogQL({
|
|
69
|
+
query: [
|
|
70
|
+
"select",
|
|
71
|
+
" properties.sequences as sequences",
|
|
72
|
+
"from events",
|
|
73
|
+
`where event = {eventName}`,
|
|
74
|
+
dateRange?.from ? "and timestamp >= {dateFrom}" : "",
|
|
75
|
+
dateRange?.to ? "and timestamp < {dateTo}" : "",
|
|
76
|
+
"order by timestamp desc",
|
|
77
|
+
"limit 50"
|
|
78
|
+
].filter(Boolean).join(`
|
|
79
|
+
`),
|
|
80
|
+
values: {
|
|
81
|
+
eventName: `${this.eventPrefix}.window`,
|
|
82
|
+
dateFrom: toIsoString(dateRange?.from),
|
|
83
|
+
dateTo: toIsoString(dateRange?.to)
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
return mergeSequences(result);
|
|
87
|
+
}
|
|
88
|
+
async readTopErrors(operation, dateRange) {
|
|
89
|
+
const result = await this.queryHogQL({
|
|
90
|
+
query: [
|
|
91
|
+
"select",
|
|
92
|
+
" properties.errorCode as errorCode,",
|
|
93
|
+
" count() as errorCount",
|
|
94
|
+
"from events",
|
|
95
|
+
`where ${buildOperationWhereClause(this.eventPrefix, {
|
|
96
|
+
operations: [operation],
|
|
97
|
+
dateRange
|
|
98
|
+
})} and properties.success = 0`,
|
|
99
|
+
"group by errorCode",
|
|
100
|
+
"order by errorCount desc",
|
|
101
|
+
"limit 5"
|
|
102
|
+
].join(`
|
|
103
|
+
`),
|
|
104
|
+
values: buildOperationValues({
|
|
105
|
+
operations: [operation],
|
|
106
|
+
dateRange
|
|
107
|
+
})
|
|
108
|
+
});
|
|
109
|
+
const rows = mapRows(result);
|
|
110
|
+
return rows.reduce((acc, row) => {
|
|
111
|
+
const code = asString(row.errorCode);
|
|
112
|
+
if (!code)
|
|
113
|
+
return acc;
|
|
114
|
+
acc[code] = asNumber(row.errorCount);
|
|
115
|
+
return acc;
|
|
116
|
+
}, {});
|
|
117
|
+
}
|
|
118
|
+
async queryHogQL(input) {
|
|
119
|
+
if (!this.reader.queryHogQL) {
|
|
120
|
+
throw new Error("Analytics reader does not support HogQL queries.");
|
|
121
|
+
}
|
|
122
|
+
return this.reader.queryHogQL(input);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function buildOperationWhereClause(eventPrefix, input) {
|
|
126
|
+
const clauses = [`event = '${eventPrefix}.operation'`];
|
|
127
|
+
if (input.operations?.length) {
|
|
128
|
+
clauses.push(`(${buildOperationFilters(input.operations)})`);
|
|
129
|
+
}
|
|
130
|
+
if (input.dateRange?.from) {
|
|
131
|
+
clauses.push("timestamp >= {dateFrom}");
|
|
132
|
+
}
|
|
133
|
+
if (input.dateRange?.to) {
|
|
134
|
+
clauses.push("timestamp < {dateTo}");
|
|
135
|
+
}
|
|
136
|
+
return clauses.join(" and ");
|
|
137
|
+
}
|
|
138
|
+
function buildOperationValues(input) {
|
|
139
|
+
const values = {
|
|
140
|
+
dateFrom: toIsoString(input.dateRange?.from),
|
|
141
|
+
dateTo: toIsoString(input.dateRange?.to)
|
|
142
|
+
};
|
|
143
|
+
input.operations?.forEach((op, index) => {
|
|
144
|
+
values[`operationName${index}`] = op.name;
|
|
145
|
+
values[`operationVersion${index}`] = op.version;
|
|
146
|
+
});
|
|
147
|
+
return values;
|
|
148
|
+
}
|
|
149
|
+
function buildOperationFilters(operations) {
|
|
150
|
+
return operations.map((_op, index) => `(properties.operation = {operationName${index}} and properties.version = {operationVersion${index}})`).join(" or ");
|
|
151
|
+
}
|
|
152
|
+
function mapTelemetrySamples(result) {
|
|
153
|
+
const rows = mapRows(result);
|
|
154
|
+
return rows.flatMap((row) => {
|
|
155
|
+
const operationName = asString(row.operationName);
|
|
156
|
+
const version = asString(row.version);
|
|
157
|
+
const timestamp = asDate(row.timestamp);
|
|
158
|
+
if (!operationName || !version || !timestamp) {
|
|
159
|
+
return [];
|
|
160
|
+
}
|
|
161
|
+
return [
|
|
162
|
+
{
|
|
163
|
+
operation: { name: operationName, version },
|
|
164
|
+
durationMs: asNumber(row.durationMs),
|
|
165
|
+
success: asBoolean(row.success),
|
|
166
|
+
timestamp,
|
|
167
|
+
errorCode: asOptionalString(row.errorCode) ?? undefined,
|
|
168
|
+
tenantId: asOptionalString(row.tenantId) ?? undefined,
|
|
169
|
+
traceId: asOptionalString(row.traceId) ?? undefined,
|
|
170
|
+
actorId: asOptionalString(row.actorId) ?? undefined,
|
|
171
|
+
metadata: isRecord(row.metadata) ? row.metadata : undefined
|
|
172
|
+
}
|
|
173
|
+
];
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
function mapAggregatedMetrics(result, operation, dateRange) {
|
|
177
|
+
const rows = mapRows(result);
|
|
178
|
+
const row = rows[0];
|
|
179
|
+
if (!row)
|
|
180
|
+
return null;
|
|
181
|
+
const totalCalls = asNumber(row.totalCalls);
|
|
182
|
+
if (!totalCalls)
|
|
183
|
+
return null;
|
|
184
|
+
const successCount = asNumber(row.successCount);
|
|
185
|
+
const errorCount = asNumber(row.errorCount);
|
|
186
|
+
const windowStart = toDate(dateRange.from) ?? new Date;
|
|
187
|
+
const windowEnd = toDate(dateRange.to) ?? new Date;
|
|
188
|
+
return {
|
|
189
|
+
operation,
|
|
190
|
+
totalCalls,
|
|
191
|
+
successRate: totalCalls ? successCount / totalCalls : 0,
|
|
192
|
+
errorRate: totalCalls ? errorCount / totalCalls : 0,
|
|
193
|
+
averageLatencyMs: asNumber(row.averageLatencyMs),
|
|
194
|
+
p95LatencyMs: asNumber(row.p95LatencyMs),
|
|
195
|
+
p99LatencyMs: asNumber(row.p99LatencyMs),
|
|
196
|
+
maxLatencyMs: asNumber(row.maxLatencyMs),
|
|
197
|
+
windowStart,
|
|
198
|
+
windowEnd,
|
|
199
|
+
topErrors: {}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function mergeSequences(result) {
|
|
203
|
+
const rows = mapRows(result);
|
|
204
|
+
const merged = new Map;
|
|
205
|
+
rows.forEach((row) => {
|
|
206
|
+
const sequences = row.sequences;
|
|
207
|
+
if (!Array.isArray(sequences))
|
|
208
|
+
return;
|
|
209
|
+
sequences.forEach((sequence) => {
|
|
210
|
+
if (!isRecord(sequence))
|
|
211
|
+
return;
|
|
212
|
+
const steps = Array.isArray(sequence.steps) ? sequence.steps.filter((step) => typeof step === "string") : [];
|
|
213
|
+
if (steps.length === 0)
|
|
214
|
+
return;
|
|
215
|
+
const tenantId = typeof sequence.tenantId === "string" ? sequence.tenantId : undefined;
|
|
216
|
+
const count = typeof sequence.count === "number" && Number.isFinite(sequence.count) ? sequence.count : 0;
|
|
217
|
+
const key = `${tenantId ?? "global"}:${steps.join(">")}`;
|
|
218
|
+
const existing = merged.get(key);
|
|
219
|
+
if (existing) {
|
|
220
|
+
existing.count += count;
|
|
221
|
+
} else {
|
|
222
|
+
merged.set(key, { steps, tenantId, count });
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
return [...merged.values()];
|
|
227
|
+
}
|
|
228
|
+
function mapRows(result) {
|
|
229
|
+
if (!Array.isArray(result.results) || !Array.isArray(result.columns)) {
|
|
230
|
+
return [];
|
|
231
|
+
}
|
|
232
|
+
const columns = result.columns;
|
|
233
|
+
return result.results.flatMap((row) => {
|
|
234
|
+
if (!Array.isArray(row))
|
|
235
|
+
return [];
|
|
236
|
+
const record = {};
|
|
237
|
+
columns.forEach((column, index) => {
|
|
238
|
+
record[column] = row[index];
|
|
239
|
+
});
|
|
240
|
+
return [record];
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
function buildWindowRange(windowDays) {
|
|
244
|
+
const windowEnd = new Date;
|
|
245
|
+
const windowStart = new Date(windowEnd.getTime() - windowDays * 24 * 60 * 60 * 1000);
|
|
246
|
+
return {
|
|
247
|
+
from: windowStart,
|
|
248
|
+
to: windowEnd
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function asString(value) {
|
|
252
|
+
if (typeof value === "string" && value.trim())
|
|
253
|
+
return value;
|
|
254
|
+
if (typeof value === "number")
|
|
255
|
+
return String(value);
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
function asOptionalString(value) {
|
|
259
|
+
if (typeof value === "string")
|
|
260
|
+
return value;
|
|
261
|
+
if (typeof value === "number")
|
|
262
|
+
return String(value);
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
function asNumber(value) {
|
|
266
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
267
|
+
return value;
|
|
268
|
+
if (typeof value === "string" && value.trim()) {
|
|
269
|
+
const parsed = Number(value);
|
|
270
|
+
if (Number.isFinite(parsed))
|
|
271
|
+
return parsed;
|
|
272
|
+
}
|
|
273
|
+
return 0;
|
|
274
|
+
}
|
|
275
|
+
function asBoolean(value) {
|
|
276
|
+
if (typeof value === "boolean")
|
|
277
|
+
return value;
|
|
278
|
+
if (typeof value === "number")
|
|
279
|
+
return value !== 0;
|
|
280
|
+
if (typeof value === "string")
|
|
281
|
+
return value.toLowerCase() === "true";
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
function asDate(value) {
|
|
285
|
+
if (value instanceof Date)
|
|
286
|
+
return value;
|
|
287
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
288
|
+
const date = new Date(value);
|
|
289
|
+
if (!Number.isNaN(date.getTime()))
|
|
290
|
+
return date;
|
|
291
|
+
}
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
function toIsoString(value) {
|
|
295
|
+
if (!value)
|
|
296
|
+
return;
|
|
297
|
+
return typeof value === "string" ? value : value.toISOString();
|
|
298
|
+
}
|
|
299
|
+
function toDate(value) {
|
|
300
|
+
if (!value)
|
|
301
|
+
return null;
|
|
302
|
+
return value instanceof Date ? value : new Date(value);
|
|
303
|
+
}
|
|
304
|
+
function isRecord(value) {
|
|
305
|
+
return typeof value === "object" && value !== null;
|
|
306
|
+
}
|
|
307
|
+
export {
|
|
308
|
+
PosthogBaselineReader
|
|
309
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AnalyticsProvider } from '@contractspec/lib.contracts/integrations/providers/analytics';
|
|
2
|
+
import type { IntentAggregatorSnapshot, TelemetrySample } from '../intent/aggregator';
|
|
3
|
+
export interface PosthogTelemetryProviderOptions {
|
|
4
|
+
eventPrefix?: string;
|
|
5
|
+
includeMetadata?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare class PosthogTelemetryProvider {
|
|
8
|
+
private readonly provider;
|
|
9
|
+
private readonly eventPrefix;
|
|
10
|
+
private readonly includeMetadata;
|
|
11
|
+
constructor(provider: AnalyticsProvider, options?: PosthogTelemetryProviderOptions);
|
|
12
|
+
captureSample(sample: TelemetrySample): Promise<void>;
|
|
13
|
+
captureSnapshot(snapshot: IntentAggregatorSnapshot): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=posthog-telemetry.d.ts.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/telemetry/posthog-telemetry.ts
|
|
3
|
+
class PosthogTelemetryProvider {
|
|
4
|
+
provider;
|
|
5
|
+
eventPrefix;
|
|
6
|
+
includeMetadata;
|
|
7
|
+
constructor(provider, options = {}) {
|
|
8
|
+
this.provider = provider;
|
|
9
|
+
this.eventPrefix = options.eventPrefix ?? "observability";
|
|
10
|
+
this.includeMetadata = options.includeMetadata ?? false;
|
|
11
|
+
}
|
|
12
|
+
async captureSample(sample) {
|
|
13
|
+
await this.provider.capture({
|
|
14
|
+
distinctId: sample.actorId ?? sample.tenantId ?? "unknown",
|
|
15
|
+
event: `${this.eventPrefix}.operation`,
|
|
16
|
+
timestamp: sample.timestamp,
|
|
17
|
+
properties: {
|
|
18
|
+
operation: sample.operation.name,
|
|
19
|
+
version: sample.operation.version,
|
|
20
|
+
durationMs: sample.durationMs,
|
|
21
|
+
success: sample.success,
|
|
22
|
+
errorCode: sample.errorCode ?? null,
|
|
23
|
+
tenantId: sample.tenantId ?? null,
|
|
24
|
+
traceId: sample.traceId ?? null,
|
|
25
|
+
...this.includeMetadata && sample.metadata ? { metadata: sample.metadata } : {}
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async captureSnapshot(snapshot) {
|
|
30
|
+
await this.provider.capture({
|
|
31
|
+
distinctId: "system",
|
|
32
|
+
event: `${this.eventPrefix}.window`,
|
|
33
|
+
timestamp: snapshot.windowEnd ?? new Date,
|
|
34
|
+
properties: {
|
|
35
|
+
sampleCount: snapshot.sampleCount,
|
|
36
|
+
metricsCount: snapshot.metrics.length,
|
|
37
|
+
sequencesCount: snapshot.sequences.length,
|
|
38
|
+
windowStart: snapshot.windowStart?.toISOString() ?? null,
|
|
39
|
+
windowEnd: snapshot.windowEnd?.toISOString() ?? null,
|
|
40
|
+
...this.includeMetadata ? {
|
|
41
|
+
metrics: snapshot.metrics.map((metric) => ({
|
|
42
|
+
operation: metric.operation.name,
|
|
43
|
+
version: metric.operation.version,
|
|
44
|
+
totalCalls: metric.totalCalls,
|
|
45
|
+
successRate: metric.successRate,
|
|
46
|
+
errorRate: metric.errorRate,
|
|
47
|
+
averageLatencyMs: metric.averageLatencyMs,
|
|
48
|
+
p95LatencyMs: metric.p95LatencyMs,
|
|
49
|
+
p99LatencyMs: metric.p99LatencyMs,
|
|
50
|
+
maxLatencyMs: metric.maxLatencyMs,
|
|
51
|
+
topErrors: metric.topErrors
|
|
52
|
+
})),
|
|
53
|
+
sequences: snapshot.sequences
|
|
54
|
+
} : {}
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export {
|
|
60
|
+
PosthogTelemetryProvider
|
|
61
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Span, type Tracer } from '@opentelemetry/api';
|
|
2
|
+
export declare function getTracer(name?: string): Tracer;
|
|
3
|
+
export declare function traceAsync<T>(name: string, fn: (span: Span) => Promise<T>, tracerName?: string): Promise<T>;
|
|
4
|
+
export declare function traceSync<T>(name: string, fn: (span: Span) => T, tracerName?: string): T;
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/tracing/index.ts
|
|
3
|
+
import {
|
|
4
|
+
SpanStatusCode,
|
|
5
|
+
trace
|
|
6
|
+
} from "@opentelemetry/api";
|
|
7
|
+
var DEFAULT_TRACER_NAME = "@contractspec/lib.observability";
|
|
8
|
+
function getTracer(name = DEFAULT_TRACER_NAME) {
|
|
9
|
+
return trace.getTracer(name);
|
|
10
|
+
}
|
|
11
|
+
async function traceAsync(name, fn, tracerName) {
|
|
12
|
+
const tracer = getTracer(tracerName);
|
|
13
|
+
return tracer.startActiveSpan(name, async (span) => {
|
|
14
|
+
try {
|
|
15
|
+
const result = await fn(span);
|
|
16
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
17
|
+
return result;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
span.recordException(error);
|
|
20
|
+
span.setStatus({
|
|
21
|
+
code: SpanStatusCode.ERROR,
|
|
22
|
+
message: error instanceof Error ? error.message : String(error)
|
|
23
|
+
});
|
|
24
|
+
throw error;
|
|
25
|
+
} finally {
|
|
26
|
+
span.end();
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function traceSync(name, fn, tracerName) {
|
|
31
|
+
const tracer = getTracer(tracerName);
|
|
32
|
+
return tracer.startActiveSpan(name, (span) => {
|
|
33
|
+
try {
|
|
34
|
+
const result = fn(span);
|
|
35
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
36
|
+
return result;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
span.recordException(error);
|
|
39
|
+
span.setStatus({
|
|
40
|
+
code: SpanStatusCode.ERROR,
|
|
41
|
+
message: error instanceof Error ? error.message : String(error)
|
|
42
|
+
});
|
|
43
|
+
throw error;
|
|
44
|
+
} finally {
|
|
45
|
+
span.end();
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export {
|
|
50
|
+
traceSync,
|
|
51
|
+
traceAsync,
|
|
52
|
+
getTracer
|
|
53
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { TelemetrySample } from '../intent/aggregator';
|
|
2
|
+
export interface TracingMiddlewareOptions {
|
|
3
|
+
resolveOperation?: (input: {
|
|
4
|
+
req: Request;
|
|
5
|
+
res?: Response;
|
|
6
|
+
}) => {
|
|
7
|
+
name: string;
|
|
8
|
+
version: string;
|
|
9
|
+
} | undefined;
|
|
10
|
+
onSample?: (sample: TelemetrySample) => void;
|
|
11
|
+
tenantResolver?: (req: Request) => string | undefined;
|
|
12
|
+
actorResolver?: (req: Request) => string | undefined;
|
|
13
|
+
}
|
|
14
|
+
export declare function createTracingMiddleware(options?: TracingMiddlewareOptions): (req: Request, next: () => Promise<Response>) => Promise<Response>;
|
|
15
|
+
//# sourceMappingURL=middleware.d.ts.map
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/tracing/index.ts
|
|
3
|
+
import {
|
|
4
|
+
SpanStatusCode,
|
|
5
|
+
trace
|
|
6
|
+
} from "@opentelemetry/api";
|
|
7
|
+
var DEFAULT_TRACER_NAME = "@contractspec/lib.observability";
|
|
8
|
+
function getTracer(name = DEFAULT_TRACER_NAME) {
|
|
9
|
+
return trace.getTracer(name);
|
|
10
|
+
}
|
|
11
|
+
async function traceAsync(name, fn, tracerName) {
|
|
12
|
+
const tracer = getTracer(tracerName);
|
|
13
|
+
return tracer.startActiveSpan(name, async (span) => {
|
|
14
|
+
try {
|
|
15
|
+
const result = await fn(span);
|
|
16
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
17
|
+
return result;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
span.recordException(error);
|
|
20
|
+
span.setStatus({
|
|
21
|
+
code: SpanStatusCode.ERROR,
|
|
22
|
+
message: error instanceof Error ? error.message : String(error)
|
|
23
|
+
});
|
|
24
|
+
throw error;
|
|
25
|
+
} finally {
|
|
26
|
+
span.end();
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function traceSync(name, fn, tracerName) {
|
|
31
|
+
const tracer = getTracer(tracerName);
|
|
32
|
+
return tracer.startActiveSpan(name, (span) => {
|
|
33
|
+
try {
|
|
34
|
+
const result = fn(span);
|
|
35
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
36
|
+
return result;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
span.recordException(error);
|
|
39
|
+
span.setStatus({
|
|
40
|
+
code: SpanStatusCode.ERROR,
|
|
41
|
+
message: error instanceof Error ? error.message : String(error)
|
|
42
|
+
});
|
|
43
|
+
throw error;
|
|
44
|
+
} finally {
|
|
45
|
+
span.end();
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/metrics/index.ts
|
|
51
|
+
import {
|
|
52
|
+
metrics
|
|
53
|
+
} from "@opentelemetry/api";
|
|
54
|
+
var DEFAULT_METER_NAME = "@contractspec/lib.observability";
|
|
55
|
+
function getMeter(name = DEFAULT_METER_NAME) {
|
|
56
|
+
return metrics.getMeter(name);
|
|
57
|
+
}
|
|
58
|
+
function createCounter(name, description, meterName) {
|
|
59
|
+
return getMeter(meterName).createCounter(name, { description });
|
|
60
|
+
}
|
|
61
|
+
function createUpDownCounter(name, description, meterName) {
|
|
62
|
+
return getMeter(meterName).createUpDownCounter(name, { description });
|
|
63
|
+
}
|
|
64
|
+
function createHistogram(name, description, meterName) {
|
|
65
|
+
return getMeter(meterName).createHistogram(name, { description });
|
|
66
|
+
}
|
|
67
|
+
var standardMetrics = {
|
|
68
|
+
httpRequests: createCounter("http_requests_total", "Total HTTP requests"),
|
|
69
|
+
httpDuration: createHistogram("http_request_duration_seconds", "HTTP request duration"),
|
|
70
|
+
operationErrors: createCounter("operation_errors_total", "Total operation errors"),
|
|
71
|
+
workflowDuration: createHistogram("workflow_duration_seconds", "Workflow execution duration")
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// src/tracing/middleware.ts
|
|
75
|
+
function createTracingMiddleware(options = {}) {
|
|
76
|
+
return async (req, next) => {
|
|
77
|
+
const method = req.method;
|
|
78
|
+
const url = new URL(req.url);
|
|
79
|
+
const path = url.pathname;
|
|
80
|
+
standardMetrics.httpRequests.add(1, { method, path });
|
|
81
|
+
const startTime = performance.now();
|
|
82
|
+
return traceAsync(`HTTP ${method} ${path}`, async (span) => {
|
|
83
|
+
span.setAttribute("http.method", method);
|
|
84
|
+
span.setAttribute("http.url", req.url);
|
|
85
|
+
try {
|
|
86
|
+
const response = await next();
|
|
87
|
+
span.setAttribute("http.status_code", response.status);
|
|
88
|
+
const duration = (performance.now() - startTime) / 1000;
|
|
89
|
+
standardMetrics.httpDuration.record(duration, {
|
|
90
|
+
method,
|
|
91
|
+
path,
|
|
92
|
+
status: response.status.toString()
|
|
93
|
+
});
|
|
94
|
+
emitTelemetrySample({
|
|
95
|
+
req,
|
|
96
|
+
res: response,
|
|
97
|
+
span,
|
|
98
|
+
success: true,
|
|
99
|
+
durationMs: duration * 1000,
|
|
100
|
+
options
|
|
101
|
+
});
|
|
102
|
+
return response;
|
|
103
|
+
} catch (error) {
|
|
104
|
+
standardMetrics.operationErrors.add(1, { method, path });
|
|
105
|
+
emitTelemetrySample({
|
|
106
|
+
req,
|
|
107
|
+
span,
|
|
108
|
+
success: false,
|
|
109
|
+
durationMs: performance.now() - startTime,
|
|
110
|
+
error,
|
|
111
|
+
options
|
|
112
|
+
});
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function emitTelemetrySample({
|
|
119
|
+
req,
|
|
120
|
+
res,
|
|
121
|
+
span,
|
|
122
|
+
success,
|
|
123
|
+
durationMs,
|
|
124
|
+
error,
|
|
125
|
+
options
|
|
126
|
+
}) {
|
|
127
|
+
if (!options.onSample || !options.resolveOperation)
|
|
128
|
+
return;
|
|
129
|
+
const operation = options.resolveOperation({ req, res });
|
|
130
|
+
if (!operation)
|
|
131
|
+
return;
|
|
132
|
+
const sample = {
|
|
133
|
+
operation,
|
|
134
|
+
durationMs,
|
|
135
|
+
success,
|
|
136
|
+
timestamp: new Date,
|
|
137
|
+
errorCode: !success && error instanceof Error ? error.name : success ? undefined : "unknown",
|
|
138
|
+
tenantId: options.tenantResolver?.(req),
|
|
139
|
+
actorId: options.actorResolver?.(req),
|
|
140
|
+
traceId: span.spanContext().traceId,
|
|
141
|
+
metadata: {
|
|
142
|
+
method: req.method,
|
|
143
|
+
path: new URL(req.url).pathname,
|
|
144
|
+
status: res?.status
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
options.onSample(sample);
|
|
148
|
+
}
|
|
149
|
+
export {
|
|
150
|
+
createTracingMiddleware
|
|
151
|
+
};
|