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