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

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,948 @@
1
+ import { Data, Context, Effect, Layer, FiberSet as FiberSet$1, Fiber, Option, FiberId, Tracer as Tracer$1 } from 'effect';
2
+ import * as Tracer from '@effect/opentelemetry/Tracer';
3
+ import * as Resource from '@effect/opentelemetry/Resource';
4
+ import * as Otlp from '@effect/opentelemetry/Otlp';
5
+ import { FetchHttpClient } from '@effect/platform';
6
+ import { TraceFlags, trace, context } from '@opentelemetry/api';
7
+ import { TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_LANGUAGE } from '@opentelemetry/semantic-conventions';
8
+ import { FileSystem } from '@effect/platform/FileSystem';
9
+ import * as HttpClient from '@effect/platform/HttpClient';
10
+ import * as HttpClientRequest from '@effect/platform/HttpClientRequest';
11
+ import { parse } from 'yaml';
12
+ import { z } from 'zod';
13
+
14
+ // src/integrations/effect/effect-tracer.ts
15
+ var __defProp = Object.defineProperty;
16
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
17
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
18
+ var PatternConfigSchema = z.object({
19
+ pattern: z.string(),
20
+ enabled: z.boolean().optional(),
21
+ description: z.string().optional()
22
+ });
23
+ var AutoIsolationConfigSchema = z.object({
24
+ // Global enable/disable for auto-isolation
25
+ enabled: z.boolean().default(false),
26
+ // Which operators to auto-isolate
27
+ operators: z.object({
28
+ fiberset_run: z.boolean().default(true),
29
+ effect_fork: z.boolean().default(true),
30
+ effect_fork_daemon: z.boolean().default(true),
31
+ effect_fork_in: z.boolean().default(false)
32
+ }).default({}),
33
+ // Virtual parent tracking configuration
34
+ tracking: z.object({
35
+ use_span_links: z.boolean().default(true),
36
+ use_attributes: z.boolean().default(true),
37
+ capture_logical_parent: z.boolean().default(true)
38
+ }).default({}),
39
+ // Span categorization
40
+ attributes: z.object({
41
+ category: z.string().default("background_task"),
42
+ add_metadata: z.boolean().default(true)
43
+ }).default({})
44
+ });
45
+ var SpanNamingRuleSchema = z.object({
46
+ // Match criteria (all specified criteria must match)
47
+ match: z.object({
48
+ // Regex pattern to match file path
49
+ file: z.string().optional(),
50
+ // Regex pattern to match function name
51
+ function: z.string().optional(),
52
+ // Regex pattern to match module name
53
+ module: z.string().optional()
54
+ }),
55
+ // Span name template with variables:
56
+ // {fiber_id} - Fiber ID
57
+ // {function} - Function name
58
+ // {module} - Module name
59
+ // {file} - File path
60
+ // {line} - Line number
61
+ // {operator} - Effect operator (gen, all, forEach, etc.)
62
+ // {match:field:N} - Captured regex group from match
63
+ name: z.string()
64
+ });
65
+ var AutoInstrumentationConfigSchema = z.object({
66
+ // Enable/disable auto-instrumentation
67
+ enabled: z.boolean().default(false),
68
+ // Tracing granularity
69
+ // - 'fiber': Trace at fiber creation (recommended, lower overhead)
70
+ // - 'operator': Trace each Effect operator (higher granularity, more overhead)
71
+ granularity: z.enum(["fiber", "operator"]).default("fiber"),
72
+ // Smart span naming configuration
73
+ span_naming: z.object({
74
+ // Default span name template when no rules match
75
+ default: z.string().default("effect.fiber.{fiber_id}"),
76
+ // Infer span names from source code (requires stack trace parsing)
77
+ // Adds ~50-100μs overhead per fiber
78
+ infer_from_source: z.boolean().default(true),
79
+ // Naming rules (first match wins)
80
+ rules: z.array(SpanNamingRuleSchema).default([])
81
+ }).default({}),
82
+ // Pattern-based filtering
83
+ filter: z.object({
84
+ // Only trace spans matching these patterns (empty = trace all)
85
+ include: z.array(z.string()).default([]),
86
+ // Never trace spans matching these patterns
87
+ exclude: z.array(z.string()).default([])
88
+ }).default({}),
89
+ // Performance controls
90
+ performance: z.object({
91
+ // Sample rate (0.0 - 1.0)
92
+ sampling_rate: z.number().min(0).max(1).default(1),
93
+ // Skip fibers shorter than this duration (e.g., "10ms", "100 millis")
94
+ min_duration: z.string().default("0ms"),
95
+ // Maximum concurrent traced fibers (0 = unlimited)
96
+ max_concurrent: z.number().default(0)
97
+ }).default({}),
98
+ // Automatic metadata extraction
99
+ metadata: z.object({
100
+ // Extract Effect fiber information
101
+ fiber_info: z.boolean().default(true),
102
+ // Extract source location (file:line)
103
+ source_location: z.boolean().default(true),
104
+ // Extract parent fiber information
105
+ parent_fiber: z.boolean().default(true)
106
+ }).default({})
107
+ });
108
+ var HttpFilteringConfigSchema = z.object({
109
+ // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)
110
+ ignore_outgoing_urls: z.array(z.string()).optional(),
111
+ // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)
112
+ ignore_incoming_paths: z.array(z.string()).optional(),
113
+ // Require parent span for outgoing requests (prevents root spans for HTTP calls)
114
+ require_parent_for_outgoing_spans: z.boolean().optional(),
115
+ // Trace context propagation configuration
116
+ // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)
117
+ propagate_trace_context: z.object({
118
+ // Strategy for trace propagation
119
+ // - "all": Propagate to all cross-origin requests (may cause CORS errors)
120
+ // - "none": Never propagate trace headers
121
+ // - "same-origin": Only propagate to same-origin requests (default, safe)
122
+ // - "patterns": Propagate based on include_urls patterns
123
+ strategy: z.enum(["all", "none", "same-origin", "patterns"]).default("same-origin"),
124
+ // URL patterns to include when strategy is "patterns"
125
+ // Supports regex patterns (e.g., "^https://api\\.myapp\\.com")
126
+ include_urls: z.array(z.string()).optional()
127
+ }).optional()
128
+ });
129
+ var ExporterConfigSchema = z.object({
130
+ // Exporter type: 'otlp' | 'console' | 'none'
131
+ // - 'otlp': Export to OTLP endpoint (production)
132
+ // - 'console': Log spans to console (development)
133
+ // - 'none': No export (disable tracing)
134
+ type: z.enum(["otlp", "console", "none"]).default("otlp"),
135
+ // OTLP endpoint URL (for type: otlp)
136
+ // Defaults to OTEL_EXPORTER_OTLP_ENDPOINT env var or http://localhost:4318
137
+ endpoint: z.string().optional(),
138
+ // Custom headers to send with OTLP requests (for type: otlp)
139
+ // Useful for authentication (x-api-key, Authorization, etc.)
140
+ headers: z.record(z.string()).optional(),
141
+ // Span processor type
142
+ // - 'batch': Batch spans for export (production, lower overhead)
143
+ // - 'simple': Export immediately (development, no batching delay)
144
+ processor: z.enum(["batch", "simple"]).default("batch"),
145
+ // Batch processor settings (for processor: batch)
146
+ batch: z.object({
147
+ // Max time to wait before exporting (milliseconds)
148
+ scheduled_delay_millis: z.number().default(1e3),
149
+ // Max batch size
150
+ max_export_batch_size: z.number().default(100)
151
+ }).optional()
152
+ });
153
+ var InstrumentationConfigSchema = z.object({
154
+ version: z.string(),
155
+ instrumentation: z.object({
156
+ enabled: z.boolean(),
157
+ description: z.string().optional(),
158
+ logging: z.enum(["on", "off", "minimal"]).optional().default("on"),
159
+ instrument_patterns: z.array(PatternConfigSchema),
160
+ ignore_patterns: z.array(PatternConfigSchema)
161
+ }),
162
+ effect: z.object({
163
+ // Enable/disable Effect tracing entirely
164
+ // When false, EffectInstrumentationLive returns Layer.empty
165
+ enabled: z.boolean().default(true),
166
+ // Exporter mode (legacy - use exporter.type instead):
167
+ // - "unified": Use global TracerProvider from Node SDK (recommended, enables filtering)
168
+ // - "standalone": Use Effect's own OTLP exporter (bypasses Node SDK filtering)
169
+ exporter: z.enum(["unified", "standalone"]).default("unified"),
170
+ // Exporter configuration (for auto-instrumentation)
171
+ exporter_config: ExporterConfigSchema.optional(),
172
+ auto_extract_metadata: z.boolean(),
173
+ auto_isolation: AutoIsolationConfigSchema.optional(),
174
+ // Auto-instrumentation: automatic tracing of all Effect fibers
175
+ auto_instrumentation: AutoInstrumentationConfigSchema.optional()
176
+ }).optional(),
177
+ http: HttpFilteringConfigSchema.optional()
178
+ });
179
+ var defaultConfig = {
180
+ version: "1.0",
181
+ instrumentation: {
182
+ enabled: true,
183
+ logging: "on",
184
+ description: "Default instrumentation configuration",
185
+ instrument_patterns: [
186
+ { pattern: "^app\\.", enabled: true, description: "Application operations" },
187
+ { pattern: "^http\\.server\\.", enabled: true, description: "HTTP server operations" },
188
+ { pattern: "^http\\.client\\.", enabled: true, description: "HTTP client operations" }
189
+ ],
190
+ ignore_patterns: [
191
+ { pattern: "^test\\.", description: "Test utilities" },
192
+ { pattern: "^internal\\.", description: "Internal operations" },
193
+ { pattern: "^health\\.", description: "Health checks" }
194
+ ]
195
+ },
196
+ effect: {
197
+ enabled: true,
198
+ exporter: "unified",
199
+ auto_extract_metadata: true
200
+ }
201
+ };
202
+ function parseAndValidateConfig(content) {
203
+ let parsed;
204
+ if (typeof content === "string") {
205
+ parsed = parse(content);
206
+ } else {
207
+ parsed = content;
208
+ }
209
+ return InstrumentationConfigSchema.parse(parsed);
210
+ }
211
+ (class extends Data.TaggedError("ConfigError") {
212
+ get message() {
213
+ return this.reason;
214
+ }
215
+ });
216
+ var ConfigUrlError = class extends Data.TaggedError("ConfigUrlError") {
217
+ get message() {
218
+ return this.reason;
219
+ }
220
+ };
221
+ var ConfigValidationError = class extends Data.TaggedError("ConfigValidationError") {
222
+ get message() {
223
+ return this.reason;
224
+ }
225
+ };
226
+ var ConfigFileError = class extends Data.TaggedError("ConfigFileError") {
227
+ get message() {
228
+ return this.reason;
229
+ }
230
+ };
231
+ (class extends Data.TaggedError("ServiceDetectionError") {
232
+ get message() {
233
+ return this.reason;
234
+ }
235
+ });
236
+ (class extends Data.TaggedError("InitializationError") {
237
+ get message() {
238
+ return this.reason;
239
+ }
240
+ });
241
+ (class extends Data.TaggedError("ExportError") {
242
+ get message() {
243
+ return this.reason;
244
+ }
245
+ });
246
+ (class extends Data.TaggedError("ShutdownError") {
247
+ get message() {
248
+ return this.reason;
249
+ }
250
+ });
251
+ var SECURITY_DEFAULTS = {
252
+ maxConfigSize: 1e6,
253
+ // 1MB
254
+ requestTimeout: 5e3
255
+ // 5 seconds
256
+ };
257
+ var ConfigLoader = class extends Context.Tag("ConfigLoader")() {
258
+ };
259
+ var parseYamlContent = (content, uri) => Effect.gen(function* () {
260
+ const parsed = yield* Effect.try({
261
+ try: () => parse(content),
262
+ catch: (error) => new ConfigValidationError({
263
+ reason: uri ? `Failed to parse YAML from ${uri}` : "Failed to parse YAML",
264
+ cause: error
265
+ })
266
+ });
267
+ return yield* Effect.try({
268
+ try: () => InstrumentationConfigSchema.parse(parsed),
269
+ catch: (error) => new ConfigValidationError({
270
+ reason: uri ? `Invalid configuration schema from ${uri}` : "Invalid configuration schema",
271
+ cause: error
272
+ })
273
+ });
274
+ });
275
+ var loadFromFileWithFs = (fs, path, uri) => Effect.gen(function* () {
276
+ const content = yield* fs.readFileString(path).pipe(
277
+ Effect.mapError(
278
+ (error) => new ConfigFileError({
279
+ reason: `Failed to read config file at ${uri}`,
280
+ cause: error
281
+ })
282
+ )
283
+ );
284
+ if (content.length > SECURITY_DEFAULTS.maxConfigSize) {
285
+ return yield* Effect.fail(
286
+ new ConfigFileError({
287
+ reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
288
+ })
289
+ );
290
+ }
291
+ return yield* parseYamlContent(content, uri);
292
+ });
293
+ var loadFromHttpWithClient = (client, url) => Effect.scoped(
294
+ Effect.gen(function* () {
295
+ if (url.startsWith("http://")) {
296
+ return yield* Effect.fail(
297
+ new ConfigUrlError({
298
+ reason: "Insecure protocol: only HTTPS URLs are allowed"
299
+ })
300
+ );
301
+ }
302
+ const request = HttpClientRequest.get(url).pipe(
303
+ HttpClientRequest.setHeaders({
304
+ Accept: "application/yaml, text/yaml, application/x-yaml"
305
+ })
306
+ );
307
+ const response = yield* client.execute(request).pipe(
308
+ Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),
309
+ Effect.mapError((error) => {
310
+ if (error._tag === "TimeoutException") {
311
+ return new ConfigUrlError({
312
+ reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`
313
+ });
314
+ }
315
+ return new ConfigUrlError({
316
+ reason: `Failed to load config from URL: ${url}`,
317
+ cause: error
318
+ });
319
+ })
320
+ );
321
+ if (response.status >= 400) {
322
+ return yield* Effect.fail(
323
+ new ConfigUrlError({
324
+ reason: `HTTP ${response.status} from ${url}`
325
+ })
326
+ );
327
+ }
328
+ const text = yield* response.text.pipe(
329
+ Effect.mapError(
330
+ (error) => new ConfigUrlError({
331
+ reason: `Failed to read response body from ${url}`,
332
+ cause: error
333
+ })
334
+ )
335
+ );
336
+ if (text.length > SECURITY_DEFAULTS.maxConfigSize) {
337
+ return yield* Effect.fail(
338
+ new ConfigUrlError({
339
+ reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
340
+ })
341
+ );
342
+ }
343
+ return yield* parseYamlContent(text, url);
344
+ })
345
+ );
346
+ var makeConfigLoader = Effect.gen(function* () {
347
+ const fs = yield* Effect.serviceOption(FileSystem);
348
+ const http = yield* HttpClient.HttpClient;
349
+ const loadFromUriUncached = (uri) => Effect.gen(function* () {
350
+ if (uri.startsWith("file://")) {
351
+ const path = uri.slice(7);
352
+ if (fs._tag === "None") {
353
+ return yield* Effect.fail(
354
+ new ConfigFileError({
355
+ reason: "FileSystem not available (browser environment?)",
356
+ cause: { uri }
357
+ })
358
+ );
359
+ }
360
+ return yield* loadFromFileWithFs(fs.value, path, uri);
361
+ }
362
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
363
+ return yield* loadFromHttpWithClient(http, uri);
364
+ }
365
+ if (fs._tag === "Some") {
366
+ return yield* loadFromFileWithFs(fs.value, uri, uri);
367
+ } else {
368
+ return yield* loadFromHttpWithClient(http, uri);
369
+ }
370
+ });
371
+ const loadFromUriCached = yield* Effect.cachedFunction(loadFromUriUncached);
372
+ return ConfigLoader.of({
373
+ loadFromUri: loadFromUriCached,
374
+ loadFromInline: (content) => Effect.gen(function* () {
375
+ if (typeof content === "string") {
376
+ return yield* parseYamlContent(content);
377
+ }
378
+ return yield* Effect.try({
379
+ try: () => InstrumentationConfigSchema.parse(content),
380
+ catch: (error) => new ConfigValidationError({
381
+ reason: "Invalid configuration schema",
382
+ cause: error
383
+ })
384
+ });
385
+ })
386
+ });
387
+ });
388
+ Layer.effect(ConfigLoader, makeConfigLoader);
389
+ var PatternMatcher = class {
390
+ constructor(config) {
391
+ __publicField(this, "ignorePatterns", []);
392
+ __publicField(this, "instrumentPatterns", []);
393
+ __publicField(this, "enabled", true);
394
+ this.enabled = config.instrumentation.enabled;
395
+ this.ignorePatterns = config.instrumentation.ignore_patterns.map((p) => this.compilePattern(p));
396
+ this.instrumentPatterns = config.instrumentation.instrument_patterns.filter((p) => p.enabled !== false).map((p) => this.compilePattern(p));
397
+ }
398
+ /**
399
+ * Compile a pattern configuration into a RegExp
400
+ */
401
+ compilePattern(pattern) {
402
+ try {
403
+ const compiled = {
404
+ regex: new RegExp(pattern.pattern),
405
+ enabled: pattern.enabled !== false
406
+ };
407
+ if (pattern.description !== void 0) {
408
+ compiled.description = pattern.description;
409
+ }
410
+ return compiled;
411
+ } catch (error) {
412
+ throw new Error(
413
+ `Failed to compile pattern "${pattern.pattern}": ${error instanceof Error ? error.message : String(error)}`
414
+ );
415
+ }
416
+ }
417
+ /**
418
+ * Check if a span should be instrumented
419
+ *
420
+ * Returns true if the span should be created, false otherwise.
421
+ *
422
+ * Logic:
423
+ * 1. If instrumentation disabled globally, return false
424
+ * 2. Check ignore patterns - if any match, return false
425
+ * 3. Check instrument patterns - if any match, return true
426
+ * 4. Default: return true (fail-open - create span if no patterns match)
427
+ */
428
+ shouldInstrument(spanName) {
429
+ if (!this.enabled) {
430
+ return false;
431
+ }
432
+ for (const pattern of this.ignorePatterns) {
433
+ if (pattern.regex.test(spanName)) {
434
+ return false;
435
+ }
436
+ }
437
+ for (const pattern of this.instrumentPatterns) {
438
+ if (pattern.enabled && pattern.regex.test(spanName)) {
439
+ return true;
440
+ }
441
+ }
442
+ return true;
443
+ }
444
+ /**
445
+ * Get statistics about pattern matching (for debugging/monitoring)
446
+ */
447
+ getStats() {
448
+ return {
449
+ enabled: this.enabled,
450
+ ignorePatternCount: this.ignorePatterns.length,
451
+ instrumentPatternCount: this.instrumentPatterns.filter((p) => p.enabled).length
452
+ };
453
+ }
454
+ };
455
+ function initializePatternMatcher(config) {
456
+ new PatternMatcher(config);
457
+ }
458
+ var Logger = class {
459
+ constructor() {
460
+ __publicField(this, "level", "on");
461
+ __publicField(this, "hasLoggedMinimal", false);
462
+ }
463
+ /**
464
+ * Set the logging level
465
+ */
466
+ setLevel(level) {
467
+ this.level = level;
468
+ this.hasLoggedMinimal = false;
469
+ }
470
+ /**
471
+ * Get the current logging level
472
+ */
473
+ getLevel() {
474
+ return this.level;
475
+ }
476
+ /**
477
+ * Log a minimal initialization message (only shown once in minimal mode)
478
+ */
479
+ minimal(message) {
480
+ if (this.level === "off") {
481
+ return;
482
+ }
483
+ if (this.level === "minimal" && !this.hasLoggedMinimal) {
484
+ console.log(message);
485
+ this.hasLoggedMinimal = true;
486
+ return;
487
+ }
488
+ if (this.level === "on") {
489
+ console.log(message);
490
+ }
491
+ }
492
+ /**
493
+ * Log an informational message
494
+ */
495
+ log(...args) {
496
+ if (this.level === "on") {
497
+ console.log(...args);
498
+ }
499
+ }
500
+ /**
501
+ * Log a warning message (shown in minimal mode)
502
+ */
503
+ warn(...args) {
504
+ if (this.level !== "off") {
505
+ console.warn(...args);
506
+ }
507
+ }
508
+ /**
509
+ * Log an error message (shown in minimal mode)
510
+ */
511
+ error(...args) {
512
+ if (this.level !== "off") {
513
+ console.error(...args);
514
+ }
515
+ }
516
+ /**
517
+ * Check if full logging is enabled
518
+ */
519
+ isEnabled() {
520
+ return this.level === "on";
521
+ }
522
+ /**
523
+ * Check if minimal logging is enabled
524
+ */
525
+ isMinimal() {
526
+ return this.level === "minimal";
527
+ }
528
+ /**
529
+ * Check if logging is completely disabled
530
+ */
531
+ isDisabled() {
532
+ return this.level === "off";
533
+ }
534
+ };
535
+ var logger = new Logger();
536
+ async function loadFromFile(filePath) {
537
+ const { readFile } = await import('fs/promises');
538
+ const content = await readFile(filePath, "utf-8");
539
+ return parseAndValidateConfig(content);
540
+ }
541
+ async function loadFromUrl(url) {
542
+ const response = await fetch(url);
543
+ if (!response.ok) {
544
+ throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`);
545
+ }
546
+ const content = await response.text();
547
+ return parseAndValidateConfig(content);
548
+ }
549
+ async function loadConfig(uri, _options) {
550
+ if (uri.startsWith("http://") || uri.startsWith("https://")) {
551
+ return loadFromUrl(uri);
552
+ }
553
+ if (uri.startsWith("file://")) {
554
+ const filePath = uri.slice(7);
555
+ return loadFromFile(filePath);
556
+ }
557
+ return loadFromFile(uri);
558
+ }
559
+ async function loadConfigFromInline(content) {
560
+ return parseAndValidateConfig(content);
561
+ }
562
+ async function loadConfigWithOptions(options = {}) {
563
+ if (options.config) {
564
+ return loadConfigFromInline(options.config);
565
+ }
566
+ const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG;
567
+ if (envConfigPath) {
568
+ return loadConfig(envConfigPath);
569
+ }
570
+ if (options.configUrl) {
571
+ return loadConfig(options.configUrl);
572
+ }
573
+ if (options.configPath) {
574
+ return loadConfig(options.configPath);
575
+ }
576
+ const { existsSync } = await import('fs');
577
+ const { join } = await import('path');
578
+ const defaultPath = join(process.cwd(), "instrumentation.yaml");
579
+ if (existsSync(defaultPath)) {
580
+ return loadConfig(defaultPath);
581
+ }
582
+ return defaultConfig;
583
+ }
584
+
585
+ // src/integrations/effect/effect-tracer.ts
586
+ var SDK_NAME = "@effect/opentelemetry";
587
+ var ATTR_TELEMETRY_EXPORTER_MODE = "telemetry.exporter.mode";
588
+ function createEffectInstrumentation(options = {}) {
589
+ return Layer.unwrapEffect(
590
+ Effect.gen(function* () {
591
+ const config = yield* Effect.tryPromise({
592
+ try: () => loadConfigWithOptions(options),
593
+ catch: (error) => ({
594
+ _tag: "ConfigError",
595
+ message: error instanceof Error ? error.message : String(error)
596
+ })
597
+ });
598
+ const effectEnabled = process.env.OTEL_EFFECT_ENABLED !== "false" && (config.effect?.enabled ?? true);
599
+ if (!effectEnabled) {
600
+ logger.log("@atrim/instrumentation/effect: Effect tracing disabled via config");
601
+ return Layer.empty;
602
+ }
603
+ yield* Effect.sync(() => {
604
+ const loggingLevel = config.instrumentation.logging || "on";
605
+ logger.setLevel(loggingLevel);
606
+ });
607
+ yield* Effect.sync(() => initializePatternMatcher(config));
608
+ const serviceName = options.serviceName || process.env.OTEL_SERVICE_NAME || "effect-service";
609
+ const serviceVersion = options.serviceVersion || process.env.npm_package_version || "1.0.0";
610
+ const exporterMode = options.exporterMode ?? config.effect?.exporter ?? "unified";
611
+ const resourceAttributes = {
612
+ "platform.component": "effect",
613
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
614
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,
615
+ [ATTR_TELEMETRY_EXPORTER_MODE]: exporterMode
616
+ };
617
+ if (exporterMode === "standalone") {
618
+ const otlpEndpoint = options.otlpEndpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
619
+ logger.log("Effect OpenTelemetry instrumentation (standalone)");
620
+ logger.log(` Service: ${serviceName}`);
621
+ logger.log(` Endpoint: ${otlpEndpoint}`);
622
+ logger.log(" WARNING: Standalone mode bypasses Node SDK filtering");
623
+ return Otlp.layer({
624
+ baseUrl: otlpEndpoint,
625
+ resource: {
626
+ serviceName,
627
+ serviceVersion,
628
+ attributes: resourceAttributes
629
+ },
630
+ // Bridge Effect context to OpenTelemetry global context
631
+ tracerContext: (f, span) => {
632
+ if (span._tag !== "Span") {
633
+ return f();
634
+ }
635
+ const spanContext = {
636
+ traceId: span.traceId,
637
+ spanId: span.spanId,
638
+ traceFlags: span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE
639
+ };
640
+ const otelSpan = trace.wrapSpanContext(spanContext);
641
+ return context.with(trace.setSpan(context.active(), otelSpan), f);
642
+ }
643
+ }).pipe(Layer.provide(FetchHttpClient.layer));
644
+ } else {
645
+ logger.log("Effect OpenTelemetry instrumentation (unified)");
646
+ logger.log(` Service: ${serviceName}`);
647
+ logger.log(" Using global TracerProvider for span export");
648
+ return Tracer.layerGlobal.pipe(
649
+ Layer.provide(
650
+ Resource.layer({
651
+ serviceName,
652
+ serviceVersion,
653
+ attributes: resourceAttributes
654
+ })
655
+ )
656
+ );
657
+ }
658
+ })
659
+ ).pipe(Layer.orDie);
660
+ }
661
+ var EffectInstrumentationLive = Effect.sync(() => {
662
+ const serviceName = process.env.OTEL_SERVICE_NAME || "effect-service";
663
+ const serviceVersion = process.env.npm_package_version || "1.0.0";
664
+ logger.minimal(`@atrim/instrumentation/effect: Effect tracing enabled (${serviceName})`);
665
+ logger.log("Effect OpenTelemetry tracer (unified)");
666
+ logger.log(` Service: ${serviceName}`);
667
+ return Tracer.layerGlobal.pipe(
668
+ Layer.provide(
669
+ Resource.layer({
670
+ serviceName,
671
+ serviceVersion,
672
+ attributes: {
673
+ "platform.component": "effect",
674
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,
675
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,
676
+ [ATTR_TELEMETRY_EXPORTER_MODE]: "unified"
677
+ }
678
+ })
679
+ )
680
+ );
681
+ }).pipe(Layer.unwrapEffect);
682
+ function annotateUser(userId, email, username) {
683
+ const attributes = {
684
+ "user.id": userId
685
+ };
686
+ if (email) attributes["user.email"] = email;
687
+ if (username) attributes["user.name"] = username;
688
+ return Effect.annotateCurrentSpan(attributes);
689
+ }
690
+ function annotateDataSize(bytes, items, compressionRatio) {
691
+ const attributes = {
692
+ "data.size.bytes": bytes,
693
+ "data.size.items": items
694
+ };
695
+ if (compressionRatio !== void 0) {
696
+ attributes["data.compression.ratio"] = compressionRatio;
697
+ }
698
+ return Effect.annotateCurrentSpan(attributes);
699
+ }
700
+ function annotateBatch(totalItems, batchSize, successCount, failureCount) {
701
+ const attributes = {
702
+ "batch.size": batchSize,
703
+ "batch.total_items": totalItems,
704
+ "batch.count": Math.ceil(totalItems / batchSize)
705
+ };
706
+ if (successCount !== void 0) {
707
+ attributes["batch.success_count"] = successCount;
708
+ }
709
+ if (failureCount !== void 0) {
710
+ attributes["batch.failure_count"] = failureCount;
711
+ }
712
+ return Effect.annotateCurrentSpan(attributes);
713
+ }
714
+ function annotateLLM(model, provider, tokens) {
715
+ const attributes = {
716
+ "llm.model": model,
717
+ "llm.provider": provider
718
+ };
719
+ if (tokens) {
720
+ if (tokens.prompt !== void 0) attributes["llm.tokens.prompt"] = tokens.prompt;
721
+ if (tokens.completion !== void 0) attributes["llm.tokens.completion"] = tokens.completion;
722
+ if (tokens.total !== void 0) attributes["llm.tokens.total"] = tokens.total;
723
+ }
724
+ return Effect.annotateCurrentSpan(attributes);
725
+ }
726
+ function annotateQuery(query, duration, rowCount, database) {
727
+ const attributes = {
728
+ "db.statement": query.length > 1e3 ? query.substring(0, 1e3) + "..." : query
729
+ };
730
+ if (duration !== void 0) attributes["db.duration.ms"] = duration;
731
+ if (rowCount !== void 0) attributes["db.row_count"] = rowCount;
732
+ if (database) attributes["db.name"] = database;
733
+ return Effect.annotateCurrentSpan(attributes);
734
+ }
735
+ function annotateHttpRequest(method, url, statusCode, contentLength) {
736
+ const attributes = {
737
+ "http.method": method,
738
+ "http.url": url
739
+ };
740
+ if (statusCode !== void 0) attributes["http.status_code"] = statusCode;
741
+ if (contentLength !== void 0) attributes["http.response.content_length"] = contentLength;
742
+ return Effect.annotateCurrentSpan(attributes);
743
+ }
744
+ function annotateError(error, recoverable, errorType) {
745
+ const errorMessage = typeof error === "string" ? error : error.message;
746
+ const errorStack = typeof error === "string" ? void 0 : error.stack;
747
+ const attributes = {
748
+ "error.message": errorMessage,
749
+ "error.recoverable": recoverable
750
+ };
751
+ if (errorType) attributes["error.type"] = errorType;
752
+ if (errorStack) attributes["error.stack"] = errorStack;
753
+ return Effect.annotateCurrentSpan(attributes);
754
+ }
755
+ function annotatePriority(priority, reason) {
756
+ const attributes = {
757
+ "operation.priority": priority
758
+ };
759
+ if (reason) attributes["operation.priority.reason"] = reason;
760
+ return Effect.annotateCurrentSpan(attributes);
761
+ }
762
+ function annotateCache(hit, key, ttl) {
763
+ const attributes = {
764
+ "cache.hit": hit,
765
+ "cache.key": key
766
+ };
767
+ if (ttl !== void 0) attributes["cache.ttl.seconds"] = ttl;
768
+ return Effect.annotateCurrentSpan(attributes);
769
+ }
770
+ function extractEffectMetadata() {
771
+ return Effect.gen(function* () {
772
+ const metadata = {};
773
+ const currentFiber = Fiber.getCurrentFiber();
774
+ if (Option.isSome(currentFiber)) {
775
+ const fiber = currentFiber.value;
776
+ const fiberId = fiber.id();
777
+ metadata["effect.fiber.id"] = FiberId.threadName(fiberId);
778
+ const status = yield* Fiber.status(fiber);
779
+ if (status._tag) {
780
+ metadata["effect.fiber.status"] = status._tag;
781
+ }
782
+ }
783
+ const parentSpanResult = yield* Effect.currentSpan.pipe(
784
+ Effect.option
785
+ // Convert NoSuchElementException to Option
786
+ );
787
+ if (Option.isSome(parentSpanResult)) {
788
+ const parentSpan = parentSpanResult.value;
789
+ metadata["effect.operation.nested"] = true;
790
+ metadata["effect.operation.root"] = false;
791
+ if (parentSpan.spanId) {
792
+ metadata["effect.parent.span.id"] = parentSpan.spanId;
793
+ }
794
+ if (parentSpan.name) {
795
+ metadata["effect.parent.span.name"] = parentSpan.name;
796
+ }
797
+ if (parentSpan.traceId) {
798
+ metadata["effect.parent.trace.id"] = parentSpan.traceId;
799
+ }
800
+ } else {
801
+ metadata["effect.operation.nested"] = false;
802
+ metadata["effect.operation.root"] = true;
803
+ }
804
+ return metadata;
805
+ });
806
+ }
807
+ function autoEnrichSpan() {
808
+ return Effect.gen(function* () {
809
+ const metadata = yield* extractEffectMetadata();
810
+ yield* Effect.annotateCurrentSpan(metadata);
811
+ });
812
+ }
813
+ function withAutoEnrichedSpan(spanName, options) {
814
+ return (self) => {
815
+ return Effect.gen(function* () {
816
+ yield* autoEnrichSpan();
817
+ return yield* self;
818
+ }).pipe(Effect.withSpan(spanName, options));
819
+ };
820
+ }
821
+ var createLogicalParentLink = (parentSpan, useSpanLinks) => {
822
+ if (!useSpanLinks) {
823
+ return [];
824
+ }
825
+ return [
826
+ {
827
+ _tag: "SpanLink",
828
+ span: parentSpan,
829
+ attributes: {
830
+ "link.type": "logical_parent",
831
+ "atrim.relationship": "spawned_by",
832
+ description: "Logical parent (isolated to prevent context leakage)"
833
+ }
834
+ }
835
+ ];
836
+ };
837
+ var createLogicalParentAttributes = (parentSpan, useAttributes, category, useSpanLinks, customAttributes) => {
838
+ if (!useAttributes) {
839
+ return customAttributes;
840
+ }
841
+ return {
842
+ // Logical parent tracking (works in ALL tools)
843
+ "atrim.logical_parent.span_id": parentSpan.spanId,
844
+ "atrim.logical_parent.trace_id": parentSpan.traceId,
845
+ "atrim.logical_parent.name": parentSpan._tag === "Span" ? parentSpan.name : "external",
846
+ // Categorization and metadata
847
+ "atrim.fiberset.isolated": true,
848
+ "atrim.span.category": category,
849
+ "atrim.has_logical_parent": true,
850
+ "atrim.isolation.method": useSpanLinks ? "hybrid" : "attributes_only",
851
+ // User-provided attributes
852
+ ...customAttributes
853
+ };
854
+ };
855
+ var runIsolated = (set, effect, name, options) => {
856
+ const {
857
+ createRoot = true,
858
+ captureLogicalParent = true,
859
+ useSpanLinks = true,
860
+ useAttributes = true,
861
+ propagateInterruption,
862
+ attributes = {},
863
+ category = "background_task"
864
+ } = options ?? {};
865
+ if (!createRoot && !captureLogicalParent) {
866
+ return FiberSet$1.run(set, effect, { propagateInterruption });
867
+ }
868
+ return Effect.gen(function* () {
869
+ const maybeParent = yield* Effect.serviceOption(Tracer$1.ParentSpan);
870
+ if (maybeParent._tag === "None" || !captureLogicalParent) {
871
+ const isolated2 = effect.pipe(
872
+ Effect.withSpan(name, {
873
+ root: createRoot,
874
+ attributes: {
875
+ "atrim.fiberset.isolated": createRoot,
876
+ "atrim.span.category": category,
877
+ "atrim.has_logical_parent": false,
878
+ ...attributes
879
+ }
880
+ })
881
+ );
882
+ return yield* FiberSet$1.run(set, isolated2, { propagateInterruption });
883
+ }
884
+ const parent = maybeParent.value;
885
+ const links = createLogicalParentLink(parent, useSpanLinks);
886
+ const spanAttributes = createLogicalParentAttributes(
887
+ parent,
888
+ useAttributes,
889
+ category,
890
+ useSpanLinks,
891
+ attributes
892
+ );
893
+ const isolated = effect.pipe(
894
+ Effect.withSpan(name, {
895
+ root: createRoot,
896
+ links: links.length > 0 ? links : void 0,
897
+ attributes: spanAttributes
898
+ })
899
+ );
900
+ return yield* FiberSet$1.run(set, isolated, { propagateInterruption });
901
+ });
902
+ };
903
+ var runWithSpan = (set, name, effect, options) => {
904
+ return runIsolated(set, effect, name, {
905
+ createRoot: true,
906
+ captureLogicalParent: true,
907
+ useSpanLinks: true,
908
+ useAttributes: true,
909
+ ...options
910
+ });
911
+ };
912
+ var annotateSpawnedTasks = (tasks) => {
913
+ return Effect.annotateCurrentSpan({
914
+ "atrim.fiberset.spawned_count": tasks.length,
915
+ "atrim.fiberset.task_names": tasks.map((t) => t.name).join(","),
916
+ "atrim.has_background_tasks": true,
917
+ "atrim.spawned_tasks": JSON.stringify(
918
+ tasks.map((t) => ({
919
+ name: t.name,
920
+ ...t.spanId && { span_id: t.spanId },
921
+ ...t.category && { category: t.category }
922
+ }))
923
+ )
924
+ });
925
+ };
926
+ var FiberSet = {
927
+ // Re-export all original FiberSet functions
928
+ make: FiberSet$1.make,
929
+ add: FiberSet$1.add,
930
+ unsafeAdd: FiberSet$1.unsafeAdd,
931
+ run: FiberSet$1.run,
932
+ clear: FiberSet$1.clear,
933
+ join: FiberSet$1.join,
934
+ awaitEmpty: FiberSet$1.awaitEmpty,
935
+ size: FiberSet$1.size,
936
+ runtime: FiberSet$1.runtime,
937
+ runtimePromise: FiberSet$1.runtimePromise,
938
+ makeRuntime: FiberSet$1.makeRuntime,
939
+ makeRuntimePromise: FiberSet$1.makeRuntimePromise,
940
+ isFiberSet: FiberSet$1.isFiberSet,
941
+ // Add our isolation helpers
942
+ runIsolated,
943
+ runWithSpan
944
+ };
945
+
946
+ export { EffectInstrumentationLive, FiberSet, annotateBatch, annotateCache, annotateDataSize, annotateError, annotateHttpRequest, annotateLLM, annotatePriority, annotateQuery, annotateSpawnedTasks, annotateUser, autoEnrichSpan, createEffectInstrumentation, extractEffectMetadata, runIsolated, runWithSpan, withAutoEnrichedSpan };
947
+ //# sourceMappingURL=index.js.map
948
+ //# sourceMappingURL=index.js.map