@atrim/instrument-node 0.7.0 → 0.7.1-dev.14fdea7.20260108220010

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,1066 @@
1
+ import { Data, Context, Effect, Layer, FiberRef, Option, Supervisor, FiberRefs, Exit } from 'effect';
2
+ import * as OtelApi from '@opentelemetry/api';
3
+ import { BasicTracerProvider, SimpleSpanProcessor, BatchSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';
4
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
5
+ import { resourceFromAttributes } from '@opentelemetry/resources';
6
+ import { ATTR_SERVICE_VERSION, ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
7
+ import { FileSystem } from '@effect/platform/FileSystem';
8
+ import * as HttpClient from '@effect/platform/HttpClient';
9
+ import * as HttpClientRequest from '@effect/platform/HttpClientRequest';
10
+ import { parse } from 'yaml';
11
+ import { z } from 'zod';
12
+ import * as path from 'path';
13
+
14
+ var __defProp = Object.defineProperty;
15
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
16
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
17
+ var __defProp2 = Object.defineProperty;
18
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
19
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+ var PatternConfigSchema = z.object({
21
+ pattern: z.string(),
22
+ enabled: z.boolean().optional(),
23
+ description: z.string().optional()
24
+ });
25
+ var AutoIsolationConfigSchema = z.object({
26
+ // Global enable/disable for auto-isolation
27
+ enabled: z.boolean().default(false),
28
+ // Which operators to auto-isolate
29
+ operators: z.object({
30
+ fiberset_run: z.boolean().default(true),
31
+ effect_fork: z.boolean().default(true),
32
+ effect_fork_daemon: z.boolean().default(true),
33
+ effect_fork_in: z.boolean().default(false)
34
+ }).default({}),
35
+ // Virtual parent tracking configuration
36
+ tracking: z.object({
37
+ use_span_links: z.boolean().default(true),
38
+ use_attributes: z.boolean().default(true),
39
+ capture_logical_parent: z.boolean().default(true)
40
+ }).default({}),
41
+ // Span categorization
42
+ attributes: z.object({
43
+ category: z.string().default("background_task"),
44
+ add_metadata: z.boolean().default(true)
45
+ }).default({})
46
+ });
47
+ var SpanNamingRuleSchema = z.object({
48
+ // Match criteria (all specified criteria must match)
49
+ match: z.object({
50
+ // Regex pattern to match file path
51
+ file: z.string().optional(),
52
+ // Regex pattern to match function name
53
+ function: z.string().optional(),
54
+ // Regex pattern to match module name
55
+ module: z.string().optional()
56
+ }),
57
+ // Span name template with variables:
58
+ // {fiber_id} - Fiber ID
59
+ // {function} - Function name
60
+ // {module} - Module name
61
+ // {file} - File path
62
+ // {line} - Line number
63
+ // {operator} - Effect operator (gen, all, forEach, etc.)
64
+ // {match:field:N} - Captured regex group from match
65
+ name: z.string()
66
+ });
67
+ var AutoInstrumentationConfigSchema = z.object({
68
+ // Enable/disable auto-instrumentation
69
+ enabled: z.boolean().default(false),
70
+ // Tracing granularity
71
+ // - 'fiber': Trace at fiber creation (recommended, lower overhead)
72
+ // - 'operator': Trace each Effect operator (higher granularity, more overhead)
73
+ granularity: z.enum(["fiber", "operator"]).default("fiber"),
74
+ // Smart span naming configuration
75
+ span_naming: z.object({
76
+ // Default span name template when no rules match
77
+ default: z.string().default("effect.fiber.{fiber_id}"),
78
+ // Infer span names from source code (requires stack trace parsing)
79
+ // Adds ~50-100μs overhead per fiber
80
+ infer_from_source: z.boolean().default(true),
81
+ // Naming rules (first match wins)
82
+ rules: z.array(SpanNamingRuleSchema).default([])
83
+ }).default({}),
84
+ // Pattern-based filtering
85
+ filter: z.object({
86
+ // Only trace spans matching these patterns (empty = trace all)
87
+ include: z.array(z.string()).default([]),
88
+ // Never trace spans matching these patterns
89
+ exclude: z.array(z.string()).default([])
90
+ }).default({}),
91
+ // Performance controls
92
+ performance: z.object({
93
+ // Sample rate (0.0 - 1.0)
94
+ sampling_rate: z.number().min(0).max(1).default(1),
95
+ // Skip fibers shorter than this duration (e.g., "10ms", "100 millis")
96
+ min_duration: z.string().default("0ms"),
97
+ // Maximum concurrent traced fibers (0 = unlimited)
98
+ max_concurrent: z.number().default(0)
99
+ }).default({}),
100
+ // Automatic metadata extraction
101
+ metadata: z.object({
102
+ // Extract Effect fiber information
103
+ fiber_info: z.boolean().default(true),
104
+ // Extract source location (file:line)
105
+ source_location: z.boolean().default(true),
106
+ // Extract parent fiber information
107
+ parent_fiber: z.boolean().default(true)
108
+ }).default({})
109
+ });
110
+ var HttpFilteringConfigSchema = z.object({
111
+ // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)
112
+ ignore_outgoing_urls: z.array(z.string()).optional(),
113
+ // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)
114
+ ignore_incoming_paths: z.array(z.string()).optional(),
115
+ // Require parent span for outgoing requests (prevents root spans for HTTP calls)
116
+ require_parent_for_outgoing_spans: z.boolean().optional(),
117
+ // Trace context propagation configuration
118
+ // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)
119
+ propagate_trace_context: z.object({
120
+ // Strategy for trace propagation
121
+ // - "all": Propagate to all cross-origin requests (may cause CORS errors)
122
+ // - "none": Never propagate trace headers
123
+ // - "same-origin": Only propagate to same-origin requests (default, safe)
124
+ // - "patterns": Propagate based on include_urls patterns
125
+ strategy: z.enum(["all", "none", "same-origin", "patterns"]).default("same-origin"),
126
+ // URL patterns to include when strategy is "patterns"
127
+ // Supports regex patterns (e.g., "^https://api\\.myapp\\.com")
128
+ include_urls: z.array(z.string()).optional()
129
+ }).optional()
130
+ });
131
+ var ExporterConfigSchema = z.object({
132
+ // Exporter type: 'otlp' | 'console' | 'none'
133
+ // - 'otlp': Export to OTLP endpoint (production)
134
+ // - 'console': Log spans to console (development)
135
+ // - 'none': No export (disable tracing)
136
+ type: z.enum(["otlp", "console", "none"]).default("otlp"),
137
+ // OTLP endpoint URL (for type: otlp)
138
+ // Defaults to OTEL_EXPORTER_OTLP_ENDPOINT env var or http://localhost:4318
139
+ endpoint: z.string().optional(),
140
+ // Span processor type
141
+ // - 'batch': Batch spans for export (production, lower overhead)
142
+ // - 'simple': Export immediately (development, no batching delay)
143
+ processor: z.enum(["batch", "simple"]).default("batch"),
144
+ // Batch processor settings (for processor: batch)
145
+ batch: z.object({
146
+ // Max time to wait before exporting (milliseconds)
147
+ scheduled_delay_millis: z.number().default(1e3),
148
+ // Max batch size
149
+ max_export_batch_size: z.number().default(100)
150
+ }).optional()
151
+ });
152
+ var InstrumentationConfigSchema = z.object({
153
+ version: z.string(),
154
+ instrumentation: z.object({
155
+ enabled: z.boolean(),
156
+ description: z.string().optional(),
157
+ logging: z.enum(["on", "off", "minimal"]).optional().default("on"),
158
+ instrument_patterns: z.array(PatternConfigSchema),
159
+ ignore_patterns: z.array(PatternConfigSchema)
160
+ }),
161
+ effect: z.object({
162
+ // Enable/disable Effect tracing entirely
163
+ // When false, EffectInstrumentationLive returns Layer.empty
164
+ enabled: z.boolean().default(true),
165
+ // Exporter mode (legacy - use exporter.type instead):
166
+ // - "unified": Use global TracerProvider from Node SDK (recommended, enables filtering)
167
+ // - "standalone": Use Effect's own OTLP exporter (bypasses Node SDK filtering)
168
+ exporter: z.enum(["unified", "standalone"]).default("unified"),
169
+ // Exporter configuration (for auto-instrumentation)
170
+ exporter_config: ExporterConfigSchema.optional(),
171
+ auto_extract_metadata: z.boolean(),
172
+ auto_isolation: AutoIsolationConfigSchema.optional(),
173
+ // Auto-instrumentation: automatic tracing of all Effect fibers
174
+ auto_instrumentation: AutoInstrumentationConfigSchema.optional()
175
+ }).optional(),
176
+ http: HttpFilteringConfigSchema.optional()
177
+ });
178
+ var defaultConfig = {
179
+ version: "1.0",
180
+ instrumentation: {
181
+ enabled: true,
182
+ logging: "on",
183
+ description: "Default instrumentation configuration",
184
+ instrument_patterns: [
185
+ { pattern: "^app\\.", enabled: true, description: "Application operations" },
186
+ { pattern: "^http\\.server\\.", enabled: true, description: "HTTP server operations" },
187
+ { pattern: "^http\\.client\\.", enabled: true, description: "HTTP client operations" }
188
+ ],
189
+ ignore_patterns: [
190
+ { pattern: "^test\\.", description: "Test utilities" },
191
+ { pattern: "^internal\\.", description: "Internal operations" },
192
+ { pattern: "^health\\.", description: "Health checks" }
193
+ ]
194
+ },
195
+ effect: {
196
+ enabled: true,
197
+ exporter: "unified",
198
+ auto_extract_metadata: true
199
+ }
200
+ };
201
+ function parseAndValidateConfig(content) {
202
+ let parsed;
203
+ if (typeof content === "string") {
204
+ parsed = parse(content);
205
+ } else {
206
+ parsed = content;
207
+ }
208
+ return InstrumentationConfigSchema.parse(parsed);
209
+ }
210
+ (class extends Data.TaggedError("ConfigError") {
211
+ get message() {
212
+ return this.reason;
213
+ }
214
+ });
215
+ var ConfigUrlError = class extends Data.TaggedError("ConfigUrlError") {
216
+ get message() {
217
+ return this.reason;
218
+ }
219
+ };
220
+ var ConfigValidationError = class extends Data.TaggedError("ConfigValidationError") {
221
+ get message() {
222
+ return this.reason;
223
+ }
224
+ };
225
+ var ConfigFileError = class extends Data.TaggedError("ConfigFileError") {
226
+ get message() {
227
+ return this.reason;
228
+ }
229
+ };
230
+ (class extends Data.TaggedError("ServiceDetectionError") {
231
+ get message() {
232
+ return this.reason;
233
+ }
234
+ });
235
+ (class extends Data.TaggedError("InitializationError") {
236
+ get message() {
237
+ return this.reason;
238
+ }
239
+ });
240
+ (class extends Data.TaggedError("ExportError") {
241
+ get message() {
242
+ return this.reason;
243
+ }
244
+ });
245
+ (class extends Data.TaggedError("ShutdownError") {
246
+ get message() {
247
+ return this.reason;
248
+ }
249
+ });
250
+ var SECURITY_DEFAULTS = {
251
+ maxConfigSize: 1e6,
252
+ // 1MB
253
+ requestTimeout: 5e3
254
+ // 5 seconds
255
+ };
256
+ var ConfigLoader = class extends Context.Tag("ConfigLoader")() {
257
+ };
258
+ var parseYamlContent = (content, uri) => Effect.gen(function* () {
259
+ const parsed = yield* Effect.try({
260
+ try: () => parse(content),
261
+ catch: (error) => new ConfigValidationError({
262
+ reason: uri ? `Failed to parse YAML from ${uri}` : "Failed to parse YAML",
263
+ cause: error
264
+ })
265
+ });
266
+ return yield* Effect.try({
267
+ try: () => InstrumentationConfigSchema.parse(parsed),
268
+ catch: (error) => new ConfigValidationError({
269
+ reason: uri ? `Invalid configuration schema from ${uri}` : "Invalid configuration schema",
270
+ cause: error
271
+ })
272
+ });
273
+ });
274
+ var loadFromFileWithFs = (fs, path2, uri) => Effect.gen(function* () {
275
+ const content = yield* fs.readFileString(path2).pipe(
276
+ Effect.mapError(
277
+ (error) => new ConfigFileError({
278
+ reason: `Failed to read config file at ${uri}`,
279
+ cause: error
280
+ })
281
+ )
282
+ );
283
+ if (content.length > SECURITY_DEFAULTS.maxConfigSize) {
284
+ return yield* Effect.fail(
285
+ new ConfigFileError({
286
+ reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
287
+ })
288
+ );
289
+ }
290
+ return yield* parseYamlContent(content, uri);
291
+ });
292
+ var loadFromHttpWithClient = (client, url) => Effect.scoped(
293
+ Effect.gen(function* () {
294
+ if (url.startsWith("http://")) {
295
+ return yield* Effect.fail(
296
+ new ConfigUrlError({
297
+ reason: "Insecure protocol: only HTTPS URLs are allowed"
298
+ })
299
+ );
300
+ }
301
+ const request = HttpClientRequest.get(url).pipe(
302
+ HttpClientRequest.setHeaders({
303
+ Accept: "application/yaml, text/yaml, application/x-yaml"
304
+ })
305
+ );
306
+ const response = yield* client.execute(request).pipe(
307
+ Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),
308
+ Effect.mapError((error) => {
309
+ if (error._tag === "TimeoutException") {
310
+ return new ConfigUrlError({
311
+ reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`
312
+ });
313
+ }
314
+ return new ConfigUrlError({
315
+ reason: `Failed to load config from URL: ${url}`,
316
+ cause: error
317
+ });
318
+ })
319
+ );
320
+ if (response.status >= 400) {
321
+ return yield* Effect.fail(
322
+ new ConfigUrlError({
323
+ reason: `HTTP ${response.status} from ${url}`
324
+ })
325
+ );
326
+ }
327
+ const text = yield* response.text.pipe(
328
+ Effect.mapError(
329
+ (error) => new ConfigUrlError({
330
+ reason: `Failed to read response body from ${url}`,
331
+ cause: error
332
+ })
333
+ )
334
+ );
335
+ if (text.length > SECURITY_DEFAULTS.maxConfigSize) {
336
+ return yield* Effect.fail(
337
+ new ConfigUrlError({
338
+ reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
339
+ })
340
+ );
341
+ }
342
+ return yield* parseYamlContent(text, url);
343
+ })
344
+ );
345
+ var makeConfigLoader = Effect.gen(function* () {
346
+ const fs = yield* Effect.serviceOption(FileSystem);
347
+ const http = yield* HttpClient.HttpClient;
348
+ const loadFromUriUncached = (uri) => Effect.gen(function* () {
349
+ if (uri.startsWith("file://")) {
350
+ const path2 = uri.slice(7);
351
+ if (fs._tag === "None") {
352
+ return yield* Effect.fail(
353
+ new ConfigFileError({
354
+ reason: "FileSystem not available (browser environment?)",
355
+ cause: { uri }
356
+ })
357
+ );
358
+ }
359
+ return yield* loadFromFileWithFs(fs.value, path2, uri);
360
+ }
361
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
362
+ return yield* loadFromHttpWithClient(http, uri);
363
+ }
364
+ if (fs._tag === "Some") {
365
+ return yield* loadFromFileWithFs(fs.value, uri, uri);
366
+ } else {
367
+ return yield* loadFromHttpWithClient(http, uri);
368
+ }
369
+ });
370
+ const loadFromUriCached = yield* Effect.cachedFunction(loadFromUriUncached);
371
+ return ConfigLoader.of({
372
+ loadFromUri: loadFromUriCached,
373
+ loadFromInline: (content) => Effect.gen(function* () {
374
+ if (typeof content === "string") {
375
+ return yield* parseYamlContent(content);
376
+ }
377
+ return yield* Effect.try({
378
+ try: () => InstrumentationConfigSchema.parse(content),
379
+ catch: (error) => new ConfigValidationError({
380
+ reason: "Invalid configuration schema",
381
+ cause: error
382
+ })
383
+ });
384
+ })
385
+ });
386
+ });
387
+ Layer.effect(ConfigLoader, makeConfigLoader);
388
+ var Logger = class {
389
+ constructor() {
390
+ __publicField2(this, "level", "on");
391
+ __publicField2(this, "hasLoggedMinimal", false);
392
+ }
393
+ /**
394
+ * Set the logging level
395
+ */
396
+ setLevel(level) {
397
+ this.level = level;
398
+ this.hasLoggedMinimal = false;
399
+ }
400
+ /**
401
+ * Get the current logging level
402
+ */
403
+ getLevel() {
404
+ return this.level;
405
+ }
406
+ /**
407
+ * Log a minimal initialization message (only shown once in minimal mode)
408
+ */
409
+ minimal(message) {
410
+ if (this.level === "off") {
411
+ return;
412
+ }
413
+ if (this.level === "minimal" && !this.hasLoggedMinimal) {
414
+ console.log(message);
415
+ this.hasLoggedMinimal = true;
416
+ return;
417
+ }
418
+ if (this.level === "on") {
419
+ console.log(message);
420
+ }
421
+ }
422
+ /**
423
+ * Log an informational message
424
+ */
425
+ log(...args) {
426
+ if (this.level === "on") {
427
+ console.log(...args);
428
+ }
429
+ }
430
+ /**
431
+ * Log a warning message (shown in minimal mode)
432
+ */
433
+ warn(...args) {
434
+ if (this.level !== "off") {
435
+ console.warn(...args);
436
+ }
437
+ }
438
+ /**
439
+ * Log an error message (shown in minimal mode)
440
+ */
441
+ error(...args) {
442
+ if (this.level !== "off") {
443
+ console.error(...args);
444
+ }
445
+ }
446
+ /**
447
+ * Check if full logging is enabled
448
+ */
449
+ isEnabled() {
450
+ return this.level === "on";
451
+ }
452
+ /**
453
+ * Check if minimal logging is enabled
454
+ */
455
+ isMinimal() {
456
+ return this.level === "minimal";
457
+ }
458
+ /**
459
+ * Check if logging is completely disabled
460
+ */
461
+ isDisabled() {
462
+ return this.level === "off";
463
+ }
464
+ };
465
+ var logger = new Logger();
466
+ var compiledRulesCache = /* @__PURE__ */ new WeakMap();
467
+ function compileNamingRules(rules) {
468
+ const cached = compiledRulesCache.get(rules);
469
+ if (cached) return cached;
470
+ const compiled = rules.map((rule) => ({
471
+ original: rule,
472
+ filePattern: rule.match.file ? new RegExp(rule.match.file) : void 0,
473
+ functionPattern: rule.match.function ? new RegExp(rule.match.function) : void 0,
474
+ modulePattern: rule.match.module ? new RegExp(rule.match.module) : void 0
475
+ }));
476
+ compiledRulesCache.set(rules, compiled);
477
+ return compiled;
478
+ }
479
+ function extractModuleName(filePath) {
480
+ const basename2 = path.basename(filePath, path.extname(filePath));
481
+ return basename2.replace(/\.(service|controller|handler|util|helper|model|repo|repository)$/i, "").replace(/(Service|Controller|Handler|Util|Helper|Model|Repo|Repository)$/i, "");
482
+ }
483
+ function applyTemplate(template, variables, matchGroups) {
484
+ let result = template;
485
+ for (const [key, value] of Object.entries(variables)) {
486
+ result = result.replace(new RegExp(`\\{${key}\\}`, "g"), value);
487
+ }
488
+ if (matchGroups) {
489
+ result = result.replace(
490
+ /\{match:(\w+):(\d+)\}/g,
491
+ (_fullMatch, field, index) => {
492
+ const groups = matchGroups.get(field);
493
+ const idx = parseInt(index, 10);
494
+ if (groups && groups[idx]) {
495
+ return groups[idx];
496
+ }
497
+ return "";
498
+ }
499
+ );
500
+ }
501
+ return result;
502
+ }
503
+ function findMatchingRule(sourceInfo, config) {
504
+ const rules = config.span_naming?.rules;
505
+ if (!rules || rules.length === 0) return void 0;
506
+ const compiledRules = compileNamingRules(rules);
507
+ for (const rule of compiledRules) {
508
+ const matchGroups = /* @__PURE__ */ new Map();
509
+ let allMatched = true;
510
+ if (rule.filePattern) {
511
+ if (sourceInfo?.file) {
512
+ const match = sourceInfo.file.match(rule.filePattern);
513
+ if (match) {
514
+ matchGroups.set("file", match.slice(1));
515
+ } else {
516
+ allMatched = false;
517
+ }
518
+ } else {
519
+ allMatched = false;
520
+ }
521
+ }
522
+ if (rule.functionPattern && allMatched) {
523
+ if (sourceInfo?.function) {
524
+ const match = sourceInfo.function.match(rule.functionPattern);
525
+ if (match) {
526
+ matchGroups.set("function", match.slice(1));
527
+ } else {
528
+ allMatched = false;
529
+ }
530
+ } else {
531
+ allMatched = false;
532
+ }
533
+ }
534
+ if (rule.modulePattern && allMatched) {
535
+ const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : "";
536
+ if (moduleName) {
537
+ const match = moduleName.match(rule.modulePattern);
538
+ if (match) {
539
+ matchGroups.set("module", match.slice(1));
540
+ } else {
541
+ allMatched = false;
542
+ }
543
+ } else {
544
+ allMatched = false;
545
+ }
546
+ }
547
+ if (allMatched) {
548
+ return { rule, matchGroups };
549
+ }
550
+ }
551
+ return void 0;
552
+ }
553
+ function inferSpanName(fiberId, sourceInfo, config) {
554
+ const variables = {
555
+ fiber_id: String(fiberId),
556
+ function: sourceInfo?.function || "anonymous",
557
+ module: sourceInfo?.file ? extractModuleName(sourceInfo.file) : "unknown",
558
+ file: sourceInfo?.file || "unknown",
559
+ line: sourceInfo?.line ? String(sourceInfo.line) : "0",
560
+ operator: "gen"
561
+ // Default operator, could be enhanced with more context
562
+ };
563
+ const match = findMatchingRule(sourceInfo, config);
564
+ if (match) {
565
+ return applyTemplate(match.rule.original.name, variables, match.matchGroups);
566
+ }
567
+ const defaultTemplate = config.span_naming?.default || "effect.fiber.{fiber_id}";
568
+ return applyTemplate(defaultTemplate, variables);
569
+ }
570
+ function sanitizeSpanName(name) {
571
+ if (!name) return "effect.fiber.unknown";
572
+ let sanitized = name.replace(/[^a-zA-Z0-9._-]/g, "_");
573
+ sanitized = sanitized.replace(/_+/g, "_");
574
+ sanitized = sanitized.replace(/^_+|_+$/g, "");
575
+ if (!sanitized) return "effect.fiber.unknown";
576
+ if (sanitized.length > 256) {
577
+ sanitized = sanitized.substring(0, 256);
578
+ }
579
+ return sanitized;
580
+ }
581
+ async function loadFromFile(filePath) {
582
+ const { readFile } = await import('fs/promises');
583
+ const content = await readFile(filePath, "utf-8");
584
+ return parseAndValidateConfig(content);
585
+ }
586
+ async function loadFromUrl(url) {
587
+ const response = await fetch(url);
588
+ if (!response.ok) {
589
+ throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`);
590
+ }
591
+ const content = await response.text();
592
+ return parseAndValidateConfig(content);
593
+ }
594
+ async function loadConfig(uri, _options) {
595
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
596
+ return loadFromUrl(uri);
597
+ }
598
+ if (uri.startsWith("file://")) {
599
+ const filePath = uri.slice(7);
600
+ return loadFromFile(filePath);
601
+ }
602
+ return loadFromFile(uri);
603
+ }
604
+ async function loadConfigFromInline(content) {
605
+ return parseAndValidateConfig(content);
606
+ }
607
+ async function loadConfigWithOptions(options = {}) {
608
+ if (options.config) {
609
+ return loadConfigFromInline(options.config);
610
+ }
611
+ const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG;
612
+ if (envConfigPath) {
613
+ return loadConfig(envConfigPath);
614
+ }
615
+ if (options.configUrl) {
616
+ return loadConfig(options.configUrl);
617
+ }
618
+ if (options.configPath) {
619
+ return loadConfig(options.configPath);
620
+ }
621
+ const { existsSync } = await import('fs');
622
+ const { join } = await import('path');
623
+ const defaultPath = join(process.cwd(), "instrumentation.yaml");
624
+ if (existsSync(defaultPath)) {
625
+ return loadConfig(defaultPath);
626
+ }
627
+ return defaultConfig;
628
+ }
629
+
630
+ // src/integrations/effect/auto/config.ts
631
+ var defaultAutoTracingConfig = {
632
+ enabled: false,
633
+ granularity: "fiber",
634
+ span_naming: {
635
+ default: "effect.fiber.{fiber_id}",
636
+ infer_from_source: true,
637
+ rules: []
638
+ },
639
+ filter: {
640
+ include: [],
641
+ exclude: []
642
+ },
643
+ performance: {
644
+ sampling_rate: 1,
645
+ min_duration: "0ms",
646
+ max_concurrent: 0
647
+ },
648
+ metadata: {
649
+ fiber_info: true,
650
+ source_location: true,
651
+ parent_fiber: true
652
+ }
653
+ };
654
+ var AutoTracingConfig = class extends Context.Tag("AutoTracingConfig")() {
655
+ };
656
+ var loadAutoTracingConfig = (options) => Effect.gen(function* () {
657
+ const config = yield* Effect.tryPromise({
658
+ try: () => loadConfigWithOptions(options),
659
+ catch: (error) => {
660
+ logger.log(`@atrim/auto-trace: Failed to load config: ${error}`);
661
+ return error;
662
+ }
663
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
664
+ if (!config) {
665
+ logger.log("@atrim/auto-trace: No config found, using defaults");
666
+ return defaultAutoTracingConfig;
667
+ }
668
+ const autoConfig = config.effect?.auto_instrumentation;
669
+ if (!autoConfig) {
670
+ logger.log("@atrim/auto-trace: No auto_instrumentation config, using defaults");
671
+ return defaultAutoTracingConfig;
672
+ }
673
+ const parsed = AutoInstrumentationConfigSchema.safeParse(autoConfig);
674
+ if (!parsed.success) {
675
+ logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${parsed.error.message}`);
676
+ return defaultAutoTracingConfig;
677
+ }
678
+ logger.log("@atrim/auto-trace: Loaded config from instrumentation.yaml");
679
+ return parsed.data;
680
+ });
681
+ var loadAutoTracingConfigSync = () => {
682
+ return defaultAutoTracingConfig;
683
+ };
684
+ var AutoTracingConfigLive = Layer.effect(AutoTracingConfig, loadAutoTracingConfig());
685
+ var AutoTracingConfigLayer = (config) => Layer.succeed(AutoTracingConfig, config);
686
+ var loadFullConfig = (options) => Effect.gen(function* () {
687
+ const config = yield* Effect.tryPromise({
688
+ try: () => loadConfigWithOptions(options),
689
+ catch: (error) => {
690
+ logger.log(`@atrim/auto-trace: Failed to load config: ${error}`);
691
+ return error;
692
+ }
693
+ }).pipe(Effect.catchAll(() => Effect.succeed(null)));
694
+ if (!config) {
695
+ logger.log("@atrim/auto-trace: No config found, using defaults");
696
+ return defaultConfig;
697
+ }
698
+ return config;
699
+ });
700
+
701
+ // src/integrations/effect/auto/supervisor.ts
702
+ var AutoTracingEnabled = FiberRef.unsafeMake(true);
703
+ var AutoTracingSpanName = FiberRef.unsafeMake(Option.none());
704
+ var AutoTracingSupervisor = class extends Supervisor.AbstractSupervisor {
705
+ constructor(config) {
706
+ super();
707
+ this.config = config;
708
+ // WeakMap to associate fibers with their OTel spans
709
+ __publicField(this, "fiberSpans", /* @__PURE__ */ new WeakMap());
710
+ // WeakMap for fiber start times (for min_duration filtering)
711
+ __publicField(this, "fiberStartTimes", /* @__PURE__ */ new WeakMap());
712
+ // OpenTelemetry tracer - lazily initialized
713
+ __publicField(this, "_tracer", null);
714
+ // Compiled filter patterns
715
+ __publicField(this, "includePatterns");
716
+ __publicField(this, "excludePatterns");
717
+ // Active fiber count (for max_concurrent limiting)
718
+ __publicField(this, "activeFiberCount", 0);
719
+ // Root span for parent context (set by withAutoTracing)
720
+ __publicField(this, "_rootSpan", null);
721
+ this.includePatterns = (config.filter?.include || []).map((p) => new RegExp(p));
722
+ this.excludePatterns = (config.filter?.exclude || []).map((p) => new RegExp(p));
723
+ logger.log("@atrim/auto-trace: Supervisor initialized");
724
+ logger.log(` Granularity: ${config.granularity || "fiber"}`);
725
+ logger.log(` Sampling rate: ${config.performance?.sampling_rate ?? 1}`);
726
+ logger.log(` Infer from source: ${config.span_naming?.infer_from_source ?? true}`);
727
+ }
728
+ /**
729
+ * Set the root span for parent context propagation
730
+ */
731
+ setRootSpan(span) {
732
+ this._rootSpan = span;
733
+ }
734
+ /**
735
+ * Get the tracer lazily - this allows time for the NodeSdk layer to register the global provider
736
+ */
737
+ get tracer() {
738
+ if (!this._tracer) {
739
+ this._tracer = OtelApi.trace.getTracer("@atrim/auto-trace", "1.0.0");
740
+ }
741
+ return this._tracer;
742
+ }
743
+ /**
744
+ * Returns the current value (void for this supervisor)
745
+ */
746
+ get value() {
747
+ return Effect.void;
748
+ }
749
+ /**
750
+ * Called when a fiber starts executing
751
+ */
752
+ onStart(_context, _effect, parent, fiber) {
753
+ const fiberRefsValue = fiber.getFiberRefs();
754
+ const enabled = FiberRefs.getOrDefault(fiberRefsValue, AutoTracingEnabled);
755
+ if (!enabled) {
756
+ return;
757
+ }
758
+ const samplingRate = this.config.performance?.sampling_rate ?? 1;
759
+ if (samplingRate < 1 && Math.random() > samplingRate) {
760
+ return;
761
+ }
762
+ const maxConcurrent = this.config.performance?.max_concurrent ?? 0;
763
+ if (maxConcurrent > 0 && this.activeFiberCount >= maxConcurrent) {
764
+ return;
765
+ }
766
+ const nameOverride = FiberRefs.getOrDefault(fiberRefsValue, AutoTracingSpanName);
767
+ const sourceInfo = this.config.span_naming?.infer_from_source ? this.parseStackTrace() : void 0;
768
+ let spanName;
769
+ if (Option.isSome(nameOverride)) {
770
+ spanName = nameOverride.value;
771
+ } else {
772
+ spanName = inferSpanName(fiber.id().id, sourceInfo, this.config);
773
+ }
774
+ if (!this.shouldTrace(spanName)) {
775
+ return;
776
+ }
777
+ let parentContext = OtelApi.ROOT_CONTEXT;
778
+ let parentFiberId;
779
+ if (Option.isSome(parent)) {
780
+ parentFiberId = parent.value.id().id;
781
+ const parentSpan = this.fiberSpans.get(parent.value);
782
+ if (parentSpan) {
783
+ parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, parentSpan);
784
+ } else if (this._rootSpan) {
785
+ parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, this._rootSpan);
786
+ }
787
+ } else if (this._rootSpan) {
788
+ parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, this._rootSpan);
789
+ }
790
+ const span = this.tracer.startSpan(
791
+ spanName,
792
+ {
793
+ kind: OtelApi.SpanKind.INTERNAL,
794
+ attributes: this.getInitialAttributes(fiber, sourceInfo, parentFiberId)
795
+ },
796
+ parentContext
797
+ );
798
+ this.fiberSpans.set(fiber, span);
799
+ this.fiberStartTimes.set(fiber, process.hrtime.bigint());
800
+ this.activeFiberCount++;
801
+ }
802
+ /**
803
+ * Called when a fiber completes (success or failure)
804
+ */
805
+ onEnd(exit, fiber) {
806
+ const span = this.fiberSpans.get(fiber);
807
+ if (!span) {
808
+ return;
809
+ }
810
+ const startTime = this.fiberStartTimes.get(fiber);
811
+ if (startTime) {
812
+ const duration = process.hrtime.bigint() - startTime;
813
+ const minDuration = this.parseMinDuration(this.config.performance?.min_duration);
814
+ if (minDuration > 0 && duration < minDuration) {
815
+ this.fiberSpans.delete(fiber);
816
+ this.fiberStartTimes.delete(fiber);
817
+ this.activeFiberCount--;
818
+ return;
819
+ }
820
+ }
821
+ if (Exit.isSuccess(exit)) {
822
+ span.setStatus({ code: OtelApi.SpanStatusCode.OK });
823
+ } else {
824
+ span.setStatus({
825
+ code: OtelApi.SpanStatusCode.ERROR,
826
+ message: "Fiber failed"
827
+ });
828
+ span.setAttribute("effect.fiber.failed", true);
829
+ }
830
+ span.end();
831
+ this.fiberSpans.delete(fiber);
832
+ this.fiberStartTimes.delete(fiber);
833
+ this.activeFiberCount--;
834
+ }
835
+ /**
836
+ * Check if a span name should be traced based on filter patterns
837
+ */
838
+ shouldTrace(spanName) {
839
+ for (const pattern of this.excludePatterns) {
840
+ if (pattern.test(spanName)) {
841
+ return false;
842
+ }
843
+ }
844
+ if (this.includePatterns.length > 0) {
845
+ for (const pattern of this.includePatterns) {
846
+ if (pattern.test(spanName)) {
847
+ return true;
848
+ }
849
+ }
850
+ return false;
851
+ }
852
+ return true;
853
+ }
854
+ /**
855
+ * Get initial span attributes for a fiber
856
+ */
857
+ getInitialAttributes(fiber, sourceInfo, parentFiberId) {
858
+ const attrs = {
859
+ "effect.auto_traced": true
860
+ };
861
+ if (this.config.metadata?.fiber_info !== false) {
862
+ attrs["effect.fiber.id"] = fiber.id().id;
863
+ }
864
+ if (this.config.metadata?.source_location !== false && sourceInfo) {
865
+ attrs["code.function"] = sourceInfo.function;
866
+ attrs["code.filepath"] = sourceInfo.file;
867
+ attrs["code.lineno"] = sourceInfo.line;
868
+ attrs["code.column"] = sourceInfo.column;
869
+ }
870
+ if (this.config.metadata?.parent_fiber !== false && parentFiberId !== void 0) {
871
+ attrs["effect.fiber.parent_id"] = parentFiberId;
872
+ }
873
+ return attrs;
874
+ }
875
+ /**
876
+ * Parse stack trace to get source info
877
+ */
878
+ parseStackTrace() {
879
+ const stack = new Error().stack;
880
+ if (!stack) return void 0;
881
+ const lines = stack.split("\n");
882
+ for (let i = 3; i < lines.length; i++) {
883
+ const line = lines[i];
884
+ if (line === void 0) continue;
885
+ if (!line.includes("node_modules/effect") && !line.includes("@atrim/instrument") && !line.includes("auto/supervisor")) {
886
+ const match = line.match(/at\s+(?:(.+?)\s+)?\(?(.+?):(\d+):(\d+)\)?/);
887
+ if (match) {
888
+ const [, funcName, filePath, lineNum, colNum] = match;
889
+ return {
890
+ function: funcName ?? "anonymous",
891
+ file: filePath ?? "unknown",
892
+ line: parseInt(lineNum ?? "0", 10),
893
+ column: parseInt(colNum ?? "0", 10)
894
+ };
895
+ }
896
+ }
897
+ }
898
+ return void 0;
899
+ }
900
+ /**
901
+ * Parse min_duration string to nanoseconds
902
+ */
903
+ parseMinDuration(duration) {
904
+ if (!duration || duration === "0ms") return BigInt(0);
905
+ const match = duration.match(/^(\d+)\s*(ms|millis|s|sec|seconds|us|micros)?$/i);
906
+ if (!match) return BigInt(0);
907
+ const value = parseInt(match[1] ?? "0", 10);
908
+ const unit = (match[2] ?? "ms").toLowerCase();
909
+ switch (unit) {
910
+ case "us":
911
+ case "micros":
912
+ return BigInt(value) * BigInt(1e3);
913
+ case "ms":
914
+ case "millis":
915
+ return BigInt(value) * BigInt(1e6);
916
+ case "s":
917
+ case "sec":
918
+ case "seconds":
919
+ return BigInt(value) * BigInt(1e9);
920
+ default:
921
+ return BigInt(value) * BigInt(1e6);
922
+ }
923
+ }
924
+ };
925
+ var createAutoTracingSupervisor = (config) => {
926
+ return new AutoTracingSupervisor(config);
927
+ };
928
+ var createAutoTracingLayer = (options) => {
929
+ return Layer.unwrapEffect(
930
+ Effect.gen(function* () {
931
+ const config = options?.config ?? (yield* loadAutoTracingConfig());
932
+ if (!config.enabled) {
933
+ logger.log("@atrim/auto-trace: Auto-tracing disabled via config");
934
+ return Layer.empty;
935
+ }
936
+ const supervisor = createAutoTracingSupervisor(config);
937
+ return Supervisor.addSupervisor(supervisor);
938
+ })
939
+ );
940
+ };
941
+ var withAutoTracing = (effect, config, mainSpanName) => {
942
+ if (!config.enabled) {
943
+ logger.log("@atrim/auto-trace: Auto-tracing disabled via config");
944
+ return effect;
945
+ }
946
+ const supervisor = createAutoTracingSupervisor(config);
947
+ const tracer = OtelApi.trace.getTracer("@atrim/auto-trace", "1.0.0");
948
+ const spanName = mainSpanName ?? inferSpanName(0, void 0, config);
949
+ const mainSpan = tracer.startSpan(spanName, {
950
+ kind: OtelApi.SpanKind.INTERNAL,
951
+ attributes: {
952
+ "effect.auto_traced": true,
953
+ "effect.fiber.id": 0,
954
+ // Main fiber
955
+ "effect.main_fiber": true
956
+ }
957
+ });
958
+ supervisor.setRootSpan(mainSpan);
959
+ return Effect.acquireUseRelease(
960
+ // Acquire: return the span (already started)
961
+ Effect.succeed(mainSpan),
962
+ // Use: run the supervised effect
963
+ () => Effect.supervised(supervisor)(effect),
964
+ // Release: end the span
965
+ (span, exit) => Effect.sync(() => {
966
+ if (Exit.isSuccess(exit)) {
967
+ span.setStatus({ code: OtelApi.SpanStatusCode.OK });
968
+ } else {
969
+ span.setStatus({
970
+ code: OtelApi.SpanStatusCode.ERROR,
971
+ message: "Effect failed"
972
+ });
973
+ }
974
+ span.end();
975
+ })
976
+ );
977
+ };
978
+ var AutoTracingLive = createAutoTracingLayer();
979
+ var withoutAutoTracing = (effect) => effect.pipe(Effect.locally(AutoTracingEnabled, false));
980
+ var setSpanName = (name) => (effect) => effect.pipe(Effect.locally(AutoTracingSpanName, Option.some(name)));
981
+ var createExporterLayer = (exporterConfig, serviceName, serviceVersion) => {
982
+ const config = exporterConfig ?? {
983
+ type: "otlp",
984
+ processor: "batch",
985
+ batch: {
986
+ scheduled_delay_millis: 1e3,
987
+ max_export_batch_size: 100
988
+ }
989
+ };
990
+ if (config.type === "none") {
991
+ logger.log('@atrim/auto-trace: Exporter type is "none", no spans will be exported');
992
+ return Layer.empty;
993
+ }
994
+ const createSpanExporter = () => {
995
+ if (config.type === "console") {
996
+ logger.log("@atrim/auto-trace: Using ConsoleSpanExporter");
997
+ return new ConsoleSpanExporter();
998
+ }
999
+ const endpoint = config.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
1000
+ logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`);
1001
+ return new OTLPTraceExporter({
1002
+ url: `${endpoint}/v1/traces`
1003
+ });
1004
+ };
1005
+ const createSpanProcessor = () => {
1006
+ const exporter = createSpanExporter();
1007
+ if (config.processor === "simple" || config.type === "console") {
1008
+ logger.log("@atrim/auto-trace: Using SimpleSpanProcessor");
1009
+ return new SimpleSpanProcessor(exporter);
1010
+ }
1011
+ const batchConfig = config.batch ?? {
1012
+ scheduled_delay_millis: 1e3,
1013
+ max_export_batch_size: 100
1014
+ };
1015
+ logger.log("@atrim/auto-trace: Using BatchSpanProcessor");
1016
+ return new BatchSpanProcessor(exporter, {
1017
+ scheduledDelayMillis: batchConfig.scheduled_delay_millis,
1018
+ maxExportBatchSize: batchConfig.max_export_batch_size
1019
+ });
1020
+ };
1021
+ return Layer.effectDiscard(
1022
+ Effect.sync(() => {
1023
+ const provider = new BasicTracerProvider({
1024
+ resource: resourceFromAttributes({
1025
+ [ATTR_SERVICE_NAME]: serviceName,
1026
+ [ATTR_SERVICE_VERSION]: serviceVersion
1027
+ }),
1028
+ spanProcessors: [createSpanProcessor()]
1029
+ });
1030
+ OtelApi.trace.setGlobalTracerProvider(provider);
1031
+ logger.log("@atrim/auto-trace: Global TracerProvider registered");
1032
+ return () => {
1033
+ provider.shutdown().catch((err) => {
1034
+ logger.log(`@atrim/auto-trace: Error shutting down provider: ${err}`);
1035
+ });
1036
+ };
1037
+ })
1038
+ );
1039
+ };
1040
+ var createFullAutoTracingLayer = () => {
1041
+ return Layer.unwrapEffect(
1042
+ Effect.gen(function* () {
1043
+ const config = yield* loadFullConfig();
1044
+ const serviceName = process.env.OTEL_SERVICE_NAME || "effect-service";
1045
+ const serviceVersion = process.env.npm_package_version || "1.0.0";
1046
+ const autoConfig = config.effect?.auto_instrumentation;
1047
+ if (!autoConfig?.enabled) {
1048
+ logger.log("@atrim/auto-trace: Auto-instrumentation disabled via config");
1049
+ return Layer.empty;
1050
+ }
1051
+ const exporterConfig = config.effect?.exporter_config;
1052
+ logger.log("@atrim/auto-trace: Full auto-instrumentation enabled");
1053
+ logger.log(` Service: ${serviceName}`);
1054
+ logger.log(` Exporter: ${exporterConfig?.type ?? "otlp"}`);
1055
+ const exporterLayer = createExporterLayer(exporterConfig, serviceName, serviceVersion);
1056
+ const supervisor = createAutoTracingSupervisor(autoConfig);
1057
+ const supervisorLayer = Supervisor.addSupervisor(supervisor);
1058
+ return Layer.mergeAll(exporterLayer, supervisorLayer);
1059
+ })
1060
+ );
1061
+ };
1062
+ var FullAutoTracingLive = createFullAutoTracingLayer();
1063
+
1064
+ export { AutoTracingConfig, AutoTracingConfigLayer, AutoTracingConfigLive, AutoTracingEnabled, AutoTracingLive, AutoTracingSpanName, AutoTracingSupervisor, FullAutoTracingLive, createAutoTracingLayer, createAutoTracingSupervisor, createFullAutoTracingLayer, defaultAutoTracingConfig, inferSpanName, loadAutoTracingConfig, loadAutoTracingConfigSync, sanitizeSpanName, setSpanName, withAutoTracing, withoutAutoTracing };
1065
+ //# sourceMappingURL=index.js.map
1066
+ //# sourceMappingURL=index.js.map