brass-runtime 1.15.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +409 -137
  2. package/dist/agent/cli/main.cjs +40 -35
  3. package/dist/agent/cli/main.js +9 -4
  4. package/dist/agent/cli/main.mjs +9 -4
  5. package/dist/agent/index.cjs +8 -4
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +7 -3
  8. package/dist/agent/index.mjs +7 -3
  9. package/dist/{chunk-PPUXIH5R.js → chunk-2WC63LJK.mjs} +11 -7
  10. package/dist/chunk-3RG5ZIWI.js +10 -0
  11. package/dist/chunk-45F7OKGT.cjs +104 -0
  12. package/dist/chunk-5YOQOXEQ.cjs +2491 -0
  13. package/dist/{chunk-STVLQ3XD.cjs → chunk-7HUOJA4W.cjs} +78 -74
  14. package/dist/{chunk-BMH5AV44.js → chunk-7LVI2GIN.js} +251 -370
  15. package/dist/chunk-7TL2LHQJ.js +2491 -0
  16. package/dist/chunk-7V4KY4RL.mjs +104 -0
  17. package/dist/chunk-7XOPAB5Q.js +2143 -0
  18. package/dist/chunk-CCKHV5BT.mjs +193 -0
  19. package/dist/{chunk-AR22SXML.js → chunk-CY33PGEX.mjs} +488 -421
  20. package/dist/chunk-DJQ7OMMB.cjs +144 -0
  21. package/dist/chunk-F5EUMJL7.mjs +2143 -0
  22. package/dist/chunk-FM4W4QPL.js +193 -0
  23. package/dist/{chunk-TO7IKXYT.js → chunk-G3XGCZDQ.js} +1 -1
  24. package/dist/{chunk-BDF4AMWX.mjs → chunk-G6IQOE4P.mjs} +251 -370
  25. package/dist/chunk-GOV47PPB.mjs +552 -0
  26. package/dist/chunk-H55LI6WY.js +93 -0
  27. package/dist/chunk-IJT6RRQ5.cjs +93 -0
  28. package/dist/{chunk-ELOOF35R.mjs → chunk-J3H54ZRV.mjs} +1 -1
  29. package/dist/chunk-JF4XXPZ5.cjs +552 -0
  30. package/dist/chunk-JNFRRJYH.cjs +2143 -0
  31. package/dist/chunk-JX3LZQJH.cjs +354 -0
  32. package/dist/chunk-K2T3DV26.mjs +93 -0
  33. package/dist/chunk-KCPT2D6G.js +552 -0
  34. package/dist/chunk-MWXMNYJS.cjs +1110 -0
  35. package/dist/{chunk-VEZNF5GZ.cjs → chunk-N6VHMOWB.cjs} +130 -126
  36. package/dist/{chunk-3QMOKAS5.js → chunk-NC5SDRYE.js} +9 -5
  37. package/dist/chunk-NOYZIMUJ.mjs +144 -0
  38. package/dist/{chunk-R3R2FVLG.cjs → chunk-NYL4D7SK.cjs} +5 -5
  39. package/dist/chunk-OBGZSXTJ.cjs +10 -0
  40. package/dist/{chunk-4NHES7VK.mjs → chunk-OOGJ73B6.js} +11 -7
  41. package/dist/chunk-PNVFW245.js +144 -0
  42. package/dist/chunk-PRWCB3QL.mjs +2491 -0
  43. package/dist/{chunk-JFPU5GQI.mjs → chunk-QY5FKYEQ.js} +488 -421
  44. package/dist/chunk-ROJC3NBJ.js +104 -0
  45. package/dist/chunk-SPUEME2B.cjs +343 -0
  46. package/dist/chunk-TDVMADDN.js +343 -0
  47. package/dist/chunk-TVN5I4U6.cjs +193 -0
  48. package/dist/chunk-U5KWK3PX.mjs +343 -0
  49. package/dist/chunk-VFIUZG7J.mjs +354 -0
  50. package/dist/{chunk-TGIFUAK4.cjs → chunk-WQ5QNU5R.cjs} +459 -578
  51. package/dist/chunk-XDZOO4L5.js +354 -0
  52. package/dist/chunk-Y6FXYEAI.mjs +10 -0
  53. package/dist/{chunk-K6M7MDZ4.mjs → chunk-ZGLD4TVZ.mjs} +9 -5
  54. package/dist/client-CtFmoDvM.d.ts +645 -0
  55. package/dist/core/index.cjs +72 -4
  56. package/dist/core/index.d.ts +92 -198
  57. package/dist/core/index.js +106 -38
  58. package/dist/core/index.mjs +106 -38
  59. package/dist/{effect-CMOQKX8y.d.ts → effect-CGNl5Rqp.d.ts} +107 -1
  60. package/dist/effectRunner-3ZHAD3LE.cjs +8 -0
  61. package/dist/effectRunner-A4CHJXJI.js +8 -0
  62. package/dist/effectRunner-OPUF6QRN.mjs +8 -0
  63. package/dist/http/index.cjs +2189 -1271
  64. package/dist/http/index.d.ts +830 -270
  65. package/dist/http/index.js +2008 -1090
  66. package/dist/http/index.mjs +2008 -1090
  67. package/dist/http/testing.cjs +159 -0
  68. package/dist/http/testing.d.ts +42 -0
  69. package/dist/http/testing.js +159 -0
  70. package/dist/http/testing.mjs +159 -0
  71. package/dist/index.cjs +246 -178
  72. package/dist/index.d.ts +9 -35
  73. package/dist/index.js +120 -52
  74. package/dist/index.mjs +120 -52
  75. package/dist/observability/index.cjs +677 -0
  76. package/dist/observability/index.d.ts +79 -0
  77. package/dist/observability/index.js +677 -0
  78. package/dist/observability/index.mjs +677 -0
  79. package/dist/schedule-Fque9Abz.d.ts +70 -0
  80. package/dist/schema/index.cjs +25 -0
  81. package/dist/schema/index.d.ts +177 -0
  82. package/dist/schema/index.js +25 -0
  83. package/dist/schema/index.mjs +25 -0
  84. package/dist/server-C8hDXA74.d.ts +674 -0
  85. package/dist/{stream-FQm9h4Mg.d.ts → stream-dvSs0QS5.d.ts} +1 -1
  86. package/dist/tracer-B5tRH9H7.d.ts +230 -0
  87. package/dist/tracing-Dt9S_6V8.d.ts +148 -0
  88. package/package.json +27 -1
  89. package/dist/chunk-BDYEENHT.js +0 -224
  90. package/dist/chunk-MS34J5LY.cjs +0 -224
  91. package/dist/chunk-UMAZLXAB.mjs +0 -224
  92. package/dist/chunk-XPZNXSVN.cjs +0 -1043
  93. package/dist/tracing-DNT9jEbr.d.ts +0 -106
