@atrim/instrument-node 0.4.0 → 0.5.0-14fdea7-20260108232035

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.
@@ -1,1174 +0,0 @@
1
- import { Data, Effect, Cache, Duration, Schedule } from 'effect';
2
- import { NodeSDK } from '@opentelemetry/sdk-node';
3
- import { SimpleSpanProcessor, BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
4
- import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
5
- import { trace } from '@opentelemetry/api';
6
- import { existsSync, readFileSync } from 'fs';
7
- import { join } from 'path';
8
- import { parse } from 'yaml';
9
- import { z } from 'zod';
10
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
11
- import { readFile } from 'fs/promises';
12
-
13
- var __defProp = Object.defineProperty;
14
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
15
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
16
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
17
- }) : x)(function(x) {
18
- if (typeof require !== "undefined") return require.apply(this, arguments);
19
- throw Error('Dynamic require of "' + x + '" is not supported');
20
- });
21
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- var __defProp2 = Object.defineProperty;
23
- var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
24
- var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
25
- var PatternConfigSchema = z.object({
26
- pattern: z.string(),
27
- enabled: z.boolean().optional(),
28
- description: z.string().optional()
29
- });
30
- var AutoIsolationConfigSchema = z.object({
31
- // Global enable/disable for auto-isolation
32
- enabled: z.boolean().default(false),
33
- // Which operators to auto-isolate
34
- operators: z.object({
35
- fiberset_run: z.boolean().default(true),
36
- effect_fork: z.boolean().default(true),
37
- effect_fork_daemon: z.boolean().default(true),
38
- effect_fork_in: z.boolean().default(false)
39
- }).default({}),
40
- // Virtual parent tracking configuration
41
- tracking: z.object({
42
- use_span_links: z.boolean().default(true),
43
- use_attributes: z.boolean().default(true),
44
- capture_logical_parent: z.boolean().default(true)
45
- }).default({}),
46
- // Span categorization
47
- attributes: z.object({
48
- category: z.string().default("background_task"),
49
- add_metadata: z.boolean().default(true)
50
- }).default({})
51
- });
52
- var HttpFilteringConfigSchema = z.object({
53
- // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)
54
- ignore_outgoing_urls: z.array(z.string()).optional(),
55
- // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)
56
- ignore_incoming_paths: z.array(z.string()).optional(),
57
- // Require parent span for outgoing requests (prevents root spans for HTTP calls)
58
- require_parent_for_outgoing_spans: z.boolean().optional()
59
- });
60
- var InstrumentationConfigSchema = z.object({
61
- version: z.string(),
62
- instrumentation: z.object({
63
- enabled: z.boolean(),
64
- description: z.string().optional(),
65
- logging: z.enum(["on", "off", "minimal"]).optional().default("on"),
66
- instrument_patterns: z.array(PatternConfigSchema),
67
- ignore_patterns: z.array(PatternConfigSchema)
68
- }),
69
- effect: z.object({
70
- auto_extract_metadata: z.boolean(),
71
- auto_isolation: AutoIsolationConfigSchema.optional()
72
- }).optional(),
73
- http: HttpFilteringConfigSchema.optional()
74
- });
75
- (class extends Data.TaggedError("ConfigError") {
76
- });
77
- var ConfigUrlError = class extends Data.TaggedError("ConfigUrlError") {
78
- };
79
- var ConfigValidationError = class extends Data.TaggedError("ConfigValidationError") {
80
- };
81
- var ConfigFileError = class extends Data.TaggedError("ConfigFileError") {
82
- };
83
- (class extends Data.TaggedError("ServiceDetectionError") {
84
- });
85
- (class extends Data.TaggedError("InitializationError") {
86
- });
87
- (class extends Data.TaggedError("ExportError") {
88
- });
89
- (class extends Data.TaggedError("ShutdownError") {
90
- });
91
- var SECURITY_DEFAULTS = {
92
- maxConfigSize: 1e6,
93
- // 1MB
94
- requestTimeout: 5e3,
95
- allowedProtocols: ["https:"],
96
- // Only HTTPS for remote configs
97
- cacheTimeout: 3e5
98
- // 5 minutes
99
- };
100
- function getDefaultConfig() {
101
- return {
102
- version: "1.0",
103
- instrumentation: {
104
- enabled: true,
105
- logging: "on",
106
- description: "Default instrumentation configuration",
107
- instrument_patterns: [
108
- { pattern: "^app\\.", enabled: true, description: "Application operations" },
109
- { pattern: "^http\\.server\\.", enabled: true, description: "HTTP server operations" },
110
- { pattern: "^http\\.client\\.", enabled: true, description: "HTTP client operations" }
111
- ],
112
- ignore_patterns: [
113
- { pattern: "^test\\.", description: "Test utilities" },
114
- { pattern: "^internal\\.", description: "Internal operations" },
115
- { pattern: "^health\\.", description: "Health checks" }
116
- ]
117
- },
118
- effect: {
119
- auto_extract_metadata: true
120
- }
121
- };
122
- }
123
- var validateConfigEffect = (rawConfig) => Effect.try({
124
- try: () => InstrumentationConfigSchema.parse(rawConfig),
125
- catch: (error) => new ConfigValidationError({
126
- reason: "Invalid configuration schema",
127
- cause: error
128
- })
129
- });
130
- var loadConfigFromFileEffect = (filePath) => Effect.gen(function* () {
131
- const fileContents = yield* Effect.try({
132
- try: () => readFileSync(filePath, "utf8"),
133
- catch: (error) => new ConfigFileError({
134
- reason: `Failed to read config file at ${filePath}`,
135
- cause: error
136
- })
137
- });
138
- if (fileContents.length > SECURITY_DEFAULTS.maxConfigSize) {
139
- return yield* Effect.fail(
140
- new ConfigFileError({
141
- reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
142
- })
143
- );
144
- }
145
- let rawConfig;
146
- try {
147
- rawConfig = parse(fileContents);
148
- } catch (error) {
149
- return yield* Effect.fail(
150
- new ConfigValidationError({
151
- reason: "Invalid YAML syntax",
152
- cause: error
153
- })
154
- );
155
- }
156
- return yield* validateConfigEffect(rawConfig);
157
- });
158
- var fetchAndParseConfig = (url) => Effect.gen(function* () {
159
- let urlObj;
160
- try {
161
- urlObj = new URL(url);
162
- } catch (error) {
163
- return yield* Effect.fail(
164
- new ConfigUrlError({
165
- reason: `Invalid URL: ${url}`,
166
- cause: error
167
- })
168
- );
169
- }
170
- if (!SECURITY_DEFAULTS.allowedProtocols.includes(urlObj.protocol)) {
171
- return yield* Effect.fail(
172
- new ConfigUrlError({
173
- reason: `Insecure protocol ${urlObj.protocol}. Only ${SECURITY_DEFAULTS.allowedProtocols.join(", ")} are allowed`
174
- })
175
- );
176
- }
177
- const response = yield* Effect.tryPromise({
178
- try: () => fetch(url, {
179
- redirect: "follow",
180
- headers: {
181
- Accept: "application/yaml, text/yaml, text/x-yaml"
182
- }
183
- }),
184
- catch: (error) => new ConfigUrlError({
185
- reason: `Failed to load config from URL ${url}`,
186
- cause: error
187
- })
188
- }).pipe(
189
- Effect.timeout(Duration.millis(SECURITY_DEFAULTS.requestTimeout)),
190
- Effect.retry({
191
- times: 3,
192
- schedule: Schedule.exponential(Duration.millis(100))
193
- }),
194
- Effect.catchAll((error) => {
195
- if (error._tag === "TimeoutException") {
196
- return Effect.fail(
197
- new ConfigUrlError({
198
- reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms`
199
- })
200
- );
201
- }
202
- return Effect.fail(error);
203
- })
204
- );
205
- if (!response.ok) {
206
- return yield* Effect.fail(
207
- new ConfigUrlError({
208
- reason: `HTTP ${response.status}: ${response.statusText}`
209
- })
210
- );
211
- }
212
- const contentLength = response.headers.get("content-length");
213
- if (contentLength && parseInt(contentLength) > SECURITY_DEFAULTS.maxConfigSize) {
214
- return yield* Effect.fail(
215
- new ConfigUrlError({
216
- reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
217
- })
218
- );
219
- }
220
- const text = yield* Effect.tryPromise({
221
- try: () => response.text(),
222
- catch: (error) => new ConfigUrlError({
223
- reason: "Failed to read response body",
224
- cause: error
225
- })
226
- });
227
- if (text.length > SECURITY_DEFAULTS.maxConfigSize) {
228
- return yield* Effect.fail(
229
- new ConfigUrlError({
230
- reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
231
- })
232
- );
233
- }
234
- let rawConfig;
235
- try {
236
- rawConfig = parse(text);
237
- } catch (error) {
238
- return yield* Effect.fail(
239
- new ConfigValidationError({
240
- reason: "Invalid YAML syntax",
241
- cause: error
242
- })
243
- );
244
- }
245
- return yield* validateConfigEffect(rawConfig);
246
- });
247
- var makeConfigCache = () => Cache.make({
248
- capacity: 100,
249
- timeToLive: Duration.minutes(5),
250
- lookup: (url) => fetchAndParseConfig(url)
251
- });
252
- var cacheInstance = null;
253
- var getCache = Effect.gen(function* () {
254
- if (!cacheInstance) {
255
- cacheInstance = yield* makeConfigCache();
256
- }
257
- return cacheInstance;
258
- });
259
- var loadConfigFromUrlEffect = (url, cacheTimeout = SECURITY_DEFAULTS.cacheTimeout) => Effect.gen(function* () {
260
- if (cacheTimeout === 0) {
261
- return yield* fetchAndParseConfig(url);
262
- }
263
- const cache = yield* getCache;
264
- return yield* cache.get(url);
265
- });
266
- var loadConfigEffect = (options = {}) => Effect.gen(function* () {
267
- if (options.config) {
268
- return yield* validateConfigEffect(options.config);
269
- }
270
- const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG;
271
- if (envConfigPath) {
272
- if (envConfigPath.startsWith("http://") || envConfigPath.startsWith("https://")) {
273
- return yield* loadConfigFromUrlEffect(envConfigPath, options.cacheTimeout);
274
- }
275
- return yield* loadConfigFromFileEffect(envConfigPath);
276
- }
277
- if (options.configUrl) {
278
- return yield* loadConfigFromUrlEffect(options.configUrl, options.cacheTimeout);
279
- }
280
- if (options.configPath) {
281
- return yield* loadConfigFromFileEffect(options.configPath);
282
- }
283
- const defaultPath = join(process.cwd(), "instrumentation.yaml");
284
- const exists = yield* Effect.sync(() => existsSync(defaultPath));
285
- if (exists) {
286
- return yield* loadConfigFromFileEffect(defaultPath);
287
- }
288
- return getDefaultConfig();
289
- });
290
- async function loadConfig(options = {}) {
291
- return Effect.runPromise(
292
- loadConfigEffect(options).pipe(
293
- // Convert typed errors to regular Error with reason message for backward compatibility
294
- Effect.mapError((error) => {
295
- const message = error.reason;
296
- const newError = new Error(message);
297
- newError.cause = error.cause;
298
- return newError;
299
- })
300
- )
301
- );
302
- }
303
- var PatternMatcher = class {
304
- constructor(config) {
305
- __publicField2(this, "ignorePatterns", []);
306
- __publicField2(this, "instrumentPatterns", []);
307
- __publicField2(this, "enabled", true);
308
- this.enabled = config.instrumentation.enabled;
309
- this.ignorePatterns = config.instrumentation.ignore_patterns.map((p) => this.compilePattern(p));
310
- this.instrumentPatterns = config.instrumentation.instrument_patterns.filter((p) => p.enabled !== false).map((p) => this.compilePattern(p));
311
- }
312
- /**
313
- * Compile a pattern configuration into a RegExp
314
- */
315
- compilePattern(pattern) {
316
- try {
317
- const compiled = {
318
- regex: new RegExp(pattern.pattern),
319
- enabled: pattern.enabled !== false
320
- };
321
- if (pattern.description !== void 0) {
322
- compiled.description = pattern.description;
323
- }
324
- return compiled;
325
- } catch (error) {
326
- throw new Error(
327
- `Failed to compile pattern "${pattern.pattern}": ${error instanceof Error ? error.message : String(error)}`
328
- );
329
- }
330
- }
331
- /**
332
- * Check if a span should be instrumented
333
- *
334
- * Returns true if the span should be created, false otherwise.
335
- *
336
- * Logic:
337
- * 1. If instrumentation disabled globally, return false
338
- * 2. Check ignore patterns - if any match, return false
339
- * 3. Check instrument patterns - if any match, return true
340
- * 4. Default: return true (fail-open - create span if no patterns match)
341
- */
342
- shouldInstrument(spanName) {
343
- if (!this.enabled) {
344
- return false;
345
- }
346
- for (const pattern of this.ignorePatterns) {
347
- if (pattern.regex.test(spanName)) {
348
- return false;
349
- }
350
- }
351
- for (const pattern of this.instrumentPatterns) {
352
- if (pattern.enabled && pattern.regex.test(spanName)) {
353
- return true;
354
- }
355
- }
356
- return true;
357
- }
358
- /**
359
- * Get statistics about pattern matching (for debugging/monitoring)
360
- */
361
- getStats() {
362
- return {
363
- enabled: this.enabled,
364
- ignorePatternCount: this.ignorePatterns.length,
365
- instrumentPatternCount: this.instrumentPatterns.filter((p) => p.enabled).length
366
- };
367
- }
368
- };
369
- var globalMatcher = null;
370
- function initializePatternMatcher(config) {
371
- globalMatcher = new PatternMatcher(config);
372
- }
373
- function shouldInstrumentSpan(spanName) {
374
- if (!globalMatcher) {
375
- return true;
376
- }
377
- return globalMatcher.shouldInstrument(spanName);
378
- }
379
- function getPatternMatcher() {
380
- return globalMatcher;
381
- }
382
- var Logger = class {
383
- constructor() {
384
- __publicField2(this, "level", "on");
385
- __publicField2(this, "hasLoggedMinimal", false);
386
- }
387
- /**
388
- * Set the logging level
389
- */
390
- setLevel(level) {
391
- this.level = level;
392
- this.hasLoggedMinimal = false;
393
- }
394
- /**
395
- * Get the current logging level
396
- */
397
- getLevel() {
398
- return this.level;
399
- }
400
- /**
401
- * Log a minimal initialization message (only shown once in minimal mode)
402
- */
403
- minimal(message) {
404
- if (this.level === "off") {
405
- return;
406
- }
407
- if (this.level === "minimal" && !this.hasLoggedMinimal) {
408
- console.log(message);
409
- this.hasLoggedMinimal = true;
410
- return;
411
- }
412
- if (this.level === "on") {
413
- console.log(message);
414
- }
415
- }
416
- /**
417
- * Log an informational message
418
- */
419
- log(...args) {
420
- if (this.level === "on") {
421
- console.log(...args);
422
- }
423
- }
424
- /**
425
- * Log a warning message (shown in minimal mode)
426
- */
427
- warn(...args) {
428
- if (this.level !== "off") {
429
- console.warn(...args);
430
- }
431
- }
432
- /**
433
- * Log an error message (shown in minimal mode)
434
- */
435
- error(...args) {
436
- if (this.level !== "off") {
437
- console.error(...args);
438
- }
439
- }
440
- /**
441
- * Check if full logging is enabled
442
- */
443
- isEnabled() {
444
- return this.level === "on";
445
- }
446
- /**
447
- * Check if minimal logging is enabled
448
- */
449
- isMinimal() {
450
- return this.level === "minimal";
451
- }
452
- /**
453
- * Check if logging is completely disabled
454
- */
455
- isDisabled() {
456
- return this.level === "off";
457
- }
458
- };
459
- var logger = new Logger();
460
-
461
- // src/core/span-processor.ts
462
- var PatternSpanProcessor = class {
463
- constructor(config, wrappedProcessor) {
464
- __publicField(this, "matcher");
465
- __publicField(this, "wrappedProcessor");
466
- this.matcher = new PatternMatcher(config);
467
- this.wrappedProcessor = wrappedProcessor;
468
- }
469
- /**
470
- * Called when a span is started
471
- *
472
- * We check if the span should be instrumented here. If not, we can mark it
473
- * to be dropped later in onEnd().
474
- */
475
- onStart(span, parentContext) {
476
- const spanName = span.name;
477
- if (this.matcher.shouldInstrument(spanName)) {
478
- this.wrappedProcessor.onStart(span, parentContext);
479
- }
480
- }
481
- /**
482
- * Called when a span is ended
483
- *
484
- * This is where we make the final decision on whether to export the span.
485
- */
486
- onEnd(span) {
487
- const spanName = span.name;
488
- if (this.matcher.shouldInstrument(spanName)) {
489
- this.wrappedProcessor.onEnd(span);
490
- }
491
- }
492
- /**
493
- * Shutdown the processor
494
- */
495
- async shutdown() {
496
- return this.wrappedProcessor.shutdown();
497
- }
498
- /**
499
- * Force flush any pending spans
500
- */
501
- async forceFlush() {
502
- return this.wrappedProcessor.forceFlush();
503
- }
504
- /**
505
- * Get the pattern matcher (for debugging/testing)
506
- */
507
- getPatternMatcher() {
508
- return this.matcher;
509
- }
510
- };
511
- var DEFAULT_OTLP_ENDPOINT = "http://localhost:4318/v1/traces";
512
- function createOtlpExporter(options = {}) {
513
- const endpoint = options.endpoint || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || DEFAULT_OTLP_ENDPOINT;
514
- const normalizedEndpoint = normalizeEndpoint(endpoint);
515
- const config = {
516
- url: normalizedEndpoint
517
- };
518
- if (options.headers) {
519
- config.headers = options.headers;
520
- }
521
- return new OTLPTraceExporter(config);
522
- }
523
- function normalizeEndpoint(endpoint) {
524
- try {
525
- const url = new URL(endpoint);
526
- if (!url.pathname || url.pathname === "/") {
527
- url.pathname = "/v1/traces";
528
- return url.toString();
529
- }
530
- return endpoint;
531
- } catch {
532
- return endpoint;
533
- }
534
- }
535
- function getOtlpEndpoint(options = {}) {
536
- const endpoint = options.endpoint || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || DEFAULT_OTLP_ENDPOINT;
537
- return normalizeEndpoint(endpoint);
538
- }
539
-
540
- // src/core/safe-exporter.ts
541
- var SafeSpanExporter = class {
542
- // Log errors max once per minute
543
- constructor(exporter) {
544
- __publicField(this, "exporter");
545
- __publicField(this, "errorCount", 0);
546
- __publicField(this, "lastErrorTime", 0);
547
- __publicField(this, "errorThrottleMs", 6e4);
548
- this.exporter = exporter;
549
- }
550
- /**
551
- * Export spans with error handling
552
- */
553
- export(spans, resultCallback) {
554
- try {
555
- this.exporter.export(spans, (result) => {
556
- if (result.code !== 0) {
557
- this.handleExportError(result.error);
558
- }
559
- resultCallback(result);
560
- });
561
- } catch (error) {
562
- this.handleExportError(error);
563
- resultCallback({
564
- code: 2,
565
- // FAILED
566
- error: error instanceof Error ? error : new Error(String(error))
567
- });
568
- }
569
- }
570
- /**
571
- * Shutdown with error handling
572
- */
573
- async shutdown() {
574
- try {
575
- await this.exporter.shutdown();
576
- } catch (error) {
577
- logger.error(
578
- "@atrim/instrumentation: Error during exporter shutdown (non-critical):",
579
- error instanceof Error ? error.message : String(error)
580
- );
581
- }
582
- }
583
- /**
584
- * Force flush with error handling
585
- */
586
- async forceFlush() {
587
- if (!this.exporter.forceFlush) {
588
- return;
589
- }
590
- try {
591
- await this.exporter.forceFlush();
592
- } catch (error) {
593
- this.handleExportError(error);
594
- }
595
- }
596
- /**
597
- * Handle export errors with throttling
598
- */
599
- handleExportError(error) {
600
- this.errorCount++;
601
- const now = Date.now();
602
- const shouldLog = now - this.lastErrorTime > this.errorThrottleMs;
603
- if (shouldLog) {
604
- const errorMessage = error instanceof Error ? error.message : String(error);
605
- if (this.isConnectionError(error)) {
606
- logger.warn(`@atrim/instrumentation: Unable to export spans - collector not available`);
607
- logger.warn(` Error: ${errorMessage}`);
608
- logger.warn(` Spans will be dropped. Ensure OTEL collector is running.`);
609
- } else {
610
- logger.error("@atrim/instrumentation: Span export failed:", errorMessage);
611
- }
612
- if (this.errorCount > 1) {
613
- logger.warn(` (${this.errorCount} errors total, throttled to 1/min)`);
614
- }
615
- this.lastErrorTime = now;
616
- this.errorCount = 0;
617
- }
618
- }
619
- /**
620
- * Check if error is a connection error (ECONNREFUSED, ENOTFOUND, etc.)
621
- */
622
- isConnectionError(error) {
623
- if (!error || typeof error !== "object") {
624
- return false;
625
- }
626
- const err = error;
627
- if (err.code === "ECONNREFUSED" || err.code === "ENOTFOUND" || err.code === "ETIMEDOUT") {
628
- return true;
629
- }
630
- if (Array.isArray(err.errors)) {
631
- return err.errors.every((e) => this.isConnectionError(e));
632
- }
633
- if (err.message) {
634
- const msg = err.message.toLowerCase();
635
- return msg.includes("econnrefused") || msg.includes("enotfound") || msg.includes("etimedout") || msg.includes("connection refused");
636
- }
637
- return false;
638
- }
639
- };
640
- var ConfigError2 = class extends Data.TaggedError("ConfigError") {
641
- };
642
- var ConfigUrlError2 = class extends Data.TaggedError("ConfigUrlError") {
643
- };
644
- var ConfigValidationError2 = class extends Data.TaggedError("ConfigValidationError") {
645
- };
646
- var ConfigFileError2 = class extends Data.TaggedError("ConfigFileError") {
647
- };
648
- var ServiceDetectionError2 = class extends Data.TaggedError("ServiceDetectionError") {
649
- };
650
- var InitializationError2 = class extends Data.TaggedError("InitializationError") {
651
- };
652
- var ExportError2 = class extends Data.TaggedError("ExportError") {
653
- };
654
- var ShutdownError2 = class extends Data.TaggedError("ShutdownError") {
655
- };
656
-
657
- // src/core/service-detector.ts
658
- var detectServiceInfo = Effect.gen(
659
- function* () {
660
- const envServiceName = process.env.OTEL_SERVICE_NAME;
661
- const envServiceVersion = process.env.OTEL_SERVICE_VERSION;
662
- if (envServiceName) {
663
- return {
664
- name: envServiceName,
665
- version: envServiceVersion
666
- };
667
- }
668
- const packageJsonPath = join(process.cwd(), "package.json");
669
- const packageJsonContent = yield* Effect.tryPromise({
670
- try: () => readFile(packageJsonPath, "utf-8"),
671
- catch: (error) => new ServiceDetectionError2({
672
- reason: `Failed to read package.json at ${packageJsonPath}`,
673
- cause: error
674
- })
675
- });
676
- let parsed;
677
- try {
678
- parsed = JSON.parse(packageJsonContent);
679
- } catch (error) {
680
- yield* Effect.fail(
681
- new ServiceDetectionError2({
682
- reason: "Invalid JSON in package.json",
683
- cause: error
684
- })
685
- );
686
- }
687
- if (typeof parsed === "object" && parsed !== null) {
688
- const packageJson = parsed;
689
- if (packageJson.name) {
690
- return {
691
- name: packageJson.name,
692
- version: envServiceVersion || packageJson.version
693
- };
694
- }
695
- }
696
- return yield* Effect.fail(
697
- new ServiceDetectionError2({
698
- reason: 'package.json exists but has no "name" field'
699
- })
700
- );
701
- }
702
- );
703
- var getServiceName = detectServiceInfo.pipe(
704
- Effect.map((info) => info.name),
705
- Effect.catchAll(() => Effect.succeed("unknown-service"))
706
- );
707
- var getServiceVersion = detectServiceInfo.pipe(
708
- Effect.map((info) => info.version),
709
- Effect.catchAll(() => Effect.succeed(void 0))
710
- );
711
- var getServiceInfoWithFallback = detectServiceInfo.pipe(
712
- Effect.catchAll(
713
- () => Effect.succeed({
714
- name: "unknown-service",
715
- version: process.env.OTEL_SERVICE_VERSION
716
- })
717
- )
718
- );
719
- async function detectServiceInfoAsync() {
720
- return Effect.runPromise(getServiceInfoWithFallback);
721
- }
722
- async function getServiceNameAsync() {
723
- return Effect.runPromise(getServiceName);
724
- }
725
- async function getServiceVersionAsync() {
726
- return Effect.runPromise(getServiceVersion);
727
- }
728
-
729
- // src/core/sdk-initializer.ts
730
- var sdkInstance = null;
731
- var initializationPromise = null;
732
- function buildHttpInstrumentationConfig(options, config, _otlpEndpoint) {
733
- const httpConfig = { enabled: true };
734
- const programmaticPatterns = options.http?.ignoreOutgoingUrls || [];
735
- const yamlPatterns = config.http?.ignore_outgoing_urls || [];
736
- const allOutgoingPatterns = [
737
- ...programmaticPatterns.map((p) => typeof p === "string" ? new RegExp(p) : p),
738
- ...yamlPatterns.map((p) => new RegExp(p))
739
- ];
740
- logger.log(`HTTP filtering: ${allOutgoingPatterns.length} outgoing patterns configured`);
741
- if (options.http?.ignoreOutgoingRequestHook) {
742
- httpConfig.ignoreOutgoingRequestHook = options.http.ignoreOutgoingRequestHook;
743
- } else if (allOutgoingPatterns.length > 0) {
744
- httpConfig.ignoreOutgoingRequestHook = (req) => {
745
- const hostname = req.hostname || req.host || "";
746
- const port = req.port || "";
747
- const protocol = req.protocol || "http:";
748
- const path = req.path || "";
749
- const portStr = port ? `:${port}` : "";
750
- const url = `${protocol}//${hostname}${portStr}${path}`;
751
- const matchesPattern = allOutgoingPatterns.some(
752
- (pattern) => pattern.test(url) || pattern.test(path)
753
- );
754
- return matchesPattern;
755
- };
756
- }
757
- const programmaticIncomingPatterns = options.http?.ignoreIncomingPaths || [];
758
- const yamlIncomingPatterns = config.http?.ignore_incoming_paths || [];
759
- const allIncomingPatterns = [
760
- ...programmaticIncomingPatterns.map((p) => typeof p === "string" ? new RegExp(p) : p),
761
- ...yamlIncomingPatterns.map((p) => new RegExp(p))
762
- ];
763
- if (options.http?.ignoreIncomingRequestHook) {
764
- httpConfig.ignoreIncomingRequestHook = options.http.ignoreIncomingRequestHook;
765
- } else if (allIncomingPatterns.length > 0) {
766
- httpConfig.ignoreIncomingRequestHook = (req) => {
767
- const path = req.url || "";
768
- return allIncomingPatterns.some((pattern) => pattern.test(path));
769
- };
770
- }
771
- if (options.http?.requireParentForOutgoingSpans !== void 0 || config.http?.require_parent_for_outgoing_spans !== void 0) {
772
- httpConfig.requireParentforOutgoingSpans = options.http?.requireParentForOutgoingSpans ?? config.http?.require_parent_for_outgoing_spans ?? false;
773
- }
774
- return httpConfig;
775
- }
776
- function buildUndiciInstrumentationConfig(options, config, _otlpEndpoint) {
777
- const undiciConfig = { enabled: true };
778
- const programmaticPatterns = options.http?.ignoreOutgoingUrls || [];
779
- const yamlPatterns = config.http?.ignore_outgoing_urls || [];
780
- const allPatterns = [
781
- ...programmaticPatterns.map((p) => typeof p === "string" ? new RegExp(p) : p),
782
- ...yamlPatterns.map((p) => new RegExp(p))
783
- ];
784
- if (allPatterns.length > 0) {
785
- undiciConfig.ignoreRequestHook = (request) => {
786
- const origin = request.origin;
787
- const path = request.path;
788
- const url = `${origin}${path}`;
789
- const matchesPattern = allPatterns.some((pattern) => pattern.test(url) || pattern.test(path));
790
- return matchesPattern;
791
- };
792
- }
793
- return undiciConfig;
794
- }
795
- function isEffectProject() {
796
- try {
797
- __require.resolve("effect");
798
- return true;
799
- } catch {
800
- return false;
801
- }
802
- }
803
- function shouldEnableAutoInstrumentation(explicitValue, hasWebFramework) {
804
- if (explicitValue !== void 0) {
805
- return explicitValue;
806
- }
807
- const isEffect = isEffectProject();
808
- if (isEffect && !hasWebFramework) {
809
- logger.log("@atrim/instrumentation: Detected Effect-TS without web framework");
810
- logger.log(" - Auto-instrumentation disabled by default");
811
- logger.log(" - Effect.withSpan() will create spans");
812
- return false;
813
- }
814
- return true;
815
- }
816
- function hasWebFrameworkInstalled() {
817
- const frameworks = ["express", "fastify", "koa", "@hono/node-server", "restify"];
818
- for (const framework of frameworks) {
819
- try {
820
- __require.resolve(framework);
821
- return true;
822
- } catch {
823
- }
824
- }
825
- return false;
826
- }
827
- function isTracingAlreadyInitialized() {
828
- try {
829
- const provider = trace.getTracerProvider();
830
- const providerWithDelegate = provider;
831
- const delegate = providerWithDelegate._delegate || providerWithDelegate.getDelegate?.();
832
- if (delegate) {
833
- const delegateName = delegate.constructor.name;
834
- if (!delegateName.includes("Noop")) {
835
- return true;
836
- }
837
- }
838
- const providerWithProps = provider;
839
- const hasResource = providerWithProps.resource !== void 0;
840
- const hasActiveSpanProcessor = providerWithProps.activeSpanProcessor !== void 0;
841
- const hasTracers = providerWithProps._tracers !== void 0;
842
- return hasResource || hasActiveSpanProcessor || hasTracers;
843
- } catch {
844
- return false;
845
- }
846
- }
847
- async function initializeSdk(options = {}) {
848
- if (sdkInstance) {
849
- logger.warn("@atrim/instrumentation: SDK already initialized. Returning existing instance.");
850
- return sdkInstance;
851
- }
852
- if (initializationPromise) {
853
- logger.log(
854
- "@atrim/instrumentation: SDK already initialized, waiting for initialization to complete..."
855
- );
856
- return initializationPromise;
857
- }
858
- initializationPromise = performInitialization(options);
859
- try {
860
- const result = await initializationPromise;
861
- return result;
862
- } finally {
863
- initializationPromise = null;
864
- }
865
- }
866
- async function performInitialization(options) {
867
- const config = await loadConfig(options);
868
- const loggingLevel = config.instrumentation.logging || "on";
869
- logger.setLevel(loggingLevel);
870
- const alreadyInitialized = isTracingAlreadyInitialized();
871
- if (alreadyInitialized) {
872
- logger.log("@atrim/instrumentation: Detected existing OpenTelemetry initialization.");
873
- logger.log(" - Skipping NodeSDK setup");
874
- logger.log(" - Setting up pattern-based filtering only");
875
- logger.log("");
876
- initializePatternMatcher(config);
877
- logger.log("@atrim/instrumentation: Pattern filtering initialized");
878
- logger.log(" \u26A0\uFE0F Note: Pattern filtering will only work with manual spans");
879
- logger.log(" \u26A0\uFE0F Auto-instrumentation must be configured separately");
880
- logger.log("");
881
- return null;
882
- }
883
- const serviceInfo = await detectServiceInfoAsync();
884
- const serviceName = options.serviceName || serviceInfo.name;
885
- const serviceVersion = options.serviceVersion || serviceInfo.version;
886
- const rawExporter = createOtlpExporter(options.otlp);
887
- const exporter = new SafeSpanExporter(rawExporter);
888
- const useSimpleProcessor = process.env.NODE_ENV === "test" || process.env.OTEL_USE_SIMPLE_PROCESSOR === "true";
889
- const baseProcessor = useSimpleProcessor ? new SimpleSpanProcessor(exporter) : new BatchSpanProcessor(exporter);
890
- const patternProcessor = new PatternSpanProcessor(config, baseProcessor);
891
- const instrumentations = [];
892
- const hasWebFramework = hasWebFrameworkInstalled();
893
- const enableAutoInstrumentation = shouldEnableAutoInstrumentation(
894
- options.autoInstrument,
895
- hasWebFramework
896
- );
897
- if (enableAutoInstrumentation) {
898
- options.otlp?.endpoint || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318/v1/traces";
899
- const httpConfig = buildHttpInstrumentationConfig(options, config);
900
- const undiciConfig = buildUndiciInstrumentationConfig(options, config);
901
- instrumentations.push(
902
- ...getNodeAutoInstrumentations({
903
- // Enable HTTP instrumentation with filtering (for http/https modules)
904
- "@opentelemetry/instrumentation-http": httpConfig,
905
- // Enable undici instrumentation with filtering (for fetch API)
906
- "@opentelemetry/instrumentation-undici": undiciConfig,
907
- // Enable web framework instrumentations
908
- "@opentelemetry/instrumentation-express": { enabled: true },
909
- "@opentelemetry/instrumentation-fastify": { enabled: true },
910
- "@opentelemetry/instrumentation-koa": { enabled: true },
911
- // Disable noisy instrumentations by default
912
- "@opentelemetry/instrumentation-fs": { enabled: false },
913
- "@opentelemetry/instrumentation-dns": { enabled: false }
914
- })
915
- );
916
- logger.log(`Auto-instrumentation: ${instrumentations.length} instrumentations enabled`);
917
- }
918
- if (options.instrumentations) {
919
- instrumentations.push(...options.instrumentations);
920
- }
921
- if (!enableAutoInstrumentation && instrumentations.length === 0) {
922
- const wasExplicit = options.autoInstrument === false;
923
- const detectionMessage = wasExplicit ? "@atrim/instrumentation: Auto-instrumentation: disabled" : "@atrim/instrumentation: Pure Effect-TS app detected (auto-detected)";
924
- logger.log(detectionMessage);
925
- logger.log(" - Skipping NodeSDK setup");
926
- logger.log(" - Pattern matching configured from instrumentation.yaml");
927
- if (!wasExplicit) {
928
- logger.log(" - Use EffectInstrumentationLive for tracing");
929
- }
930
- logger.log("");
931
- initializePatternMatcher(config);
932
- return null;
933
- }
934
- const sdkConfig = {
935
- spanProcessor: patternProcessor,
936
- serviceName,
937
- ...serviceVersion && { serviceVersion },
938
- instrumentations,
939
- // Allow advanced overrides
940
- ...options.sdk
941
- };
942
- const sdk = new NodeSDK(sdkConfig);
943
- sdk.start();
944
- sdkInstance = sdk;
945
- if (!options.disableAutoShutdown) {
946
- registerShutdownHandlers(sdk);
947
- }
948
- logInitialization(config, serviceName, serviceVersion, options, enableAutoInstrumentation);
949
- return sdk;
950
- }
951
- function getSdkInstance() {
952
- return sdkInstance;
953
- }
954
- async function shutdownSdk() {
955
- if (!sdkInstance) {
956
- return;
957
- }
958
- await sdkInstance.shutdown();
959
- sdkInstance = null;
960
- }
961
- function resetSdk() {
962
- sdkInstance = null;
963
- initializationPromise = null;
964
- }
965
- function registerShutdownHandlers(sdk) {
966
- const shutdown = async (signal) => {
967
- logger.log(`
968
- @atrim/instrumentation: Received ${signal}, shutting down gracefully...`);
969
- try {
970
- await sdk.shutdown();
971
- logger.log("@atrim/instrumentation: Shutdown complete");
972
- process.exit(0);
973
- } catch (error) {
974
- logger.error(
975
- "@atrim/instrumentation: Error during shutdown:",
976
- error instanceof Error ? error.message : String(error)
977
- );
978
- process.exit(1);
979
- }
980
- };
981
- process.on("SIGTERM", () => shutdown("SIGTERM"));
982
- process.on("SIGINT", () => shutdown("SIGINT"));
983
- process.on("uncaughtException", async (error) => {
984
- logger.error("@atrim/instrumentation: Uncaught exception:", error);
985
- await sdk.shutdown();
986
- process.exit(1);
987
- });
988
- process.on("unhandledRejection", async (reason) => {
989
- logger.error("@atrim/instrumentation: Unhandled rejection:", reason);
990
- await sdk.shutdown();
991
- process.exit(1);
992
- });
993
- }
994
- function logInitialization(config, serviceName, serviceVersion, options, autoInstrumentEnabled) {
995
- logger.minimal("@atrim/instrumentation: SDK initialized successfully");
996
- logger.log(` - Service: ${serviceName}${serviceVersion ? ` v${serviceVersion}` : ""}`);
997
- if (config.instrumentation.enabled) {
998
- const instrumentCount = config.instrumentation.instrument_patterns.filter(
999
- (p) => p.enabled !== false
1000
- ).length;
1001
- const ignoreCount = config.instrumentation.ignore_patterns.length;
1002
- logger.log(` - Pattern filtering: enabled`);
1003
- logger.log(` - Instrument patterns: ${instrumentCount}`);
1004
- logger.log(` - Ignore patterns: ${ignoreCount}`);
1005
- } else {
1006
- logger.log(` - Pattern filtering: disabled`);
1007
- }
1008
- const autoInstrumentLabel = autoInstrumentEnabled ? "enabled" : "disabled";
1009
- const autoDetected = options.autoInstrument === void 0 ? " (auto-detected)" : "";
1010
- logger.log(` - Auto-instrumentation: ${autoInstrumentLabel}${autoDetected}`);
1011
- if (options.instrumentations && options.instrumentations.length > 0) {
1012
- logger.log(` - Custom instrumentations: ${options.instrumentations.length}`);
1013
- }
1014
- const endpoint = options.otlp?.endpoint || process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318/v1/traces";
1015
- logger.log(` - OTLP endpoint: ${endpoint}`);
1016
- logger.log("");
1017
- }
1018
-
1019
- // src/api.ts
1020
- async function initializeInstrumentation(options = {}) {
1021
- const sdk = await initializeSdk(options);
1022
- if (sdk) {
1023
- const config = await loadConfig(options);
1024
- initializePatternMatcher(config);
1025
- }
1026
- return sdk;
1027
- }
1028
- async function initializePatternMatchingOnly(options = {}) {
1029
- const config = await loadConfig(options);
1030
- initializePatternMatcher(config);
1031
- logger.log("@atrim/instrumentation: Pattern matching initialized (legacy mode)");
1032
- logger.log(
1033
- " Note: NodeSDK is not initialized. Use initializeInstrumentation() for complete setup."
1034
- );
1035
- }
1036
- var initializeInstrumentationEffect = (options = {}) => Effect.gen(function* () {
1037
- const sdk = yield* Effect.tryPromise({
1038
- try: () => initializeSdk(options),
1039
- catch: (error) => new InitializationError2({
1040
- reason: "SDK initialization failed",
1041
- cause: error
1042
- })
1043
- });
1044
- if (sdk) {
1045
- yield* Effect.tryPromise({
1046
- try: () => loadConfig(options),
1047
- catch: (error) => new ConfigError2({
1048
- reason: "Failed to load config for pattern matcher",
1049
- cause: error
1050
- })
1051
- }).pipe(
1052
- Effect.tap(
1053
- (config) => Effect.sync(() => {
1054
- initializePatternMatcher(config);
1055
- })
1056
- )
1057
- );
1058
- }
1059
- return sdk;
1060
- });
1061
- var initializePatternMatchingOnlyEffect = (options = {}) => Effect.gen(function* () {
1062
- const config = yield* Effect.tryPromise({
1063
- try: () => loadConfig(options),
1064
- catch: (error) => new ConfigError2({
1065
- reason: "Failed to load configuration",
1066
- cause: error
1067
- })
1068
- });
1069
- yield* Effect.sync(() => {
1070
- initializePatternMatcher(config);
1071
- logger.log("@atrim/instrumentation: Pattern matching initialized (legacy mode)");
1072
- logger.log(
1073
- " Note: NodeSDK is not initialized. Use initializeInstrumentation() for complete setup."
1074
- );
1075
- });
1076
- });
1077
-
1078
- // src/integrations/standard/span-helpers.ts
1079
- function setSpanAttributes(span, attributes) {
1080
- for (const [key, value] of Object.entries(attributes)) {
1081
- span.setAttribute(key, value);
1082
- }
1083
- }
1084
- function recordException(span, error, context) {
1085
- span.recordException(error);
1086
- if (context) {
1087
- for (const [key, value] of Object.entries(context)) {
1088
- span.setAttribute(`error.${key}`, value);
1089
- }
1090
- }
1091
- }
1092
- function markSpanSuccess(span) {
1093
- span.setStatus({ code: 1 });
1094
- }
1095
- function markSpanError(span, message) {
1096
- if (message !== void 0) {
1097
- span.setStatus({
1098
- code: 2,
1099
- // SpanStatusCode.ERROR = 2
1100
- message
1101
- });
1102
- } else {
1103
- span.setStatus({
1104
- code: 2
1105
- // SpanStatusCode.ERROR = 2
1106
- });
1107
- }
1108
- }
1109
- function annotateHttpRequest(span, method, url, statusCode) {
1110
- span.setAttribute("http.method", method);
1111
- span.setAttribute("http.url", url);
1112
- if (statusCode !== void 0) {
1113
- span.setAttribute("http.status_code", statusCode);
1114
- if (statusCode >= 400) {
1115
- markSpanError(span, `HTTP ${statusCode}`);
1116
- } else {
1117
- markSpanSuccess(span);
1118
- }
1119
- }
1120
- }
1121
- function annotateDbQuery(span, system, statement, table) {
1122
- span.setAttribute("db.system", system);
1123
- span.setAttribute("db.statement", statement);
1124
- if (table) {
1125
- span.setAttribute("db.table", table);
1126
- }
1127
- }
1128
- function annotateCacheOperation(span, operation, key, hit) {
1129
- span.setAttribute("cache.operation", operation);
1130
- span.setAttribute("cache.key", key);
1131
- if (hit !== void 0) {
1132
- span.setAttribute("cache.hit", hit);
1133
- }
1134
- }
1135
-
1136
- // src/core/test-utils.ts
1137
- function suppressShutdownErrors() {
1138
- if (!process.env.CI && process.env.NODE_ENV !== "test") {
1139
- return;
1140
- }
1141
- const isHarmlessConnectionError = (error) => {
1142
- if (!error || typeof error !== "object") {
1143
- return false;
1144
- }
1145
- const nodeError = error;
1146
- if (nodeError.code === "ECONNREFUSED") {
1147
- return true;
1148
- }
1149
- if (nodeError.errors && Array.isArray(nodeError.errors) && nodeError.errors.length > 0 && nodeError.errors.every((e) => e?.code === "ECONNREFUSED")) {
1150
- return true;
1151
- }
1152
- return false;
1153
- };
1154
- process.on("uncaughtException", (error) => {
1155
- if (isHarmlessConnectionError(error)) {
1156
- console.log("\u{1F4E4} Export failed (collector stopped) - this is expected in tests");
1157
- return;
1158
- }
1159
- console.error("Uncaught exception:", error);
1160
- process.exit(1);
1161
- });
1162
- process.on("unhandledRejection", (reason) => {
1163
- if (isHarmlessConnectionError(reason)) {
1164
- console.log("\u{1F4E4} Export failed (collector stopped) - this is expected in tests");
1165
- return;
1166
- }
1167
- console.error("Unhandled rejection:", reason);
1168
- process.exit(1);
1169
- });
1170
- }
1171
-
1172
- export { ConfigError2 as ConfigError, ConfigFileError2 as ConfigFileError, ConfigUrlError2 as ConfigUrlError, ConfigValidationError2 as ConfigValidationError, ExportError2 as ExportError, InitializationError2 as InitializationError, PatternMatcher, PatternSpanProcessor, ServiceDetectionError2 as ServiceDetectionError, ShutdownError2 as ShutdownError, annotateCacheOperation, annotateDbQuery, annotateHttpRequest, createOtlpExporter, detectServiceInfoAsync as detectServiceInfo, detectServiceInfo as detectServiceInfoEffect, getOtlpEndpoint, getPatternMatcher, getSdkInstance, getServiceInfoWithFallback, getServiceNameAsync as getServiceName, getServiceName as getServiceNameEffect, getServiceVersionAsync as getServiceVersion, getServiceVersion as getServiceVersionEffect, initializeInstrumentation, initializeInstrumentationEffect, initializePatternMatchingOnly, initializePatternMatchingOnlyEffect, loadConfig, markSpanError, markSpanSuccess, recordException, resetSdk, setSpanAttributes, shouldInstrumentSpan, shutdownSdk, suppressShutdownErrors };
1173
- //# sourceMappingURL=index.js.map
1174
- //# sourceMappingURL=index.js.map