@libo11y/server 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +234 -2
- package/dist/context.d.ts +10 -0
- package/dist/context.js +5 -0
- package/dist/exporters.d.ts +12 -0
- package/dist/exporters.js +90 -0
- package/dist/fetch.d.ts +28 -0
- package/dist/fetch.js +107 -0
- package/dist/glob.d.ts +14 -0
- package/dist/glob.js +177 -0
- package/dist/http-common.d.ts +50 -0
- package/dist/http-common.js +105 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/otlp-proto-metrics.d.ts +21 -0
- package/dist/otlp-proto-metrics.js +401 -0
- package/dist/platform.d.ts +3 -0
- package/dist/platform.js +31 -0
- package/dist/registry.d.ts +8 -0
- package/dist/registry.js +66 -0
- package/dist/resource.d.ts +13 -0
- package/dist/resource.js +67 -0
- package/dist/runtime-metrics.d.ts +23 -0
- package/dist/runtime-metrics.js +62 -0
- package/dist/serve.d.ts +85 -0
- package/dist/serve.js +321 -0
- package/dist/setup.d.ts +13 -0
- package/dist/setup.js +18 -0
- package/dist/signals.d.ts +35 -0
- package/dist/signals.js +58 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +50 -4
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OTLP/protobuf metrics with exemplars. Upstream's ProtobufMetricsSerializer writes no exemplars, so
|
|
3
|
+
* this is a dependency-free encoder of opentelemetry-proto's ExportMetricsServiceRequest. It writes
|
|
4
|
+
* every field upstream writes, in upstream's order, so a collection without exemplars encodes to
|
|
5
|
+
* upstream's bytes exactly, and adds each data point's exemplars (NumberDataPoint field 5,
|
|
6
|
+
* HistogramDataPoint field 8, ExponentialHistogramDataPoint field 11).
|
|
7
|
+
*
|
|
8
|
+
* It walks the SDK's ResourceMetrics rather than the OTLP/JSON object core's JSON serializer builds,
|
|
9
|
+
* because JSON has no NaN or Infinity: a NaN gauge or an empty exponential histogram's infinite
|
|
10
|
+
* bounds would come back as null.
|
|
11
|
+
*/
|
|
12
|
+
import { exemplarsOf } from "@libo11y/core";
|
|
13
|
+
import { ValueType } from "@opentelemetry/api";
|
|
14
|
+
import { ProtobufMetricsSerializer, } from "@opentelemetry/otlp-transformer";
|
|
15
|
+
import { AggregationTemporality, DataPointType, } from "@opentelemetry/sdk-metrics";
|
|
16
|
+
const VARINT = 0;
|
|
17
|
+
const FIXED64 = 1;
|
|
18
|
+
const LEN = 2;
|
|
19
|
+
const TWO_32 = 4294967296;
|
|
20
|
+
const MIN_INT64 = -(2 ** 63);
|
|
21
|
+
const MAX_INT64 = 2 ** 63;
|
|
22
|
+
const encoder = new TextEncoder();
|
|
23
|
+
/** A protobuf wire writer. Embedded messages are written to their own writer and then copied in. */
|
|
24
|
+
class Writer {
|
|
25
|
+
buf = new Uint8Array(256);
|
|
26
|
+
pos = 0;
|
|
27
|
+
reserve(n) {
|
|
28
|
+
if (this.pos + n <= this.buf.length)
|
|
29
|
+
return;
|
|
30
|
+
let size = this.buf.length * 2;
|
|
31
|
+
while (size < this.pos + n)
|
|
32
|
+
size *= 2;
|
|
33
|
+
const next = new Uint8Array(size);
|
|
34
|
+
next.set(this.buf.subarray(0, this.pos));
|
|
35
|
+
this.buf = next;
|
|
36
|
+
}
|
|
37
|
+
byte(b) {
|
|
38
|
+
this.reserve(1);
|
|
39
|
+
this.buf[this.pos++] = b;
|
|
40
|
+
}
|
|
41
|
+
tag(field, wireType) {
|
|
42
|
+
this.varint((field << 3) | wireType);
|
|
43
|
+
}
|
|
44
|
+
/** A varint from a 64-bit two's complement pair. */
|
|
45
|
+
varint64(low, high) {
|
|
46
|
+
let lo = low >>> 0;
|
|
47
|
+
let hi = high >>> 0;
|
|
48
|
+
while (hi > 0 || lo > 0x7f) {
|
|
49
|
+
this.byte((lo & 0x7f) | 0x80);
|
|
50
|
+
lo = ((lo >>> 7) | (hi << 25)) >>> 0;
|
|
51
|
+
hi >>>= 7;
|
|
52
|
+
}
|
|
53
|
+
this.byte(lo);
|
|
54
|
+
}
|
|
55
|
+
/** A varint for an integer number; a negative one is written as its 64-bit two's complement. */
|
|
56
|
+
varint(value) {
|
|
57
|
+
const [low, high] = split64(value);
|
|
58
|
+
this.varint64(low, high);
|
|
59
|
+
}
|
|
60
|
+
/** A zigzag varint, as sint32 fields take. */
|
|
61
|
+
sint32(value) {
|
|
62
|
+
this.varint64(((value << 1) ^ (value >> 31)) >>> 0, 0);
|
|
63
|
+
}
|
|
64
|
+
fixed64(low, high) {
|
|
65
|
+
this.reserve(8);
|
|
66
|
+
const l = low >>> 0;
|
|
67
|
+
const h = high >>> 0;
|
|
68
|
+
this.buf[this.pos++] = l & 0xff;
|
|
69
|
+
this.buf[this.pos++] = (l >>> 8) & 0xff;
|
|
70
|
+
this.buf[this.pos++] = (l >>> 16) & 0xff;
|
|
71
|
+
this.buf[this.pos++] = (l >>> 24) & 0xff;
|
|
72
|
+
this.buf[this.pos++] = h & 0xff;
|
|
73
|
+
this.buf[this.pos++] = (h >>> 8) & 0xff;
|
|
74
|
+
this.buf[this.pos++] = (h >>> 16) & 0xff;
|
|
75
|
+
this.buf[this.pos++] = (h >>> 24) & 0xff;
|
|
76
|
+
}
|
|
77
|
+
/** An unsigned or signed 64-bit integer number as fixed64 or sfixed64, as upstream converts it. */
|
|
78
|
+
fixed64Number(value) {
|
|
79
|
+
const [low, high] = split64(value);
|
|
80
|
+
this.fixed64(low, high);
|
|
81
|
+
}
|
|
82
|
+
fixed64BigInt(value) {
|
|
83
|
+
const v = BigInt.asUintN(64, value);
|
|
84
|
+
this.fixed64(Number(v & 0xffffffffn), Number(v >> 32n));
|
|
85
|
+
}
|
|
86
|
+
double(value) {
|
|
87
|
+
this.reserve(8);
|
|
88
|
+
new DataView(this.buf.buffer, this.buf.byteOffset + this.pos, 8).setFloat64(0, value, true);
|
|
89
|
+
this.pos += 8;
|
|
90
|
+
}
|
|
91
|
+
bytes(value) {
|
|
92
|
+
this.varint(value.length);
|
|
93
|
+
this.reserve(value.length);
|
|
94
|
+
this.buf.set(value, this.pos);
|
|
95
|
+
this.pos += value.length;
|
|
96
|
+
}
|
|
97
|
+
string(value) {
|
|
98
|
+
this.bytes(encoder.encode(value));
|
|
99
|
+
}
|
|
100
|
+
/** A length-delimited field whose content fn writes. */
|
|
101
|
+
message(field, fn) {
|
|
102
|
+
const inner = new Writer();
|
|
103
|
+
fn(inner);
|
|
104
|
+
this.tag(field, LEN);
|
|
105
|
+
this.bytes(inner.finish());
|
|
106
|
+
}
|
|
107
|
+
finish() {
|
|
108
|
+
return this.buf.slice(0, this.pos);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// split64 is upstream's conversion of a number to a 64-bit two's complement pair: the low and high
|
|
112
|
+
// 32 bits of its magnitude, negated for a negative value.
|
|
113
|
+
function split64(value) {
|
|
114
|
+
if (value >= 0)
|
|
115
|
+
return [value >>> 0, (value / TWO_32) >>> 0];
|
|
116
|
+
const abs = Math.abs(value);
|
|
117
|
+
let low = ~(abs >>> 0) >>> 0;
|
|
118
|
+
let high = ~((abs / TWO_32) >>> 0) >>> 0;
|
|
119
|
+
low = (low + 1) >>> 0;
|
|
120
|
+
if (low === 0)
|
|
121
|
+
high = (high + 1) >>> 0;
|
|
122
|
+
return [low, high];
|
|
123
|
+
}
|
|
124
|
+
function hrTimeNanos(t) {
|
|
125
|
+
return BigInt(Math.trunc(t[0])) * 1000000000n + BigInt(Math.trunc(t[1]));
|
|
126
|
+
}
|
|
127
|
+
function hex(id) {
|
|
128
|
+
const out = new Uint8Array(id.length >>> 1);
|
|
129
|
+
for (let i = 0; i < out.length; i++)
|
|
130
|
+
out[i] = Number.parseInt(id.slice(i * 2, i * 2 + 2), 16);
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
// anyValue writes an AnyValue's content as upstream's writeAnyValue does.
|
|
134
|
+
function anyValue(w, value) {
|
|
135
|
+
switch (typeof value) {
|
|
136
|
+
case "string":
|
|
137
|
+
w.tag(1, LEN);
|
|
138
|
+
w.string(value);
|
|
139
|
+
return;
|
|
140
|
+
case "boolean":
|
|
141
|
+
w.tag(2, VARINT);
|
|
142
|
+
w.varint(value ? 1 : 0);
|
|
143
|
+
return;
|
|
144
|
+
case "number":
|
|
145
|
+
if (Number.isInteger(value) && value >= MIN_INT64 && value < MAX_INT64) {
|
|
146
|
+
w.tag(3, VARINT);
|
|
147
|
+
w.varint(value);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
w.tag(4, FIXED64);
|
|
151
|
+
w.double(value);
|
|
152
|
+
}
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (value instanceof Uint8Array) {
|
|
156
|
+
w.tag(7, LEN);
|
|
157
|
+
w.bytes(value);
|
|
158
|
+
}
|
|
159
|
+
else if (Array.isArray(value)) {
|
|
160
|
+
w.message(5, (arr) => {
|
|
161
|
+
for (const item of value)
|
|
162
|
+
arr.message(1, (v) => anyValue(v, item));
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
else if (typeof value === "object" && value !== null) {
|
|
166
|
+
w.message(6, (list) => {
|
|
167
|
+
for (const [k, v] of Object.entries(value))
|
|
168
|
+
list.message(1, (kv) => keyValue(kv, k, v));
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function keyValue(w, key, value) {
|
|
173
|
+
w.tag(1, LEN);
|
|
174
|
+
w.string(key);
|
|
175
|
+
w.message(2, (v) => anyValue(v, value));
|
|
176
|
+
}
|
|
177
|
+
function attributes(w, field, attrs) {
|
|
178
|
+
if (attrs === undefined)
|
|
179
|
+
return;
|
|
180
|
+
for (const [key, value] of Object.entries(attrs))
|
|
181
|
+
w.message(field, (kv) => keyValue(kv, key, value));
|
|
182
|
+
}
|
|
183
|
+
function exemplars(w, field, point, valueType) {
|
|
184
|
+
for (const e of exemplarsOf(point)) {
|
|
185
|
+
w.message(field, (x) => {
|
|
186
|
+
attributes(x, 7, e.filteredAttributes);
|
|
187
|
+
x.tag(2, FIXED64);
|
|
188
|
+
x.fixed64BigInt(e.timeUnixNano);
|
|
189
|
+
if (valueType === ValueType.INT) {
|
|
190
|
+
x.tag(6, FIXED64);
|
|
191
|
+
x.fixed64Number(e.value);
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
x.tag(3, FIXED64);
|
|
195
|
+
x.double(e.value);
|
|
196
|
+
}
|
|
197
|
+
if (e.traceId !== undefined && e.spanId !== undefined) {
|
|
198
|
+
x.tag(4, LEN);
|
|
199
|
+
x.bytes(hex(e.spanId));
|
|
200
|
+
x.tag(5, LEN);
|
|
201
|
+
x.bytes(hex(e.traceId));
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function times(w, point) {
|
|
207
|
+
w.tag(2, FIXED64);
|
|
208
|
+
w.fixed64BigInt(hrTimeNanos(point.startTime));
|
|
209
|
+
w.tag(3, FIXED64);
|
|
210
|
+
w.fixed64BigInt(hrTimeNanos(point.endTime));
|
|
211
|
+
}
|
|
212
|
+
function numberPoint(w, point, valueType) {
|
|
213
|
+
times(w, point);
|
|
214
|
+
if (valueType === ValueType.INT) {
|
|
215
|
+
w.tag(6, FIXED64);
|
|
216
|
+
w.fixed64Number(point.value);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
w.tag(4, FIXED64);
|
|
220
|
+
w.double(point.value);
|
|
221
|
+
}
|
|
222
|
+
attributes(w, 7, point.attributes);
|
|
223
|
+
exemplars(w, 5, point, valueType);
|
|
224
|
+
}
|
|
225
|
+
function histogramPoint(w, point, valueType) {
|
|
226
|
+
const h = point.value;
|
|
227
|
+
times(w, point);
|
|
228
|
+
w.tag(4, FIXED64);
|
|
229
|
+
w.fixed64Number(h.count);
|
|
230
|
+
if (h.sum !== undefined) {
|
|
231
|
+
w.tag(5, FIXED64);
|
|
232
|
+
w.double(h.sum);
|
|
233
|
+
}
|
|
234
|
+
if (h.buckets.counts.length > 0) {
|
|
235
|
+
w.message(6, (p) => {
|
|
236
|
+
for (const c of h.buckets.counts)
|
|
237
|
+
p.fixed64Number(c);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
if (h.buckets.boundaries.length > 0) {
|
|
241
|
+
w.message(7, (p) => {
|
|
242
|
+
for (const b of h.buckets.boundaries)
|
|
243
|
+
p.double(b);
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
attributes(w, 9, point.attributes);
|
|
247
|
+
if (h.min !== undefined) {
|
|
248
|
+
w.tag(11, FIXED64);
|
|
249
|
+
w.double(h.min);
|
|
250
|
+
}
|
|
251
|
+
if (h.max !== undefined) {
|
|
252
|
+
w.tag(12, FIXED64);
|
|
253
|
+
w.double(h.max);
|
|
254
|
+
}
|
|
255
|
+
exemplars(w, 8, point, valueType);
|
|
256
|
+
}
|
|
257
|
+
function buckets(w, field, offset, counts) {
|
|
258
|
+
w.message(field, (b) => {
|
|
259
|
+
if (offset !== 0) {
|
|
260
|
+
b.tag(1, VARINT);
|
|
261
|
+
b.sint32(offset);
|
|
262
|
+
}
|
|
263
|
+
if (counts.length > 0) {
|
|
264
|
+
b.message(2, (p) => {
|
|
265
|
+
for (const c of counts)
|
|
266
|
+
p.varint(c);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
function exponentialPoint(w, point, valueType) {
|
|
272
|
+
const h = point.value;
|
|
273
|
+
attributes(w, 1, point.attributes);
|
|
274
|
+
times(w, point);
|
|
275
|
+
w.tag(4, FIXED64);
|
|
276
|
+
w.fixed64Number(h.count);
|
|
277
|
+
if (h.sum !== undefined) {
|
|
278
|
+
w.tag(5, FIXED64);
|
|
279
|
+
w.double(h.sum);
|
|
280
|
+
}
|
|
281
|
+
if (h.scale !== 0) {
|
|
282
|
+
w.tag(6, VARINT);
|
|
283
|
+
w.sint32(h.scale);
|
|
284
|
+
}
|
|
285
|
+
w.tag(7, FIXED64);
|
|
286
|
+
w.fixed64Number(h.zeroCount);
|
|
287
|
+
buckets(w, 8, h.positive.offset, h.positive.bucketCounts);
|
|
288
|
+
buckets(w, 9, h.negative.offset, h.negative.bucketCounts);
|
|
289
|
+
if (h.min !== undefined) {
|
|
290
|
+
w.tag(12, FIXED64);
|
|
291
|
+
w.double(h.min);
|
|
292
|
+
}
|
|
293
|
+
if (h.max !== undefined) {
|
|
294
|
+
w.tag(13, FIXED64);
|
|
295
|
+
w.double(h.max);
|
|
296
|
+
}
|
|
297
|
+
exemplars(w, 11, point, valueType);
|
|
298
|
+
}
|
|
299
|
+
function temporality(w, t) {
|
|
300
|
+
const value = t === AggregationTemporality.DELTA ? 1 : t === AggregationTemporality.CUMULATIVE ? 2 : 0;
|
|
301
|
+
if (value === 0)
|
|
302
|
+
return;
|
|
303
|
+
w.tag(2, VARINT);
|
|
304
|
+
w.varint(value);
|
|
305
|
+
}
|
|
306
|
+
function metric(w, m) {
|
|
307
|
+
const valueType = m.descriptor.valueType;
|
|
308
|
+
w.tag(1, LEN);
|
|
309
|
+
w.string(m.descriptor.name);
|
|
310
|
+
if (m.descriptor.description) {
|
|
311
|
+
w.tag(2, LEN);
|
|
312
|
+
w.string(m.descriptor.description);
|
|
313
|
+
}
|
|
314
|
+
if (m.descriptor.unit) {
|
|
315
|
+
w.tag(3, LEN);
|
|
316
|
+
w.string(m.descriptor.unit);
|
|
317
|
+
}
|
|
318
|
+
switch (m.dataPointType) {
|
|
319
|
+
case DataPointType.GAUGE:
|
|
320
|
+
w.message(5, (g) => {
|
|
321
|
+
for (const p of m.dataPoints)
|
|
322
|
+
g.message(1, (dp) => numberPoint(dp, p, valueType));
|
|
323
|
+
});
|
|
324
|
+
return;
|
|
325
|
+
case DataPointType.SUM:
|
|
326
|
+
w.message(7, (s) => {
|
|
327
|
+
for (const p of m.dataPoints)
|
|
328
|
+
s.message(1, (dp) => numberPoint(dp, p, valueType));
|
|
329
|
+
temporality(s, m.aggregationTemporality);
|
|
330
|
+
if (m.isMonotonic) {
|
|
331
|
+
s.tag(3, VARINT);
|
|
332
|
+
s.varint(1);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
return;
|
|
336
|
+
case DataPointType.HISTOGRAM:
|
|
337
|
+
w.message(9, (h) => {
|
|
338
|
+
for (const p of m.dataPoints)
|
|
339
|
+
h.message(1, (dp) => histogramPoint(dp, p, valueType));
|
|
340
|
+
temporality(h, m.aggregationTemporality);
|
|
341
|
+
});
|
|
342
|
+
return;
|
|
343
|
+
case DataPointType.EXPONENTIAL_HISTOGRAM:
|
|
344
|
+
w.message(10, (h) => {
|
|
345
|
+
for (const p of m.dataPoints)
|
|
346
|
+
h.message(1, (dp) => exponentialPoint(dp, p, valueType));
|
|
347
|
+
temporality(h, m.aggregationTemporality);
|
|
348
|
+
});
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
function scopeMetrics(w, sm) {
|
|
353
|
+
const scope = sm.scope;
|
|
354
|
+
w.message(1, (s) => {
|
|
355
|
+
s.tag(1, LEN);
|
|
356
|
+
s.string(scope.name);
|
|
357
|
+
if (scope.version) {
|
|
358
|
+
s.tag(2, LEN);
|
|
359
|
+
s.string(scope.version);
|
|
360
|
+
}
|
|
361
|
+
attributes(s, 3, scope.attributes);
|
|
362
|
+
if (scope.droppedAttributesCount) {
|
|
363
|
+
s.tag(4, VARINT);
|
|
364
|
+
s.varint(scope.droppedAttributesCount);
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
for (const m of sm.metrics)
|
|
368
|
+
w.message(2, (mw) => metric(mw, m));
|
|
369
|
+
if (scope.schemaUrl) {
|
|
370
|
+
w.tag(3, LEN);
|
|
371
|
+
w.string(scope.schemaUrl);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function resourceMetrics(w, rm) {
|
|
375
|
+
w.message(1, (r) => {
|
|
376
|
+
attributes(r, 1, rm.resource.attributes);
|
|
377
|
+
r.tag(2, VARINT);
|
|
378
|
+
r.varint(0);
|
|
379
|
+
});
|
|
380
|
+
for (const sm of rm.scopeMetrics)
|
|
381
|
+
w.message(2, (s) => scopeMetrics(s, sm));
|
|
382
|
+
if (rm.resource.schemaUrl) {
|
|
383
|
+
w.tag(3, LEN);
|
|
384
|
+
w.string(rm.resource.schemaUrl);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Encodes an ExportMetricsServiceRequest holding each collection in order, with the exemplars
|
|
389
|
+
* ExemplarStore.attach gave its data points.
|
|
390
|
+
*/
|
|
391
|
+
export function encodeMetricsRequest(collections) {
|
|
392
|
+
const w = new Writer();
|
|
393
|
+
for (const rm of collections)
|
|
394
|
+
w.message(1, (r) => resourceMetrics(r, rm));
|
|
395
|
+
return w.finish();
|
|
396
|
+
}
|
|
397
|
+
/** OTLP/protobuf metrics with exemplars, for upstream's OTLP HTTP export delegate. */
|
|
398
|
+
export const OtlpProtobufMetricsSerializer = {
|
|
399
|
+
serializeRequest: (rm) => encodeMetricsRequest([rm]),
|
|
400
|
+
deserializeResponse: (data) => ProtobufMetricsSerializer.deserializeResponse(data),
|
|
401
|
+
};
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server Platform: process.env, AsyncLocalStorage context, resource detection, exporters from
|
|
3
|
+
* OTEL_*, stdout and stderr lines, node:crypto hashing and UUIDs, runtime metrics, and the global
|
|
4
|
+
* console for console capture.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash, createHmac, randomUUID } from "node:crypto";
|
|
7
|
+
import { createContextManager } from "./context.js";
|
|
8
|
+
import { buildExporters } from "./exporters.js";
|
|
9
|
+
import { detectResource } from "./resource.js";
|
|
10
|
+
import { startRuntimeMetrics } from "./runtime-metrics.js";
|
|
11
|
+
/** A new server Platform for createTelemetryWith and setupWith. */
|
|
12
|
+
export function serverPlatform() {
|
|
13
|
+
return {
|
|
14
|
+
name: "server",
|
|
15
|
+
env: () => process.env,
|
|
16
|
+
detectResource,
|
|
17
|
+
contextManager: createContextManager,
|
|
18
|
+
buildExporters,
|
|
19
|
+
writeConsoleLine: (line) => {
|
|
20
|
+
process.stdout.write(`${line}\n`);
|
|
21
|
+
},
|
|
22
|
+
writeDiagnosticLine: (line) => {
|
|
23
|
+
process.stderr.write(`${line}\n`);
|
|
24
|
+
},
|
|
25
|
+
sha1: async (data) => new Uint8Array(createHash("sha1").update(data).digest()),
|
|
26
|
+
hmacSha256: (key, data) => new Uint8Array(createHmac("sha256", key).update(data).digest()),
|
|
27
|
+
randomUUID: () => randomUUID(),
|
|
28
|
+
startRuntimeMetrics: (meterProvider) => startRuntimeMetrics(meterProvider),
|
|
29
|
+
console: globalThis.console,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type CompiledAppRegistry } from "@libo11y/spec";
|
|
2
|
+
/**
|
|
3
|
+
* Reads, parses and validates the registry file at path and compiles it, with path as its source.
|
|
4
|
+
* Rejects with O11yError INVALID_APP_REGISTRY: "o11y: reading application registry: ..." when the
|
|
5
|
+
* file cannot be read, "o11y: <path>: ..." when it does not parse, and
|
|
6
|
+
* "o11y: invalid application registry: <path>: <violation>; ..." when it breaks a rule.
|
|
7
|
+
*/
|
|
8
|
+
export declare function loadAppRegistry(path: string): Promise<CompiledAppRegistry>;
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loading an application registry file: read, parse, validate and compile, failing with Go's
|
|
3
|
+
* messages (WithAppRegistry, appregistry.go loadAppRegistries) under the code INVALID_APP_REGISTRY.
|
|
4
|
+
*/
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { O11yError } from "@libo11y/core";
|
|
7
|
+
import { compileAppRegistry, validateAppRegistry } from "@libo11y/spec";
|
|
8
|
+
import { AppRegistryParseError, parseAppRegistryBytes } from "@libo11y/spec/yaml";
|
|
9
|
+
// GO_READ_ERRORS maps a Node file system error code to the operation and reason Go's os.ReadFile
|
|
10
|
+
// reports, as the libo11y CLI does.
|
|
11
|
+
const GO_READ_ERRORS = {
|
|
12
|
+
ENOENT: ["open", "no such file or directory"],
|
|
13
|
+
EACCES: ["open", "permission denied"],
|
|
14
|
+
EPERM: ["open", "operation not permitted"],
|
|
15
|
+
EISDIR: ["read", "is a directory"],
|
|
16
|
+
};
|
|
17
|
+
function message(err) {
|
|
18
|
+
return err instanceof Error ? err.message : String(err);
|
|
19
|
+
}
|
|
20
|
+
function readError(path, err) {
|
|
21
|
+
const code = typeof err === "object" && err !== null && "code" in err ? String(err.code) : "";
|
|
22
|
+
const known = GO_READ_ERRORS[code];
|
|
23
|
+
return known === undefined ? `open ${path}: ${message(err)}` : `${known[0]} ${path}: ${known[1]}`;
|
|
24
|
+
}
|
|
25
|
+
// parseMessage is Go's Parse error for the two failures whose wording Go fixes, and the parse
|
|
26
|
+
// class with its detail for the others, whose wording is yaml.v3's in Go.
|
|
27
|
+
function parseMessage(err) {
|
|
28
|
+
if (err instanceof AppRegistryParseError) {
|
|
29
|
+
if (err.kind === "empty")
|
|
30
|
+
return "application registry is empty";
|
|
31
|
+
if (err.kind === "second-document") {
|
|
32
|
+
return "parsing application registry: an application registry holds one YAML document, found a second";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return message(err);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Reads, parses and validates the registry file at path and compiles it, with path as its source.
|
|
39
|
+
* Rejects with O11yError INVALID_APP_REGISTRY: "o11y: reading application registry: ..." when the
|
|
40
|
+
* file cannot be read, "o11y: <path>: ..." when it does not parse, and
|
|
41
|
+
* "o11y: invalid application registry: <path>: <violation>; ..." when it breaks a rule.
|
|
42
|
+
*/
|
|
43
|
+
export async function loadAppRegistry(path) {
|
|
44
|
+
let bytes;
|
|
45
|
+
try {
|
|
46
|
+
bytes = await readFile(path);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
throw new O11yError("INVALID_APP_REGISTRY", `o11y: reading application registry: ${readError(path, err)}`, {
|
|
50
|
+
cause: err,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = parseAppRegistryBytes(bytes);
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
throw new O11yError("INVALID_APP_REGISTRY", `o11y: ${path}: ${parseMessage(err)}`, { cause: err });
|
|
59
|
+
}
|
|
60
|
+
const result = validateAppRegistry(parsed);
|
|
61
|
+
if (!result.ok) {
|
|
62
|
+
const violations = result.violations.map((v) => v.toString()).join("; ");
|
|
63
|
+
throw new O11yError("INVALID_APP_REGISTRY", `o11y: invalid application registry: ${path}: ${violations}`);
|
|
64
|
+
}
|
|
65
|
+
return { ...compileAppRegistry(result.registry), source: path };
|
|
66
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ResourceLayers } from "@libo11y/core";
|
|
2
|
+
import { type ResourceDetector } from "@opentelemetry/resources";
|
|
3
|
+
/** The detectors detectResourceWith takes, so tests can replace the container lookup. */
|
|
4
|
+
export interface ResourceDetectors {
|
|
5
|
+
readonly container: ResourceDetector;
|
|
6
|
+
}
|
|
7
|
+
/** detectResource with the given detectors. */
|
|
8
|
+
export declare function detectResourceWith(hermetic: boolean, detectors: ResourceDetectors): Promise<ResourceLayers>;
|
|
9
|
+
/**
|
|
10
|
+
* Detects the server resource layers. fromEnv is empty when hermetic is true, and the container
|
|
11
|
+
* lookup is awaited, so every value is final.
|
|
12
|
+
*/
|
|
13
|
+
export declare function detectResource(hermetic: boolean): Promise<ResourceLayers>;
|
package/dist/resource.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server resource detection, in the two layers core merges. The detected layer holds what Go
|
|
3
|
+
* records: the upstream telemetry.sdk.* attributes, the runtime (Bun reports itself as bun, which
|
|
4
|
+
* upstream's processDetector would call nodejs), host.name and container.id. It never holds the
|
|
5
|
+
* process command, command line, pid or host.id. The environment layer comes from upstream's
|
|
6
|
+
* OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME detectors, so OTEL_SERVICE_NAME wins.
|
|
7
|
+
*/
|
|
8
|
+
import { hostname } from "node:os";
|
|
9
|
+
import { SDK_INFO } from "@opentelemetry/core";
|
|
10
|
+
import { containerDetector } from "@opentelemetry/resource-detector-container";
|
|
11
|
+
import { resourceAttributesEnvDetector, serviceNameEnvDetector, } from "@opentelemetry/resources";
|
|
12
|
+
function runtimeAttributes() {
|
|
13
|
+
const bun = globalThis.Bun;
|
|
14
|
+
if (bun !== undefined) {
|
|
15
|
+
return {
|
|
16
|
+
"process.runtime.name": "bun",
|
|
17
|
+
"process.runtime.version": bun.version,
|
|
18
|
+
"process.runtime.description": "Bun",
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
"process.runtime.name": "nodejs",
|
|
23
|
+
"process.runtime.version": process.versions.node,
|
|
24
|
+
"process.runtime.description": "Node.js",
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
// settle awaits every attribute a detector returned, dropping undefined, empty strings and values
|
|
28
|
+
// whose promise rejected, as upstream's resource merge drops a failed asynchronous attribute.
|
|
29
|
+
async function settle(detector) {
|
|
30
|
+
const attrs = detector.detect().attributes ?? {};
|
|
31
|
+
const out = {};
|
|
32
|
+
await Promise.all(Object.entries(attrs).map(async ([key, value]) => {
|
|
33
|
+
try {
|
|
34
|
+
const v = (await value);
|
|
35
|
+
if (v !== undefined && v !== "")
|
|
36
|
+
out[key] = v;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// A detector that cannot read its source contributes nothing.
|
|
40
|
+
}
|
|
41
|
+
}));
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
/** detectResource with the given detectors. */
|
|
45
|
+
export async function detectResourceWith(hermetic, detectors) {
|
|
46
|
+
const sdk = Object.fromEntries(Object.entries(SDK_INFO).filter(([k]) => k.startsWith("telemetry.sdk.")));
|
|
47
|
+
const detected = {
|
|
48
|
+
...sdk,
|
|
49
|
+
...runtimeAttributes(),
|
|
50
|
+
"host.name": hostname(),
|
|
51
|
+
...(await settle(detectors.container)),
|
|
52
|
+
};
|
|
53
|
+
if (hermetic)
|
|
54
|
+
return { detected, fromEnv: {} };
|
|
55
|
+
const fromEnv = {
|
|
56
|
+
...(await settle(resourceAttributesEnvDetector)),
|
|
57
|
+
...(await settle(serviceNameEnvDetector)),
|
|
58
|
+
};
|
|
59
|
+
return { detected, fromEnv };
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Detects the server resource layers. fromEnv is empty when hermetic is true, and the container
|
|
63
|
+
* lookup is awaited, so every value is final.
|
|
64
|
+
*/
|
|
65
|
+
export function detectResource(hermetic) {
|
|
66
|
+
return detectResourceWith(hermetic, { container: containerDetector });
|
|
67
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime metrics through upstream's RuntimeNodeInstrumentation, on the meter provider core hands
|
|
3
|
+
* over rather than the global one. Bun always reports zero event loop utilization
|
|
4
|
+
* (oven-sh/bun#34068), so on Bun the instrumentation sees a meter provider whose
|
|
5
|
+
* nodejs.eventloop.utilization instrument is a no-op. Bun also has no
|
|
6
|
+
* v8.getHeapSpaceStatistics, so the v8js.memory.heap.* instruments report nothing there.
|
|
7
|
+
*/
|
|
8
|
+
import type { RuntimeMetrics } from "@libo11y/core";
|
|
9
|
+
import { type MeterProvider } from "@opentelemetry/api";
|
|
10
|
+
/** The instrument Bun cannot report. */
|
|
11
|
+
export declare const EVENT_LOOP_UTILIZATION = "nodejs.eventloop.utilization";
|
|
12
|
+
/** A meter provider whose meters turn the instruments named in dropped into no-ops. */
|
|
13
|
+
export declare function withoutInstruments(provider: MeterProvider, dropped: readonly string[]): MeterProvider;
|
|
14
|
+
/** Options for startRuntimeMetrics. */
|
|
15
|
+
export interface RuntimeMetricsOptions {
|
|
16
|
+
/** Make nodejs.eventloop.utilization a no-op. Default: true on Bun, false on Node. */
|
|
17
|
+
readonly dropEventLoopUtilization?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Starts upstream's runtime instrumentation on meterProvider. It is built disabled, so nothing
|
|
21
|
+
* registers on the global meter provider, then pointed at meterProvider and enabled. stop disables it.
|
|
22
|
+
*/
|
|
23
|
+
export declare function startRuntimeMetrics(meterProvider: MeterProvider, options?: RuntimeMetricsOptions): RuntimeMetrics;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createNoopMeter, } from "@opentelemetry/api";
|
|
2
|
+
import { RuntimeNodeInstrumentation } from "@opentelemetry/instrumentation-runtime-node";
|
|
3
|
+
/** The instrument Bun cannot report. */
|
|
4
|
+
export const EVENT_LOOP_UTILIZATION = "nodejs.eventloop.utilization";
|
|
5
|
+
const NOOP = createNoopMeter();
|
|
6
|
+
/** A meter whose instruments named in dropped are no-ops. */
|
|
7
|
+
class FilteredMeter {
|
|
8
|
+
inner;
|
|
9
|
+
dropped;
|
|
10
|
+
constructor(inner, dropped) {
|
|
11
|
+
this.inner = inner;
|
|
12
|
+
this.dropped = dropped;
|
|
13
|
+
}
|
|
14
|
+
pick(name) {
|
|
15
|
+
return this.dropped.has(name) ? NOOP : this.inner;
|
|
16
|
+
}
|
|
17
|
+
createGauge(name, options) {
|
|
18
|
+
return this.pick(name).createGauge(name, options);
|
|
19
|
+
}
|
|
20
|
+
createHistogram(name, options) {
|
|
21
|
+
return this.pick(name).createHistogram(name, options);
|
|
22
|
+
}
|
|
23
|
+
createCounter(name, options) {
|
|
24
|
+
return this.pick(name).createCounter(name, options);
|
|
25
|
+
}
|
|
26
|
+
createUpDownCounter(name, options) {
|
|
27
|
+
return this.pick(name).createUpDownCounter(name, options);
|
|
28
|
+
}
|
|
29
|
+
createObservableGauge(name, options) {
|
|
30
|
+
return this.pick(name).createObservableGauge(name, options);
|
|
31
|
+
}
|
|
32
|
+
createObservableCounter(name, options) {
|
|
33
|
+
return this.pick(name).createObservableCounter(name, options);
|
|
34
|
+
}
|
|
35
|
+
createObservableUpDownCounter(name, options) {
|
|
36
|
+
return this.pick(name).createObservableUpDownCounter(name, options);
|
|
37
|
+
}
|
|
38
|
+
addBatchObservableCallback(callback, observables) {
|
|
39
|
+
this.inner.addBatchObservableCallback(callback, observables);
|
|
40
|
+
}
|
|
41
|
+
removeBatchObservableCallback(callback, observables) {
|
|
42
|
+
this.inner.removeBatchObservableCallback(callback, observables);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** A meter provider whose meters turn the instruments named in dropped into no-ops. */
|
|
46
|
+
export function withoutInstruments(provider, dropped) {
|
|
47
|
+
const names = new Set(dropped);
|
|
48
|
+
return {
|
|
49
|
+
getMeter: (name, version, options) => new FilteredMeter(provider.getMeter(name, version, options), names),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Starts upstream's runtime instrumentation on meterProvider. It is built disabled, so nothing
|
|
54
|
+
* registers on the global meter provider, then pointed at meterProvider and enabled. stop disables it.
|
|
55
|
+
*/
|
|
56
|
+
export function startRuntimeMetrics(meterProvider, options = {}) {
|
|
57
|
+
const drop = options.dropEventLoopUtilization ?? "Bun" in globalThis;
|
|
58
|
+
const instrumentation = new RuntimeNodeInstrumentation({ enabled: false });
|
|
59
|
+
instrumentation.setMeterProvider(drop ? withoutInstruments(meterProvider, [EVENT_LOOP_UTILIZATION]) : meterProvider);
|
|
60
|
+
instrumentation.enable();
|
|
61
|
+
return { stop: () => instrumentation.disable() };
|
|
62
|
+
}
|