@obzerver/server 0.15.0 → 0.17.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/dist/otlp.js ADDED
@@ -0,0 +1,680 @@
1
+ // OpenTelemetry (OTLP/HTTP) traces in, Obzerver executions out.
2
+ //
3
+ // Apps in any language can report with the official OpenTelemetry SDKs: they POST ExportTraceServiceRequest to
4
+ // /v1/traces, as protobuf (the SDKs' default) or JSON. Here the spans are decoded (a small protobuf reader for
5
+ // the trace schema; no generated code, no dependency) and mapped onto what the Node SDK sends:
6
+ //
7
+ // - a SERVER span is a request, a CONSUMER span a job run: one execution each, with the span's service;
8
+ // - the spans under it, down to the next SERVER/CONSUMER span, are its spans: CLIENT spans with `db.*` are
9
+ // queries, CLIENT spans with `http.*`/`url.*` are outbound calls, the rest are methods;
10
+ // - `exception` events become errors (grouped by class and in-app frames, like the SDK's);
11
+ // - the resource gives the app (`service.name`), version, environment, instance and runtime, and the
12
+ // instrumentation scopes the frameworks shown next to it.
13
+ //
14
+ // Exporters send spans as they end, several exports at once, so a request's spans can come before or just after
15
+ // the request's own span. Spans are kept by trace, and a request is written GRACE_MS after its span came, with
16
+ // every span of its trace that came by then (per project; spans with no request wait up to a minute).
17
+ import crypto from 'node:crypto';
18
+ // ---------------------------------------------------------------- protobuf
19
+ /** Reads protobuf wire format: varints, fixed 32/64-bit numbers and length-delimited fields. */
20
+ class Reader {
21
+ buf;
22
+ end;
23
+ pos = 0;
24
+ constructor(buf, end = buf.length) {
25
+ this.buf = buf;
26
+ this.end = end;
27
+ }
28
+ get more() { return this.pos < this.end; }
29
+ varint() {
30
+ // Up to 64 bits, as a float: exact to 2^53, close enough beyond (only counts and enums are read this way).
31
+ let result = 0;
32
+ let mul = 1;
33
+ for (let i = 0; i < 10; i++) {
34
+ const b = this.buf[this.pos++];
35
+ result += (b & 0x7f) * mul;
36
+ if (b < 0x80)
37
+ return result;
38
+ mul *= 128;
39
+ }
40
+ throw new Error('Malformed varint');
41
+ }
42
+ /** A signed int64 varint (two's complement for negatives). */
43
+ int64() {
44
+ const v = this.varint();
45
+ return v >= 2 ** 63 ? v - 2 ** 64 : v;
46
+ }
47
+ fixed64() {
48
+ const lo = this.fixed32();
49
+ const hi = this.fixed32();
50
+ return hi * 4294967296 + lo;
51
+ }
52
+ /** A fixed64 time in nanoseconds, as milliseconds to the microsecond (exact: no float rounding on the way). */
53
+ nanosAsMs() {
54
+ const lo = BigInt(this.fixed32());
55
+ const hi = BigInt(this.fixed32());
56
+ return Number(((hi << 32n) | lo) / 1000n) / 1000;
57
+ }
58
+ fixed32() {
59
+ const b = this.buf;
60
+ const p = this.pos;
61
+ this.pos += 4;
62
+ if (this.pos > this.end)
63
+ throw new Error('Truncated');
64
+ return (b[p] | (b[p + 1] << 8) | (b[p + 2] << 16)) + b[p + 3] * 16777216;
65
+ }
66
+ double() {
67
+ const v = new DataView(this.buf.buffer, this.buf.byteOffset + this.pos, 8).getFloat64(0, true);
68
+ this.pos += 8;
69
+ return v;
70
+ }
71
+ bytes() {
72
+ const n = this.varint();
73
+ const start = this.pos;
74
+ this.pos += n;
75
+ if (this.pos > this.end)
76
+ throw new Error('Truncated');
77
+ return this.buf.subarray(start, this.pos);
78
+ }
79
+ string() { return utf8.decode(this.bytes()); }
80
+ /** A nested message: a reader over its bytes. */
81
+ sub() { const b = this.bytes(); return new Reader(b); }
82
+ skip(wire) {
83
+ if (wire === 0)
84
+ this.varint();
85
+ else if (wire === 1)
86
+ this.pos += 8;
87
+ else if (wire === 2)
88
+ this.bytes();
89
+ else if (wire === 5)
90
+ this.pos += 4;
91
+ else
92
+ throw new Error(`Unsupported wire type ${wire}`);
93
+ }
94
+ /** Each field: number and wire type. */
95
+ *fields() {
96
+ while (this.more) {
97
+ const tag = this.varint();
98
+ yield [Math.floor(tag / 8), tag & 7];
99
+ }
100
+ }
101
+ }
102
+ const utf8 = new TextDecoder();
103
+ const hex = (b) => Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString('hex');
104
+ function pbAnyValue(r) {
105
+ let v = null;
106
+ for (const [f, w] of r.fields()) {
107
+ if (f === 1 && w === 2)
108
+ v = r.string();
109
+ else if (f === 2 && w === 0)
110
+ v = r.varint() !== 0;
111
+ else if (f === 3 && w === 0)
112
+ v = r.int64();
113
+ else if (f === 4 && w === 1)
114
+ v = r.double();
115
+ else if (f === 5 && w === 2) {
116
+ const a = r.sub();
117
+ const out = [];
118
+ for (const [g, x] of a.fields()) {
119
+ if (g === 1 && x === 2)
120
+ out.push(pbAnyValue(a.sub()));
121
+ else
122
+ a.skip(x);
123
+ }
124
+ v = out;
125
+ }
126
+ else if (f === 6 && w === 2) {
127
+ const a = r.sub();
128
+ const out = {};
129
+ for (const [g, x] of a.fields()) {
130
+ if (g === 1 && x === 2)
131
+ pbKeyValue(a.sub(), out);
132
+ else
133
+ a.skip(x);
134
+ }
135
+ v = out;
136
+ }
137
+ else if (f === 7 && w === 2)
138
+ v = hex(r.bytes());
139
+ else
140
+ r.skip(w);
141
+ }
142
+ return v;
143
+ }
144
+ function pbKeyValue(r, into) {
145
+ let key = '';
146
+ let value = null;
147
+ for (const [f, w] of r.fields()) {
148
+ if (f === 1 && w === 2)
149
+ key = r.string();
150
+ else if (f === 2 && w === 2)
151
+ value = pbAnyValue(r.sub());
152
+ else
153
+ r.skip(w);
154
+ }
155
+ if (key)
156
+ into[key] = value;
157
+ }
158
+ function pbSpan(r, scope) {
159
+ const s = { traceId: '', spanId: '', parentId: null, name: '', kind: 0, start: 0, end: 0, attrs: {}, status: 0, statusMessage: '', events: [], scope };
160
+ for (const [f, w] of r.fields()) {
161
+ if (f === 1 && w === 2)
162
+ s.traceId = hex(r.bytes());
163
+ else if (f === 2 && w === 2)
164
+ s.spanId = hex(r.bytes());
165
+ else if (f === 4 && w === 2) {
166
+ const p = hex(r.bytes());
167
+ s.parentId = p && !/^0+$/.test(p) ? p : null;
168
+ }
169
+ else if (f === 5 && w === 2)
170
+ s.name = r.string();
171
+ else if (f === 6 && w === 0)
172
+ s.kind = r.varint();
173
+ else if (f === 7 && w === 1)
174
+ s.start = r.nanosAsMs();
175
+ else if (f === 8 && w === 1)
176
+ s.end = r.nanosAsMs();
177
+ else if (f === 9 && w === 2)
178
+ pbKeyValue(r.sub(), s.attrs);
179
+ else if (f === 11 && w === 2) {
180
+ const e = r.sub();
181
+ const ev = { name: '', time: 0, attrs: {} };
182
+ for (const [g, x] of e.fields()) {
183
+ if (g === 1 && x === 1)
184
+ ev.time = e.nanosAsMs();
185
+ else if (g === 2 && x === 2)
186
+ ev.name = e.string();
187
+ else if (g === 3 && x === 2)
188
+ pbKeyValue(e.sub(), ev.attrs);
189
+ else
190
+ e.skip(x);
191
+ }
192
+ s.events.push(ev);
193
+ }
194
+ else if (f === 15 && w === 2) {
195
+ const st = r.sub();
196
+ for (const [g, x] of st.fields()) {
197
+ if (g === 2 && x === 2)
198
+ s.statusMessage = st.string();
199
+ else if (g === 3 && x === 0)
200
+ s.status = st.varint();
201
+ else
202
+ st.skip(x);
203
+ }
204
+ }
205
+ else
206
+ r.skip(w);
207
+ }
208
+ return s;
209
+ }
210
+ /** ExportTraceServiceRequest, protobuf. */
211
+ export function decodeProtobuf(buf) {
212
+ const out = [];
213
+ const r = new Reader(buf);
214
+ for (const [f, w] of r.fields()) {
215
+ if (f !== 1 || w !== 2) {
216
+ r.skip(w);
217
+ continue;
218
+ }
219
+ const rs = r.sub();
220
+ const res = { attrs: {}, spans: [], scopes: [] };
221
+ for (const [g, x] of rs.fields()) {
222
+ if (g === 1 && x === 2) {
223
+ const re = rs.sub();
224
+ for (const [h, y] of re.fields()) {
225
+ if (h === 1 && y === 2)
226
+ pbKeyValue(re.sub(), res.attrs);
227
+ else
228
+ re.skip(y);
229
+ }
230
+ }
231
+ else if (g === 2 && x === 2) {
232
+ const ss = rs.sub();
233
+ let scope = '';
234
+ const spans = [];
235
+ for (const [h, y] of ss.fields()) {
236
+ if (h === 1 && y === 2) {
237
+ const sc = ss.sub();
238
+ for (const [k, z] of sc.fields()) {
239
+ if (k === 1 && z === 2)
240
+ scope = sc.string();
241
+ else
242
+ sc.skip(z);
243
+ }
244
+ }
245
+ else if (h === 2 && y === 2)
246
+ spans.push(ss.sub());
247
+ else
248
+ ss.skip(y);
249
+ }
250
+ if (scope)
251
+ res.scopes.push(scope);
252
+ for (const sp of spans)
253
+ res.spans.push(pbSpan(sp, scope));
254
+ }
255
+ else
256
+ rs.skip(x);
257
+ }
258
+ out.push(res);
259
+ }
260
+ return out;
261
+ }
262
+ /** OTLP/JSON ids are hex; tolerate base64 (some older exporters). */
263
+ const jsonId = (v) => {
264
+ if (typeof v !== 'string' || !v)
265
+ return '';
266
+ if (/^[0-9a-f]+$/i.test(v) && (v.length === 32 || v.length === 16))
267
+ return v.toLowerCase();
268
+ try {
269
+ return Buffer.from(v, 'base64').toString('hex');
270
+ }
271
+ catch {
272
+ return '';
273
+ }
274
+ };
275
+ const jsonNum = (v) => (typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : 0);
276
+ /** A nanosecond time (a string in OTLP/JSON) as milliseconds to the microsecond. */
277
+ const jsonNanos = (v) => {
278
+ try {
279
+ return Number(BigInt(typeof v === 'number' ? Math.round(v) : String(v ?? 0)) / 1000n) / 1000;
280
+ }
281
+ catch {
282
+ return jsonNum(v) / 1e6;
283
+ }
284
+ };
285
+ function jsonAny(v) {
286
+ if (!v || typeof v !== 'object')
287
+ return null;
288
+ if ('stringValue' in v)
289
+ return v.stringValue;
290
+ if ('boolValue' in v)
291
+ return Boolean(v.boolValue);
292
+ if ('intValue' in v)
293
+ return jsonNum(v.intValue);
294
+ if ('doubleValue' in v)
295
+ return jsonNum(v.doubleValue);
296
+ if ('arrayValue' in v)
297
+ return (v.arrayValue?.values ?? []).map(jsonAny);
298
+ if ('kvlistValue' in v)
299
+ return jsonAttrs(v.kvlistValue?.values);
300
+ if ('bytesValue' in v)
301
+ return Buffer.from(String(v.bytesValue), 'base64').toString('hex');
302
+ return null;
303
+ }
304
+ function jsonAttrs(list) {
305
+ const out = {};
306
+ if (Array.isArray(list))
307
+ for (const kv of list)
308
+ if (kv && typeof kv.key === 'string')
309
+ out[kv.key] = jsonAny(kv.value);
310
+ return out;
311
+ }
312
+ /** ExportTraceServiceRequest, JSON. */
313
+ export function decodeJson(body) {
314
+ const out = [];
315
+ for (const rs of (Array.isArray(body?.resourceSpans) ? body.resourceSpans : [])) {
316
+ const res = { attrs: jsonAttrs(rs?.resource?.attributes), spans: [], scopes: [] };
317
+ for (const ss of (Array.isArray(rs?.scopeSpans) ? rs.scopeSpans : [])) {
318
+ const scope = typeof ss?.scope?.name === 'string' ? ss.scope.name : '';
319
+ if (scope)
320
+ res.scopes.push(scope);
321
+ for (const sp of (Array.isArray(ss?.spans) ? ss.spans : [])) {
322
+ const parent = jsonId(sp.parentSpanId);
323
+ res.spans.push({
324
+ traceId: jsonId(sp.traceId), spanId: jsonId(sp.spanId), parentId: parent && !/^0+$/.test(parent) ? parent : null,
325
+ name: String(sp.name ?? ''), kind: typeof sp.kind === 'string' ? KIND_NAMES[sp.kind] ?? 0 : jsonNum(sp.kind),
326
+ start: jsonNanos(sp.startTimeUnixNano), end: jsonNanos(sp.endTimeUnixNano), attrs: jsonAttrs(sp.attributes),
327
+ status: typeof sp.status?.code === 'string' ? STATUS_NAMES[sp.status.code] ?? 0 : jsonNum(sp.status?.code), statusMessage: String(sp.status?.message ?? ''),
328
+ events: (Array.isArray(sp.events) ? sp.events : []).map((e) => ({ name: String(e.name ?? ''), time: jsonNanos(e.timeUnixNano), attrs: jsonAttrs(e.attributes) })),
329
+ scope,
330
+ });
331
+ }
332
+ }
333
+ out.push(res);
334
+ }
335
+ return out;
336
+ }
337
+ const KIND_NAMES = { SPAN_KIND_UNSPECIFIED: 0, SPAN_KIND_INTERNAL: 1, SPAN_KIND_SERVER: 2, SPAN_KIND_CLIENT: 3, SPAN_KIND_PRODUCER: 4, SPAN_KIND_CONSUMER: 5 };
338
+ const STATUS_NAMES = { STATUS_CODE_UNSET: 0, STATUS_CODE_OK: 1, STATUS_CODE_ERROR: 2 };
339
+ // ---------------------------------------------------------------- spans to executions
340
+ const KIND_LABELS = { 0: 'unspecified', 1: 'internal', 2: 'server', 3: 'client', 4: 'producer', 5: 'consumer' };
341
+ const SERVER = 2;
342
+ const CLIENT = 3;
343
+ const CONSUMER = 5;
344
+ const isEntry = (s) => s.kind === SERVER || s.kind === CONSUMER;
345
+ const str = (v) => (typeof v === 'string' && v ? v : typeof v === 'number' ? String(v) : null);
346
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : typeof v === 'string' && v.trim() && Number.isFinite(Number(v)) ? Number(v) : null);
347
+ const first = (a, ...keys) => { for (const k of keys)
348
+ if (a[k] != null && a[k] !== '')
349
+ return a[k]; return undefined; };
350
+ /** Framework names from instrumentation scope names, across languages. */
351
+ export function frameworksOf(scopes) {
352
+ const out = new Set();
353
+ for (const raw of scopes) {
354
+ const s = raw.toLowerCase();
355
+ const m = /instrumentation[-._/]([a-z0-9_]+)/.exec(s);
356
+ const name = s === 'next.js' || s.startsWith('next.js') ? 'nextjs'
357
+ : s.startsWith('microsoft.aspnetcore') ? 'aspnetcore'
358
+ : s.startsWith('system.net.http') ? null
359
+ : m ? m[1].replace(/_/g, '-') : null;
360
+ if (name && WEB_FRAMEWORKS.has(name))
361
+ out.add(name);
362
+ }
363
+ return [...out].sort();
364
+ }
365
+ const WEB_FRAMEWORKS = new Set(['express', 'fastify', 'koa', 'hapi', 'nestjs-core', 'nextjs', 'fastapi', 'flask', 'django', 'starlette', 'falcon', 'tornado', 'aiohttp-server',
366
+ 'aspnetcore', 'spring-webmvc', 'spring-webflux', 'gin', 'echo', 'rails', 'sinatra', 'laravel', 'celery', 'graphql']);
367
+ /** Stack frames from a stack trace in Node, Python, .NET or Java format. */
368
+ export function framesOf(stack) {
369
+ const frames = [];
370
+ const lines = stack.split('\n');
371
+ for (let i = 0; i < lines.length; i++) {
372
+ const line = lines[i];
373
+ let fn = '';
374
+ let file = '';
375
+ let ln = 0;
376
+ let col = 0;
377
+ let m;
378
+ if ((m = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/.exec(line))) {
379
+ fn = m[1] || '<anonymous>';
380
+ file = m[2];
381
+ ln = Number(m[3]);
382
+ col = Number(m[4]);
383
+ } // Node
384
+ else if ((m = /^\s*File "(.+?)", line (\d+), in (.+)$/.exec(line))) {
385
+ file = m[1];
386
+ ln = Number(m[2]);
387
+ fn = m[3];
388
+ } // Python
389
+ else if ((m = /^\s*at (.+?)\(.*?\)(?: in (.+?):line (\d+))?\s*$/.exec(line))) {
390
+ fn = m[1];
391
+ file = m[2] || '';
392
+ ln = Number(m[3] || 0);
393
+ } // .NET
394
+ else if ((m = /^\s*at ([\w$.<>]+)\((.+?)(?::(\d+))?\)$/.exec(line))) {
395
+ fn = m[1];
396
+ file = m[2];
397
+ ln = Number(m[3] || 0);
398
+ } // Java
399
+ else
400
+ continue;
401
+ file = file.replace(/^file:\/\//, '');
402
+ const lib = /node_modules|site-packages|dist-packages|^node:|^internal\/|^<frozen|\/lib\/python\d|^System\.|^Microsoft\.|^java\.|^jdk\.|^sun\./.test(file) || /^(System|Microsoft|java|jdk|sun)\./.test(fn);
403
+ frames.push({ fn, file, rel: file.split(/[\\/]/).filter(Boolean).slice(-3).join('/'), line: ln, col, inApp: !!file && !lib });
404
+ }
405
+ // Python prints the innermost call last; the others first.
406
+ return /^\s*File "/m.test(stack) ? frames.reverse() : frames;
407
+ }
408
+ function fingerprintOf(cls, message, frames) {
409
+ const app = frames.filter((f) => f.inApp).slice(0, 3).map((f) => `${f.rel}:${f.fn}`);
410
+ const basis = app.length
411
+ ? `${cls}|${app.join('|')}`
412
+ : `${cls}|${message.replace(/\d+/g, '#').replace(/[0-9a-f]{8,}/gi, '#').slice(0, 200)}|${frames.slice(0, 2).map((f) => f.fn).join('|')}`;
413
+ return crypto.createHash('sha1').update(basis).digest('hex').slice(0, 16);
414
+ }
415
+ /** What kind of Obzerver span an OpenTelemetry span is, and the attributes the dashboard reads. */
416
+ function spanOf(s) {
417
+ const a = s.attrs;
418
+ const system = str(first(a, 'db.system.name', 'db.system'));
419
+ if (system) {
420
+ const statement = str(first(a, 'db.query.text', 'db.statement'));
421
+ return { kind: 'db', name: statement ? statement.slice(0, 300) : s.name, attrs: { system, statement, table: str(first(a, 'db.collection.name', 'db.sql.table', 'db.mongodb.collection')) } };
422
+ }
423
+ const method = str(first(a, 'http.request.method', 'http.method'));
424
+ const url = str(first(a, 'url.full', 'http.url'));
425
+ if (s.kind === CLIENT && (method || url)) {
426
+ let host = str(first(a, 'server.address', 'net.peer.name', 'http.host'));
427
+ if (!host && url) {
428
+ try {
429
+ host = new URL(url).host;
430
+ }
431
+ catch { /* not a URL */ }
432
+ }
433
+ return { kind: 'http', name: `${method ?? 'GET'} ${host ?? s.name}`, attrs: { method, url, host, status: num(first(a, 'http.response.status_code', 'http.status_code')) } };
434
+ }
435
+ if (a['graphql.operation.name'] != null || a['graphql.operation.type'] != null)
436
+ return { kind: 'graphql', name: s.name, attrs: {} };
437
+ return { kind: 'function', name: s.name, attrs: {} };
438
+ }
439
+ const isPlumbing = (s) => s.kind === 1 && s.attrs['asgi.event.type'] != null;
440
+ /** Milliseconds to the microsecond. */
441
+ const us = (ms) => Math.round(ms * 1000) / 1000;
442
+ /** One execution from its entry span and the spans under it (stopping at the next entry span). */
443
+ function buildExecution(entry, byParent, used, version) {
444
+ const a = entry.attrs;
445
+ const job = entry.kind === CONSUMER;
446
+ const method = job ? null : str(first(a, 'http.request.method', 'http.method'))?.toUpperCase() ?? null;
447
+ const route = str(first(a, 'http.route', 'next.route'));
448
+ const urlPath = (() => {
449
+ const p = str(first(a, 'url.path', 'http.target'));
450
+ if (p)
451
+ return p.split('?')[0];
452
+ const u = str(first(a, 'url.full', 'http.url'));
453
+ if (u) {
454
+ try {
455
+ return new URL(u).pathname;
456
+ }
457
+ catch { /* not a URL */ }
458
+ }
459
+ return null;
460
+ })();
461
+ const status = job ? null : num(first(a, 'http.response.status_code', 'http.status_code'));
462
+ const name = !job && method ? `${method} ${route ?? urlPath ?? '/'}` : entry.name;
463
+ // Spans under the entry: the entry is the root (as the Node SDK sends it), its descendants below.
464
+ const spans = [];
465
+ const all = [entry];
466
+ // Framework plumbing that says nothing about the app's code (ASGI's per-message send/receive spans) is left
467
+ // out; anything under it is kept, under the nearest span that stays.
468
+ const lift = new Map();
469
+ const walk = (parent, keptParent) => {
470
+ for (const c of byParent.get(parent.spanId) ?? []) {
471
+ if (isEntry(c) || used.has(c))
472
+ continue;
473
+ used.add(c);
474
+ if (isPlumbing(c)) {
475
+ walk(c, keptParent);
476
+ continue;
477
+ }
478
+ if (c.parentId !== keptParent)
479
+ lift.set(c, keptParent);
480
+ all.push(c);
481
+ walk(c, c.spanId);
482
+ }
483
+ };
484
+ walk(entry, entry.spanId);
485
+ const t0 = entry.start;
486
+ const childrenOf = new Map();
487
+ const parentOf = (s) => lift.get(s) ?? s.parentId;
488
+ for (const s of all) {
489
+ const p = parentOf(s);
490
+ if (s !== entry && p) {
491
+ const l = childrenOf.get(p) ?? [];
492
+ l.push(s);
493
+ childrenOf.set(p, l);
494
+ }
495
+ }
496
+ const selfOf = (s) => {
497
+ // Duration minus the union of the children's intervals, clipped to the span.
498
+ const iv = (childrenOf.get(s.spanId) ?? []).map((c) => [Math.max(c.start, s.start), Math.min(c.end, s.end)]).filter(([x, y]) => y > x).sort((p, q) => p[0] - q[0]);
499
+ let covered = 0;
500
+ let cur = null;
501
+ for (const v of iv) {
502
+ if (cur && v[0] <= cur[1])
503
+ cur[1] = Math.max(cur[1], v[1]);
504
+ else {
505
+ if (cur)
506
+ covered += cur[1] - cur[0];
507
+ cur = [...v];
508
+ }
509
+ }
510
+ if (cur)
511
+ covered += cur[1] - cur[0];
512
+ return Math.max(0, s.end - s.start - covered);
513
+ };
514
+ for (const s of all) {
515
+ const isRoot = s === entry;
516
+ const m = isRoot ? { kind: (job ? 'job' : 'request'), name, attrs: {} } : spanOf(s);
517
+ spans.push({
518
+ id: s.spanId, parentId: isRoot ? null : parentOf(s), name: m.name, kind: m.kind,
519
+ start: us(Math.max(0, s.start - t0)), duration: us(Math.max(0, s.end - s.start)), self: us(selfOf(s)), count: 1,
520
+ ...(Object.keys(m.attrs).length ? { attrs: m.attrs } : {}),
521
+ ...(s.status === 2 ? { error: s.statusMessage || 'error' } : {}),
522
+ });
523
+ }
524
+ const failed = job ? entry.status === 2 : (status != null ? status >= 500 : entry.status === 2);
525
+ const userId = str(first(a, 'enduser.id', 'user.id'));
526
+ const errors = [];
527
+ for (const s of all) {
528
+ for (const e of s.events) {
529
+ if (e.name !== 'exception')
530
+ continue;
531
+ const cls = str(e.attrs['exception.type']) ?? 'Error';
532
+ const message = str(e.attrs['exception.message']) ?? '';
533
+ const stack = str(e.attrs['exception.stacktrace']) ?? '';
534
+ const frames = framesOf(stack);
535
+ errors.push({
536
+ ts: e.time || s.end, class: cls.split('.').pop() || cls, message, stack, frames, fingerprint: fingerprintOf(cls, message, frames),
537
+ status, handled: !failed, code: null, httpStatus: status, traceId: entry.traceId, operation: name, kind: job ? 'job' : 'http', userId, version,
538
+ });
539
+ }
540
+ }
541
+ const main = failed ? errors[errors.length - 1] : undefined;
542
+ const trace = {
543
+ traceId: entry.traceId, spanId: entry.spanId, parentSpanId: entry.parentId, kind: job ? 'job' : 'http', name,
544
+ method, route: route ?? urlPath, path: urlPath, status, ts: entry.start, duration: us(Math.max(0, entry.end - entry.start)), userId, failed,
545
+ errorClass: main?.class ?? (failed && entry.statusMessage ? 'Error' : null), fingerprint: main?.fingerprint ?? null, errorMessage: main?.message ?? (failed ? entry.statusMessage || null : null),
546
+ queue: job ? str(first(a, 'messaging.destination.name')) : null, queueWait: null, attempt: null, sampled: true, spans,
547
+ tags: { otel: entry.scope || true },
548
+ };
549
+ return { trace, errors };
550
+ }
551
+ // ---------------------------------------------------------------- the per-project converter
552
+ const MAX_PENDING = 100_000;
553
+ /** How long a trace's spans wait for the request they belong to. */
554
+ const PENDING_MS = 60_000;
555
+ /**
556
+ * How long a request's span waits for the rest of its spans before its execution is written. Exporters send
557
+ * spans as they end, often several requests in flight at once, so a child can arrive just after its parent.
558
+ */
559
+ export const GRACE_MS = 2000;
560
+ /**
561
+ * Turns OTLP exports into ingest payloads. Spans are kept by trace; a trace with a request (SERVER or CONSUMER
562
+ * span) is written GRACE_MS after that span came, with every span under it by then. Spans with no request yet
563
+ * wait up to PENDING_MS, then are dropped (counted).
564
+ */
565
+ export class OtlpConverter {
566
+ traces = new Map();
567
+ count = 0;
568
+ /** Spans dropped: their request never came, or the buffer was full. */
569
+ dropped = 0;
570
+ /** The names of the last few dropped spans, to see what is missing its request. */
571
+ lastDropped = [];
572
+ drop(spans) {
573
+ this.dropped += spans.length;
574
+ for (const s of spans.slice(-5))
575
+ this.lastDropped.push(`${s.name} (${KIND_LABELS[s.kind] ?? s.kind})`);
576
+ if (this.lastDropped.length > 10)
577
+ this.lastDropped.splice(0, this.lastDropped.length - 10);
578
+ }
579
+ add(resources, now = Date.now()) {
580
+ for (const res of resources) {
581
+ for (const s of res.spans) {
582
+ if (!s.traceId || !s.spanId)
583
+ continue;
584
+ if (this.count >= MAX_PENDING) {
585
+ this.drop([s]);
586
+ continue;
587
+ }
588
+ // One bucket per trace and app: the same trace id can cross several services.
589
+ const key = `${s.traceId}\u0000${str(res.attrs['service.name']) ?? ''}`;
590
+ let b = this.traces.get(key);
591
+ if (!b)
592
+ this.traces.set(key, (b = { at: now, ready: null, spans: [], res: res.attrs, scopes: [] }));
593
+ b.spans.push(s);
594
+ this.count++;
595
+ if (s.scope && !b.scopes.includes(s.scope))
596
+ b.scopes.push(s.scope);
597
+ if (isEntry(s) && b.ready == null)
598
+ b.ready = now + GRACE_MS;
599
+ }
600
+ }
601
+ }
602
+ /** Payloads for the traces whose wait is over (all of them with `all`, when the server stops). */
603
+ take(now = Date.now(), all = false) {
604
+ const byService = new Map();
605
+ for (const [key, b] of this.traces) {
606
+ if (b.ready == null || (!all && b.ready > now)) {
607
+ if (now - b.at > PENDING_MS || all) {
608
+ this.traces.delete(key);
609
+ this.count -= b.spans.length;
610
+ this.drop(b.spans);
611
+ }
612
+ continue;
613
+ }
614
+ this.traces.delete(key);
615
+ this.count -= b.spans.length;
616
+ const byParent = new Map();
617
+ for (const s of b.spans)
618
+ if (s.parentId) {
619
+ const l = byParent.get(s.parentId) ?? [];
620
+ l.push(s);
621
+ byParent.set(s.parentId, l);
622
+ }
623
+ const used = new Set();
624
+ const svc = str(b.res['service.name']) ?? 'unknown_service';
625
+ let out = byService.get(svc);
626
+ if (!out)
627
+ byService.set(svc, (out = { res: b.res, scopes: new Set(), traces: [], errors: [] }));
628
+ for (const sc of b.scopes)
629
+ out.scopes.add(sc);
630
+ for (const e of b.spans.filter(isEntry)) {
631
+ used.add(e);
632
+ const x = buildExecution(e, byParent, used, str(b.res['service.version']));
633
+ out.traces.push(x.trace);
634
+ out.errors.push(...x.errors);
635
+ }
636
+ // Spans under no request of this trace: dropped (their request was written before they came).
637
+ this.drop(b.spans.filter((s) => !used.has(s)));
638
+ }
639
+ const payloads = [];
640
+ for (const [id, x] of byService) {
641
+ const r = x.res;
642
+ // Some setups (@vercel/otel) leave out telemetry.sdk.*: the runtime says the language then.
643
+ const lang = str(r['telemetry.sdk.language']) ?? str(r['process.runtime.name']);
644
+ const runtime = [str(r['process.runtime.name']), str(r['process.runtime.version'])].filter(Boolean).join(' ');
645
+ payloads.push({
646
+ sdk: { name: lang ? `opentelemetry-${lang}` : 'opentelemetry', version: str(r['telemetry.sdk.version']) ?? '' },
647
+ service: {
648
+ id, version: str(r['service.version']),
649
+ instance: str(first(r, 'service.instance.id', 'host.name', 'host.id')) ?? 'otlp',
650
+ environment: str(first(r, 'deployment.environment.name', 'deployment.environment')) ?? undefined,
651
+ node: runtime || undefined, host: str(r['host.name']) ?? undefined, pid: num(r['process.pid']) ?? undefined,
652
+ frameworks: frameworksOf([...x.scopes]),
653
+ },
654
+ sentAt: now, traces: x.traces, errors: x.errors,
655
+ });
656
+ }
657
+ return payloads;
658
+ }
659
+ /** Spans waiting (for their request, or for the grace period to end). */
660
+ get waiting() { return this.count; }
661
+ }
662
+ // ---------------------------------------------------------------- responses
663
+ /** ExportTrace/Metrics/LogsServiceResponse with a partial-success message (field 1, its error_message = 2). */
664
+ export function partialSuccess(message, protobuf) {
665
+ if (!protobuf)
666
+ return { partialSuccess: { errorMessage: message } };
667
+ const msg = Buffer.from(message, 'utf8');
668
+ const inner = Buffer.concat([Buffer.from([0x12]), varintBytes(msg.length), msg]);
669
+ return Buffer.concat([Buffer.from([0x0a]), varintBytes(inner.length), inner]);
670
+ }
671
+ function varintBytes(n) {
672
+ const out = [];
673
+ while (n > 127) {
674
+ out.push((n & 0x7f) | 0x80);
675
+ n = Math.floor(n / 128);
676
+ }
677
+ out.push(n);
678
+ return Buffer.from(out);
679
+ }
680
+ //# sourceMappingURL=otlp.js.map