@dyrected/core 2.6.4 → 2.7.1

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.
@@ -0,0 +1,513 @@
1
+ // src/observability.ts
2
+ import {
3
+ TraceFlags,
4
+ context as otelContext,
5
+ trace
6
+ } from "@opentelemetry/api";
7
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
8
+ import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
9
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
10
+ import { resourceFromAttributes } from "@opentelemetry/resources";
11
+ import {
12
+ MeterProvider,
13
+ PeriodicExportingMetricReader
14
+ } from "@opentelemetry/sdk-metrics";
15
+ import {
16
+ BasicTracerProvider,
17
+ BatchSpanProcessor,
18
+ ConsoleSpanExporter
19
+ } from "@opentelemetry/sdk-trace-base";
20
+ import pino, {
21
+ destination as pinoDestination,
22
+ multistream,
23
+ stdTimeFunctions
24
+ } from "pino";
25
+ import pinoPretty from "pino-pretty";
26
+ import { Writable } from "stream";
27
+ var DEFAULT_REDACT_HEADERS = ["authorization", "cookie", "set-cookie", "x-api-key"];
28
+ var DEFAULT_REDACT_PATHS = [
29
+ "password",
30
+ "currentPassword",
31
+ "newPassword",
32
+ "confirmPassword",
33
+ "token",
34
+ "refreshToken",
35
+ "accessToken",
36
+ "secret",
37
+ "apiKey",
38
+ "inviteToken",
39
+ "resetToken"
40
+ ];
41
+ var DEFAULT_MAX_BODY_BYTES = 8192;
42
+ var DEFAULT_SUCCESS_SAMPLE_RATE = 0.1;
43
+ var DEFAULT_BODY_SAMPLE_RATE = 0.02;
44
+ var REDACTED_VALUE = "[REDACTED]";
45
+ var runtimeByConfig = /* @__PURE__ */ new WeakMap();
46
+ var fallbackLogger = pino({
47
+ name: "dyrected",
48
+ enabled: process.env.DISABLE_LOGGING !== "true",
49
+ timestamp: stdTimeFunctions.isoTime
50
+ });
51
+ function resolveObservabilityConfig(config) {
52
+ const requestLogging = config?.requestLogging;
53
+ const sampling = config?.sampling;
54
+ const tracing = config?.tracing;
55
+ const metrics = config?.metrics;
56
+ return {
57
+ requestLogging: {
58
+ enabled: requestLogging?.enabled ?? true,
59
+ logBodies: requestLogging?.logBodies ?? false,
60
+ maxBodyBytes: requestLogging?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,
61
+ redactPaths: uniqueValues([
62
+ ...DEFAULT_REDACT_PATHS,
63
+ ...requestLogging?.redactPaths ?? []
64
+ ]),
65
+ includeHeaders: normalizeHeaderNames(requestLogging?.includeHeaders ?? []),
66
+ redactHeaders: uniqueValues(
67
+ normalizeHeaderNames([
68
+ ...DEFAULT_REDACT_HEADERS,
69
+ ...requestLogging?.redactHeaders ?? []
70
+ ])
71
+ )
72
+ },
73
+ sampling: {
74
+ successRate: clampRate(sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE),
75
+ traceSuccessRate: clampRate(
76
+ sampling?.traceSuccessRate ?? sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE
77
+ ),
78
+ bodySuccessRate: clampRate(
79
+ sampling?.bodySuccessRate ?? Math.min(DEFAULT_BODY_SAMPLE_RATE, sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE)
80
+ ),
81
+ alwaysKeep4xx: sampling?.alwaysKeep4xx ?? true,
82
+ alwaysKeep5xx: sampling?.alwaysKeep5xx ?? true
83
+ },
84
+ tracing: {
85
+ enabled: tracing?.enabled ?? false,
86
+ serviceName: tracing?.serviceName ?? "dyrected",
87
+ exporter: tracing?.exporter ?? "none",
88
+ headers: tracing?.headers ?? {},
89
+ endpoint: tracing?.endpoint
90
+ },
91
+ metrics: {
92
+ enabled: metrics?.enabled ?? false,
93
+ exporter: metrics?.exporter ?? "none",
94
+ endpoint: metrics?.endpoint,
95
+ path: metrics?.path ?? "/metrics"
96
+ },
97
+ transports: {
98
+ targets: config?.transports?.targets && config.transports.targets.length > 0 ? config.transports.targets : [{ type: "stdout" }]
99
+ }
100
+ };
101
+ }
102
+ function createObservabilityRuntime(config) {
103
+ const resolved = resolveObservabilityConfig(config.observability);
104
+ const logger = createRootLogger(config.logger, resolved);
105
+ const shutdownTasks = [];
106
+ const meterRuntime = resolved.metrics.enabled || resolved.metrics.exporter === "prometheus" ? createMeterProvider(resolved) : void 0;
107
+ const tracerProvider = resolved.tracing.enabled ? createTracerProvider(resolved) : void 0;
108
+ const tracer = tracerProvider?.getTracer("dyrected");
109
+ const meter = meterRuntime?.provider.getMeter("dyrected");
110
+ const metrics = meter ? {
111
+ requestCount: meter.createCounter("dyrected_http_requests_total", {
112
+ description: "Total HTTP requests served by Dyrected"
113
+ }),
114
+ authFailureCount: meter.createCounter("dyrected_auth_failures_total", {
115
+ description: "Authentication failures"
116
+ }),
117
+ uncaughtErrorCount: meter.createCounter("dyrected_uncaught_errors_total", {
118
+ description: "Uncaught application errors"
119
+ }),
120
+ auditWriteFailureCount: meter.createCounter("dyrected_audit_write_failures_total", {
121
+ description: "Audit log persistence failures"
122
+ }),
123
+ emailSendFailureCount: meter.createCounter("dyrected_email_send_failures_total", {
124
+ description: "Transactional email delivery failures"
125
+ }),
126
+ workflowHookFailureCount: meter.createCounter("dyrected_workflow_hook_failures_total", {
127
+ description: "Workflow hook failures isolated after successful writes"
128
+ }),
129
+ requestDuration: meter.createHistogram("dyrected_http_request_duration_ms", {
130
+ description: "HTTP request duration in milliseconds",
131
+ unit: "ms"
132
+ })
133
+ } : void 0;
134
+ if (meterRuntime) {
135
+ shutdownTasks.push(() => meterRuntime.provider.shutdown());
136
+ }
137
+ if (tracerProvider) {
138
+ shutdownTasks.push(() => tracerProvider.shutdown());
139
+ }
140
+ return {
141
+ logger,
142
+ config: resolved,
143
+ tracer,
144
+ metrics,
145
+ prometheusExporter: meterRuntime?.prometheusExporter,
146
+ shutdown: async () => {
147
+ for (const task of shutdownTasks) {
148
+ await task();
149
+ }
150
+ },
151
+ recordAuthFailure: (attributes) => metrics?.authFailureCount.add(1, attributes),
152
+ recordUncaughtError: (attributes) => metrics?.uncaughtErrorCount.add(1, attributes),
153
+ recordAuditWriteFailure: (attributes) => metrics?.auditWriteFailureCount.add(1, attributes),
154
+ recordEmailSendFailure: (attributes) => metrics?.emailSendFailureCount.add(1, attributes),
155
+ recordWorkflowHookFailure: (attributes) => metrics?.workflowHookFailureCount.add(1, attributes)
156
+ };
157
+ }
158
+ function bindObservabilityRuntime(config, runtime) {
159
+ runtimeByConfig.set(config, runtime);
160
+ }
161
+ function getObservabilityRuntime(config) {
162
+ if (!config || typeof config !== "object") return void 0;
163
+ return runtimeByConfig.get(config);
164
+ }
165
+ function createRootLogger(loggerConfig, observability) {
166
+ if (loggerConfig && !("options" in loggerConfig)) {
167
+ return loggerConfig;
168
+ }
169
+ const options = loggerConfig?.options ?? {};
170
+ const enabled = options.enabled ?? process.env.DISABLE_LOGGING !== "true";
171
+ const name = options.name ?? "dyrected";
172
+ if (loggerConfig?.destination) {
173
+ return pino(
174
+ {
175
+ ...options,
176
+ enabled,
177
+ name,
178
+ timestamp: options.timestamp ?? stdTimeFunctions.isoTime
179
+ },
180
+ loggerConfig.destination
181
+ );
182
+ }
183
+ const streams = buildTransportStreams(observability);
184
+ const destination = streams.length === 1 ? streams[0] : multistream(streams.map((stream) => ({ stream })));
185
+ return pino(
186
+ {
187
+ ...options,
188
+ enabled,
189
+ name,
190
+ timestamp: options.timestamp ?? stdTimeFunctions.isoTime
191
+ },
192
+ destination
193
+ );
194
+ }
195
+ function buildTransportStreams(observability) {
196
+ const targets = observability.transports.targets;
197
+ if (targets.length === 0) {
198
+ return [defaultLoggerDestination()];
199
+ }
200
+ return targets.map((target) => {
201
+ switch (target.type) {
202
+ case "stdout":
203
+ return defaultLoggerDestination();
204
+ case "stderr":
205
+ return pinoDestination(2);
206
+ case "file":
207
+ return pinoDestination(target.path);
208
+ case "otlp":
209
+ return new OtlpLogWritable(target.endpoint, target.headers);
210
+ }
211
+ });
212
+ }
213
+ function defaultLoggerDestination() {
214
+ if (process.env.NODE_ENV !== "production") {
215
+ return pinoPretty({
216
+ colorize: true,
217
+ ignore: "pid,hostname",
218
+ translateTime: "SYS:HH:MM:ss",
219
+ destination: 1,
220
+ sync: true
221
+ });
222
+ }
223
+ return pinoDestination(1);
224
+ }
225
+ var OtlpLogWritable = class extends Writable {
226
+ constructor(endpoint, headers = {}) {
227
+ super();
228
+ this.endpoint = endpoint;
229
+ this.headers = headers;
230
+ }
231
+ endpoint;
232
+ headers;
233
+ _write(chunk, _encoding, callback) {
234
+ const payload = chunk.toString();
235
+ void fetch(this.endpoint, {
236
+ method: "POST",
237
+ headers: {
238
+ "content-type": "application/json",
239
+ ...this.headers
240
+ },
241
+ body: JSON.stringify({ logs: payload.trim().split("\n").filter(Boolean) })
242
+ }).then(() => callback()).catch(
243
+ (error) => callback(error instanceof Error ? error : new Error(String(error)))
244
+ );
245
+ }
246
+ };
247
+ function createTracerProvider(observability) {
248
+ const exporter = createTraceExporter(observability);
249
+ const provider = new BasicTracerProvider({
250
+ resource: resourceFromAttributes({
251
+ "service.name": observability.tracing.serviceName
252
+ }),
253
+ spanProcessors: exporter ? [new BatchSpanProcessor(exporter)] : []
254
+ });
255
+ trace.setGlobalTracerProvider(provider);
256
+ return provider;
257
+ }
258
+ function createTraceExporter(observability) {
259
+ switch (observability.tracing.exporter) {
260
+ case "console":
261
+ return new ConsoleSpanExporter();
262
+ case "otlp":
263
+ return new OTLPTraceExporter({
264
+ url: observability.tracing.endpoint,
265
+ headers: observability.tracing.headers
266
+ });
267
+ default:
268
+ return void 0;
269
+ }
270
+ }
271
+ function createMeterProvider(observability) {
272
+ const readers = [];
273
+ let prometheusExporter;
274
+ switch (observability.metrics.exporter) {
275
+ case "otlp":
276
+ readers.push(
277
+ new PeriodicExportingMetricReader({
278
+ exporter: new OTLPMetricExporter({
279
+ url: observability.metrics.endpoint
280
+ })
281
+ })
282
+ );
283
+ break;
284
+ case "prometheus":
285
+ prometheusExporter = new PrometheusExporter({
286
+ endpoint: observability.metrics.path,
287
+ preventServerStart: true
288
+ });
289
+ readers.push(prometheusExporter);
290
+ break;
291
+ }
292
+ const provider = new MeterProvider({
293
+ resource: resourceFromAttributes({
294
+ "service.name": observability.tracing.serviceName
295
+ }),
296
+ readers
297
+ });
298
+ return { provider, prometheusExporter };
299
+ }
300
+ function getConfigLogger(config, component) {
301
+ const base = config?.logger && !("options" in config.logger) ? config.logger : fallbackLogger;
302
+ return base.child({ component });
303
+ }
304
+ function getRequestLogger(c, component) {
305
+ const base = c.get("logger") ?? fallbackLogger;
306
+ return component ? base.child({ component }) : base;
307
+ }
308
+ function buildRequestLogger(runtime, vars, requestId) {
309
+ const trace2 = vars.requestTrace;
310
+ return runtime.logger.child({
311
+ requestId,
312
+ siteId: vars.siteId,
313
+ workspaceId: vars.workspaceId,
314
+ traceId: trace2?.traceId,
315
+ spanId: trace2?.spanId
316
+ });
317
+ }
318
+ function shouldSampleRequest(requestId, statusCode, sampling, kind) {
319
+ if (statusCode >= 500 && sampling.alwaysKeep5xx) return true;
320
+ if (statusCode >= 400 && sampling.alwaysKeep4xx) return true;
321
+ const rate = kind === "trace" ? sampling.traceSuccessRate : kind === "body" ? sampling.bodySuccessRate : sampling.successRate;
322
+ return deterministicSample(requestId ?? "no-request-id", rate);
323
+ }
324
+ function redactHeaders(headers, observability) {
325
+ const includeHeaders = new Set(observability.requestLogging.includeHeaders);
326
+ const redactHeaders2 = new Set(observability.requestLogging.redactHeaders);
327
+ const output = {};
328
+ for (const [key, value] of Object.entries(headers)) {
329
+ const normalizedKey = key.toLowerCase();
330
+ if (includeHeaders.size > 0 && !includeHeaders.has(normalizedKey)) continue;
331
+ output[normalizedKey] = redactHeaders2.has(normalizedKey) ? REDACTED_VALUE : value;
332
+ }
333
+ return output;
334
+ }
335
+ async function captureRequestBody(request, observability) {
336
+ const contentType = request.headers.get("content-type") ?? void 0;
337
+ const contentLength = toNumber(request.headers.get("content-length"));
338
+ const jsonBody = contentType?.includes("application/json");
339
+ if (!jsonBody) {
340
+ return {
341
+ attempted: false,
342
+ contentType,
343
+ contentLength
344
+ };
345
+ }
346
+ try {
347
+ const text = await request.clone().text();
348
+ if (!text) {
349
+ return { attempted: true, contentType, contentLength };
350
+ }
351
+ const truncated = text.length > observability.requestLogging.maxBodyBytes;
352
+ const raw = truncated ? text.slice(0, observability.requestLogging.maxBodyBytes) : text;
353
+ try {
354
+ const parsed = JSON.parse(raw);
355
+ return {
356
+ attempted: true,
357
+ contentType,
358
+ contentLength: contentLength ?? text.length,
359
+ truncated,
360
+ body: redactBody(parsed, observability.requestLogging.redactPaths)
361
+ };
362
+ } catch {
363
+ return {
364
+ attempted: true,
365
+ contentType,
366
+ contentLength: contentLength ?? text.length,
367
+ truncated,
368
+ parseFailed: true
369
+ };
370
+ }
371
+ } catch {
372
+ return {
373
+ attempted: true,
374
+ contentType,
375
+ contentLength,
376
+ parseFailed: true
377
+ };
378
+ }
379
+ }
380
+ function redactBody(value, redactPaths) {
381
+ const cloned = deepClone(value);
382
+ for (const path of redactPaths) {
383
+ applyRedaction(cloned, path.split("."));
384
+ }
385
+ return cloned;
386
+ }
387
+ function applyRedaction(target, segments) {
388
+ if (!target || segments.length === 0) return;
389
+ const [segment, ...rest] = segments;
390
+ if (Array.isArray(target)) {
391
+ for (const item of target) {
392
+ if (segment === "*") {
393
+ applyRedaction(item, rest);
394
+ } else {
395
+ applyRedaction(item, segments);
396
+ }
397
+ }
398
+ return;
399
+ }
400
+ if (typeof target !== "object") return;
401
+ const record = target;
402
+ if (segment === "*") {
403
+ for (const value of Object.values(record)) {
404
+ applyRedaction(value, rest);
405
+ }
406
+ return;
407
+ }
408
+ if (!(segment in record)) return;
409
+ if (rest.length === 0) {
410
+ record[segment] = REDACTED_VALUE;
411
+ return;
412
+ }
413
+ applyRedaction(record[segment], rest);
414
+ }
415
+ function deepClone(value) {
416
+ if (typeof structuredClone === "function") {
417
+ return structuredClone(value);
418
+ }
419
+ return JSON.parse(JSON.stringify(value));
420
+ }
421
+ function createRequestSpan(runtime, name, attributes) {
422
+ if (!runtime.tracer) return void 0;
423
+ const span = runtime.tracer.startSpan(name, { attributes }, otelContext.active());
424
+ const spanContext = span.spanContext();
425
+ return {
426
+ span,
427
+ traceId: spanContext.traceId,
428
+ spanId: spanContext.spanId,
429
+ sampled: spanContext.traceFlags === TraceFlags.SAMPLED
430
+ };
431
+ }
432
+ function endRequestSpan(requestTrace, statusCode, error) {
433
+ if (!requestTrace) return;
434
+ requestTrace.span.setAttribute("http.status_code", statusCode);
435
+ if (error) {
436
+ requestTrace.span.recordException(error instanceof Error ? error : new Error(String(error)));
437
+ }
438
+ requestTrace.span.end();
439
+ }
440
+ function attachRequestMetrics(runtime, args) {
441
+ runtime.metrics?.requestCount.add(1, {
442
+ method: args.method,
443
+ route: args.route,
444
+ status_class: `${Math.floor(args.statusCode / 100)}xx`
445
+ });
446
+ runtime.metrics?.requestDuration.record(args.durationMs, {
447
+ method: args.method,
448
+ route: args.route,
449
+ status_class: `${Math.floor(args.statusCode / 100)}xx`
450
+ });
451
+ }
452
+ async function renderPrometheusMetrics(exporter) {
453
+ let statusCode = 200;
454
+ const headers = {};
455
+ let body = "";
456
+ await new Promise((resolve) => {
457
+ const response = {
458
+ statusCode,
459
+ setHeader(name, value) {
460
+ headers[name.toLowerCase()] = value;
461
+ },
462
+ end(chunk) {
463
+ if (chunk) body += chunk;
464
+ statusCode = this.statusCode;
465
+ resolve();
466
+ }
467
+ };
468
+ exporter.getMetricsRequestHandler({}, response);
469
+ });
470
+ return { body, headers, statusCode };
471
+ }
472
+ function normalizeHeaderNames(headers) {
473
+ return headers.map((value) => value.toLowerCase());
474
+ }
475
+ function uniqueValues(values) {
476
+ return [...new Set(values)];
477
+ }
478
+ function clampRate(value) {
479
+ if (Number.isNaN(value)) return 0;
480
+ return Math.max(0, Math.min(1, value));
481
+ }
482
+ function deterministicSample(seed, rate) {
483
+ if (rate >= 1) return true;
484
+ if (rate <= 0) return false;
485
+ let hash = 0;
486
+ for (let index = 0; index < seed.length; index += 1) {
487
+ hash = hash * 31 + seed.charCodeAt(index) >>> 0;
488
+ }
489
+ return hash / 4294967295 <= rate;
490
+ }
491
+ function toNumber(value) {
492
+ if (!value) return void 0;
493
+ const parsed = Number(value);
494
+ return Number.isFinite(parsed) ? parsed : void 0;
495
+ }
496
+
497
+ export {
498
+ resolveObservabilityConfig,
499
+ createObservabilityRuntime,
500
+ bindObservabilityRuntime,
501
+ getObservabilityRuntime,
502
+ getConfigLogger,
503
+ getRequestLogger,
504
+ buildRequestLogger,
505
+ shouldSampleRequest,
506
+ redactHeaders,
507
+ captureRequestBody,
508
+ redactBody,
509
+ createRequestSpan,
510
+ endRequestSpan,
511
+ attachRequestMetrics,
512
+ renderPrometheusMetrics
513
+ };