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