@contractspec/lib.observability 3.7.16 → 3.7.18
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 +25 -0
- package/dist/anomaly/alert-manager.js +1 -23
- package/dist/anomaly/anomaly-detector.js +1 -101
- package/dist/anomaly/baseline-calculator.js +1 -39
- package/dist/anomaly/root-cause-analyzer.js +1 -31
- package/dist/index.js +5 -1128
- package/dist/intent/aggregator.js +1 -109
- package/dist/intent/detector.js +1 -132
- package/dist/logging/index.js +1 -41
- package/dist/metrics/index.js +1 -30
- package/dist/node/anomaly/alert-manager.js +1 -23
- package/dist/node/anomaly/anomaly-detector.js +1 -101
- package/dist/node/anomaly/baseline-calculator.js +1 -39
- package/dist/node/anomaly/root-cause-analyzer.js +1 -31
- package/dist/node/index.js +5 -1128
- package/dist/node/intent/aggregator.js +1 -109
- package/dist/node/intent/detector.js +1 -132
- package/dist/node/logging/index.js +1 -41
- package/dist/node/metrics/index.js +1 -30
- package/dist/node/pipeline/evolution-pipeline.js +1 -299
- package/dist/node/pipeline/lifecycle-pipeline.js +1 -85
- package/dist/node/telemetry/model-selection-telemetry.js +1 -30
- package/dist/node/telemetry/posthog-baseline-reader.js +5 -308
- package/dist/node/telemetry/posthog-telemetry.js +1 -60
- package/dist/node/tracing/core.js +1 -52
- package/dist/node/tracing/index.js +1 -75
- package/dist/node/tracing/middleware.js +1 -171
- package/dist/node/tracing/model-selection.span.js +1 -72
- package/dist/pipeline/evolution-pipeline.js +1 -299
- package/dist/pipeline/lifecycle-pipeline.js +1 -85
- package/dist/telemetry/model-selection-telemetry.js +1 -30
- package/dist/telemetry/posthog-baseline-reader.js +5 -308
- package/dist/telemetry/posthog-telemetry.js +1 -60
- package/dist/tracing/core.js +1 -52
- package/dist/tracing/index.js +1 -75
- package/dist/tracing/middleware.js +1 -171
- package/dist/tracing/model-selection.span.js +1 -72
- package/package.json +8 -8
|
@@ -1,309 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
eventPrefix
|
|
6
|
-
|
|
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
|
-
};
|
|
2
|
+
class M{reader;eventPrefix;constructor(e,r={}){this.reader=e,this.eventPrefix=r.eventPrefix??"observability"}async readSamples(e){let r=await this.queryHogQL({query:["select"," properties.operation as operationName,"," properties.version as version,"," properties.durationMs as durationMs,"," properties.success as success,"," properties.errorCode as errorCode,"," properties.tenantId as tenantId,"," properties.traceId as traceId,"," properties.metadata as metadata,"," distinct_id as actorId,"," timestamp as timestamp","from events",`where ${g(this.eventPrefix,e)}`,"order by timestamp desc",`limit ${e.limit??1000}`].join(`
|
|
3
|
+
`),values:l(e)});return A(r)}async readAggregatedMetrics(e,r=7){let t=D(r),o=await this.queryHogQL({query:["select"," count() as totalCalls,"," avg(properties.durationMs) as averageLatencyMs,"," quantile(0.95)(properties.durationMs) as p95LatencyMs,"," quantile(0.99)(properties.durationMs) as p99LatencyMs,"," max(properties.durationMs) as maxLatencyMs,"," sum(if(properties.success = 1, 1, 0)) as successCount,"," sum(if(properties.success = 0, 1, 0)) as errorCount","from events",`where ${g(this.eventPrefix,{operations:[e],dateRange:t})}`].join(`
|
|
4
|
+
`),values:l({operations:[e],dateRange:t})}),s=S(o,e,t);if(!s)return null;let n=await this.readTopErrors(e,t);return{...s,topErrors:n}}async readOperationSequences(e){let r=await this.queryHogQL({query:["select"," properties.sequences as sequences","from events","where event = {eventName}",e?.from?"and timestamp >= {dateFrom}":"",e?.to?"and timestamp < {dateTo}":"","order by timestamp desc","limit 50"].filter(Boolean).join(`
|
|
5
|
+
`),values:{eventName:`${this.eventPrefix}.window`,dateFrom:m(e?.from),dateTo:m(e?.to)}});return C(r)}async readTopErrors(e,r){let t=await this.queryHogQL({query:["select"," properties.errorCode as errorCode,"," count() as errorCount","from events",`where ${g(this.eventPrefix,{operations:[e],dateRange:r})} and properties.success = 0`,"group by errorCode","order by errorCount desc","limit 5"].join(`
|
|
6
|
+
`),values:l({operations:[e],dateRange:r})});return f(t).reduce((s,n)=>{let a=y(n.errorCode);if(!a)return s;return s[a]=i(n.errorCount),s},{})}async queryHogQL(e){if(!this.reader.queryHogQL)throw Error("Analytics reader does not support HogQL queries.");return this.reader.queryHogQL(e)}}function g(e,r){let t=[`event = '${e}.operation'`];if(r.operations?.length)t.push(`(${I(r.operations)})`);if(r.dateRange?.from)t.push("timestamp >= {dateFrom}");if(r.dateRange?.to)t.push("timestamp < {dateTo}");return t.join(" and ")}function l(e){let r={dateFrom:m(e.dateRange?.from),dateTo:m(e.dateRange?.to)};return e.operations?.forEach((t,o)=>{r[`operationName${o}`]=t.name,r[`operationVersion${o}`]=t.version}),r}function I(e){return e.map((r,t)=>`(properties.operation = {operationName${t}} and properties.version = {operationVersion${t}})`).join(" or ")}function A(e){return f(e).flatMap((t)=>{let o=y(t.operationName),s=y(t.version),n=q(t.timestamp);if(!o||!s||!n)return[];return[{operation:{name:o,version:s},durationMs:i(t.durationMs),success:L(t.success),timestamp:n,errorCode:d(t.errorCode)??void 0,tenantId:d(t.tenantId)??void 0,traceId:d(t.traceId)??void 0,actorId:d(t.actorId)??void 0,metadata:b(t.metadata)?t.metadata:void 0}]})}function S(e,r,t){let s=f(e)[0];if(!s)return null;let n=i(s.totalCalls);if(!n)return null;let a=i(s.successCount),u=i(s.errorCount),c=R(t.from)??new Date,p=R(t.to)??new Date;return{operation:r,totalCalls:n,successRate:n?a/n:0,errorRate:n?u/n:0,averageLatencyMs:i(s.averageLatencyMs),p95LatencyMs:i(s.p95LatencyMs),p99LatencyMs:i(s.p99LatencyMs),maxLatencyMs:i(s.maxLatencyMs),windowStart:c,windowEnd:p,topErrors:{}}}function C(e){let r=f(e),t=new Map;return r.forEach((o)=>{let s=o.sequences;if(!Array.isArray(s))return;s.forEach((n)=>{if(!b(n))return;let a=Array.isArray(n.steps)?n.steps.filter((h)=>typeof h==="string"):[];if(a.length===0)return;let u=typeof n.tenantId==="string"?n.tenantId:void 0,c=typeof n.count==="number"&&Number.isFinite(n.count)?n.count:0,p=`${u??"global"}:${a.join(">")}`,w=t.get(p);if(w)w.count+=c;else t.set(p,{steps:a,tenantId:u,count:c})})}),[...t.values()]}function f(e){if(!Array.isArray(e.results)||!Array.isArray(e.columns))return[];let r=e.columns;return e.results.flatMap((t)=>{if(!Array.isArray(t))return[];let o={};return r.forEach((s,n)=>{o[s]=t[n]}),[o]})}function D(e){let r=new Date;return{from:new Date(r.getTime()-e*24*60*60*1000),to:r}}function y(e){if(typeof e==="string"&&e.trim())return e;if(typeof e==="number")return String(e);return null}function d(e){if(typeof e==="string")return e;if(typeof e==="number")return String(e);return null}function i(e){if(typeof e==="number"&&Number.isFinite(e))return e;if(typeof e==="string"&&e.trim()){let r=Number(e);if(Number.isFinite(r))return r}return 0}function L(e){if(typeof e==="boolean")return e;if(typeof e==="number")return e!==0;if(typeof e==="string")return e.toLowerCase()==="true";return!1}function q(e){if(e instanceof Date)return e;if(typeof e==="string"||typeof e==="number"){let r=new Date(e);if(!Number.isNaN(r.getTime()))return r}return null}function m(e){if(!e)return;return typeof e==="string"?e:e.toISOString()}function R(e){if(!e)return null;return e instanceof Date?e:new Date(e)}function b(e){return typeof e==="object"&&e!==null}export{M as PosthogBaselineReader};
|
|
@@ -1,61 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
|
|
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
|
-
};
|
|
2
|
+
class r{provider;eventPrefix;includeMetadata;constructor(e,t={}){this.provider=e,this.eventPrefix=t.eventPrefix??"observability",this.includeMetadata=t.includeMetadata??!1}async captureSample(e){await this.provider.capture({distinctId:e.actorId??e.tenantId??"unknown",event:`${this.eventPrefix}.operation`,timestamp:e.timestamp,properties:{operation:e.operation.name,version:e.operation.version,durationMs:e.durationMs,success:e.success,errorCode:e.errorCode??null,tenantId:e.tenantId??null,traceId:e.traceId??null,...this.includeMetadata&&e.metadata?{metadata:e.metadata}:{}}})}async captureSnapshot(e){await this.provider.capture({distinctId:"system",event:`${this.eventPrefix}.window`,timestamp:e.windowEnd??new Date,properties:{sampleCount:e.sampleCount,metricsCount:e.metrics.length,sequencesCount:e.sequences.length,windowStart:e.windowStart?.toISOString()??null,windowEnd:e.windowEnd?.toISOString()??null,...this.includeMetadata?{metrics:e.metrics.map((t)=>({operation:t.operation.name,version:t.operation.version,totalCalls:t.totalCalls,successRate:t.successRate,errorRate:t.errorRate,averageLatencyMs:t.averageLatencyMs,p95LatencyMs:t.p95LatencyMs,p99LatencyMs:t.p99LatencyMs,maxLatencyMs:t.maxLatencyMs,topErrors:t.topErrors})),sequences:e.sequences}:{}}})}}export{r as PosthogTelemetryProvider};
|
package/dist/tracing/core.js
CHANGED
|
@@ -1,53 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
|
|
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
|
-
};
|
|
2
|
+
import{SpanStatusCode as c,trace as i}from"@opentelemetry/api";var u="@contractspec/lib.observability";function o(e=u){return i.getTracer(e)}async function g(e,n,a){return o(a).startActiveSpan(e,async(t)=>{try{let r=await n(t);return t.setStatus({code:c.OK}),r}catch(r){throw t.recordException(r),t.setStatus({code:c.ERROR,message:r instanceof Error?r.message:String(r)}),r}finally{t.end()}})}function T(e,n,a){return o(a).startActiveSpan(e,(t)=>{try{let r=n(t);return t.setStatus({code:c.OK}),r}catch(r){throw t.recordException(r),t.setStatus({code:c.ERROR,message:r instanceof Error?r.message:String(r)}),r}finally{t.end()}})}export{T as traceSync,g as traceAsync,o as getTracer};
|
package/dist/tracing/index.js
CHANGED
|
@@ -1,76 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
|
|
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/tracing/model-selection.span.ts
|
|
51
|
-
async function traceModelSelection(fn, input) {
|
|
52
|
-
const startMs = performance.now();
|
|
53
|
-
return traceAsync("model.selection", async (span) => {
|
|
54
|
-
const result = await fn();
|
|
55
|
-
const durationMs = performance.now() - startMs;
|
|
56
|
-
span.setAttribute("model.selected", input.modelId);
|
|
57
|
-
span.setAttribute("model.provider", input.providerKey);
|
|
58
|
-
span.setAttribute("model.score", input.score);
|
|
59
|
-
span.setAttribute("model.alternatives_count", input.alternativesCount);
|
|
60
|
-
span.setAttribute("model.selection_duration_ms", durationMs);
|
|
61
|
-
span.setAttribute("model.reason", input.reason);
|
|
62
|
-
if (input.dimension) {
|
|
63
|
-
span.setAttribute("model.dimension", input.dimension);
|
|
64
|
-
}
|
|
65
|
-
if (input.constraints) {
|
|
66
|
-
span.setAttribute("model.constraints", JSON.stringify(input.constraints));
|
|
67
|
-
}
|
|
68
|
-
return result;
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
export {
|
|
72
|
-
traceSync,
|
|
73
|
-
traceModelSelection,
|
|
74
|
-
traceAsync,
|
|
75
|
-
getTracer
|
|
76
|
-
};
|
|
2
|
+
import{SpanStatusCode as g,trace as m}from"@opentelemetry/api";var y="@contractspec/lib.observability";function E(o=y){return m.getTracer(o)}async function T(o,e,S){return E(S).startActiveSpan(o,async(t)=>{try{let r=await e(t);return t.setStatus({code:g.OK}),r}catch(r){throw t.recordException(r),t.setStatus({code:g.ERROR,message:r instanceof Error?r.message:String(r)}),r}finally{t.end()}})}function R(o,e,S){return E(S).startActiveSpan(o,(t)=>{try{let r=e(t);return t.setStatus({code:g.OK}),r}catch(r){throw t.recordException(r),t.setStatus({code:g.ERROR,message:r instanceof Error?r.message:String(r)}),r}finally{t.end()}})}async function a(o,e){let S=performance.now();return T("model.selection",async(c)=>{let t=await o(),r=performance.now()-S;if(c.setAttribute("model.selected",e.modelId),c.setAttribute("model.provider",e.providerKey),c.setAttribute("model.score",e.score),c.setAttribute("model.alternatives_count",e.alternativesCount),c.setAttribute("model.selection_duration_ms",r),c.setAttribute("model.reason",e.reason),e.dimension)c.setAttribute("model.dimension",e.dimension);if(e.constraints)c.setAttribute("model.constraints",JSON.stringify(e.constraints));return t})}export{R as traceSync,a as traceModelSelection,T as traceAsync,E as getTracer};
|