@@ -0,0 +1,677 @@
1
+ import {
2
+ OTLP_JSON_CONTENT_TYPE,
3
+ PROMETHEUS_CONTENT_TYPE,
4
+ alwaysOffSampler,
5
+ alwaysOnSampler,
6
+ currentBaggage,
7
+ currentSpanLink,
8
+ defaultStructuredLogWriter,
9
+ exemplarFromTraceContext,
10
+ exportWithRetry,
11
+ extractBaggage,
12
+ extractTraceContext,
13
+ formatBaggage,
14
+ formatPrometheusMetrics,
15
+ formatStructuredLog,
16
+ formatTraceparent,
17
+ healthToHttpResponse,
18
+ injectBaggage,
19
+ injectTraceContext,
20
+ logEffect,
21
+ makeCardinalityLimitedMetrics,
22
+ makeExportPipeline,
23
+ makeObservability,
24
+ makeObservabilityRedactor,
25
+ makeOtlpHttpLogExporter,
26
+ makeOtlpHttpMetricsExporter,
27
+ makeOtlpHttpSpanExporter,
28
+ makePrometheusMetricsExporter,
29
+ makeRequestObservabilityContext,
30
+ makeRuntimeHealth,
31
+ makeRuntimeMetricsSink,
32
+ makeStructuredLogSink,
33
+ makeTraceSampler,
34
+ metricsSnapshotToOtlp,
35
+ normalizeHttpRoute,
36
+ normalizeSpanId,
37
+ normalizeTraceId,
38
+ observeHttpServerRequest,
39
+ otlpAnyValue,
40
+ parseBaggage,
41
+ parseTraceparent,
42
+ postOtlpJson,
43
+ ratioSampler,
44
+ readiness,
45
+ resolveRequestBaggage,
46
+ resolveRequestTraceSeed,
47
+ resolveTraceSampling,
48
+ runObservedHttpServerEffect,
49
+ runtimeHealth,
50
+ sanitizeHttpTarget,
51
+ shouldSampleWith,
52
+ snapshotRuntimeHealth,
53
+ spanEvent,
54
+ spanLink,
55
+ spansToOtlp,
56
+ structuredLogsToOtlp,
57
+ toOtlpAttributes,
58
+ unixNanoFromMs,
59
+ withBaggage,
60
+ withLogContext,
61
+ withSpan,
62
+ withTimeout
63
+ } from "../chunk-7XOPAB5Q.js";
64
+ import "../chunk-XDZOO4L5.js";
65
+ import {
66
+ getCurrentFiber
67
+ } from "../chunk-7LVI2GIN.js";
68
+ import {
69
+ asyncFail,
70
+ asyncFlatMap,
71
+ asyncFold,
72
+ asyncSucceed,
73
+ asyncSync
74
+ } from "../chunk-PNVFW245.js";
75
+ import "../chunk-TDVMADDN.js";
76
+ import "../chunk-3RG5ZIWI.js";
77
+
78
+ // src/observability/http.ts
79
+ var DEFAULT_DURATION_BUCKETS = [1, 5, 10, 25, 50, 100, 250, 500, 1e3, 2500, 5e3, 1e4];
80
+ function withHttpObservability(options) {
81
+ const resolved = resolveHttpObservabilityOptions(options);
82
+ return (next) => {
83
+ return (req) => {
84
+ const run = asyncFlatMap(
85
+ beginHttpObservation(req, resolved),
86
+ (state) => asyncFlatMap(
87
+ logHttpRequest(req, resolved),
88
+ () => asyncFlatMap(
89
+ prepareHttpRequest(req, resolved),
90
+ (wireReq) => asyncFold(
91
+ next(wireReq),
92
+ (error) => {
93
+ const finish = state.finishWithError(error);
94
+ const adaptiveLimiterAttrs = observeAdaptiveLimiter(wireReq, next, resolved);
95
+ return asyncFlatMap(
96
+ spanEvent("http.client.error", {
97
+ ...finish.spanAttributes,
98
+ ...adaptiveLimiterAttrs,
99
+ "error.type": error._tag
100
+ }),
101
+ () => asyncFlatMap(logHttpError(req, error, finish, resolved), () => asyncFail(error))
102
+ );
103
+ },
104
+ (res) => {
105
+ const finish = state.finishWithResponse(res);
106
+ const adaptiveLimiterAttrs = observeAdaptiveLimiter(wireReq, next, resolved);
107
+ return asyncFlatMap(
108
+ spanEvent("http.client.response", {
109
+ ...finish.spanAttributes,
110
+ ...adaptiveLimiterAttrs
111
+ }),
112
+ () => asyncFlatMap(logHttpResponse(req, res, finish, resolved), () => asyncSucceed(res))
113
+ );
114
+ }
115
+ )
116
+ )
117
+ )
118
+ );
119
+ if (resolved.spans === false) return run;
120
+ return withSpan(spanName(req, resolved.spans), run, spanStartAttributes(req, resolved));
121
+ };
122
+ };
123
+ }
124
+ var makeHttpObservabilityMiddleware = withHttpObservability;
125
+ function beginHttpObservation(req, options) {
126
+ return asyncSync(() => {
127
+ const startedAt = options.clock();
128
+ let finished = false;
129
+ const inFlight = options.metrics?.gauge("brass_http_client_in_flight", requestBaseLabels(req, options));
130
+ inFlight?.increment();
131
+ const finish = (outcome, status, extra = {}) => {
132
+ const durationMs = Math.max(0, options.clock() - startedAt);
133
+ const labels = requestFinishLabels(req, outcome, status, options);
134
+ if (!finished) {
135
+ finished = true;
136
+ if (inFlight && inFlight.value() > 0) inFlight.decrement();
137
+ options.metrics?.counter("brass_http_client_requests_total", labels).increment();
138
+ options.metrics?.histogram("brass_http_client_duration_ms", [...options.durationBuckets ?? DEFAULT_DURATION_BUCKETS], labels).observe(durationMs, currentTraceExemplar(durationMs, startedAt + durationMs));
139
+ }
140
+ return {
141
+ durationMs,
142
+ outcome,
143
+ labels,
144
+ spanAttributes: {
145
+ "http.duration_ms": durationMs,
146
+ "http.outcome": outcome,
147
+ ...status ? { "http.status_code": Number(status) } : {},
148
+ ...status ? { "http.response.status_code": Number(status) } : {},
149
+ ...extra
150
+ }
151
+ };
152
+ };
153
+ const fiber = getCurrentFiber();
154
+ fiber?.addFinalizer?.(() => {
155
+ finish("abort", void 0, { "http.cancelled": true });
156
+ });
157
+ return {
158
+ finishWithResponse: (res) => finish(httpStatusOutcome(res.status), String(res.status)),
159
+ finishWithError: (error) => finish(httpErrorOutcome(error), void 0, { "error.type": error._tag })
160
+ };
161
+ });
162
+ }
163
+ function prepareHttpRequest(req, options) {
164
+ if (!options.injectTraceHeaders) return asyncSucceed(req);
165
+ return asyncSync(() => injectCurrentTraceContext(req));
166
+ }
167
+ function logHttpRequest(req, options) {
168
+ const level = options.logs === false ? false : options.logs.requestLevel ?? false;
169
+ if (!level) return asyncSucceed(void 0);
170
+ return logEffect(level, "http.client.request", requestLogFields(req, options));
171
+ }
172
+ function logHttpResponse(req, res, finish, options) {
173
+ const configured = options.logs === false ? false : options.logs.responseLevel ?? false;
174
+ const level = configured || (finish.outcome === "error" ? options.logs !== false ? options.logs.errorLevel ?? "warn" : false : false);
175
+ if (!level) return asyncSucceed(void 0);
176
+ return logEffect(level, "http.client.response", {
177
+ ...requestLogFields(req, options),
178
+ status: res.status,
179
+ statusText: res.statusText,
180
+ outcome: finish.outcome,
181
+ durationMs: finish.durationMs
182
+ });
183
+ }
184
+ function logHttpError(req, error, finish, options) {
185
+ const level = options.logs === false ? false : options.logs.errorLevel ?? "error";
186
+ if (!level) return asyncSucceed(void 0);
187
+ return logEffect(level, "http.client.error", {
188
+ ...requestLogFields(req, options),
189
+ outcome: finish.outcome,
190
+ durationMs: finish.durationMs,
191
+ errorTag: error._tag,
192
+ message: httpErrorMessage(error)
193
+ });
194
+ }
195
+ function resolveHttpObservabilityOptions(options) {
196
+ const maybeObservability = options && "eventBus" in options && "prometheus" in options ? options : void 0;
197
+ const raw = maybeObservability ? { metrics: maybeObservability.metrics } : options;
198
+ return {
199
+ metrics: raw?.metrics === false ? void 0 : raw?.metrics,
200
+ logs: raw?.logs ?? {},
201
+ spans: raw?.spans ?? {},
202
+ adaptiveLimiter: resolveAdaptiveLimiterObservabilityOptions(raw?.adaptiveLimiter),
203
+ injectTraceHeaders: raw?.injectTraceHeaders ?? true,
204
+ includeHostLabel: raw?.includeHostLabel ?? true,
205
+ route: raw?.route,
206
+ clock: raw?.clock ?? Date.now,
207
+ durationBuckets: raw?.durationBuckets
208
+ };
209
+ }
210
+ function resolveAdaptiveLimiterObservabilityOptions(options) {
211
+ if (options === false) return { enabled: false, includeKeyLabel: false };
212
+ if (options === true || options === void 0) return { enabled: true, includeKeyLabel: false };
213
+ return {
214
+ enabled: options.enabled ?? true,
215
+ includeKeyLabel: options.includeKeyLabel ?? false
216
+ };
217
+ }
218
+ function observeAdaptiveLimiter(req, next, options) {
219
+ if (!options.adaptiveLimiter.enabled) return {};
220
+ const limiter = adaptiveLimiterOf(next);
221
+ if (!limiter || !options.metrics && options.spans === false) return {};
222
+ const stats = limiter.stats();
223
+ const labels = adaptiveLimiterLabels(req, stats, options);
224
+ setGauge(options.metrics, "brass_http_adaptive_limiter_limit", stats.limit, labels);
225
+ setGauge(options.metrics, "brass_http_adaptive_limiter_in_flight", stats.inFlight, labels);
226
+ setGauge(options.metrics, "brass_http_adaptive_limiter_queue_depth", stats.queueDepth, labels);
227
+ setGauge(options.metrics, "brass_http_adaptive_limiter_state_count", stats.stateCount, labels);
228
+ setGauge(options.metrics, "brass_http_adaptive_limiter_utilization", stats.utilization, labels);
229
+ setGauge(options.metrics, "brass_http_adaptive_limiter_error_rate", stats.errorRate, labels);
230
+ setGauge(options.metrics, "brass_http_adaptive_limiter_requests_per_second", stats.requestsPerSecond, labels);
231
+ setGauge(options.metrics, "brass_http_adaptive_limiter_completions_per_second", stats.completionsPerSecond, labels);
232
+ setGauge(options.metrics, "brass_http_adaptive_limiter_rejection_rate", stats.rejectionRate, labels);
233
+ return compactSpanAttributes({
234
+ "http.adaptive_limiter.limit": stats.limit,
235
+ "http.adaptive_limiter.in_flight": stats.inFlight,
236
+ "http.adaptive_limiter.queue_depth": stats.queueDepth,
237
+ "http.adaptive_limiter.state_count": stats.stateCount,
238
+ "http.adaptive_limiter.utilization": stats.utilization,
239
+ "http.adaptive_limiter.error_rate": stats.errorRate,
240
+ "http.adaptive_limiter.requests_per_second": stats.requestsPerSecond,
241
+ "http.adaptive_limiter.completions_per_second": stats.completionsPerSecond,
242
+ "http.adaptive_limiter.rejection_rate": stats.rejectionRate
243
+ });
244
+ }
245
+ function adaptiveLimiterOf(next) {
246
+ const limiter = next.adaptiveLimiter;
247
+ return limiter && typeof limiter.stats === "function" ? limiter : void 0;
248
+ }
249
+ function adaptiveLimiterLabels(req, stats, options) {
250
+ const key = options.adaptiveLimiter.includeKeyLabel ? inferAdaptiveLimiterKey(req, stats) : void 0;
251
+ return compactLabels({
252
+ ...requestBaseLabels(req, options),
253
+ key
254
+ });
255
+ }
256
+ function inferAdaptiveLimiterKey(req, stats) {
257
+ if (req.poolKey) return req.poolKey;
258
+ const host = requestHost(req);
259
+ if (host) return host;
260
+ return stats.keys?.length === 1 ? stats.keys[0] : void 0;
261
+ }
262
+ function setGauge(metrics, name, value, labels) {
263
+ if (!metrics || value === void 0 || !Number.isFinite(value)) return;
264
+ metrics.gauge(name, labels).set(value);
265
+ }
266
+ function compactSpanAttributes(attrs) {
267
+ const out = {};
268
+ for (const [key, value] of Object.entries(attrs)) {
269
+ if (value !== void 0 && Number.isFinite(value)) out[key] = value;
270
+ }
271
+ return out;
272
+ }
273
+ function spanName(req, options) {
274
+ if (options && options.name) {
275
+ return typeof options.name === "function" ? options.name(req) : options.name;
276
+ }
277
+ return `HTTP ${req.method}`;
278
+ }
279
+ function spanStartAttributes(req, options) {
280
+ const spanOptions = options.spans === false ? {} : options.spans.attributes;
281
+ const custom = typeof spanOptions === "function" ? spanOptions(req) : spanOptions ?? {};
282
+ const host = requestHost(req);
283
+ const route = requestRoute(req, options);
284
+ return {
285
+ "span.kind": "client",
286
+ "http.method": req.method,
287
+ "http.request.method": req.method,
288
+ "http.url": sanitizeUrl(req.url),
289
+ "url.full": sanitizeUrl(req.url),
290
+ ...urlScheme(req.url) ? { "url.scheme": urlScheme(req.url) } : {},
291
+ ...urlPath(req.url) ? { "url.path": urlPath(req.url) } : {},
292
+ ...host ? { "server.address": host } : {},
293
+ ...route ? { "http.route": route } : {},
294
+ ...custom
295
+ };
296
+ }
297
+ function requestBaseLabels(req, options) {
298
+ return compactLabels({
299
+ method: req.method,
300
+ ...options.includeHostLabel ? { host: requestHost(req) } : {},
301
+ ...requestRoute(req, options) ? { route: requestRoute(req, options) } : {}
302
+ });
303
+ }
304
+ function requestFinishLabels(req, outcome, status, options) {
305
+ return {
306
+ ...requestBaseLabels(req, options),
307
+ outcome,
308
+ status: status ?? "none"
309
+ };
310
+ }
311
+ function requestLogFields(req, options) {
312
+ const host = requestHost(req);
313
+ const route = requestRoute(req, options);
314
+ return {
315
+ method: req.method,
316
+ url: sanitizeUrl(req.url),
317
+ ...host ? { host } : {},
318
+ ...route ? { route } : {}
319
+ };
320
+ }
321
+ function requestRoute(req, options) {
322
+ if (typeof options.route === "function") return options.route(req);
323
+ return options.route;
324
+ }
325
+ function httpStatusOutcome(status) {
326
+ return status >= 400 ? "error" : "success";
327
+ }
328
+ function httpErrorOutcome(error) {
329
+ switch (error._tag) {
330
+ case "Abort":
331
+ return "abort";
332
+ case "BadUrl":
333
+ return "bad_url";
334
+ case "FetchError":
335
+ return "fetch_error";
336
+ case "Timeout":
337
+ return "timeout";
338
+ case "PoolRejected":
339
+ return "pool_rejected";
340
+ case "PoolTimeout":
341
+ return "pool_timeout";
342
+ case "PoolClosed":
343
+ return "pool_closed";
344
+ case "BatchSplitError":
345
+ return "batch_split_error";
346
+ }
347
+ }
348
+ function httpErrorMessage(error) {
349
+ return "message" in error ? error.message : void 0;
350
+ }
351
+ function injectCurrentTraceContext(req) {
352
+ const fiber = getCurrentFiber();
353
+ const trace = fiber?.fiberContext?.trace;
354
+ if (!trace?.traceId || !trace?.spanId) return req;
355
+ return {
356
+ ...req,
357
+ headers: injectTraceContext(req.headers, trace)
358
+ };
359
+ }
360
+ function currentTraceExemplar(value, timestamp) {
361
+ const fiber = getCurrentFiber();
362
+ return exemplarFromTraceContext(fiber?.fiberContext?.trace, value, timestamp);
363
+ }
364
+ function requestHost(req) {
365
+ try {
366
+ return new URL(req.url).host;
367
+ } catch {
368
+ return void 0;
369
+ }
370
+ }
371
+ function urlScheme(url) {
372
+ try {
373
+ return new URL(url).protocol.replace(/:$/, "");
374
+ } catch {
375
+ return void 0;
376
+ }
377
+ }
378
+ function urlPath(url) {
379
+ try {
380
+ return new URL(url).pathname;
381
+ } catch {
382
+ return void 0;
383
+ }
384
+ }
385
+ function sanitizeUrl(url) {
386
+ try {
387
+ const parsed = new URL(url);
388
+ parsed.search = "";
389
+ parsed.hash = "";
390
+ return parsed.toString();
391
+ } catch {
392
+ const [withoutHash] = url.split("#", 1);
393
+ const [withoutQuery] = withoutHash.split("?", 1);
394
+ return withoutQuery;
395
+ }
396
+ }
397
+ function compactLabels(labels) {
398
+ const out = {};
399
+ for (const [key, value] of Object.entries(labels)) {
400
+ if (value !== void 0 && value !== "") out[key] = value;
401
+ }
402
+ return out;
403
+ }
404
+
405
+ // src/observability/adapters.ts
406
+ function makeFetchRequestObservabilityContext(observability, request, input = {}) {
407
+ return makeRequestObservabilityContext(observability, {
408
+ headers: request.headers,
409
+ method: request.method,
410
+ target: sanitizeHttpTarget(request.url),
411
+ route: input.route ?? normalizeHttpRoute(urlPathname(request.url)),
412
+ ...input
413
+ });
414
+ }
415
+ function makeNodeRequestObservabilityContext(observability, request, input = {}) {
416
+ return makeRequestObservabilityContext(observability, {
417
+ headers: request.headers,
418
+ method: request.method,
419
+ target: sanitizeHttpTarget(request.url),
420
+ route: input.route ?? normalizeHttpRoute(request.url),
421
+ ...input
422
+ });
423
+ }
424
+ function makeExpressRequestObservabilityContext(observability, request, input = {}) {
425
+ return makeRequestObservabilityContext(observability, {
426
+ headers: request.headers,
427
+ method: request.method,
428
+ target: sanitizeHttpTarget(request.originalUrl ?? request.url),
429
+ route: input.route ?? request.route?.path ?? normalizeHttpRoute(request.path ?? request.url),
430
+ ...input
431
+ });
432
+ }
433
+ function makeFastifyRequestObservabilityContext(observability, request, input = {}) {
434
+ return makeRequestObservabilityContext(observability, {
435
+ headers: request.headers,
436
+ method: request.method,
437
+ target: sanitizeHttpTarget(request.url),
438
+ route: input.route ?? request.routeOptions?.url ?? request.routerPath ?? normalizeHttpRoute(request.url),
439
+ ...input
440
+ });
441
+ }
442
+ function withFetchRequestObservability(observability, handler, input = {}) {
443
+ return async (request) => handler(makeFetchRequestObservabilityContext(observability, request, input), request);
444
+ }
445
+ function withNodeRequestObservability(observability, handler, input = {}) {
446
+ return async (request) => handler(makeNodeRequestObservabilityContext(observability, request, input), request);
447
+ }
448
+ function urlPathname(url) {
449
+ if (!url) return void 0;
450
+ try {
451
+ return new URL(url, "http://local").pathname;
452
+ } catch {
453
+ return url;
454
+ }
455
+ }
456
+
457
+ // src/observability/config.ts
458
+ function makeNoopObservability() {
459
+ return makeObservability({
460
+ metrics: false,
461
+ logs: false,
462
+ traces: false,
463
+ autoStart: false
464
+ });
465
+ }
466
+ function makeObservabilityPreset(preset, overrides = {}) {
467
+ if (preset === "disabled") return makeNoopObservability();
468
+ return makeObservability(mergeObservabilityOptions(observabilityOptionsForPreset(preset), overrides));
469
+ }
470
+ function makeObservabilityFromEnv(env = readProcessEnv(), overrides = {}) {
471
+ const preset = env.BRASS_OBSERVABILITY === "disabled" ? "disabled" : parsePreset(env.BRASS_OBSERVABILITY_PRESET ?? env.NODE_ENV);
472
+ if (preset === "disabled") return makeNoopObservability();
473
+ return makeObservability(mergeObservabilityOptions(observabilityOptionsFromEnv(env, preset), overrides));
474
+ }
475
+ function observabilityOptionsForPreset(preset) {
476
+ switch (preset) {
477
+ case "production":
478
+ return {
479
+ logs: { minLevel: "info" },
480
+ sampling: { ratio: 1, respectRemoteSampled: true, forceSampleOnError: true },
481
+ redaction: {},
482
+ cardinality: { maxValuesPerLabel: 100 },
483
+ otlp: {
484
+ timeoutMs: 1e4,
485
+ retry: { attempts: 3, initialDelayMs: 100, maxDelayMs: 2e3 },
486
+ pipeline: {
487
+ maxQueueSize: 1e4,
488
+ batchSize: 512,
489
+ dropPolicy: "drop-oldest",
490
+ shutdownTimeoutMs: 1e4
491
+ }
492
+ },
493
+ flushIntervalMs: 1e4,
494
+ autoStart: true
495
+ };
496
+ case "test":
497
+ return {
498
+ logs: false,
499
+ sampling: 1,
500
+ redaction: {},
501
+ otlp: {
502
+ timeoutMs: 1e3,
503
+ retry: { attempts: 1 },
504
+ pipeline: { maxQueueSize: 1e3, batchSize: 256, shutdownTimeoutMs: 1e3 }
505
+ },
506
+ autoStart: false
507
+ };
508
+ case "development":
509
+ return {
510
+ logs: { minLevel: "debug" },
511
+ sampling: 1,
512
+ redaction: {},
513
+ cardinality: { maxValuesPerLabel: 100 },
514
+ autoStart: false
515
+ };
516
+ }
517
+ }
518
+ function observabilityOptionsFromEnv(env = readProcessEnv(), preset = parsePreset(env.BRASS_OBSERVABILITY_PRESET ?? env.NODE_ENV)) {
519
+ const base = observabilityOptionsForPreset(preset);
520
+ const serviceName = env.OTEL_SERVICE_NAME ?? env.BRASS_SERVICE_NAME;
521
+ const serviceVersion = env.OTEL_SERVICE_VERSION ?? env.BRASS_SERVICE_VERSION;
522
+ const endpoint = trimTrailingSlash(env.OTEL_EXPORTER_OTLP_ENDPOINT);
523
+ const metricsUrl = env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ?? (endpoint ? `${endpoint}/v1/metrics` : void 0);
524
+ const tracesUrl = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? (endpoint ? `${endpoint}/v1/traces` : void 0);
525
+ const logsUrl = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT ?? (endpoint ? `${endpoint}/v1/logs` : void 0);
526
+ const headers = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS);
527
+ const flushIntervalMs = parsePositiveInt(env.BRASS_OBSERVABILITY_FLUSH_INTERVAL_MS);
528
+ const timeoutMs = parsePositiveInt(env.BRASS_OBSERVABILITY_EXPORT_TIMEOUT_MS);
529
+ const sampleRatio = parseRatio(env.BRASS_TRACE_SAMPLE_RATIO ?? env.OTEL_TRACES_SAMPLER_ARG);
530
+ const minLevel = env.BRASS_OBSERVABILITY_LOG_LEVEL;
531
+ const otlp = {
532
+ ...base.otlp ?? {},
533
+ ...metricsUrl ? { metricsUrl } : {},
534
+ ...tracesUrl ? { tracesUrl } : {},
535
+ ...logsUrl ? { logsUrl } : {},
536
+ ...headers ? { headers } : {},
537
+ ...timeoutMs ? { timeoutMs } : {}
538
+ };
539
+ return mergeObservabilityOptions(base, {
540
+ ...serviceName ? { serviceName } : {},
541
+ ...serviceVersion ? { serviceVersion } : {},
542
+ ...Object.keys(otlp).length > 0 ? { otlp } : {},
543
+ ...flushIntervalMs ? { flushIntervalMs, autoStart: true } : {},
544
+ ...sampleRatio !== void 0 ? { sampling: { ratio: sampleRatio, respectRemoteSampled: true, forceSampleOnError: true } } : {},
545
+ ...minLevel === "debug" || minLevel === "info" || minLevel === "warn" || minLevel === "error" ? { logs: { minLevel } } : {}
546
+ });
547
+ }
548
+ function mergeObservabilityOptions(base, overrides) {
549
+ return {
550
+ ...base,
551
+ ...overrides,
552
+ metrics: overrides.metrics ?? base.metrics,
553
+ logs: overrides.logs ?? base.logs,
554
+ otlp: {
555
+ ...base.otlp ?? {},
556
+ ...overrides.otlp ?? {},
557
+ retry: overrides.otlp?.retry ?? base.otlp?.retry,
558
+ pipeline: {
559
+ ...base.otlp?.pipeline ?? {},
560
+ ...overrides.otlp?.pipeline ?? {}
561
+ }
562
+ }
563
+ };
564
+ }
565
+ function parsePreset(value) {
566
+ if (value === "production" || value === "prod") return "production";
567
+ if (value === "test") return "test";
568
+ return "development";
569
+ }
570
+ function parseHeaders(value) {
571
+ if (!value) return void 0;
572
+ const out = {};
573
+ for (const part of value.split(",")) {
574
+ const index = part.indexOf("=");
575
+ if (index <= 0) continue;
576
+ const key = part.slice(0, index).trim();
577
+ const headerValue = part.slice(index + 1).trim();
578
+ if (key) out[key] = headerValue;
579
+ }
580
+ return Object.keys(out).length > 0 ? out : void 0;
581
+ }
582
+ function parsePositiveInt(value) {
583
+ if (!value) return void 0;
584
+ const parsed = Number.parseInt(value, 10);
585
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
586
+ }
587
+ function parseRatio(value) {
588
+ if (!value) return void 0;
589
+ const parsed = Number.parseFloat(value);
590
+ if (!Number.isFinite(parsed)) return void 0;
591
+ return Math.max(0, Math.min(1, parsed));
592
+ }
593
+ function trimTrailingSlash(value) {
594
+ if (!value) return void 0;
595
+ let out = value;
596
+ while (out.endsWith("/")) out = out.slice(0, -1);
597
+ return out || void 0;
598
+ }
599
+ function readProcessEnv() {
600
+ return typeof process !== "undefined" ? process.env : {};
601
+ }
602
+ export {
603
+ OTLP_JSON_CONTENT_TYPE,
604
+ PROMETHEUS_CONTENT_TYPE,
605
+ alwaysOffSampler,
606
+ alwaysOnSampler,
607
+ currentBaggage,
608
+ currentSpanLink,
609
+ defaultStructuredLogWriter,
610
+ exemplarFromTraceContext,
611
+ exportWithRetry,
612
+ extractBaggage,
613
+ extractTraceContext,
614
+ formatBaggage,
615
+ formatPrometheusMetrics,
616
+ formatStructuredLog,
617
+ formatTraceparent,
618
+ healthToHttpResponse,
619
+ injectBaggage,
620
+ injectTraceContext,
621
+ logEffect,
622
+ makeCardinalityLimitedMetrics,
623
+ makeExportPipeline,
624
+ makeExpressRequestObservabilityContext,
625
+ makeFastifyRequestObservabilityContext,
626
+ makeFetchRequestObservabilityContext,
627
+ makeHttpObservabilityMiddleware,
628
+ makeNodeRequestObservabilityContext,
629
+ makeNoopObservability,
630
+ makeObservability,
631
+ makeObservabilityFromEnv,
632
+ makeObservabilityPreset,
633
+ makeObservabilityRedactor,
634
+ makeOtlpHttpLogExporter,
635
+ makeOtlpHttpMetricsExporter,
636
+ makeOtlpHttpSpanExporter,
637
+ makePrometheusMetricsExporter,
638
+ makeRequestObservabilityContext,
639
+ makeRuntimeHealth,
640
+ makeRuntimeMetricsSink,
641
+ makeStructuredLogSink,
642
+ makeTraceSampler,
643
+ metricsSnapshotToOtlp,
644
+ normalizeHttpRoute,
645
+ normalizeSpanId,
646
+ normalizeTraceId,
647
+ observabilityOptionsForPreset,
648
+ observabilityOptionsFromEnv,
649
+ observeHttpServerRequest,
650
+ otlpAnyValue,
651
+ parseBaggage,
652
+ parseTraceparent,
653
+ postOtlpJson,
654
+ ratioSampler,
655
+ readiness,
656
+ resolveRequestBaggage,
657
+ resolveRequestTraceSeed,
658
+ resolveTraceSampling,
659
+ runObservedHttpServerEffect,
660
+ runtimeHealth,
661
+ sanitizeHttpTarget,
662
+ shouldSampleWith,
663
+ snapshotRuntimeHealth,
664
+ spanEvent,
665
+ spanLink,
666
+ spansToOtlp,
667
+ structuredLogsToOtlp,
668
+ toOtlpAttributes,
669
+ unixNanoFromMs,
670
+ withBaggage,
671
+ withFetchRequestObservability,
672
+ withHttpObservability,
673
+ withLogContext,
674
+ withNodeRequestObservability,
675
+ withSpan,
676
+ withTimeout
677
+ };