@atrim/instrument-node 0.7.0 → 0.7.1-dev.14fdea7.20260108224013
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.
- package/package.json +6 -1
- package/target/dist/index.cjs +93 -2
- package/target/dist/index.cjs.map +1 -1
- package/target/dist/index.js +93 -2
- package/target/dist/index.js.map +1 -1
- package/target/dist/integrations/effect/auto/index.cjs +1117 -0
- package/target/dist/integrations/effect/auto/index.cjs.map +1 -0
- package/target/dist/integrations/effect/auto/index.d.cts +359 -0
- package/target/dist/integrations/effect/auto/index.d.ts +359 -0
- package/target/dist/integrations/effect/auto/index.js +1074 -0
- package/target/dist/integrations/effect/auto/index.js.map +1 -0
- package/target/dist/integrations/effect/index.cjs +93 -2
- package/target/dist/integrations/effect/index.cjs.map +1 -1
- package/target/dist/integrations/effect/index.js +93 -2
- package/target/dist/integrations/effect/index.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../core/src/instrumentation-schema.ts","../../../../../core/src/errors.ts","../../../../../core/src/services/config-loader.ts","../../../../../core/src/pattern-matcher.ts","../../../../../core/src/logger.ts","../../../../src/core/config-loader.ts","../../../../src/integrations/effect/effect-tracer.ts","../../../../src/integrations/effect/effect-helpers.ts","../../../../src/integrations/effect/metadata-extractor.ts","../../../../src/integrations/effect/auto-enrichment.ts","../../../../src/integrations/effect/fiberset.ts"],"names":["parseYaml","parseYAML","Layer","Effect","EffectFiberSet","Tracer","isolated"],"mappings":";;;;;;;;;;;;;;;;;AAMO,IAAM,mBAAA,GAAsB,EAAE,MAAA,CAAO;AAC1C,EAAA,OAAA,EAAS,EAAE,MAAA,EAAA;EACX,OAAA,EAAS,CAAA,CAAE,OAAA,EAAA,CAAU,QAAA,EAAA;EACrB,WAAA,EAAa,CAAA,CAAE,MAAA,EAAA,CAAS,QAAA;AAC1B,CAAC,CAAA;AAQM,IAAM,yBAAA,GAA4B,EAAE,MAAA,CAAO;;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AAA,EAAU,EAAE,QAAA;AAAS,OAC3C,CAAE;AAAA;AACJ,GACD,CAAA;AACH;AAUO,IAAM,QAAA,GAAW;AAAA;AAAA,EAEtB,MAAMC,UAAA,CAAe,IAAA;AAAA,EACrB,KAAKA,UAAA,CAAe,GAAA;AAAA,EACpB,WAAWA,UAAA,CAAe,SAAA;AAAA,EAC1B,KAAKA,UAAA,CAAe,GAAA;AAAA,EACpB,OAAOA,UAAA,CAAe,KAAA;AAAA,EACtB,MAAMA,UAAA,CAAe,IAAA;AAAA,EACrB,YAAYA,UAAA,CAAe,UAAA;AAAA,EAC3B,MAAMA,UAAA,CAAe,IAAA;AAAA,EACrB,SAASA,UAAA,CAAe,OAAA;AAAA,EACxB,gBAAgBA,UAAA,CAAe,cAAA;AAAA,EAC/B,aAAaA,UAAA,CAAe,WAAA;AAAA,EAC5B,oBAAoBA,UAAA,CAAe,kBAAA;AAAA,EACnC,YAAYA,UAAA,CAAe,UAAA;AAAA;AAAA,EAG3B,WAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["/**\n * Configuration schema using Zod\n */\nimport { z } from 'zod'\nimport { parse as parseYaml } from 'yaml'\n\nexport const PatternConfigSchema = z.object({\n pattern: z.string(),\n enabled: z.boolean().optional(),\n description: z.string().optional()\n})\n\n/**\n * Configuration for automatic span isolation in Effect operations\n *\n * This prevents context leakage when using FiberSet.run, Effect.fork, etc.\n * while maintaining logical parent relationships via span links.\n */\nexport const AutoIsolationConfigSchema = z.object({\n // Global enable/disable for auto-isolation\n enabled: z.boolean().default(false),\n\n // Which operators to auto-isolate\n operators: z\n .object({\n fiberset_run: z.boolean().default(true),\n effect_fork: z.boolean().default(true),\n effect_fork_daemon: z.boolean().default(true),\n effect_fork_in: z.boolean().default(false)\n })\n .default({}),\n\n // Virtual parent tracking configuration\n tracking: z\n .object({\n use_span_links: z.boolean().default(true),\n use_attributes: z.boolean().default(true),\n capture_logical_parent: z.boolean().default(true)\n })\n .default({}),\n\n // Span categorization\n attributes: z\n .object({\n category: z.string().default('background_task'),\n add_metadata: z.boolean().default(true)\n })\n .default({})\n})\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\nexport const HttpFilteringConfigSchema = z.object({\n // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)\n ignore_outgoing_urls: z.array(z.string()).optional(),\n\n // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)\n ignore_incoming_paths: z.array(z.string()).optional(),\n\n // Require parent span for outgoing requests (prevents root spans for HTTP calls)\n require_parent_for_outgoing_spans: z.boolean().optional(),\n\n // Trace context propagation configuration\n // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)\n propagate_trace_context: z\n .object({\n // Strategy for trace propagation\n // - \"all\": Propagate to all cross-origin requests (may cause CORS errors)\n // - \"none\": Never propagate trace headers\n // - \"same-origin\": Only propagate to same-origin requests (default, safe)\n // - \"patterns\": Propagate based on include_urls patterns\n strategy: z.enum(['all', 'none', 'same-origin', 'patterns']).default('same-origin'),\n\n // URL patterns to include when strategy is \"patterns\"\n // Supports regex patterns (e.g., \"^https://api\\\\.myapp\\\\.com\")\n include_urls: z.array(z.string()).optional()\n })\n .optional()\n})\n\nexport const InstrumentationConfigSchema = z.object({\n version: z.string(),\n instrumentation: z.object({\n enabled: z.boolean(),\n description: z.string().optional(),\n logging: z.enum(['on', 'off', 'minimal']).optional().default('on'),\n instrument_patterns: z.array(PatternConfigSchema),\n ignore_patterns: z.array(PatternConfigSchema)\n }),\n effect: z\n .object({\n // Enable/disable Effect tracing entirely\n // When false, EffectInstrumentationLive returns Layer.empty\n enabled: z.boolean().default(true),\n // Exporter mode:\n // - \"unified\": Use global TracerProvider from Node SDK (recommended, enables filtering)\n // - \"standalone\": Use Effect's own OTLP exporter (bypasses Node SDK filtering)\n exporter: z.enum(['unified', 'standalone']).default('unified'),\n auto_extract_metadata: z.boolean(),\n auto_isolation: AutoIsolationConfigSchema.optional()\n })\n .optional(),\n http: HttpFilteringConfigSchema.optional()\n})\n\nexport type InstrumentationConfig = z.infer<typeof InstrumentationConfigSchema>\nexport type PatternConfig = z.infer<typeof PatternConfigSchema>\nexport type AutoIsolationConfig = z.infer<typeof AutoIsolationConfigSchema>\nexport type HttpFilteringConfig = z.infer<typeof HttpFilteringConfigSchema>\n\n/**\n * Default configuration when no config file is found\n */\nexport const defaultConfig: InstrumentationConfig = {\n version: '1.0',\n instrumentation: {\n enabled: true,\n logging: 'on',\n description: 'Default instrumentation configuration',\n instrument_patterns: [\n { pattern: '^app\\\\.', enabled: true, description: 'Application operations' },\n { pattern: '^http\\\\.server\\\\.', enabled: true, description: 'HTTP server operations' },\n { pattern: '^http\\\\.client\\\\.', enabled: true, description: 'HTTP client operations' }\n ],\n ignore_patterns: [\n { pattern: '^test\\\\.', description: 'Test utilities' },\n { pattern: '^internal\\\\.', description: 'Internal operations' },\n { pattern: '^health\\\\.', description: 'Health checks' }\n ]\n },\n effect: {\n enabled: true,\n exporter: 'unified' as const,\n auto_extract_metadata: true\n }\n}\n\n/**\n * Parse and validate configuration content (YAML string, JSON string, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Validated InstrumentationConfig\n * @throws Error if parsing or validation fails\n */\nexport function parseAndValidateConfig(content: string | unknown): InstrumentationConfig {\n let parsed: unknown\n\n // If string, parse as YAML (YAML is a superset of JSON)\n if (typeof content === 'string') {\n parsed = parseYaml(content)\n } else {\n parsed = content\n }\n\n // Validate with schema\n return InstrumentationConfigSchema.parse(parsed)\n}\n","/**\n * Typed error hierarchy for @atrim/instrumentation\n *\n * These errors use Effect's Data.TaggedError for typed error handling\n * with proper discriminated unions.\n */\n\nimport { Data } from 'effect'\n\n/**\n * Base error for configuration-related failures\n */\nexport class ConfigError extends Data.TaggedError('ConfigError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when fetching configuration from a URL fails\n */\nexport class ConfigUrlError extends Data.TaggedError('ConfigUrlError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when configuration validation fails (invalid YAML, schema mismatch)\n */\nexport class ConfigValidationError extends Data.TaggedError('ConfigValidationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when reading configuration from a file fails\n */\nexport class ConfigFileError extends Data.TaggedError('ConfigFileError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when service detection fails (package.json not found, invalid format)\n */\nexport class ServiceDetectionError extends Data.TaggedError('ServiceDetectionError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when OpenTelemetry SDK initialization fails\n */\nexport class InitializationError extends Data.TaggedError('InitializationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when span export fails (e.g., ECONNREFUSED to collector)\n */\nexport class ExportError extends Data.TaggedError('ExportError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when shutting down the SDK fails\n */\nexport class ShutdownError extends Data.TaggedError('ShutdownError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n","/**\n * ConfigLoader service using Effect Platform\n *\n * Provides URI-based configuration loading with pluggable platform services:\n * - FileSystem for file:// URIs (Node.js/Bun/Deno)\n * - HttpClient for http:// and https:// URIs (universal)\n *\n * This service has NO Node.js-specific dependencies - it depends only on\n * abstract Effect Platform services that are provided by environment-specific layers.\n */\n\nimport { Effect, Context, Layer } from 'effect'\nimport { FileSystem } from '@effect/platform/FileSystem'\nimport * as HttpClient from '@effect/platform/HttpClient'\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest'\nimport { parse as parseYAML } from 'yaml'\nimport {\n InstrumentationConfigSchema,\n type InstrumentationConfig\n} from '../instrumentation-schema.js'\nimport { ConfigError, ConfigFileError, ConfigUrlError, ConfigValidationError } from '../errors.js'\n\n// Security constraints\nconst SECURITY_DEFAULTS = {\n maxConfigSize: 1_000_000, // 1MB\n requestTimeout: 5_000 // 5 seconds\n} as const\n\n/**\n * ConfigLoader service interface\n */\nexport interface ConfigLoaderService {\n /**\n * Load configuration from a URI\n *\n * Supports:\n * - file:// URIs (uses FileSystem if available)\n * - http:// and https:// URIs (uses HttpClient)\n * - Relative paths (treated as file:// in Node, http:// in browser)\n *\n * @param uri - Configuration URI\n * @returns Effect that resolves to validated configuration (NO requirements)\n */\n readonly loadFromUri: (\n uri: string\n ) => Effect.Effect<\n InstrumentationConfig,\n ConfigError | ConfigFileError | ConfigUrlError | ConfigValidationError\n >\n\n /**\n * Load configuration from inline content (YAML, JSON, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Effect that resolves to validated configuration\n */\n readonly loadFromInline: (\n content: string | unknown\n ) => Effect.Effect<InstrumentationConfig, ConfigError | ConfigValidationError>\n}\n\n/**\n * ConfigLoader service tag\n */\nexport class ConfigLoader extends Context.Tag('ConfigLoader')<\n ConfigLoader,\n ConfigLoaderService\n>() {}\n\n/**\n * Parse and validate YAML content\n */\nconst parseYamlContent = (\n content: string,\n uri?: string\n): Effect.Effect<InstrumentationConfig, ConfigValidationError> =>\n Effect.gen(function* () {\n // Parse YAML\n const parsed = yield* Effect.try({\n try: () => parseYAML(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Failed to parse YAML from ${uri}` : 'Failed to parse YAML',\n cause: error\n })\n })\n\n // Validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(parsed),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Invalid configuration schema from ${uri}` : 'Invalid configuration schema',\n cause: error\n })\n })\n })\n\n/**\n * Load configuration from file using captured FileSystem service\n */\nconst loadFromFileWithFs = (\n fs: FileSystem,\n path: string,\n uri: string\n): Effect.Effect<InstrumentationConfig, ConfigFileError | ConfigValidationError> =>\n Effect.gen(function* () {\n // Read file\n const content = yield* fs.readFileString(path).pipe(\n Effect.mapError(\n (error) =>\n new ConfigFileError({\n reason: `Failed to read config file at ${uri}`,\n cause: error\n })\n )\n )\n\n // Security: Check file size\n if (content.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(content, uri)\n })\n\n/**\n * Load configuration from http using captured HttpClient service\n */\nconst loadFromHttpWithClient = (\n client: HttpClient.HttpClient,\n url: string\n): Effect.Effect<InstrumentationConfig, ConfigUrlError | ConfigValidationError> =>\n Effect.scoped(\n Effect.gen(function* () {\n // Security: Reject non-HTTPS URLs\n if (url.startsWith('http://')) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: 'Insecure protocol: only HTTPS URLs are allowed'\n })\n )\n }\n\n // Create request\n const request = HttpClientRequest.get(url).pipe(\n HttpClientRequest.setHeaders({\n Accept: 'application/yaml, text/yaml, application/x-yaml'\n })\n )\n\n // Execute request with timeout\n const response = yield* client.execute(request).pipe(\n Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),\n Effect.mapError((error) => {\n if (error._tag === 'TimeoutException') {\n return new ConfigUrlError({\n reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`\n })\n }\n return new ConfigUrlError({\n reason: `Failed to load config from URL: ${url}`,\n cause: error\n })\n })\n )\n\n // Check HTTP status\n if (response.status >= 400) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `HTTP ${response.status} from ${url}`\n })\n )\n }\n\n // Get response text\n const text = yield* response.text.pipe(\n Effect.mapError(\n (error) =>\n new ConfigUrlError({\n reason: `Failed to read response body from ${url}`,\n cause: error\n })\n )\n )\n\n // Security: Check size\n if (text.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(text, url)\n })\n )\n\n/**\n * ConfigLoader service implementation\n *\n * Captures FileSystem and HttpClient dependencies at construction time\n */\nconst makeConfigLoader = Effect.gen(function* () {\n // Capture dependencies at construction time\n const fs = yield* Effect.serviceOption(FileSystem)\n const http = yield* HttpClient.HttpClient\n\n // Create the loadFromUri function\n const loadFromUriUncached = (uri: string) =>\n Effect.gen(function* () {\n // file:// protocol\n if (uri.startsWith('file://')) {\n const path = uri.slice(7) // Remove \"file://\"\n\n if (fs._tag === 'None') {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: 'FileSystem not available (browser environment?)',\n cause: { uri }\n })\n )\n }\n\n return yield* loadFromFileWithFs(fs.value, path, uri)\n }\n\n // http:// or https:// protocol\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return yield* loadFromHttpWithClient(http, uri)\n }\n\n // Relative path - try FileSystem first, fallback to HTTP\n if (fs._tag === 'Some') {\n // FileSystem available (Node.js environment)\n return yield* loadFromFileWithFs(fs.value, uri, uri)\n } else {\n // No FileSystem (browser environment) - treat as HTTP\n // Relative URLs will be resolved by browser fetch to current origin\n return yield* loadFromHttpWithClient(http, uri)\n }\n })\n\n // Cache the loadFromUri function with 5 minute TTL (default cache timeout)\n const loadFromUriCached = yield* Effect.cachedFunction(loadFromUriUncached)\n\n return ConfigLoader.of({\n loadFromUri: loadFromUriCached,\n\n loadFromInline: (content: string | unknown) =>\n Effect.gen(function* () {\n // If string, parse as YAML\n if (typeof content === 'string') {\n return yield* parseYamlContent(content)\n }\n\n // Already an object - just validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: 'Invalid configuration schema',\n cause: error\n })\n })\n })\n })\n})\n\n/**\n * ConfigLoader Live layer\n *\n * Provides ConfigLoader service implementation.\n * Requires HttpClient to be provided by platform-specific layers.\n * FileSystem is optional (for browser compatibility).\n */\nexport const ConfigLoaderLive = Layer.effect(ConfigLoader, makeConfigLoader)\n","/**\n * Pattern matching utilities\n *\n * Implements efficient pattern-based span filtering with caching.\n *\n * Matching rules:\n * 1. Check ignore patterns first (takes precedence)\n * 2. Check instrument patterns second\n * 3. Default behavior: If no patterns match, span is created (fail-open)\n */\n\nimport type { InstrumentationConfig, PatternConfig } from './instrumentation-schema.js'\n\n/**\n * Compiled pattern with metadata\n */\ninterface CompiledPattern {\n regex: RegExp\n enabled: boolean\n description?: string\n}\n\n/**\n * Pattern matcher with compiled regex cache\n */\nexport class PatternMatcher {\n private ignorePatterns: CompiledPattern[] = []\n private instrumentPatterns: CompiledPattern[] = []\n private enabled: boolean = true\n\n constructor(config: InstrumentationConfig) {\n this.enabled = config.instrumentation.enabled\n\n // Compile ignore patterns (highest priority)\n this.ignorePatterns = config.instrumentation.ignore_patterns.map((p) => this.compilePattern(p))\n\n // Compile instrument patterns\n this.instrumentPatterns = config.instrumentation.instrument_patterns\n .filter((p) => p.enabled !== false) // Filter out disabled patterns\n .map((p) => this.compilePattern(p))\n }\n\n /**\n * Compile a pattern configuration into a RegExp\n */\n private compilePattern(pattern: PatternConfig): CompiledPattern {\n try {\n const compiled: CompiledPattern = {\n regex: new RegExp(pattern.pattern),\n enabled: pattern.enabled !== false\n }\n if (pattern.description !== undefined) {\n compiled.description = pattern.description\n }\n return compiled\n } catch (error) {\n throw new Error(\n `Failed to compile pattern \"${pattern.pattern}\": ${error instanceof Error ? error.message : String(error)}`\n )\n }\n }\n\n /**\n * Check if a span should be instrumented\n *\n * Returns true if the span should be created, false otherwise.\n *\n * Logic:\n * 1. If instrumentation disabled globally, return false\n * 2. Check ignore patterns - if any match, return false\n * 3. Check instrument patterns - if any match, return true\n * 4. Default: return true (fail-open - create span if no patterns match)\n */\n shouldInstrument(spanName: string): boolean {\n // Global disable\n if (!this.enabled) {\n return false\n }\n\n // Check ignore patterns first (highest priority)\n for (const pattern of this.ignorePatterns) {\n if (pattern.regex.test(spanName)) {\n return false\n }\n }\n\n // Check instrument patterns\n for (const pattern of this.instrumentPatterns) {\n if (pattern.enabled && pattern.regex.test(spanName)) {\n return true\n }\n }\n\n // Default: fail-open (create span if no patterns match)\n // This ensures backward compatibility and doesn't break existing instrumentation\n return true\n }\n\n /**\n * Get statistics about pattern matching (for debugging/monitoring)\n */\n getStats(): {\n enabled: boolean\n ignorePatternCount: number\n instrumentPatternCount: number\n } {\n return {\n enabled: this.enabled,\n ignorePatternCount: this.ignorePatterns.length,\n instrumentPatternCount: this.instrumentPatterns.filter((p) => p.enabled).length\n }\n }\n}\n\n// Global pattern matcher instance\nlet globalMatcher: PatternMatcher | null = null\n\n/**\n * Initialize the global pattern matcher\n */\nexport function initializePatternMatcher(config: InstrumentationConfig): void {\n globalMatcher = new PatternMatcher(config)\n}\n\n/**\n * Check if a span should be instrumented (uses global matcher)\n *\n * This is a convenience function for use without direct access to the matcher instance.\n * If no matcher is initialized, defaults to true (fail-open).\n */\nexport function shouldInstrumentSpan(spanName: string): boolean {\n if (!globalMatcher) {\n // No matcher initialized - fail open\n return true\n }\n return globalMatcher.shouldInstrument(spanName)\n}\n\n/**\n * Get the global pattern matcher (for advanced use cases)\n */\nexport function getPatternMatcher(): PatternMatcher | null {\n return globalMatcher\n}\n\n/**\n * Clear the global pattern matcher (useful for testing)\n */\nexport function clearPatternMatcher(): void {\n globalMatcher = null\n}\n","/**\n * Centralized logging utility for @atrim/instrumentation\n *\n * Supports three levels:\n * - 'on' (default): All logging enabled\n * - 'minimal': Only a single initialization message + errors/warnings\n * - 'off': No logging at all\n */\n\nexport type LogLevel = 'on' | 'off' | 'minimal'\n\nclass Logger {\n private level: LogLevel = 'on'\n private hasLoggedMinimal = false\n\n /**\n * Set the logging level\n */\n setLevel(level: LogLevel): void {\n this.level = level\n this.hasLoggedMinimal = false\n }\n\n /**\n * Get the current logging level\n */\n getLevel(): LogLevel {\n return this.level\n }\n\n /**\n * Log a minimal initialization message (only shown once in minimal mode)\n */\n minimal(message: string): void {\n if (this.level === 'off') {\n return\n }\n\n if (this.level === 'minimal' && !this.hasLoggedMinimal) {\n console.log(message)\n this.hasLoggedMinimal = true\n return\n }\n\n if (this.level === 'on') {\n console.log(message)\n }\n }\n\n /**\n * Log an informational message\n */\n log(...args: unknown[]): void {\n if (this.level === 'on') {\n console.log(...args)\n }\n }\n\n /**\n * Log a warning message (shown in minimal mode)\n */\n warn(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.warn(...args)\n }\n }\n\n /**\n * Log an error message (shown in minimal mode)\n */\n error(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.error(...args)\n }\n }\n\n /**\n * Check if full logging is enabled\n */\n isEnabled(): boolean {\n return this.level === 'on'\n }\n\n /**\n * Check if minimal logging is enabled\n */\n isMinimal(): boolean {\n return this.level === 'minimal'\n }\n\n /**\n * Check if logging is completely disabled\n */\n isDisabled(): boolean {\n return this.level === 'off'\n }\n}\n\n// Singleton instance\nexport const logger = new Logger()\n","/**\n * Node.js configuration loader\n *\n * Provides configuration loading using native Node.js APIs (fs, fetch)\n * This module doesn't require Effect Platform, making it work without Effect installed.\n */\n\nimport { Effect } from 'effect'\nimport {\n type InstrumentationConfig,\n parseAndValidateConfig,\n defaultConfig\n} from '@atrim/instrument-core'\n\n/**\n * Load configuration from a file path using native Node.js fs\n */\nasync function loadFromFile(filePath: string): Promise<InstrumentationConfig> {\n const { readFile } = await import('fs/promises')\n const content = await readFile(filePath, 'utf-8')\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from a URL using native fetch\n */\nasync function loadFromUrl(url: string): Promise<InstrumentationConfig> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`)\n }\n const content = await response.text()\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from URI (file path or URL)\n *\n * @param uri - Configuration URI (file://, http://, https://, or relative path)\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfig(\n uri: string,\n _options?: { cacheTimeout?: number }\n): Promise<InstrumentationConfig> {\n // Handle URL protocols\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return loadFromUrl(uri)\n }\n\n // Handle file:// protocol\n if (uri.startsWith('file://')) {\n const filePath = uri.slice(7) // Remove 'file://'\n return loadFromFile(filePath)\n }\n\n // Treat as file path\n return loadFromFile(uri)\n}\n\n/**\n * Load configuration from inline content\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigFromInline(\n content: string | unknown\n): Promise<InstrumentationConfig> {\n return parseAndValidateConfig(content)\n}\n\n/**\n * Reset the config loader cache (no-op for native implementation)\n * @internal\n */\nexport function _resetConfigLoaderCache(): void {\n // No cache in native implementation\n}\n\n/**\n * Legacy options interface for backward compatibility\n */\nexport interface ConfigLoaderOptions {\n configPath?: string\n configUrl?: string\n config?: InstrumentationConfig\n cacheTimeout?: number\n}\n\n/**\n * Load configuration with priority order (backward compatible API)\n *\n * Priority order (highest to lowest):\n * 1. Explicit config object (options.config)\n * 2. Environment variable (ATRIM_INSTRUMENTATION_CONFIG)\n * 3. Explicit path/URL (options.configPath or options.configUrl)\n * 4. Project root file (./instrumentation.yaml)\n * 5. Default config (built-in defaults)\n *\n * @param options - Configuration options\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigWithOptions(\n options: ConfigLoaderOptions = {}\n): Promise<InstrumentationConfig> {\n // Priority 1: Explicit config object\n if (options.config) {\n return loadConfigFromInline(options.config)\n }\n\n // Priority 2: Environment variable\n const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG\n if (envConfigPath) {\n return loadConfig(envConfigPath, options)\n }\n\n // Priority 3: Explicit options\n if (options.configUrl) {\n return loadConfig(options.configUrl, options)\n }\n if (options.configPath) {\n return loadConfig(options.configPath, options)\n }\n\n // Priority 4: Project root file\n const { existsSync } = await import('fs')\n const { join } = await import('path')\n\n const defaultPath = join(process.cwd(), 'instrumentation.yaml')\n if (existsSync(defaultPath)) {\n return loadConfig(defaultPath, options)\n }\n\n // Priority 5: Default config\n return defaultConfig\n}\n\n// ============================================================================\n// Effect-Based API (for Effect users)\n// ============================================================================\n\n/**\n * Load configuration from URI (Effect version)\n */\nexport const loadConfigEffect = (\n uri: string,\n options?: { cacheTimeout?: number }\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfig(uri, options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration from inline content (Effect version)\n */\nexport const loadConfigFromInlineEffect = (\n content: string | unknown\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigFromInline(content),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration with priority order (Effect version)\n */\nexport const loadConfigWithOptionsEffect = (\n options: ConfigLoaderOptions = {}\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n","/**\n * Effect-TS Tracer integration with context propagation\n *\n * This module provides Effect-TS tracing that seamlessly integrates with\n * OpenTelemetry NodeSDK auto-instrumentation. Effect spans will automatically\n * continue existing traces created by NodeSDK (e.g., HTTP requests).\n *\n * Context Propagation:\n * - NodeSDK auto-instrumentation creates root spans (e.g., HTTP requests)\n * - Effect operations automatically become child spans of the active trace\n * - Uses OpenTelemetry Context API (equivalent to Java thread-local)\n * - No configuration needed - works out of the box\n *\n * Architecture:\n * 1. @effect/opentelemetry uses the global OpenTelemetry tracer provider\n * 2. When an Effect operation starts, it checks context.active() for existing spans\n * 3. If found, creates child spans. If not, creates new root span.\n * 4. This happens automatically via OpenTelemetry Context propagation\n */\n\nimport { Effect, Layer } from 'effect'\nimport type { Tracer as EffectTracer } from 'effect'\nimport * as Tracer from '@effect/opentelemetry/Tracer'\nimport * as Resource from '@effect/opentelemetry/Resource'\nimport * as Otlp from '@effect/opentelemetry/Otlp'\nimport { FetchHttpClient } from '@effect/platform'\nimport { context, trace, type SpanContext, TraceFlags } from '@opentelemetry/api'\nimport {\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS\n} from '@opentelemetry/semantic-conventions'\nimport { initializePatternMatcher, logger } from '@atrim/instrument-core'\nimport { loadConfigWithOptions, type ConfigLoaderOptions } from '../../core/config-loader.js'\n\n// SDK metadata for resource attributes\n// telemetry.sdk.name identifies the INSTRUMENTATION library, not the exporter\nconst SDK_NAME = '@effect/opentelemetry'\n\n// Custom attribute for exporter mode\nconst ATTR_TELEMETRY_EXPORTER_MODE = 'telemetry.exporter.mode'\n\n/**\n * Configuration options for Effect instrumentation\n */\nexport interface EffectInstrumentationOptions extends ConfigLoaderOptions {\n /**\n * Service name for Effect spans\n * @default process.env.OTEL_SERVICE_NAME || 'effect-service'\n */\n serviceName?: string\n\n /**\n * Service version for Effect spans\n * @default process.env.npm_package_version || '1.0.0'\n */\n serviceVersion?: string\n\n /**\n * Whether to automatically extract Effect fiber metadata\n * @default true\n */\n autoExtractMetadata?: boolean\n\n /**\n * OTLP endpoint URL (only used when exporter mode is 'standalone')\n * @default process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n */\n otlpEndpoint?: string\n\n /**\n * Exporter mode:\n * - 'unified': Use global TracerProvider from Node SDK (recommended, enables filtering)\n * - 'standalone': Use Effect's own OTLP exporter (bypasses Node SDK filtering)\n * @default 'unified'\n */\n exporterMode?: 'unified' | 'standalone'\n}\n\n/**\n * Create Effect instrumentation layer with custom options\n *\n * This function creates an Effect Layer that provides OpenTelemetry tracing\n * with automatic context propagation from NodeSDK auto-instrumentation.\n *\n * @example\n * ```typescript\n * // With NodeSDK auto-instrumentation\n * import { NodeSDK } from '@opentelemetry/sdk-node'\n * import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'\n *\n * // 1. Start NodeSDK (creates HTTP spans automatically)\n * const sdk = new NodeSDK({\n * instrumentations: [getNodeAutoInstrumentations()]\n * })\n * sdk.start()\n *\n * // 2. Create Effect instrumentation (will continue NodeSDK traces)\n * const EffectLayer = createEffectInstrumentation()\n *\n * // 3. Use in Effect operations\n * const program = Effect.gen(function* () {\n * // This span will be a child of the HTTP request span (if any)\n * yield* Effect.log(\"Business logic\")\n * }).pipe(\n * Effect.withSpan(\"app.business.logic\"),\n * Effect.provide(EffectLayer)\n * )\n * ```\n */\nexport function createEffectInstrumentation(options: EffectInstrumentationOptions = {}) {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n // 1. Load configuration\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => ({\n _tag: 'ConfigError' as const,\n message: error instanceof Error ? error.message : String(error)\n })\n })\n\n // 2. Check effect.enabled flag (supports env var override)\n const effectEnabled =\n process.env.OTEL_EFFECT_ENABLED !== 'false' && (config.effect?.enabled ?? true)\n\n if (!effectEnabled) {\n logger.log('@atrim/instrumentation/effect: Effect tracing disabled via config')\n return Layer.empty\n }\n\n // 3. Configure logger based on config\n yield* Effect.sync(() => {\n const loggingLevel = config.instrumentation.logging || 'on'\n logger.setLevel(loggingLevel)\n })\n\n // 4. Initialize pattern matcher (for global shouldInstrumentSpan function)\n yield* Effect.sync(() => initializePatternMatcher(config))\n\n // 5. Extract service info and exporter mode\n const serviceName = options.serviceName || process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = options.serviceVersion || process.env.npm_package_version || '1.0.0'\n const exporterMode = options.exporterMode ?? config.effect?.exporter ?? 'unified'\n\n // Common resource attributes\n const resourceAttributes = {\n 'platform.component': 'effect',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,\n [ATTR_TELEMETRY_EXPORTER_MODE]: exporterMode\n }\n\n if (exporterMode === 'standalone') {\n // Standalone mode: Use Effect's own OTLP exporter\n // NOTE: This bypasses Node SDK filtering (PatternSpanProcessor)\n const otlpEndpoint =\n options.otlpEndpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n\n logger.log('Effect OpenTelemetry instrumentation (standalone)')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Endpoint: ${otlpEndpoint}`)\n logger.log(' WARNING: Standalone mode bypasses Node SDK filtering')\n\n return Otlp.layer({\n baseUrl: otlpEndpoint,\n resource: {\n serviceName,\n serviceVersion,\n attributes: resourceAttributes\n },\n // Bridge Effect context to OpenTelemetry global context\n tracerContext: <X>(f: () => X, span: EffectTracer.AnySpan): X => {\n if (span._tag !== 'Span') {\n return f()\n }\n const spanContext: SpanContext = {\n traceId: span.traceId,\n spanId: span.spanId,\n traceFlags: span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE\n }\n const otelSpan = trace.wrapSpanContext(spanContext)\n return context.with(trace.setSpan(context.active(), otelSpan), f)\n }\n }).pipe(Layer.provide(FetchHttpClient.layer))\n } else {\n // Unified mode (default): Use global TracerProvider from Node SDK\n // This ensures Effect spans go through PatternSpanProcessor for filtering\n logger.log('Effect OpenTelemetry instrumentation (unified)')\n logger.log(` Service: ${serviceName}`)\n logger.log(' Using global TracerProvider for span export')\n\n return Tracer.layerGlobal.pipe(\n Layer.provide(\n Resource.layer({\n serviceName,\n serviceVersion,\n attributes: resourceAttributes\n })\n )\n )\n }\n })\n ).pipe(Layer.orDie)\n}\n\n/**\n * Zero-config Effect instrumentation layer\n *\n * Uses the global OpenTelemetry tracer provider that was set up by\n * initializeInstrumentation(). This ensures all traces (Express, Effect, etc.)\n * go through the same TracerProvider and PatternSpanProcessor.\n *\n * Context Propagation:\n * - Automatically continues traces from NodeSDK auto-instrumentation\n * - Effect spans become children of HTTP request spans\n * - Respects http.ignore_incoming_paths and other filtering patterns\n * - No configuration needed\n *\n * @example\n * ```typescript\n * import { EffectInstrumentationLive } from '@atrim/instrumentation/effect'\n *\n * const program = Effect.gen(function* () {\n * // This span continues any existing trace from NodeSDK\n * yield* Effect.log(\"Processing\")\n * }).pipe(\n * Effect.withSpan(\"app.process\"),\n * Effect.provide(EffectInstrumentationLive)\n * )\n * ```\n */\nexport const EffectInstrumentationLive = Effect.sync(() => {\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n logger.minimal(`@atrim/instrumentation/effect: Effect tracing enabled (${serviceName})`)\n logger.log('Effect OpenTelemetry tracer (unified)')\n logger.log(` Service: ${serviceName}`)\n\n // Use Tracer.layerGlobal which uses trace.getTracerProvider()\n // This connects to NodeSDK's TracerProvider with PatternSpanProcessor\n // for unified filtering based on instrumentation.yaml\n return Tracer.layerGlobal.pipe(\n Layer.provide(\n Resource.layer({\n serviceName,\n serviceVersion,\n attributes: {\n 'platform.component': 'effect',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,\n [ATTR_TELEMETRY_EXPORTER_MODE]: 'unified'\n }\n })\n )\n )\n}).pipe(Layer.unwrapEffect)\n","/**\n * Effect-specific span annotation helpers\n *\n * Provides reusable helper functions for adding common span attributes.\n * These helpers follow OpenTelemetry semantic conventions and platform patterns.\n *\n * Usage:\n * ```typescript\n * Effect.gen(function* () {\n * yield* annotateUser(userId, email)\n * yield* annotateBatch(items.length, 5)\n * const results = yield* storage.writeBatch(items)\n * yield* annotateBatch(items.length, 5, results.success, results.failures)\n * }).pipe(Effect.withSpan('storage.writeBatch'))\n * ```\n */\n\nimport { Effect } from 'effect'\n\n/**\n * Annotate span with user context\n *\n * @param userId - User identifier\n * @param email - Optional user email\n * @param username - Optional username\n */\nexport function annotateUser(\n userId: string,\n email?: string,\n username?: string\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string> = {\n 'user.id': userId\n }\n if (email) attributes['user.email'] = email\n if (username) attributes['user.name'] = username\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with data size metrics\n *\n * @param bytes - Total bytes processed\n * @param items - Number of items\n * @param compressionRatio - Optional compression ratio\n */\nexport function annotateDataSize(\n bytes: number,\n items: number,\n compressionRatio?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, number> = {\n 'data.size.bytes': bytes,\n 'data.size.items': items\n }\n if (compressionRatio !== undefined) {\n attributes['data.compression.ratio'] = compressionRatio\n }\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with batch operation metadata\n *\n * @param totalItems - Total number of items in batch\n * @param batchSize - Size of each batch\n * @param successCount - Optional number of successful items\n * @param failureCount - Optional number of failed items\n */\nexport function annotateBatch(\n totalItems: number,\n batchSize: number,\n successCount?: number,\n failureCount?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, number> = {\n 'batch.size': batchSize,\n 'batch.total_items': totalItems,\n 'batch.count': Math.ceil(totalItems / batchSize)\n }\n\n if (successCount !== undefined) {\n attributes['batch.success_count'] = successCount\n }\n if (failureCount !== undefined) {\n attributes['batch.failure_count'] = failureCount\n }\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with LLM operation metadata\n *\n * @param model - Model name (e.g., 'gpt-4', 'claude-3-opus')\n * @param provider - LLM provider (e.g., 'openai', 'anthropic')\n * @param tokens - Optional token usage information\n */\nexport function annotateLLM(\n model: string,\n provider: string,\n tokens?: { prompt?: number; completion?: number; total?: number }\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number> = {\n 'llm.model': model,\n 'llm.provider': provider\n }\n\n if (tokens) {\n if (tokens.prompt !== undefined) attributes['llm.tokens.prompt'] = tokens.prompt\n if (tokens.completion !== undefined) attributes['llm.tokens.completion'] = tokens.completion\n if (tokens.total !== undefined) attributes['llm.tokens.total'] = tokens.total\n }\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with database query metadata\n *\n * @param query - SQL query or query description\n * @param duration - Optional query duration in milliseconds\n * @param rowCount - Optional number of rows returned/affected\n * @param database - Optional database name\n */\nexport function annotateQuery(\n query: string,\n duration?: number,\n rowCount?: number,\n database?: string\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number> = {\n 'db.statement': query.length > 1000 ? query.substring(0, 1000) + '...' : query\n }\n\n if (duration !== undefined) attributes['db.duration.ms'] = duration\n if (rowCount !== undefined) attributes['db.row_count'] = rowCount\n if (database) attributes['db.name'] = database\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with HTTP request metadata\n *\n * @param method - HTTP method (GET, POST, etc.)\n * @param url - Request URL\n * @param statusCode - Optional HTTP status code\n * @param contentLength - Optional response content length\n */\nexport function annotateHttpRequest(\n method: string,\n url: string,\n statusCode?: number,\n contentLength?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number> = {\n 'http.method': method,\n 'http.url': url\n }\n\n if (statusCode !== undefined) attributes['http.status_code'] = statusCode\n if (contentLength !== undefined) attributes['http.response.content_length'] = contentLength\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with error context\n *\n * @param error - Error object or message\n * @param recoverable - Whether the error is recoverable\n * @param errorType - Optional error type/category\n */\nexport function annotateError(\n error: Error | string,\n recoverable: boolean,\n errorType?: string\n): Effect.Effect<void, never, never> {\n const errorMessage = typeof error === 'string' ? error : error.message\n const errorStack = typeof error === 'string' ? undefined : error.stack\n\n const attributes: Record<string, string | boolean> = {\n 'error.message': errorMessage,\n 'error.recoverable': recoverable\n }\n\n if (errorType) attributes['error.type'] = errorType\n if (errorStack) attributes['error.stack'] = errorStack\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with operation priority\n *\n * @param priority - Priority level (high, medium, low)\n * @param reason - Optional reason for priority level\n */\nexport function annotatePriority(\n priority: 'high' | 'medium' | 'low',\n reason?: string\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string> = {\n 'operation.priority': priority\n }\n\n if (reason) attributes['operation.priority.reason'] = reason\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with cache operation metadata\n *\n * @param hit - Whether the cache was hit\n * @param key - Cache key\n * @param ttl - Optional time-to-live in seconds\n */\nexport function annotateCache(\n hit: boolean,\n key: string,\n ttl?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number | boolean> = {\n 'cache.hit': hit,\n 'cache.key': key\n }\n\n if (ttl !== undefined) attributes['cache.ttl.seconds'] = ttl\n\n return Effect.annotateCurrentSpan(attributes)\n}\n","/**\n * Effect metadata extraction\n *\n * Automatically extracts metadata from Effect fibers and adds them as span attributes.\n * This provides valuable context about the Effect execution environment.\n *\n * Uses Effect's public APIs:\n * - Fiber.getCurrentFiber() - Get current fiber information\n * - Effect.currentSpan - Detect parent spans and nesting\n */\n\nimport { Effect, Fiber, FiberId, Option } from 'effect'\n\n/**\n * Metadata extracted from Effect fibers\n */\nexport interface EffectMetadata {\n 'effect.fiber.id'?: string\n 'effect.fiber.status'?: string\n 'effect.operation.root'?: boolean\n 'effect.operation.nested'?: boolean\n 'effect.parent.span.id'?: string\n 'effect.parent.span.name'?: string\n 'effect.parent.trace.id'?: string\n}\n\n/**\n * Extract Effect-native metadata from current execution context\n *\n * Uses Effect's native APIs:\n * - Fiber.getCurrentFiber() - Get current fiber information\n * - Effect.currentSpan - Detect parent spans and nesting\n *\n * @returns Effect that yields extracted metadata\n */\nexport function extractEffectMetadata(): Effect.Effect<EffectMetadata> {\n return Effect.gen(function* () {\n const metadata: EffectMetadata = {}\n\n // Extract fiber metadata using Fiber.getCurrentFiber()\n const currentFiber = Fiber.getCurrentFiber()\n\n if (Option.isSome(currentFiber)) {\n const fiber = currentFiber.value\n const fiberId = fiber.id()\n\n // Add fiber ID\n metadata['effect.fiber.id'] = FiberId.threadName(fiberId)\n\n // Get fiber status (returns an Effect)\n const status = yield* Fiber.status(fiber)\n if (status._tag) {\n metadata['effect.fiber.status'] = status._tag\n }\n }\n\n // Detect parent span for nesting analysis\n const parentSpanResult = yield* Effect.currentSpan.pipe(\n Effect.option // Convert NoSuchElementException to Option\n )\n\n if (Option.isSome(parentSpanResult)) {\n const parentSpan = parentSpanResult.value\n metadata['effect.operation.nested'] = true\n metadata['effect.operation.root'] = false\n\n // Extract parent span information\n if (parentSpan.spanId) {\n metadata['effect.parent.span.id'] = parentSpan.spanId\n }\n\n if (parentSpan.name) {\n metadata['effect.parent.span.name'] = parentSpan.name\n }\n\n // Detect forking: if parent span exists in different context\n // This is a best-effort detection based on span context\n if (parentSpan.traceId) {\n metadata['effect.parent.trace.id'] = parentSpan.traceId\n }\n } else {\n // No parent span - this is a root span\n metadata['effect.operation.nested'] = false\n metadata['effect.operation.root'] = true\n }\n\n return metadata\n })\n}\n","/**\n * Effect Auto-Enrichment Utilities\n *\n * Provides utilities for automatically extracting and enriching spans with Effect-native metadata.\n *\n * Usage:\n * ```typescript\n * import { autoEnrichSpan, withAutoEnrichedSpan } from '@atrim/instrument-node/effect'\n *\n * // Option 1: Manual enrichment\n * Effect.gen(function* () {\n * yield* autoEnrichSpan() // Auto-add Effect metadata\n * yield* annotateBatch(items.length, 10) // Add custom attributes\n * const result = yield* storage.writeBatch(items)\n * return result\n * }).pipe(Effect.withSpan('storage.writeBatch'))\n *\n * // Option 2: Automatic enrichment wrapper\n * const instrumented = withAutoEnrichedSpan('storage.writeBatch')(\n * Effect.gen(function* () {\n * yield* annotateBatch(items.length, 10)\n * return yield* storage.writeBatch(items)\n * })\n * )\n * ```\n */\n\nimport { Effect } from 'effect'\nimport { extractEffectMetadata } from './metadata-extractor.js'\n\n/**\n * Auto-enrich the current span with Effect metadata\n *\n * This function should be called within an Effect.withSpan() context.\n * It extracts Effect metadata (fiber ID, status, parent span info)\n * and adds it as span attributes.\n *\n * Best practice: Call this at the start of your instrumented Effect:\n *\n * ```typescript\n * Effect.gen(function* () {\n * yield* autoEnrichSpan() // Auto-add metadata\n * yield* annotateBatch(items.length, 10) // Add custom attributes\n * const result = yield* storage.writeBatch(items)\n * return result\n * }).pipe(Effect.withSpan('storage.writeBatch'))\n * ```\n *\n * @returns Effect that annotates the current span with Effect metadata\n */\nexport function autoEnrichSpan(): Effect.Effect<void> {\n return Effect.gen(function* () {\n // Extract Effect metadata\n const metadata = yield* extractEffectMetadata()\n\n // Add metadata as span attributes\n // Cast to Record<string, unknown> to satisfy Effect.annotateCurrentSpan type\n yield* Effect.annotateCurrentSpan(metadata as Record<string, unknown>)\n })\n}\n\n/**\n * Create a wrapper that combines Effect.withSpan with automatic enrichment\n *\n * This is a convenience function that wraps an Effect with both:\n * 1. A span (via Effect.withSpan)\n * 2. Automatic metadata extraction (via autoEnrichSpan)\n *\n * Usage:\n * ```typescript\n * const instrumented = withAutoEnrichedSpan('storage.writeBatch')(\n * Effect.gen(function* () {\n * yield* annotateBatch(items.length, 10)\n * return yield* storage.writeBatch(items)\n * })\n * )\n * ```\n *\n * @param spanName - The name of the span\n * @param options - Optional span options\n * @returns Function that wraps an Effect with an auto-enriched span\n */\nexport function withAutoEnrichedSpan<A, E, R>(\n spanName: string,\n options?: {\n readonly attributes?: Record<string, unknown>\n readonly kind?: 'client' | 'server' | 'producer' | 'consumer' | 'internal'\n }\n) {\n return (self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n return Effect.gen(function* () {\n // Auto-enrich with metadata\n yield* autoEnrichSpan()\n\n // Execute the wrapped effect\n return yield* self\n }).pipe(Effect.withSpan(spanName, options))\n }\n}\n","/**\n * FiberSet helpers with automatic span isolation and virtual parent tracking\n *\n * Provides wrappers around Effect's FiberSet.run that automatically:\n * 1. Isolate span context (prevent leakage via { root: true })\n * 2. Track logical parent via OpenTelemetry span links\n * 3. Add custom attributes as universal fallback\n *\n * @module\n */\n\nimport { Effect, FiberSet as EffectFiberSet, Tracer } from 'effect'\nimport type { RuntimeFiber } from 'effect/Fiber'\n\n/**\n * Options for span isolation when running effects in FiberSet\n */\nexport interface IsolationOptions {\n /**\n * Whether to create a root span (breaks parent chain)\n * @default true (from config or this default)\n */\n readonly createRoot?: boolean\n\n /**\n * Capture logical parent relationship via span links and attributes\n * @default true\n */\n readonly captureLogicalParent?: boolean\n\n /**\n * Use OpenTelemetry span links to track logical parent\n * Works in: Honeycomb, Datadog, Lightstep, SigNoz, Splunk\n * @default true\n */\n readonly useSpanLinks?: boolean\n\n /**\n * Add custom attributes for logical parent tracking\n * Works in: ALL observability tools (universal fallback)\n * @default true\n */\n readonly useAttributes?: boolean\n\n /**\n * Propagate interruption from parent\n * @default undefined (FiberSet.run default behavior)\n */\n readonly propagateInterruption?: boolean\n\n /**\n * Custom span attributes to add\n */\n readonly attributes?: Record<string, unknown>\n\n /**\n * Span category for Atrim grouping\n * @default \"background_task\"\n */\n readonly category?: string\n}\n\n/**\n * Create a span link to the logical parent span\n *\n * This maintains observability while using root spans to prevent context leakage.\n */\nconst createLogicalParentLink = (\n parentSpan: Tracer.AnySpan,\n useSpanLinks: boolean\n): Tracer.SpanLink[] => {\n if (!useSpanLinks) {\n return []\n }\n\n return [\n {\n _tag: 'SpanLink' as const,\n span: parentSpan,\n attributes: {\n 'link.type': 'logical_parent',\n 'atrim.relationship': 'spawned_by',\n description: 'Logical parent (isolated to prevent context leakage)'\n }\n }\n ]\n}\n\n/**\n * Create attributes for logical parent tracking\n *\n * These serve as universal fallback for tools that don't support span links well.\n */\nconst createLogicalParentAttributes = (\n parentSpan: Tracer.AnySpan,\n useAttributes: boolean,\n category: string,\n useSpanLinks: boolean,\n customAttributes: Record<string, unknown>\n): Record<string, unknown> => {\n if (!useAttributes) {\n return customAttributes\n }\n\n return {\n // Logical parent tracking (works in ALL tools)\n 'atrim.logical_parent.span_id': parentSpan.spanId,\n 'atrim.logical_parent.trace_id': parentSpan.traceId,\n 'atrim.logical_parent.name': parentSpan._tag === 'Span' ? parentSpan.name : 'external',\n\n // Categorization and metadata\n 'atrim.fiberset.isolated': true,\n 'atrim.span.category': category,\n 'atrim.has_logical_parent': true,\n 'atrim.isolation.method': useSpanLinks ? 'hybrid' : 'attributes_only',\n\n // User-provided attributes\n ...customAttributes\n }\n}\n\n/**\n * Run an effect in a FiberSet with automatic span isolation and virtual parent tracking.\n *\n * This function prevents span context leakage (fibers inheriting parent spans incorrectly)\n * while maintaining logical parent relationships for observability.\n *\n * **Technical:** Uses `{ root: true }` to create independent root span\n * **Observability:** Uses span links + attributes to track logical parent\n *\n * @example\n * ```typescript\n * import { runIsolated } from \"@atrim/instrumentation/effect/fiberset\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function* () {\n * const set = yield* FiberSet.make()\n *\n * yield* Effect.gen(function* () {\n * // Spawn background tasks with automatic isolation\n * yield* runIsolated(set, backgroundTask1(), \"background-task-1\")\n * yield* runIsolated(set, backgroundTask2(), \"background-task-2\")\n * }).pipe(\n * Effect.withSpan(\"parent-operation\")\n * )\n *\n * yield* Effect.sleep(\"100 millis\")\n * })\n * )\n *\n * // In Honeycomb/Datadog/SigNoz:\n * // - background tasks are ROOT spans (no context leakage)\n * // - span links show they were spawned by parent-operation\n * // - can reconstruct virtual hierarchy\n * ```\n *\n * @param set - The FiberSet to run the effect in\n * @param effect - The effect to run (will be isolated)\n * @param name - Span name for the isolated effect\n * @param options - Configuration options\n * @returns Effect that returns the forked fiber\n *\n * @see https://github.com/atrim-ai/instrumentation/issues/5\n */\nexport const runIsolated = <A, E, R>(\n set: EffectFiberSet.FiberSet<A, E>,\n effect: Effect.Effect<A, E, R>,\n name: string,\n options?: IsolationOptions\n): Effect.Effect<RuntimeFiber<A, E>, never, R> => {\n const {\n createRoot = true,\n captureLogicalParent = true,\n useSpanLinks = true,\n useAttributes = true,\n propagateInterruption,\n attributes = {},\n category = 'background_task'\n } = options ?? {}\n\n // If not creating root and not capturing parent, just use standard FiberSet.run\n if (!createRoot && !captureLogicalParent) {\n return EffectFiberSet.run(set, effect, { propagateInterruption })\n }\n\n return Effect.gen(function* () {\n // Get current parent span (if any)\n const maybeParent = yield* Effect.serviceOption(Tracer.ParentSpan)\n\n // If no parent, just create root span\n if (maybeParent._tag === 'None' || !captureLogicalParent) {\n const isolated = effect.pipe(\n Effect.withSpan(name, {\n root: createRoot,\n attributes: {\n 'atrim.fiberset.isolated': createRoot,\n 'atrim.span.category': category,\n 'atrim.has_logical_parent': false,\n ...attributes\n }\n })\n )\n\n return yield* EffectFiberSet.run(set, isolated, { propagateInterruption })\n }\n\n const parent = maybeParent.value\n\n // Create span links for logical parent tracking\n const links = createLogicalParentLink(parent, useSpanLinks)\n\n // Create attributes for universal fallback\n const spanAttributes = createLogicalParentAttributes(\n parent,\n useAttributes,\n category,\n useSpanLinks,\n attributes\n )\n\n // Create isolated effect with root span + logical parent tracking\n const isolated = effect.pipe(\n Effect.withSpan(name, {\n root: createRoot,\n links: links.length > 0 ? links : undefined,\n attributes: spanAttributes\n })\n )\n\n return yield* EffectFiberSet.run(set, isolated, { propagateInterruption })\n })\n}\n\n/**\n * Convenience function to run an effect in a FiberSet with automatic span isolation.\n *\n * This is a simpler version of `runIsolated` with sensible defaults.\n *\n * @example\n * ```typescript\n * yield* runWithSpan(set, \"background-task\", backgroundTask(), {\n * attributes: { \"task.priority\": \"high\" }\n * })\n * ```\n */\nexport const runWithSpan = <A, E, R>(\n set: EffectFiberSet.FiberSet<A, E>,\n name: string,\n effect: Effect.Effect<A, E, R>,\n options?: {\n readonly propagateInterruption?: boolean\n readonly attributes?: Record<string, unknown>\n readonly category?: string\n }\n): Effect.Effect<RuntimeFiber<A, E>, never, R> => {\n return runIsolated(set, effect, name, {\n createRoot: true,\n captureLogicalParent: true,\n useSpanLinks: true,\n useAttributes: true,\n ...options\n })\n}\n\n/**\n * Annotate the current span with metadata about spawned FiberSet tasks.\n *\n * Call this in the parent operation before spawning tasks to add metadata\n * that helps reconstruct the virtual hierarchy.\n *\n * @example\n * ```typescript\n * yield* Effect.gen(function* () {\n * yield* annotateSpawnedTasks([\n * { name: \"background-task-1\" },\n * { name: \"background-task-2\" },\n * { name: \"background-task-3\" }\n * ])\n *\n * yield* runIsolated(set, task1(), \"background-task-1\")\n * yield* runIsolated(set, task2(), \"background-task-2\")\n * yield* runIsolated(set, task3(), \"background-task-3\")\n * }).pipe(\n * Effect.withSpan(\"parent-operation\")\n * )\n * ```\n */\nexport const annotateSpawnedTasks = (\n tasks: Array<{ name: string; spanId?: string; category?: string }>\n): Effect.Effect<void> => {\n return Effect.annotateCurrentSpan({\n 'atrim.fiberset.spawned_count': tasks.length,\n 'atrim.fiberset.task_names': tasks.map((t) => t.name).join(','),\n 'atrim.has_background_tasks': true,\n 'atrim.spawned_tasks': JSON.stringify(\n tasks.map((t) => ({\n name: t.name,\n ...(t.spanId && { span_id: t.spanId }),\n ...(t.category && { category: t.category })\n }))\n )\n })\n}\n\n/**\n * Re-export FiberSet namespace with isolation helpers\n *\n * This provides a convenient way to import all FiberSet functions:\n * ```typescript\n * import { FiberSet } from \"@atrim/instrumentation/effect/fiberset\"\n * ```\n */\nexport const FiberSet = {\n // Re-export all original FiberSet functions\n make: EffectFiberSet.make,\n add: EffectFiberSet.add,\n unsafeAdd: EffectFiberSet.unsafeAdd,\n run: EffectFiberSet.run,\n clear: EffectFiberSet.clear,\n join: EffectFiberSet.join,\n awaitEmpty: EffectFiberSet.awaitEmpty,\n size: EffectFiberSet.size,\n runtime: EffectFiberSet.runtime,\n runtimePromise: EffectFiberSet.runtimePromise,\n makeRuntime: EffectFiberSet.makeRuntime,\n makeRuntimePromise: EffectFiberSet.makeRuntimePromise,\n isFiberSet: EffectFiberSet.isFiberSet,\n\n // Add our isolation helpers\n runIsolated,\n runWithSpan\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../../core/src/instrumentation-schema.ts","../../../../../core/src/errors.ts","../../../../../core/src/services/config-loader.ts","../../../../../core/src/pattern-matcher.ts","../../../../../core/src/logger.ts","../../../../src/core/config-loader.ts","../../../../src/integrations/effect/effect-tracer.ts","../../../../src/integrations/effect/effect-helpers.ts","../../../../src/integrations/effect/metadata-extractor.ts","../../../../src/integrations/effect/auto-enrichment.ts","../../../../src/integrations/effect/fiberset.ts"],"names":["parseYaml","parseYAML","Layer","Effect","EffectFiberSet","Tracer","isolated"],"mappings":";;;;;;;;;;;;;;;;;AAMO,IAAM,mBAAA,GAAsB,EAAE,MAAA,CAAO;AAC1C,EAAA,OAAA,EAAS,EAAE,MAAA,EAAA;EACX,OAAA,EAAS,CAAA,CAAE,OAAA,EAAA,CAAU,QAAA,EAAA;EACrB,WAAA,EAAa,CAAA,CAAE,MAAA,EAAA,CAAS,QAAA;AAC1B,CAAC,CAAA;AAQM,IAAM,yBAAA,GAA4B,EAAE,MAAA,CAAO;;AAEhD,EAAA,OAAA,EAAS,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,KAAK,CAAA;;AAGlC,EAAA,SAAA,EAAW,EACR,MAAA,CAAO;AACN,IAAA,YAAA,EAAc,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,IAAI,CAAA;AACtC,IAAA,WAAA,EAAa,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,IAAI,CAAA;AACrC,IAAA,kBAAA,EAAoB,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,IAAI,CAAA;AAC5C,IAAA,cAAA,EAAgB,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,KAAK;GAC1C,CAAA,CACA,OAAA,CAAQ,EAAE,CAAA;;AAGb,EAAA,QAAA,EAAU,EACP,MAAA,CAAO;AACN,IAAA,cAAA,EAAgB,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,IAAI,CAAA;AACxC,IAAA,cAAA,EAAgB,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,IAAI,CAAA;AACxC,IAAA,sBAAA,EAAwB,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,IAAI;GACjD,CAAA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AAA,CAAe,UAAA;AAAA;AAAA,EAG3B,WAAA;AAAA,EACA;AACF","file":"index.js","sourcesContent":["/**\n * Configuration schema using Zod\n */\nimport { z } from 'zod'\nimport { parse as parseYaml } from 'yaml'\n\nexport const PatternConfigSchema = z.object({\n pattern: z.string(),\n enabled: z.boolean().optional(),\n description: z.string().optional()\n})\n\n/**\n * Configuration for automatic span isolation in Effect operations\n *\n * This prevents context leakage when using FiberSet.run, Effect.fork, etc.\n * while maintaining logical parent relationships via span links.\n */\nexport const AutoIsolationConfigSchema = z.object({\n // Global enable/disable for auto-isolation\n enabled: z.boolean().default(false),\n\n // Which operators to auto-isolate\n operators: z\n .object({\n fiberset_run: z.boolean().default(true),\n effect_fork: z.boolean().default(true),\n effect_fork_daemon: z.boolean().default(true),\n effect_fork_in: z.boolean().default(false)\n })\n .default({}),\n\n // Virtual parent tracking configuration\n tracking: z\n .object({\n use_span_links: z.boolean().default(true),\n use_attributes: z.boolean().default(true),\n capture_logical_parent: z.boolean().default(true)\n })\n .default({}),\n\n // Span categorization\n attributes: z\n .object({\n category: z.string().default('background_task'),\n add_metadata: z.boolean().default(true)\n })\n .default({})\n})\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\n/**\n * Span naming rule for auto-instrumentation\n *\n * Allows matching fibers based on file path, function name, etc.\n * and applying custom span names with template variables.\n */\nexport const SpanNamingRuleSchema = z.object({\n // Match criteria (all specified criteria must match)\n match: z.object({\n // Regex pattern to match file path\n file: z.string().optional(),\n // Regex pattern to match function name\n function: z.string().optional(),\n // Regex pattern to match module name\n module: z.string().optional()\n }),\n // Span name template with variables:\n // {fiber_id} - Fiber ID\n // {function} - Function name\n // {module} - Module name\n // {file} - File path\n // {line} - Line number\n // {operator} - Effect operator (gen, all, forEach, etc.)\n // {match:field:N} - Captured regex group from match\n name: z.string()\n})\n\n/**\n * Auto-instrumentation configuration for Effect operations\n *\n * Enables automatic tracing of all Effect fibers without manual\n * Effect.withSpan() calls. Configuration-driven via instrumentation.yaml.\n */\nexport const AutoInstrumentationConfigSchema = z.object({\n // Enable/disable auto-instrumentation\n enabled: z.boolean().default(false),\n\n // Tracing granularity\n // - 'fiber': Trace at fiber creation (recommended, lower overhead)\n // - 'operator': Trace each Effect operator (higher granularity, more overhead)\n granularity: z.enum(['fiber', 'operator']).default('fiber'),\n\n // Smart span naming configuration\n span_naming: z\n .object({\n // Default span name template when no rules match\n default: z.string().default('effect.fiber.{fiber_id}'),\n\n // Infer span names from source code (requires stack trace parsing)\n // Adds ~50-100μs overhead per fiber\n infer_from_source: z.boolean().default(true),\n\n // Naming rules (first match wins)\n rules: z.array(SpanNamingRuleSchema).default([])\n })\n .default({}),\n\n // Pattern-based filtering\n filter: z\n .object({\n // Only trace spans matching these patterns (empty = trace all)\n include: z.array(z.string()).default([]),\n\n // Never trace spans matching these patterns\n exclude: z.array(z.string()).default([])\n })\n .default({}),\n\n // Performance controls\n performance: z\n .object({\n // Sample rate (0.0 - 1.0)\n sampling_rate: z.number().min(0).max(1).default(1.0),\n\n // Skip fibers shorter than this duration (e.g., \"10ms\", \"100 millis\")\n min_duration: z.string().default('0ms'),\n\n // Maximum concurrent traced fibers (0 = unlimited)\n max_concurrent: z.number().default(0)\n })\n .default({}),\n\n // Automatic metadata extraction\n metadata: z\n .object({\n // Extract Effect fiber information\n fiber_info: z.boolean().default(true),\n\n // Extract source location (file:line)\n source_location: z.boolean().default(true),\n\n // Extract parent fiber information\n parent_fiber: z.boolean().default(true)\n })\n .default({})\n})\n\nexport type AutoInstrumentationConfig = z.infer<typeof AutoInstrumentationConfigSchema>\nexport type SpanNamingRule = z.infer<typeof SpanNamingRuleSchema>\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\nexport const HttpFilteringConfigSchema = z.object({\n // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)\n ignore_outgoing_urls: z.array(z.string()).optional(),\n\n // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)\n ignore_incoming_paths: z.array(z.string()).optional(),\n\n // Require parent span for outgoing requests (prevents root spans for HTTP calls)\n require_parent_for_outgoing_spans: z.boolean().optional(),\n\n // Trace context propagation configuration\n // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)\n propagate_trace_context: z\n .object({\n // Strategy for trace propagation\n // - \"all\": Propagate to all cross-origin requests (may cause CORS errors)\n // - \"none\": Never propagate trace headers\n // - \"same-origin\": Only propagate to same-origin requests (default, safe)\n // - \"patterns\": Propagate based on include_urls patterns\n strategy: z.enum(['all', 'none', 'same-origin', 'patterns']).default('same-origin'),\n\n // URL patterns to include when strategy is \"patterns\"\n // Supports regex patterns (e.g., \"^https://api\\\\.myapp\\\\.com\")\n include_urls: z.array(z.string()).optional()\n })\n .optional()\n})\n\n/**\n * Exporter configuration for OpenTelemetry tracing\n *\n * Allows configuring how traces are exported via instrumentation.yaml\n */\nexport const ExporterConfigSchema = z.object({\n // Exporter type: 'otlp' | 'console' | 'none'\n // - 'otlp': Export to OTLP endpoint (production)\n // - 'console': Log spans to console (development)\n // - 'none': No export (disable tracing)\n type: z.enum(['otlp', 'console', 'none']).default('otlp'),\n\n // OTLP endpoint URL (for type: otlp)\n // Defaults to OTEL_EXPORTER_OTLP_ENDPOINT env var or http://localhost:4318\n endpoint: z.string().optional(),\n\n // Custom headers to send with OTLP requests (for type: otlp)\n // Useful for authentication (x-api-key, Authorization, etc.)\n headers: z.record(z.string()).optional(),\n\n // Span processor type\n // - 'batch': Batch spans for export (production, lower overhead)\n // - 'simple': Export immediately (development, no batching delay)\n processor: z.enum(['batch', 'simple']).default('batch'),\n\n // Batch processor settings (for processor: batch)\n batch: z\n .object({\n // Max time to wait before exporting (milliseconds)\n scheduled_delay_millis: z.number().default(1000),\n // Max batch size\n max_export_batch_size: z.number().default(100)\n })\n .optional()\n})\n\nexport type ExporterConfig = z.infer<typeof ExporterConfigSchema>\n\nexport const InstrumentationConfigSchema = z.object({\n version: z.string(),\n instrumentation: z.object({\n enabled: z.boolean(),\n description: z.string().optional(),\n logging: z.enum(['on', 'off', 'minimal']).optional().default('on'),\n instrument_patterns: z.array(PatternConfigSchema),\n ignore_patterns: z.array(PatternConfigSchema)\n }),\n effect: z\n .object({\n // Enable/disable Effect tracing entirely\n // When false, EffectInstrumentationLive returns Layer.empty\n enabled: z.boolean().default(true),\n // Exporter mode (legacy - use exporter.type instead):\n // - \"unified\": Use global TracerProvider from Node SDK (recommended, enables filtering)\n // - \"standalone\": Use Effect's own OTLP exporter (bypasses Node SDK filtering)\n exporter: z.enum(['unified', 'standalone']).default('unified'),\n // Exporter configuration (for auto-instrumentation)\n exporter_config: ExporterConfigSchema.optional(),\n auto_extract_metadata: z.boolean(),\n auto_isolation: AutoIsolationConfigSchema.optional(),\n // Auto-instrumentation: automatic tracing of all Effect fibers\n auto_instrumentation: AutoInstrumentationConfigSchema.optional()\n })\n .optional(),\n http: HttpFilteringConfigSchema.optional()\n})\n\nexport type InstrumentationConfig = z.infer<typeof InstrumentationConfigSchema>\nexport type PatternConfig = z.infer<typeof PatternConfigSchema>\nexport type AutoIsolationConfig = z.infer<typeof AutoIsolationConfigSchema>\nexport type HttpFilteringConfig = z.infer<typeof HttpFilteringConfigSchema>\n\n/**\n * Default configuration when no config file is found\n */\nexport const defaultConfig: InstrumentationConfig = {\n version: '1.0',\n instrumentation: {\n enabled: true,\n logging: 'on',\n description: 'Default instrumentation configuration',\n instrument_patterns: [\n { pattern: '^app\\\\.', enabled: true, description: 'Application operations' },\n { pattern: '^http\\\\.server\\\\.', enabled: true, description: 'HTTP server operations' },\n { pattern: '^http\\\\.client\\\\.', enabled: true, description: 'HTTP client operations' }\n ],\n ignore_patterns: [\n { pattern: '^test\\\\.', description: 'Test utilities' },\n { pattern: '^internal\\\\.', description: 'Internal operations' },\n { pattern: '^health\\\\.', description: 'Health checks' }\n ]\n },\n effect: {\n enabled: true,\n exporter: 'unified' as const,\n auto_extract_metadata: true\n }\n}\n\n/**\n * Parse and validate configuration content (YAML string, JSON string, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Validated InstrumentationConfig\n * @throws Error if parsing or validation fails\n */\nexport function parseAndValidateConfig(content: string | unknown): InstrumentationConfig {\n let parsed: unknown\n\n // If string, parse as YAML (YAML is a superset of JSON)\n if (typeof content === 'string') {\n parsed = parseYaml(content)\n } else {\n parsed = content\n }\n\n // Validate with schema\n return InstrumentationConfigSchema.parse(parsed)\n}\n","/**\n * Typed error hierarchy for @atrim/instrumentation\n *\n * These errors use Effect's Data.TaggedError for typed error handling\n * with proper discriminated unions.\n */\n\nimport { Data } from 'effect'\n\n/**\n * Base error for configuration-related failures\n */\nexport class ConfigError extends Data.TaggedError('ConfigError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when fetching configuration from a URL fails\n */\nexport class ConfigUrlError extends Data.TaggedError('ConfigUrlError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when configuration validation fails (invalid YAML, schema mismatch)\n */\nexport class ConfigValidationError extends Data.TaggedError('ConfigValidationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when reading configuration from a file fails\n */\nexport class ConfigFileError extends Data.TaggedError('ConfigFileError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when service detection fails (package.json not found, invalid format)\n */\nexport class ServiceDetectionError extends Data.TaggedError('ServiceDetectionError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when OpenTelemetry SDK initialization fails\n */\nexport class InitializationError extends Data.TaggedError('InitializationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when span export fails (e.g., ECONNREFUSED to collector)\n */\nexport class ExportError extends Data.TaggedError('ExportError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when shutting down the SDK fails\n */\nexport class ShutdownError extends Data.TaggedError('ShutdownError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n","/**\n * ConfigLoader service using Effect Platform\n *\n * Provides URI-based configuration loading with pluggable platform services:\n * - FileSystem for file:// URIs (Node.js/Bun/Deno)\n * - HttpClient for http:// and https:// URIs (universal)\n *\n * This service has NO Node.js-specific dependencies - it depends only on\n * abstract Effect Platform services that are provided by environment-specific layers.\n */\n\nimport { Effect, Context, Layer } from 'effect'\nimport { FileSystem } from '@effect/platform/FileSystem'\nimport * as HttpClient from '@effect/platform/HttpClient'\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest'\nimport { parse as parseYAML } from 'yaml'\nimport {\n InstrumentationConfigSchema,\n type InstrumentationConfig\n} from '../instrumentation-schema.js'\nimport { ConfigError, ConfigFileError, ConfigUrlError, ConfigValidationError } from '../errors.js'\n\n// Security constraints\nconst SECURITY_DEFAULTS = {\n maxConfigSize: 1_000_000, // 1MB\n requestTimeout: 5_000 // 5 seconds\n} as const\n\n/**\n * ConfigLoader service interface\n */\nexport interface ConfigLoaderService {\n /**\n * Load configuration from a URI\n *\n * Supports:\n * - file:// URIs (uses FileSystem if available)\n * - http:// and https:// URIs (uses HttpClient)\n * - Relative paths (treated as file:// in Node, http:// in browser)\n *\n * @param uri - Configuration URI\n * @returns Effect that resolves to validated configuration (NO requirements)\n */\n readonly loadFromUri: (\n uri: string\n ) => Effect.Effect<\n InstrumentationConfig,\n ConfigError | ConfigFileError | ConfigUrlError | ConfigValidationError\n >\n\n /**\n * Load configuration from inline content (YAML, JSON, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Effect that resolves to validated configuration\n */\n readonly loadFromInline: (\n content: string | unknown\n ) => Effect.Effect<InstrumentationConfig, ConfigError | ConfigValidationError>\n}\n\n/**\n * ConfigLoader service tag\n */\nexport class ConfigLoader extends Context.Tag('ConfigLoader')<\n ConfigLoader,\n ConfigLoaderService\n>() {}\n\n/**\n * Parse and validate YAML content\n */\nconst parseYamlContent = (\n content: string,\n uri?: string\n): Effect.Effect<InstrumentationConfig, ConfigValidationError> =>\n Effect.gen(function* () {\n // Parse YAML\n const parsed = yield* Effect.try({\n try: () => parseYAML(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Failed to parse YAML from ${uri}` : 'Failed to parse YAML',\n cause: error\n })\n })\n\n // Validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(parsed),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Invalid configuration schema from ${uri}` : 'Invalid configuration schema',\n cause: error\n })\n })\n })\n\n/**\n * Load configuration from file using captured FileSystem service\n */\nconst loadFromFileWithFs = (\n fs: FileSystem,\n path: string,\n uri: string\n): Effect.Effect<InstrumentationConfig, ConfigFileError | ConfigValidationError> =>\n Effect.gen(function* () {\n // Read file\n const content = yield* fs.readFileString(path).pipe(\n Effect.mapError(\n (error) =>\n new ConfigFileError({\n reason: `Failed to read config file at ${uri}`,\n cause: error\n })\n )\n )\n\n // Security: Check file size\n if (content.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(content, uri)\n })\n\n/**\n * Load configuration from http using captured HttpClient service\n */\nconst loadFromHttpWithClient = (\n client: HttpClient.HttpClient,\n url: string\n): Effect.Effect<InstrumentationConfig, ConfigUrlError | ConfigValidationError> =>\n Effect.scoped(\n Effect.gen(function* () {\n // Security: Reject non-HTTPS URLs\n if (url.startsWith('http://')) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: 'Insecure protocol: only HTTPS URLs are allowed'\n })\n )\n }\n\n // Create request\n const request = HttpClientRequest.get(url).pipe(\n HttpClientRequest.setHeaders({\n Accept: 'application/yaml, text/yaml, application/x-yaml'\n })\n )\n\n // Execute request with timeout\n const response = yield* client.execute(request).pipe(\n Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),\n Effect.mapError((error) => {\n if (error._tag === 'TimeoutException') {\n return new ConfigUrlError({\n reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`\n })\n }\n return new ConfigUrlError({\n reason: `Failed to load config from URL: ${url}`,\n cause: error\n })\n })\n )\n\n // Check HTTP status\n if (response.status >= 400) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `HTTP ${response.status} from ${url}`\n })\n )\n }\n\n // Get response text\n const text = yield* response.text.pipe(\n Effect.mapError(\n (error) =>\n new ConfigUrlError({\n reason: `Failed to read response body from ${url}`,\n cause: error\n })\n )\n )\n\n // Security: Check size\n if (text.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(text, url)\n })\n )\n\n/**\n * ConfigLoader service implementation\n *\n * Captures FileSystem and HttpClient dependencies at construction time\n */\nconst makeConfigLoader = Effect.gen(function* () {\n // Capture dependencies at construction time\n const fs = yield* Effect.serviceOption(FileSystem)\n const http = yield* HttpClient.HttpClient\n\n // Create the loadFromUri function\n const loadFromUriUncached = (uri: string) =>\n Effect.gen(function* () {\n // file:// protocol\n if (uri.startsWith('file://')) {\n const path = uri.slice(7) // Remove \"file://\"\n\n if (fs._tag === 'None') {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: 'FileSystem not available (browser environment?)',\n cause: { uri }\n })\n )\n }\n\n return yield* loadFromFileWithFs(fs.value, path, uri)\n }\n\n // http:// or https:// protocol\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return yield* loadFromHttpWithClient(http, uri)\n }\n\n // Relative path - try FileSystem first, fallback to HTTP\n if (fs._tag === 'Some') {\n // FileSystem available (Node.js environment)\n return yield* loadFromFileWithFs(fs.value, uri, uri)\n } else {\n // No FileSystem (browser environment) - treat as HTTP\n // Relative URLs will be resolved by browser fetch to current origin\n return yield* loadFromHttpWithClient(http, uri)\n }\n })\n\n // Cache the loadFromUri function with 5 minute TTL (default cache timeout)\n const loadFromUriCached = yield* Effect.cachedFunction(loadFromUriUncached)\n\n return ConfigLoader.of({\n loadFromUri: loadFromUriCached,\n\n loadFromInline: (content: string | unknown) =>\n Effect.gen(function* () {\n // If string, parse as YAML\n if (typeof content === 'string') {\n return yield* parseYamlContent(content)\n }\n\n // Already an object - just validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: 'Invalid configuration schema',\n cause: error\n })\n })\n })\n })\n})\n\n/**\n * ConfigLoader Live layer\n *\n * Provides ConfigLoader service implementation.\n * Requires HttpClient to be provided by platform-specific layers.\n * FileSystem is optional (for browser compatibility).\n */\nexport const ConfigLoaderLive = Layer.effect(ConfigLoader, makeConfigLoader)\n","/**\n * Pattern matching utilities\n *\n * Implements efficient pattern-based span filtering with caching.\n *\n * Matching rules:\n * 1. Check ignore patterns first (takes precedence)\n * 2. Check instrument patterns second\n * 3. Default behavior: If no patterns match, span is created (fail-open)\n */\n\nimport type { InstrumentationConfig, PatternConfig } from './instrumentation-schema.js'\n\n/**\n * Compiled pattern with metadata\n */\ninterface CompiledPattern {\n regex: RegExp\n enabled: boolean\n description?: string\n}\n\n/**\n * Pattern matcher with compiled regex cache\n */\nexport class PatternMatcher {\n private ignorePatterns: CompiledPattern[] = []\n private instrumentPatterns: CompiledPattern[] = []\n private enabled: boolean = true\n\n constructor(config: InstrumentationConfig) {\n this.enabled = config.instrumentation.enabled\n\n // Compile ignore patterns (highest priority)\n this.ignorePatterns = config.instrumentation.ignore_patterns.map((p) => this.compilePattern(p))\n\n // Compile instrument patterns\n this.instrumentPatterns = config.instrumentation.instrument_patterns\n .filter((p) => p.enabled !== false) // Filter out disabled patterns\n .map((p) => this.compilePattern(p))\n }\n\n /**\n * Compile a pattern configuration into a RegExp\n */\n private compilePattern(pattern: PatternConfig): CompiledPattern {\n try {\n const compiled: CompiledPattern = {\n regex: new RegExp(pattern.pattern),\n enabled: pattern.enabled !== false\n }\n if (pattern.description !== undefined) {\n compiled.description = pattern.description\n }\n return compiled\n } catch (error) {\n throw new Error(\n `Failed to compile pattern \"${pattern.pattern}\": ${error instanceof Error ? error.message : String(error)}`\n )\n }\n }\n\n /**\n * Check if a span should be instrumented\n *\n * Returns true if the span should be created, false otherwise.\n *\n * Logic:\n * 1. If instrumentation disabled globally, return false\n * 2. Check ignore patterns - if any match, return false\n * 3. Check instrument patterns - if any match, return true\n * 4. Default: return true (fail-open - create span if no patterns match)\n */\n shouldInstrument(spanName: string): boolean {\n // Global disable\n if (!this.enabled) {\n return false\n }\n\n // Check ignore patterns first (highest priority)\n for (const pattern of this.ignorePatterns) {\n if (pattern.regex.test(spanName)) {\n return false\n }\n }\n\n // Check instrument patterns\n for (const pattern of this.instrumentPatterns) {\n if (pattern.enabled && pattern.regex.test(spanName)) {\n return true\n }\n }\n\n // Default: fail-open (create span if no patterns match)\n // This ensures backward compatibility and doesn't break existing instrumentation\n return true\n }\n\n /**\n * Get statistics about pattern matching (for debugging/monitoring)\n */\n getStats(): {\n enabled: boolean\n ignorePatternCount: number\n instrumentPatternCount: number\n } {\n return {\n enabled: this.enabled,\n ignorePatternCount: this.ignorePatterns.length,\n instrumentPatternCount: this.instrumentPatterns.filter((p) => p.enabled).length\n }\n }\n}\n\n// Global pattern matcher instance\nlet globalMatcher: PatternMatcher | null = null\n\n/**\n * Initialize the global pattern matcher\n */\nexport function initializePatternMatcher(config: InstrumentationConfig): void {\n globalMatcher = new PatternMatcher(config)\n}\n\n/**\n * Check if a span should be instrumented (uses global matcher)\n *\n * This is a convenience function for use without direct access to the matcher instance.\n * If no matcher is initialized, defaults to true (fail-open).\n */\nexport function shouldInstrumentSpan(spanName: string): boolean {\n if (!globalMatcher) {\n // No matcher initialized - fail open\n return true\n }\n return globalMatcher.shouldInstrument(spanName)\n}\n\n/**\n * Get the global pattern matcher (for advanced use cases)\n */\nexport function getPatternMatcher(): PatternMatcher | null {\n return globalMatcher\n}\n\n/**\n * Clear the global pattern matcher (useful for testing)\n */\nexport function clearPatternMatcher(): void {\n globalMatcher = null\n}\n","/**\n * Centralized logging utility for @atrim/instrumentation\n *\n * Supports three levels:\n * - 'on' (default): All logging enabled\n * - 'minimal': Only a single initialization message + errors/warnings\n * - 'off': No logging at all\n */\n\nexport type LogLevel = 'on' | 'off' | 'minimal'\n\nclass Logger {\n private level: LogLevel = 'on'\n private hasLoggedMinimal = false\n\n /**\n * Set the logging level\n */\n setLevel(level: LogLevel): void {\n this.level = level\n this.hasLoggedMinimal = false\n }\n\n /**\n * Get the current logging level\n */\n getLevel(): LogLevel {\n return this.level\n }\n\n /**\n * Log a minimal initialization message (only shown once in minimal mode)\n */\n minimal(message: string): void {\n if (this.level === 'off') {\n return\n }\n\n if (this.level === 'minimal' && !this.hasLoggedMinimal) {\n console.log(message)\n this.hasLoggedMinimal = true\n return\n }\n\n if (this.level === 'on') {\n console.log(message)\n }\n }\n\n /**\n * Log an informational message\n */\n log(...args: unknown[]): void {\n if (this.level === 'on') {\n console.log(...args)\n }\n }\n\n /**\n * Log a warning message (shown in minimal mode)\n */\n warn(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.warn(...args)\n }\n }\n\n /**\n * Log an error message (shown in minimal mode)\n */\n error(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.error(...args)\n }\n }\n\n /**\n * Check if full logging is enabled\n */\n isEnabled(): boolean {\n return this.level === 'on'\n }\n\n /**\n * Check if minimal logging is enabled\n */\n isMinimal(): boolean {\n return this.level === 'minimal'\n }\n\n /**\n * Check if logging is completely disabled\n */\n isDisabled(): boolean {\n return this.level === 'off'\n }\n}\n\n// Singleton instance\nexport const logger = new Logger()\n","/**\n * Node.js configuration loader\n *\n * Provides configuration loading using native Node.js APIs (fs, fetch)\n * This module doesn't require Effect Platform, making it work without Effect installed.\n */\n\nimport { Effect } from 'effect'\nimport {\n type InstrumentationConfig,\n parseAndValidateConfig,\n defaultConfig\n} from '@atrim/instrument-core'\n\n/**\n * Load configuration from a file path using native Node.js fs\n */\nasync function loadFromFile(filePath: string): Promise<InstrumentationConfig> {\n const { readFile } = await import('fs/promises')\n const content = await readFile(filePath, 'utf-8')\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from a URL using native fetch\n */\nasync function loadFromUrl(url: string): Promise<InstrumentationConfig> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`)\n }\n const content = await response.text()\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from URI (file path or URL)\n *\n * @param uri - Configuration URI (file://, http://, https://, or relative path)\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfig(\n uri: string,\n _options?: { cacheTimeout?: number }\n): Promise<InstrumentationConfig> {\n // Handle URL protocols\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return loadFromUrl(uri)\n }\n\n // Handle file:// protocol\n if (uri.startsWith('file://')) {\n const filePath = uri.slice(7) // Remove 'file://'\n return loadFromFile(filePath)\n }\n\n // Treat as file path\n return loadFromFile(uri)\n}\n\n/**\n * Load configuration from inline content\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigFromInline(\n content: string | unknown\n): Promise<InstrumentationConfig> {\n return parseAndValidateConfig(content)\n}\n\n/**\n * Reset the config loader cache (no-op for native implementation)\n * @internal\n */\nexport function _resetConfigLoaderCache(): void {\n // No cache in native implementation\n}\n\n/**\n * Legacy options interface for backward compatibility\n */\nexport interface ConfigLoaderOptions {\n configPath?: string\n configUrl?: string\n config?: InstrumentationConfig\n cacheTimeout?: number\n}\n\n/**\n * Load configuration with priority order (backward compatible API)\n *\n * Priority order (highest to lowest):\n * 1. Explicit config object (options.config)\n * 2. Environment variable (ATRIM_INSTRUMENTATION_CONFIG)\n * 3. Explicit path/URL (options.configPath or options.configUrl)\n * 4. Project root file (./instrumentation.yaml)\n * 5. Default config (built-in defaults)\n *\n * @param options - Configuration options\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigWithOptions(\n options: ConfigLoaderOptions = {}\n): Promise<InstrumentationConfig> {\n // Priority 1: Explicit config object\n if (options.config) {\n return loadConfigFromInline(options.config)\n }\n\n // Priority 2: Environment variable\n const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG\n if (envConfigPath) {\n return loadConfig(envConfigPath, options)\n }\n\n // Priority 3: Explicit options\n if (options.configUrl) {\n return loadConfig(options.configUrl, options)\n }\n if (options.configPath) {\n return loadConfig(options.configPath, options)\n }\n\n // Priority 4: Project root file\n const { existsSync } = await import('fs')\n const { join } = await import('path')\n\n const defaultPath = join(process.cwd(), 'instrumentation.yaml')\n if (existsSync(defaultPath)) {\n return loadConfig(defaultPath, options)\n }\n\n // Priority 5: Default config\n return defaultConfig\n}\n\n// ============================================================================\n// Effect-Based API (for Effect users)\n// ============================================================================\n\n/**\n * Load configuration from URI (Effect version)\n */\nexport const loadConfigEffect = (\n uri: string,\n options?: { cacheTimeout?: number }\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfig(uri, options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration from inline content (Effect version)\n */\nexport const loadConfigFromInlineEffect = (\n content: string | unknown\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigFromInline(content),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration with priority order (Effect version)\n */\nexport const loadConfigWithOptionsEffect = (\n options: ConfigLoaderOptions = {}\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n","/**\n * Effect-TS Tracer integration with context propagation\n *\n * This module provides Effect-TS tracing that seamlessly integrates with\n * OpenTelemetry NodeSDK auto-instrumentation. Effect spans will automatically\n * continue existing traces created by NodeSDK (e.g., HTTP requests).\n *\n * Context Propagation:\n * - NodeSDK auto-instrumentation creates root spans (e.g., HTTP requests)\n * - Effect operations automatically become child spans of the active trace\n * - Uses OpenTelemetry Context API (equivalent to Java thread-local)\n * - No configuration needed - works out of the box\n *\n * Architecture:\n * 1. @effect/opentelemetry uses the global OpenTelemetry tracer provider\n * 2. When an Effect operation starts, it checks context.active() for existing spans\n * 3. If found, creates child spans. If not, creates new root span.\n * 4. This happens automatically via OpenTelemetry Context propagation\n */\n\nimport { Effect, Layer } from 'effect'\nimport type { Tracer as EffectTracer } from 'effect'\nimport * as Tracer from '@effect/opentelemetry/Tracer'\nimport * as Resource from '@effect/opentelemetry/Resource'\nimport * as Otlp from '@effect/opentelemetry/Otlp'\nimport { FetchHttpClient } from '@effect/platform'\nimport { context, trace, type SpanContext, TraceFlags } from '@opentelemetry/api'\nimport {\n ATTR_TELEMETRY_SDK_LANGUAGE,\n ATTR_TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS\n} from '@opentelemetry/semantic-conventions'\nimport { initializePatternMatcher, logger } from '@atrim/instrument-core'\nimport { loadConfigWithOptions, type ConfigLoaderOptions } from '../../core/config-loader.js'\n\n// SDK metadata for resource attributes\n// telemetry.sdk.name identifies the INSTRUMENTATION library, not the exporter\nconst SDK_NAME = '@effect/opentelemetry'\n\n// Custom attribute for exporter mode\nconst ATTR_TELEMETRY_EXPORTER_MODE = 'telemetry.exporter.mode'\n\n/**\n * Configuration options for Effect instrumentation\n */\nexport interface EffectInstrumentationOptions extends ConfigLoaderOptions {\n /**\n * Service name for Effect spans\n * @default process.env.OTEL_SERVICE_NAME || 'effect-service'\n */\n serviceName?: string\n\n /**\n * Service version for Effect spans\n * @default process.env.npm_package_version || '1.0.0'\n */\n serviceVersion?: string\n\n /**\n * Whether to automatically extract Effect fiber metadata\n * @default true\n */\n autoExtractMetadata?: boolean\n\n /**\n * OTLP endpoint URL (only used when exporter mode is 'standalone')\n * @default process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n */\n otlpEndpoint?: string\n\n /**\n * Exporter mode:\n * - 'unified': Use global TracerProvider from Node SDK (recommended, enables filtering)\n * - 'standalone': Use Effect's own OTLP exporter (bypasses Node SDK filtering)\n * @default 'unified'\n */\n exporterMode?: 'unified' | 'standalone'\n}\n\n/**\n * Create Effect instrumentation layer with custom options\n *\n * This function creates an Effect Layer that provides OpenTelemetry tracing\n * with automatic context propagation from NodeSDK auto-instrumentation.\n *\n * @example\n * ```typescript\n * // With NodeSDK auto-instrumentation\n * import { NodeSDK } from '@opentelemetry/sdk-node'\n * import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'\n *\n * // 1. Start NodeSDK (creates HTTP spans automatically)\n * const sdk = new NodeSDK({\n * instrumentations: [getNodeAutoInstrumentations()]\n * })\n * sdk.start()\n *\n * // 2. Create Effect instrumentation (will continue NodeSDK traces)\n * const EffectLayer = createEffectInstrumentation()\n *\n * // 3. Use in Effect operations\n * const program = Effect.gen(function* () {\n * // This span will be a child of the HTTP request span (if any)\n * yield* Effect.log(\"Business logic\")\n * }).pipe(\n * Effect.withSpan(\"app.business.logic\"),\n * Effect.provide(EffectLayer)\n * )\n * ```\n */\nexport function createEffectInstrumentation(options: EffectInstrumentationOptions = {}) {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n // 1. Load configuration\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => ({\n _tag: 'ConfigError' as const,\n message: error instanceof Error ? error.message : String(error)\n })\n })\n\n // 2. Check effect.enabled flag (supports env var override)\n const effectEnabled =\n process.env.OTEL_EFFECT_ENABLED !== 'false' && (config.effect?.enabled ?? true)\n\n if (!effectEnabled) {\n logger.log('@atrim/instrumentation/effect: Effect tracing disabled via config')\n return Layer.empty\n }\n\n // 3. Configure logger based on config\n yield* Effect.sync(() => {\n const loggingLevel = config.instrumentation.logging || 'on'\n logger.setLevel(loggingLevel)\n })\n\n // 4. Initialize pattern matcher (for global shouldInstrumentSpan function)\n yield* Effect.sync(() => initializePatternMatcher(config))\n\n // 5. Extract service info and exporter mode\n const serviceName = options.serviceName || process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = options.serviceVersion || process.env.npm_package_version || '1.0.0'\n const exporterMode = options.exporterMode ?? config.effect?.exporter ?? 'unified'\n\n // Common resource attributes\n const resourceAttributes = {\n 'platform.component': 'effect',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,\n [ATTR_TELEMETRY_EXPORTER_MODE]: exporterMode\n }\n\n if (exporterMode === 'standalone') {\n // Standalone mode: Use Effect's own OTLP exporter\n // NOTE: This bypasses Node SDK filtering (PatternSpanProcessor)\n const otlpEndpoint =\n options.otlpEndpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n\n logger.log('Effect OpenTelemetry instrumentation (standalone)')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Endpoint: ${otlpEndpoint}`)\n logger.log(' WARNING: Standalone mode bypasses Node SDK filtering')\n\n return Otlp.layer({\n baseUrl: otlpEndpoint,\n resource: {\n serviceName,\n serviceVersion,\n attributes: resourceAttributes\n },\n // Bridge Effect context to OpenTelemetry global context\n tracerContext: <X>(f: () => X, span: EffectTracer.AnySpan): X => {\n if (span._tag !== 'Span') {\n return f()\n }\n const spanContext: SpanContext = {\n traceId: span.traceId,\n spanId: span.spanId,\n traceFlags: span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE\n }\n const otelSpan = trace.wrapSpanContext(spanContext)\n return context.with(trace.setSpan(context.active(), otelSpan), f)\n }\n }).pipe(Layer.provide(FetchHttpClient.layer))\n } else {\n // Unified mode (default): Use global TracerProvider from Node SDK\n // This ensures Effect spans go through PatternSpanProcessor for filtering\n logger.log('Effect OpenTelemetry instrumentation (unified)')\n logger.log(` Service: ${serviceName}`)\n logger.log(' Using global TracerProvider for span export')\n\n return Tracer.layerGlobal.pipe(\n Layer.provide(\n Resource.layer({\n serviceName,\n serviceVersion,\n attributes: resourceAttributes\n })\n )\n )\n }\n })\n ).pipe(Layer.orDie)\n}\n\n/**\n * Zero-config Effect instrumentation layer\n *\n * Uses the global OpenTelemetry tracer provider that was set up by\n * initializeInstrumentation(). This ensures all traces (Express, Effect, etc.)\n * go through the same TracerProvider and PatternSpanProcessor.\n *\n * Context Propagation:\n * - Automatically continues traces from NodeSDK auto-instrumentation\n * - Effect spans become children of HTTP request spans\n * - Respects http.ignore_incoming_paths and other filtering patterns\n * - No configuration needed\n *\n * @example\n * ```typescript\n * import { EffectInstrumentationLive } from '@atrim/instrumentation/effect'\n *\n * const program = Effect.gen(function* () {\n * // This span continues any existing trace from NodeSDK\n * yield* Effect.log(\"Processing\")\n * }).pipe(\n * Effect.withSpan(\"app.process\"),\n * Effect.provide(EffectInstrumentationLive)\n * )\n * ```\n */\nexport const EffectInstrumentationLive = Effect.sync(() => {\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n logger.minimal(`@atrim/instrumentation/effect: Effect tracing enabled (${serviceName})`)\n logger.log('Effect OpenTelemetry tracer (unified)')\n logger.log(` Service: ${serviceName}`)\n\n // Use Tracer.layerGlobal which uses trace.getTracerProvider()\n // This connects to NodeSDK's TracerProvider with PatternSpanProcessor\n // for unified filtering based on instrumentation.yaml\n return Tracer.layerGlobal.pipe(\n Layer.provide(\n Resource.layer({\n serviceName,\n serviceVersion,\n attributes: {\n 'platform.component': 'effect',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,\n [ATTR_TELEMETRY_EXPORTER_MODE]: 'unified'\n }\n })\n )\n )\n}).pipe(Layer.unwrapEffect)\n","/**\n * Effect-specific span annotation helpers\n *\n * Provides reusable helper functions for adding common span attributes.\n * These helpers follow OpenTelemetry semantic conventions and platform patterns.\n *\n * Usage:\n * ```typescript\n * Effect.gen(function* () {\n * yield* annotateUser(userId, email)\n * yield* annotateBatch(items.length, 5)\n * const results = yield* storage.writeBatch(items)\n * yield* annotateBatch(items.length, 5, results.success, results.failures)\n * }).pipe(Effect.withSpan('storage.writeBatch'))\n * ```\n */\n\nimport { Effect } from 'effect'\n\n/**\n * Annotate span with user context\n *\n * @param userId - User identifier\n * @param email - Optional user email\n * @param username - Optional username\n */\nexport function annotateUser(\n userId: string,\n email?: string,\n username?: string\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string> = {\n 'user.id': userId\n }\n if (email) attributes['user.email'] = email\n if (username) attributes['user.name'] = username\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with data size metrics\n *\n * @param bytes - Total bytes processed\n * @param items - Number of items\n * @param compressionRatio - Optional compression ratio\n */\nexport function annotateDataSize(\n bytes: number,\n items: number,\n compressionRatio?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, number> = {\n 'data.size.bytes': bytes,\n 'data.size.items': items\n }\n if (compressionRatio !== undefined) {\n attributes['data.compression.ratio'] = compressionRatio\n }\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with batch operation metadata\n *\n * @param totalItems - Total number of items in batch\n * @param batchSize - Size of each batch\n * @param successCount - Optional number of successful items\n * @param failureCount - Optional number of failed items\n */\nexport function annotateBatch(\n totalItems: number,\n batchSize: number,\n successCount?: number,\n failureCount?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, number> = {\n 'batch.size': batchSize,\n 'batch.total_items': totalItems,\n 'batch.count': Math.ceil(totalItems / batchSize)\n }\n\n if (successCount !== undefined) {\n attributes['batch.success_count'] = successCount\n }\n if (failureCount !== undefined) {\n attributes['batch.failure_count'] = failureCount\n }\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with LLM operation metadata\n *\n * @param model - Model name (e.g., 'gpt-4', 'claude-3-opus')\n * @param provider - LLM provider (e.g., 'openai', 'anthropic')\n * @param tokens - Optional token usage information\n */\nexport function annotateLLM(\n model: string,\n provider: string,\n tokens?: { prompt?: number; completion?: number; total?: number }\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number> = {\n 'llm.model': model,\n 'llm.provider': provider\n }\n\n if (tokens) {\n if (tokens.prompt !== undefined) attributes['llm.tokens.prompt'] = tokens.prompt\n if (tokens.completion !== undefined) attributes['llm.tokens.completion'] = tokens.completion\n if (tokens.total !== undefined) attributes['llm.tokens.total'] = tokens.total\n }\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with database query metadata\n *\n * @param query - SQL query or query description\n * @param duration - Optional query duration in milliseconds\n * @param rowCount - Optional number of rows returned/affected\n * @param database - Optional database name\n */\nexport function annotateQuery(\n query: string,\n duration?: number,\n rowCount?: number,\n database?: string\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number> = {\n 'db.statement': query.length > 1000 ? query.substring(0, 1000) + '...' : query\n }\n\n if (duration !== undefined) attributes['db.duration.ms'] = duration\n if (rowCount !== undefined) attributes['db.row_count'] = rowCount\n if (database) attributes['db.name'] = database\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with HTTP request metadata\n *\n * @param method - HTTP method (GET, POST, etc.)\n * @param url - Request URL\n * @param statusCode - Optional HTTP status code\n * @param contentLength - Optional response content length\n */\nexport function annotateHttpRequest(\n method: string,\n url: string,\n statusCode?: number,\n contentLength?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number> = {\n 'http.method': method,\n 'http.url': url\n }\n\n if (statusCode !== undefined) attributes['http.status_code'] = statusCode\n if (contentLength !== undefined) attributes['http.response.content_length'] = contentLength\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with error context\n *\n * @param error - Error object or message\n * @param recoverable - Whether the error is recoverable\n * @param errorType - Optional error type/category\n */\nexport function annotateError(\n error: Error | string,\n recoverable: boolean,\n errorType?: string\n): Effect.Effect<void, never, never> {\n const errorMessage = typeof error === 'string' ? error : error.message\n const errorStack = typeof error === 'string' ? undefined : error.stack\n\n const attributes: Record<string, string | boolean> = {\n 'error.message': errorMessage,\n 'error.recoverable': recoverable\n }\n\n if (errorType) attributes['error.type'] = errorType\n if (errorStack) attributes['error.stack'] = errorStack\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with operation priority\n *\n * @param priority - Priority level (high, medium, low)\n * @param reason - Optional reason for priority level\n */\nexport function annotatePriority(\n priority: 'high' | 'medium' | 'low',\n reason?: string\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string> = {\n 'operation.priority': priority\n }\n\n if (reason) attributes['operation.priority.reason'] = reason\n\n return Effect.annotateCurrentSpan(attributes)\n}\n\n/**\n * Annotate span with cache operation metadata\n *\n * @param hit - Whether the cache was hit\n * @param key - Cache key\n * @param ttl - Optional time-to-live in seconds\n */\nexport function annotateCache(\n hit: boolean,\n key: string,\n ttl?: number\n): Effect.Effect<void, never, never> {\n const attributes: Record<string, string | number | boolean> = {\n 'cache.hit': hit,\n 'cache.key': key\n }\n\n if (ttl !== undefined) attributes['cache.ttl.seconds'] = ttl\n\n return Effect.annotateCurrentSpan(attributes)\n}\n","/**\n * Effect metadata extraction\n *\n * Automatically extracts metadata from Effect fibers and adds them as span attributes.\n * This provides valuable context about the Effect execution environment.\n *\n * Uses Effect's public APIs:\n * - Fiber.getCurrentFiber() - Get current fiber information\n * - Effect.currentSpan - Detect parent spans and nesting\n */\n\nimport { Effect, Fiber, FiberId, Option } from 'effect'\n\n/**\n * Metadata extracted from Effect fibers\n */\nexport interface EffectMetadata {\n 'effect.fiber.id'?: string\n 'effect.fiber.status'?: string\n 'effect.operation.root'?: boolean\n 'effect.operation.nested'?: boolean\n 'effect.parent.span.id'?: string\n 'effect.parent.span.name'?: string\n 'effect.parent.trace.id'?: string\n}\n\n/**\n * Extract Effect-native metadata from current execution context\n *\n * Uses Effect's native APIs:\n * - Fiber.getCurrentFiber() - Get current fiber information\n * - Effect.currentSpan - Detect parent spans and nesting\n *\n * @returns Effect that yields extracted metadata\n */\nexport function extractEffectMetadata(): Effect.Effect<EffectMetadata> {\n return Effect.gen(function* () {\n const metadata: EffectMetadata = {}\n\n // Extract fiber metadata using Fiber.getCurrentFiber()\n const currentFiber = Fiber.getCurrentFiber()\n\n if (Option.isSome(currentFiber)) {\n const fiber = currentFiber.value\n const fiberId = fiber.id()\n\n // Add fiber ID\n metadata['effect.fiber.id'] = FiberId.threadName(fiberId)\n\n // Get fiber status (returns an Effect)\n const status = yield* Fiber.status(fiber)\n if (status._tag) {\n metadata['effect.fiber.status'] = status._tag\n }\n }\n\n // Detect parent span for nesting analysis\n const parentSpanResult = yield* Effect.currentSpan.pipe(\n Effect.option // Convert NoSuchElementException to Option\n )\n\n if (Option.isSome(parentSpanResult)) {\n const parentSpan = parentSpanResult.value\n metadata['effect.operation.nested'] = true\n metadata['effect.operation.root'] = false\n\n // Extract parent span information\n if (parentSpan.spanId) {\n metadata['effect.parent.span.id'] = parentSpan.spanId\n }\n\n if (parentSpan.name) {\n metadata['effect.parent.span.name'] = parentSpan.name\n }\n\n // Detect forking: if parent span exists in different context\n // This is a best-effort detection based on span context\n if (parentSpan.traceId) {\n metadata['effect.parent.trace.id'] = parentSpan.traceId\n }\n } else {\n // No parent span - this is a root span\n metadata['effect.operation.nested'] = false\n metadata['effect.operation.root'] = true\n }\n\n return metadata\n })\n}\n","/**\n * Effect Auto-Enrichment Utilities\n *\n * Provides utilities for automatically extracting and enriching spans with Effect-native metadata.\n *\n * Usage:\n * ```typescript\n * import { autoEnrichSpan, withAutoEnrichedSpan } from '@atrim/instrument-node/effect'\n *\n * // Option 1: Manual enrichment\n * Effect.gen(function* () {\n * yield* autoEnrichSpan() // Auto-add Effect metadata\n * yield* annotateBatch(items.length, 10) // Add custom attributes\n * const result = yield* storage.writeBatch(items)\n * return result\n * }).pipe(Effect.withSpan('storage.writeBatch'))\n *\n * // Option 2: Automatic enrichment wrapper\n * const instrumented = withAutoEnrichedSpan('storage.writeBatch')(\n * Effect.gen(function* () {\n * yield* annotateBatch(items.length, 10)\n * return yield* storage.writeBatch(items)\n * })\n * )\n * ```\n */\n\nimport { Effect } from 'effect'\nimport { extractEffectMetadata } from './metadata-extractor.js'\n\n/**\n * Auto-enrich the current span with Effect metadata\n *\n * This function should be called within an Effect.withSpan() context.\n * It extracts Effect metadata (fiber ID, status, parent span info)\n * and adds it as span attributes.\n *\n * Best practice: Call this at the start of your instrumented Effect:\n *\n * ```typescript\n * Effect.gen(function* () {\n * yield* autoEnrichSpan() // Auto-add metadata\n * yield* annotateBatch(items.length, 10) // Add custom attributes\n * const result = yield* storage.writeBatch(items)\n * return result\n * }).pipe(Effect.withSpan('storage.writeBatch'))\n * ```\n *\n * @returns Effect that annotates the current span with Effect metadata\n */\nexport function autoEnrichSpan(): Effect.Effect<void> {\n return Effect.gen(function* () {\n // Extract Effect metadata\n const metadata = yield* extractEffectMetadata()\n\n // Add metadata as span attributes\n // Cast to Record<string, unknown> to satisfy Effect.annotateCurrentSpan type\n yield* Effect.annotateCurrentSpan(metadata as Record<string, unknown>)\n })\n}\n\n/**\n * Create a wrapper that combines Effect.withSpan with automatic enrichment\n *\n * This is a convenience function that wraps an Effect with both:\n * 1. A span (via Effect.withSpan)\n * 2. Automatic metadata extraction (via autoEnrichSpan)\n *\n * Usage:\n * ```typescript\n * const instrumented = withAutoEnrichedSpan('storage.writeBatch')(\n * Effect.gen(function* () {\n * yield* annotateBatch(items.length, 10)\n * return yield* storage.writeBatch(items)\n * })\n * )\n * ```\n *\n * @param spanName - The name of the span\n * @param options - Optional span options\n * @returns Function that wraps an Effect with an auto-enriched span\n */\nexport function withAutoEnrichedSpan<A, E, R>(\n spanName: string,\n options?: {\n readonly attributes?: Record<string, unknown>\n readonly kind?: 'client' | 'server' | 'producer' | 'consumer' | 'internal'\n }\n) {\n return (self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n return Effect.gen(function* () {\n // Auto-enrich with metadata\n yield* autoEnrichSpan()\n\n // Execute the wrapped effect\n return yield* self\n }).pipe(Effect.withSpan(spanName, options))\n }\n}\n","/**\n * FiberSet helpers with automatic span isolation and virtual parent tracking\n *\n * Provides wrappers around Effect's FiberSet.run that automatically:\n * 1. Isolate span context (prevent leakage via { root: true })\n * 2. Track logical parent via OpenTelemetry span links\n * 3. Add custom attributes as universal fallback\n *\n * @module\n */\n\nimport { Effect, FiberSet as EffectFiberSet, Tracer } from 'effect'\nimport type { RuntimeFiber } from 'effect/Fiber'\n\n/**\n * Options for span isolation when running effects in FiberSet\n */\nexport interface IsolationOptions {\n /**\n * Whether to create a root span (breaks parent chain)\n * @default true (from config or this default)\n */\n readonly createRoot?: boolean\n\n /**\n * Capture logical parent relationship via span links and attributes\n * @default true\n */\n readonly captureLogicalParent?: boolean\n\n /**\n * Use OpenTelemetry span links to track logical parent\n * Works in: Honeycomb, Datadog, Lightstep, SigNoz, Splunk\n * @default true\n */\n readonly useSpanLinks?: boolean\n\n /**\n * Add custom attributes for logical parent tracking\n * Works in: ALL observability tools (universal fallback)\n * @default true\n */\n readonly useAttributes?: boolean\n\n /**\n * Propagate interruption from parent\n * @default undefined (FiberSet.run default behavior)\n */\n readonly propagateInterruption?: boolean\n\n /**\n * Custom span attributes to add\n */\n readonly attributes?: Record<string, unknown>\n\n /**\n * Span category for Atrim grouping\n * @default \"background_task\"\n */\n readonly category?: string\n}\n\n/**\n * Create a span link to the logical parent span\n *\n * This maintains observability while using root spans to prevent context leakage.\n */\nconst createLogicalParentLink = (\n parentSpan: Tracer.AnySpan,\n useSpanLinks: boolean\n): Tracer.SpanLink[] => {\n if (!useSpanLinks) {\n return []\n }\n\n return [\n {\n _tag: 'SpanLink' as const,\n span: parentSpan,\n attributes: {\n 'link.type': 'logical_parent',\n 'atrim.relationship': 'spawned_by',\n description: 'Logical parent (isolated to prevent context leakage)'\n }\n }\n ]\n}\n\n/**\n * Create attributes for logical parent tracking\n *\n * These serve as universal fallback for tools that don't support span links well.\n */\nconst createLogicalParentAttributes = (\n parentSpan: Tracer.AnySpan,\n useAttributes: boolean,\n category: string,\n useSpanLinks: boolean,\n customAttributes: Record<string, unknown>\n): Record<string, unknown> => {\n if (!useAttributes) {\n return customAttributes\n }\n\n return {\n // Logical parent tracking (works in ALL tools)\n 'atrim.logical_parent.span_id': parentSpan.spanId,\n 'atrim.logical_parent.trace_id': parentSpan.traceId,\n 'atrim.logical_parent.name': parentSpan._tag === 'Span' ? parentSpan.name : 'external',\n\n // Categorization and metadata\n 'atrim.fiberset.isolated': true,\n 'atrim.span.category': category,\n 'atrim.has_logical_parent': true,\n 'atrim.isolation.method': useSpanLinks ? 'hybrid' : 'attributes_only',\n\n // User-provided attributes\n ...customAttributes\n }\n}\n\n/**\n * Run an effect in a FiberSet with automatic span isolation and virtual parent tracking.\n *\n * This function prevents span context leakage (fibers inheriting parent spans incorrectly)\n * while maintaining logical parent relationships for observability.\n *\n * **Technical:** Uses `{ root: true }` to create independent root span\n * **Observability:** Uses span links + attributes to track logical parent\n *\n * @example\n * ```typescript\n * import { runIsolated } from \"@atrim/instrumentation/effect/fiberset\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function* () {\n * const set = yield* FiberSet.make()\n *\n * yield* Effect.gen(function* () {\n * // Spawn background tasks with automatic isolation\n * yield* runIsolated(set, backgroundTask1(), \"background-task-1\")\n * yield* runIsolated(set, backgroundTask2(), \"background-task-2\")\n * }).pipe(\n * Effect.withSpan(\"parent-operation\")\n * )\n *\n * yield* Effect.sleep(\"100 millis\")\n * })\n * )\n *\n * // In Honeycomb/Datadog/SigNoz:\n * // - background tasks are ROOT spans (no context leakage)\n * // - span links show they were spawned by parent-operation\n * // - can reconstruct virtual hierarchy\n * ```\n *\n * @param set - The FiberSet to run the effect in\n * @param effect - The effect to run (will be isolated)\n * @param name - Span name for the isolated effect\n * @param options - Configuration options\n * @returns Effect that returns the forked fiber\n *\n * @see https://github.com/atrim-ai/instrumentation/issues/5\n */\nexport const runIsolated = <A, E, R>(\n set: EffectFiberSet.FiberSet<A, E>,\n effect: Effect.Effect<A, E, R>,\n name: string,\n options?: IsolationOptions\n): Effect.Effect<RuntimeFiber<A, E>, never, R> => {\n const {\n createRoot = true,\n captureLogicalParent = true,\n useSpanLinks = true,\n useAttributes = true,\n propagateInterruption,\n attributes = {},\n category = 'background_task'\n } = options ?? {}\n\n // If not creating root and not capturing parent, just use standard FiberSet.run\n if (!createRoot && !captureLogicalParent) {\n return EffectFiberSet.run(set, effect, { propagateInterruption })\n }\n\n return Effect.gen(function* () {\n // Get current parent span (if any)\n const maybeParent = yield* Effect.serviceOption(Tracer.ParentSpan)\n\n // If no parent, just create root span\n if (maybeParent._tag === 'None' || !captureLogicalParent) {\n const isolated = effect.pipe(\n Effect.withSpan(name, {\n root: createRoot,\n attributes: {\n 'atrim.fiberset.isolated': createRoot,\n 'atrim.span.category': category,\n 'atrim.has_logical_parent': false,\n ...attributes\n }\n })\n )\n\n return yield* EffectFiberSet.run(set, isolated, { propagateInterruption })\n }\n\n const parent = maybeParent.value\n\n // Create span links for logical parent tracking\n const links = createLogicalParentLink(parent, useSpanLinks)\n\n // Create attributes for universal fallback\n const spanAttributes = createLogicalParentAttributes(\n parent,\n useAttributes,\n category,\n useSpanLinks,\n attributes\n )\n\n // Create isolated effect with root span + logical parent tracking\n const isolated = effect.pipe(\n Effect.withSpan(name, {\n root: createRoot,\n links: links.length > 0 ? links : undefined,\n attributes: spanAttributes\n })\n )\n\n return yield* EffectFiberSet.run(set, isolated, { propagateInterruption })\n })\n}\n\n/**\n * Convenience function to run an effect in a FiberSet with automatic span isolation.\n *\n * This is a simpler version of `runIsolated` with sensible defaults.\n *\n * @example\n * ```typescript\n * yield* runWithSpan(set, \"background-task\", backgroundTask(), {\n * attributes: { \"task.priority\": \"high\" }\n * })\n * ```\n */\nexport const runWithSpan = <A, E, R>(\n set: EffectFiberSet.FiberSet<A, E>,\n name: string,\n effect: Effect.Effect<A, E, R>,\n options?: {\n readonly propagateInterruption?: boolean\n readonly attributes?: Record<string, unknown>\n readonly category?: string\n }\n): Effect.Effect<RuntimeFiber<A, E>, never, R> => {\n return runIsolated(set, effect, name, {\n createRoot: true,\n captureLogicalParent: true,\n useSpanLinks: true,\n useAttributes: true,\n ...options\n })\n}\n\n/**\n * Annotate the current span with metadata about spawned FiberSet tasks.\n *\n * Call this in the parent operation before spawning tasks to add metadata\n * that helps reconstruct the virtual hierarchy.\n *\n * @example\n * ```typescript\n * yield* Effect.gen(function* () {\n * yield* annotateSpawnedTasks([\n * { name: \"background-task-1\" },\n * { name: \"background-task-2\" },\n * { name: \"background-task-3\" }\n * ])\n *\n * yield* runIsolated(set, task1(), \"background-task-1\")\n * yield* runIsolated(set, task2(), \"background-task-2\")\n * yield* runIsolated(set, task3(), \"background-task-3\")\n * }).pipe(\n * Effect.withSpan(\"parent-operation\")\n * )\n * ```\n */\nexport const annotateSpawnedTasks = (\n tasks: Array<{ name: string; spanId?: string; category?: string }>\n): Effect.Effect<void> => {\n return Effect.annotateCurrentSpan({\n 'atrim.fiberset.spawned_count': tasks.length,\n 'atrim.fiberset.task_names': tasks.map((t) => t.name).join(','),\n 'atrim.has_background_tasks': true,\n 'atrim.spawned_tasks': JSON.stringify(\n tasks.map((t) => ({\n name: t.name,\n ...(t.spanId && { span_id: t.spanId }),\n ...(t.category && { category: t.category })\n }))\n )\n })\n}\n\n/**\n * Re-export FiberSet namespace with isolation helpers\n *\n * This provides a convenient way to import all FiberSet functions:\n * ```typescript\n * import { FiberSet } from \"@atrim/instrumentation/effect/fiberset\"\n * ```\n */\nexport const FiberSet = {\n // Re-export all original FiberSet functions\n make: EffectFiberSet.make,\n add: EffectFiberSet.add,\n unsafeAdd: EffectFiberSet.unsafeAdd,\n run: EffectFiberSet.run,\n clear: EffectFiberSet.clear,\n join: EffectFiberSet.join,\n awaitEmpty: EffectFiberSet.awaitEmpty,\n size: EffectFiberSet.size,\n runtime: EffectFiberSet.runtime,\n runtimePromise: EffectFiberSet.runtimePromise,\n makeRuntime: EffectFiberSet.makeRuntime,\n makeRuntimePromise: EffectFiberSet.makeRuntimePromise,\n isFiberSet: EffectFiberSet.isFiberSet,\n\n // Add our isolation helpers\n runIsolated,\n runWithSpan\n}\n"]}
|