@burdenoff/be-sdk 2026.1125.1 → 2026.1127.2
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/dist/{index-BgOU0pxB.d.ts → index-jStzN9rq.d.ts} +6 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/instrumentation/index.js +2 -2
- package/dist/{instrumentation-C738xDj8.js → instrumentation-DKHAGCoz.js} +107 -4
- package/dist/instrumentation-DKHAGCoz.js.map +1 -0
- package/dist/{sdk-BkIS_wTK.js → sdk-7TBR987n.js} +141 -3
- package/dist/sdk-7TBR987n.js.map +1 -0
- package/dist/telemetry/index.d.ts +3 -2
- package/dist/telemetry/index.js +2 -2
- package/package.json +1 -1
- package/dist/instrumentation-C738xDj8.js.map +0 -1
- package/dist/sdk-BkIS_wTK.js.map +0 -1
|
@@ -1,6 +1,132 @@
|
|
|
1
1
|
import { t as importOptionalPeer } from "./import-optional-peer-B82VYxeX.js";
|
|
2
2
|
import { n as isBunRuntime } from "./bun-runtime-metrics-CPy5D6NT.js";
|
|
3
3
|
|
|
4
|
+
// src/telemetry/instrumentations.ts
|
|
5
|
+
/**
|
|
6
|
+
* Which OpenTelemetry instrumentations `createOtelSdk` registers (BOFF-16818).
|
|
7
|
+
*
|
|
8
|
+
* `@opentelemetry/auto-instrumentations-node` imports every one of its ~39
|
|
9
|
+
* bundled instrumentation packages as soon as it is loaded, whether or not a
|
|
10
|
+
* service uses the library behind it, and each registers a module-load hook.
|
|
11
|
+
* In a Bun GraphQL subgraph that costs about 13 MiB of RSS and 0.5–1.5 s of
|
|
12
|
+
* start-up CPU for instrumentations that never produce a span. The fleet's
|
|
13
|
+
* traces come from a short list of libraries, so by default be-sdk imports
|
|
14
|
+
* only those packages, one by one, and never loads the meta package.
|
|
15
|
+
*
|
|
16
|
+
* Selection (first match wins):
|
|
17
|
+
* 1. `BOFF_OTEL_INSTRUMENTATIONS=auto` → the full auto-instrumentations set.
|
|
18
|
+
* 2. `BOFF_OTEL_INSTRUMENTATIONS=<comma list>` (`http,pg,…`) → exactly those.
|
|
19
|
+
* 3. `OTEL_NODE_ENABLED_INSTRUMENTATIONS` or `OTEL_NODE_DISABLED_INSTRUMENTATIONS`
|
|
20
|
+
* set → the full set, filtered by those standard variables as before.
|
|
21
|
+
* 4. The caller injected `@opentelemetry/auto-instrumentations-node` through
|
|
22
|
+
* `OtelSdkConfig.modules` (a `bun build --compile` binary that has no
|
|
23
|
+
* `node_modules`) → the full set, as before.
|
|
24
|
+
* 5. Otherwise → `DEFAULT_INSTRUMENTATIONS`.
|
|
25
|
+
*
|
|
26
|
+
* When none of the explicit packages can be loaded (a service that installs
|
|
27
|
+
* only the meta package under an isolated linker), `createOtelSdk` falls back to
|
|
28
|
+
* the full set, so a service never ends up with no instrumentation at all.
|
|
29
|
+
*/
|
|
30
|
+
/** The env var that picks the instrumentation set (`auto` or a comma-separated list). */
|
|
31
|
+
const INSTRUMENTATIONS_ENV = "BOFF_OTEL_INSTRUMENTATIONS";
|
|
32
|
+
/**
|
|
33
|
+
* The libraries the fleet's traces and dashboards come from: outbound HTTP
|
|
34
|
+
* (`http`, `undici` for `fetch`), Postgres through the Prisma pg adapter,
|
|
35
|
+
* Redis/Valkey clients, GraphQL execution, pino log correlation, the AWS SDK
|
|
36
|
+
* and DataLoader batches.
|
|
37
|
+
*/
|
|
38
|
+
const DEFAULT_INSTRUMENTATIONS = [
|
|
39
|
+
"http",
|
|
40
|
+
"undici",
|
|
41
|
+
"pg",
|
|
42
|
+
"ioredis",
|
|
43
|
+
"redis",
|
|
44
|
+
"graphql",
|
|
45
|
+
"pino",
|
|
46
|
+
"aws-sdk",
|
|
47
|
+
"dataloader"
|
|
48
|
+
];
|
|
49
|
+
/**
|
|
50
|
+
* Export names that do not follow `<Pascal name>Instrumentation`. Any other
|
|
51
|
+
* package is read through the first export whose name ends in `Instrumentation`.
|
|
52
|
+
*/
|
|
53
|
+
const EXPORT_NAMES = {
|
|
54
|
+
http: "HttpInstrumentation",
|
|
55
|
+
undici: "UndiciInstrumentation",
|
|
56
|
+
pg: "PgInstrumentation",
|
|
57
|
+
ioredis: "IORedisInstrumentation",
|
|
58
|
+
redis: "RedisInstrumentation",
|
|
59
|
+
graphql: "GraphQLInstrumentation",
|
|
60
|
+
pino: "PinoInstrumentation",
|
|
61
|
+
"aws-sdk": "AwsInstrumentation",
|
|
62
|
+
dataloader: "DataloaderInstrumentation"
|
|
63
|
+
};
|
|
64
|
+
/** The package that holds the instrumentation called `name` (`pg` → `@opentelemetry/instrumentation-pg`). */
|
|
65
|
+
const instrumentationPackage = (name) => `@opentelemetry/instrumentation-${name}`;
|
|
66
|
+
const parseList = (value) => [...new Set(value.split(",").map((entry) => entry.trim().toLowerCase()).filter((entry) => entry.length > 0))];
|
|
67
|
+
const isSet = (value) => value !== void 0 && value.trim().length > 0;
|
|
68
|
+
/** Decides between the full auto-instrumentations set and an explicit list (see the module comment). */
|
|
69
|
+
function planInstrumentations(env = process.env, autoInjected = false) {
|
|
70
|
+
const raw = env["BOFF_OTEL_INSTRUMENTATIONS"]?.trim() ?? "";
|
|
71
|
+
if (raw.toLowerCase() === "auto") return {
|
|
72
|
+
mode: "auto",
|
|
73
|
+
reason: `${INSTRUMENTATIONS_ENV}=auto`
|
|
74
|
+
};
|
|
75
|
+
if (raw.length > 0) {
|
|
76
|
+
const names = parseList(raw);
|
|
77
|
+
if (names.length > 0) return {
|
|
78
|
+
mode: "explicit",
|
|
79
|
+
names,
|
|
80
|
+
reason: INSTRUMENTATIONS_ENV
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (isSet(env["OTEL_NODE_ENABLED_INSTRUMENTATIONS"]) || isSet(env["OTEL_NODE_DISABLED_INSTRUMENTATIONS"])) return {
|
|
84
|
+
mode: "auto",
|
|
85
|
+
reason: "OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS is set"
|
|
86
|
+
};
|
|
87
|
+
if (autoInjected) return {
|
|
88
|
+
mode: "auto",
|
|
89
|
+
reason: "auto-instrumentations-node was injected"
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
mode: "explicit",
|
|
93
|
+
names: [...DEFAULT_INSTRUMENTATIONS],
|
|
94
|
+
reason: "default list"
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** The instrumentation class a loaded package exports, or undefined when there is none. */
|
|
98
|
+
function instrumentationClass(name, mod) {
|
|
99
|
+
if (typeof mod !== "object" || mod === null) return void 0;
|
|
100
|
+
const exports = mod;
|
|
101
|
+
const known = EXPORT_NAMES[name];
|
|
102
|
+
const candidate = known !== void 0 ? exports[known] : Object.entries(exports).find(([key, value]) => key.endsWith("Instrumentation") && typeof value === "function")?.[1];
|
|
103
|
+
return typeof candidate === "function" ? candidate : void 0;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Imports and instantiates each named instrumentation. A package that is not
|
|
107
|
+
* installed or does not export an instrumentation is skipped and reported,
|
|
108
|
+
* never fatal.
|
|
109
|
+
*/
|
|
110
|
+
async function loadExplicitInstrumentations(names, load) {
|
|
111
|
+
const result = {
|
|
112
|
+
instances: [],
|
|
113
|
+
loaded: [],
|
|
114
|
+
missing: []
|
|
115
|
+
};
|
|
116
|
+
for (const name of names) try {
|
|
117
|
+
const Instrumentation = instrumentationClass(name, await load(instrumentationPackage(name)));
|
|
118
|
+
if (Instrumentation === void 0) {
|
|
119
|
+
result.missing.push(`${name}: no instrumentation export`);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
result.instances.push(new Instrumentation());
|
|
123
|
+
result.loaded.push(name);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
result.missing.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
|
|
4
130
|
// src/telemetry/sdk.ts
|
|
5
131
|
/**
|
|
6
132
|
* Thin wrapper that initializes `@opentelemetry/sdk-node` with the
|
|
@@ -152,9 +278,21 @@ async function createOtelSdk(cfg) {
|
|
|
152
278
|
const sampler = samplerResult.sampler;
|
|
153
279
|
if (samplerResult.source) console.log(`[sdk] sampler built from ${samplerResult.source}`);
|
|
154
280
|
else console.log(`[sdk] sampler not available (non-fatal): ${samplerResult.failures.join("; ")}`);
|
|
155
|
-
console.log("[sdk] importing @opentelemetry/auto-instrumentations-node...");
|
|
156
281
|
let autoInstrumentations;
|
|
157
|
-
|
|
282
|
+
const plan = planInstrumentations(process.env, cfg.modules?.["@opentelemetry/auto-instrumentations-node"] !== void 0);
|
|
283
|
+
if (plan.mode === "explicit") {
|
|
284
|
+
const explicit = await loadExplicitInstrumentations(plan.names, (specifier) => {
|
|
285
|
+
const injected = cfg.modules?.[specifier];
|
|
286
|
+
return injected !== void 0 ? Promise.resolve(injected) : importOptionalPeer(specifier);
|
|
287
|
+
});
|
|
288
|
+
if (explicit.instances.length > 0) {
|
|
289
|
+
autoInstrumentations = explicit.instances;
|
|
290
|
+
console.log(`[sdk] instrumentations (${plan.reason}): ${explicit.loaded.join(",")}`);
|
|
291
|
+
if (explicit.missing.length > 0) console.log(`[sdk] instrumentations skipped: ${explicit.missing.join("; ")}`);
|
|
292
|
+
} else console.log(`[sdk] none of the explicit instrumentations could be loaded (${explicit.missing.join("; ")}); falling back to auto-instrumentations-node`);
|
|
293
|
+
} else console.log(`[sdk] full auto-instrumentations set (${plan.reason})`);
|
|
294
|
+
if (autoInstrumentations === void 0) try {
|
|
295
|
+
console.log("[sdk] importing @opentelemetry/auto-instrumentations-node...");
|
|
158
296
|
const auto = await load("@opentelemetry/auto-instrumentations-node");
|
|
159
297
|
const instrumentationConfig = autoInstrumentationConfig();
|
|
160
298
|
autoInstrumentations = auto.getNodeAutoInstrumentations(instrumentationConfig);
|
|
@@ -215,4 +353,4 @@ async function createOtelSdk(cfg) {
|
|
|
215
353
|
}
|
|
216
354
|
|
|
217
355
|
export { createOtelSdk };
|
|
218
|
-
//# sourceMappingURL=sdk-
|
|
356
|
+
//# sourceMappingURL=sdk-7TBR987n.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sdk-7TBR987n.js","names":[],"sources":["../src/telemetry/instrumentations.ts","../src/telemetry/sdk.ts"],"sourcesContent":["/**\n * Which OpenTelemetry instrumentations `createOtelSdk` registers (BOFF-16818).\n *\n * `@opentelemetry/auto-instrumentations-node` imports every one of its ~39\n * bundled instrumentation packages as soon as it is loaded, whether or not a\n * service uses the library behind it, and each registers a module-load hook.\n * In a Bun GraphQL subgraph that costs about 13 MiB of RSS and 0.5–1.5 s of\n * start-up CPU for instrumentations that never produce a span. The fleet's\n * traces come from a short list of libraries, so by default be-sdk imports\n * only those packages, one by one, and never loads the meta package.\n *\n * Selection (first match wins):\n * 1. `BOFF_OTEL_INSTRUMENTATIONS=auto` → the full auto-instrumentations set.\n * 2. `BOFF_OTEL_INSTRUMENTATIONS=<comma list>` (`http,pg,…`) → exactly those.\n * 3. `OTEL_NODE_ENABLED_INSTRUMENTATIONS` or `OTEL_NODE_DISABLED_INSTRUMENTATIONS`\n * set → the full set, filtered by those standard variables as before.\n * 4. The caller injected `@opentelemetry/auto-instrumentations-node` through\n * `OtelSdkConfig.modules` (a `bun build --compile` binary that has no\n * `node_modules`) → the full set, as before.\n * 5. Otherwise → `DEFAULT_INSTRUMENTATIONS`.\n *\n * When none of the explicit packages can be loaded (a service that installs\n * only the meta package under an isolated linker), `createOtelSdk` falls back to\n * the full set, so a service never ends up with no instrumentation at all.\n */\n\n/** The env var that picks the instrumentation set (`auto` or a comma-separated list). */\nexport const INSTRUMENTATIONS_ENV = 'BOFF_OTEL_INSTRUMENTATIONS';\n\n/**\n * The libraries the fleet's traces and dashboards come from: outbound HTTP\n * (`http`, `undici` for `fetch`), Postgres through the Prisma pg adapter,\n * Redis/Valkey clients, GraphQL execution, pino log correlation, the AWS SDK\n * and DataLoader batches.\n */\nexport const DEFAULT_INSTRUMENTATIONS: readonly string[] = [\n 'http',\n 'undici',\n 'pg',\n 'ioredis',\n 'redis',\n 'graphql',\n 'pino',\n 'aws-sdk',\n 'dataloader',\n];\n\n/**\n * Export names that do not follow `<Pascal name>Instrumentation`. Any other\n * package is read through the first export whose name ends in `Instrumentation`.\n */\nconst EXPORT_NAMES: Readonly<Record<string, string>> = {\n http: 'HttpInstrumentation',\n undici: 'UndiciInstrumentation',\n pg: 'PgInstrumentation',\n ioredis: 'IORedisInstrumentation',\n redis: 'RedisInstrumentation',\n graphql: 'GraphQLInstrumentation',\n pino: 'PinoInstrumentation',\n 'aws-sdk': 'AwsInstrumentation',\n dataloader: 'DataloaderInstrumentation',\n};\n\n/** The package that holds the instrumentation called `name` (`pg` → `@opentelemetry/instrumentation-pg`). */\nexport const instrumentationPackage = (name: string): string => `@opentelemetry/instrumentation-${name}`;\n\nexport type InstrumentationPlan =\n { mode: 'auto'; reason: string } | { mode: 'explicit'; names: string[]; reason: string };\n\nconst parseList = (value: string): string[] => [\n ...new Set(\n value\n .split(',')\n .map((entry) => entry.trim().toLowerCase())\n .filter((entry) => entry.length > 0)\n ),\n];\n\nconst isSet = (value: string | undefined): boolean => value !== undefined && value.trim().length > 0;\n\n/** Decides between the full auto-instrumentations set and an explicit list (see the module comment). */\nexport function planInstrumentations(\n env: Readonly<Record<string, string | undefined>> = process.env,\n autoInjected = false\n): InstrumentationPlan {\n const raw = env[INSTRUMENTATIONS_ENV]?.trim() ?? '';\n if (raw.toLowerCase() === 'auto') return { mode: 'auto', reason: `${INSTRUMENTATIONS_ENV}=auto` };\n if (raw.length > 0) {\n const names = parseList(raw);\n if (names.length > 0) return { mode: 'explicit', names, reason: INSTRUMENTATIONS_ENV };\n }\n if (isSet(env['OTEL_NODE_ENABLED_INSTRUMENTATIONS']) || isSet(env['OTEL_NODE_DISABLED_INSTRUMENTATIONS'])) {\n return { mode: 'auto', reason: 'OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS is set' };\n }\n if (autoInjected) return { mode: 'auto', reason: 'auto-instrumentations-node was injected' };\n return { mode: 'explicit', names: [...DEFAULT_INSTRUMENTATIONS], reason: 'default list' };\n}\n\ntype InstrumentationClass = new (config?: Record<string, unknown>) => unknown;\n\n/** The instrumentation class a loaded package exports, or undefined when there is none. */\nexport function instrumentationClass(name: string, mod: unknown): InstrumentationClass | undefined {\n if (typeof mod !== 'object' || mod === null) return undefined;\n const exports = mod as Record<string, unknown>;\n const known = EXPORT_NAMES[name];\n const candidate =\n known !== undefined\n ? exports[known]\n : Object.entries(exports).find(\n ([key, value]) => key.endsWith('Instrumentation') && typeof value === 'function'\n )?.[1];\n // A class is a function at runtime; it is only ever called with `new` below.\n return typeof candidate === 'function' ? (candidate as InstrumentationClass) : undefined;\n}\n\nexport interface ExplicitInstrumentations {\n instances: unknown[];\n loaded: string[];\n /** `name: reason` for each instrumentation that could not be loaded or built. */\n missing: string[];\n}\n\n/**\n * Imports and instantiates each named instrumentation. A package that is not\n * installed or does not export an instrumentation is skipped and reported,\n * never fatal.\n */\nexport async function loadExplicitInstrumentations(\n names: readonly string[],\n load: (specifier: string) => Promise<unknown>\n): Promise<ExplicitInstrumentations> {\n const result: ExplicitInstrumentations = { instances: [], loaded: [], missing: [] };\n for (const name of names) {\n try {\n const Instrumentation = instrumentationClass(name, await load(instrumentationPackage(name)));\n if (Instrumentation === undefined) {\n result.missing.push(`${name}: no instrumentation export`);\n continue;\n }\n result.instances.push(new Instrumentation());\n result.loaded.push(name);\n } catch (error) {\n result.missing.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return result;\n}\n","/**\n * Thin wrapper that initializes `@opentelemetry/sdk-node` with the\n * OTLPTrace + OTLPMetric exporters and standard auto-instrumentations.\n *\n * All imports are dynamic so services that haven't installed sdk-node\n * still compile and run. The function resolves `undefined` when the SDK\n * isn't available, letting `bootstrapTelemetry` fall back gracefully.\n */\nimport { importOptionalPeer } from '../utils/import-optional-peer.js';\nimport { isBunRuntime } from './bun-runtime-metrics.js';\nimport type { TelemetryIdGenerator } from './id-generator.js';\nimport type { Boundary, Env } from './index.js';\nimport { loadExplicitInstrumentations, planInstrumentations } from './instrumentations.js';\n\nexport interface OtelSdkConfig {\n serviceName: string;\n serviceVersion: string;\n boundary: Boundary;\n module?: string;\n env: Env;\n otlpEndpoint: string;\n sampleRatio: number;\n /**\n * Optional trace/span id generator handed to NodeSDK's tracer provider.\n * Omitted means the SDK's default random generator.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name. A package found\n * here is used as is; any other one is loaded at runtime from the consumer's\n * `node_modules` through `importOptionalPeer`. A service built with\n * `bun build --compile` has no `node_modules` at runtime, so it imports the\n * packages statically and hands them in here.\n */\n modules?: OtelModules;\n}\n\n/** The OpenTelemetry packages `createOtelSdk` can load. */\nexport type OtelPeerPackage =\n | '@opentelemetry/api'\n | '@opentelemetry/auto-instrumentations-node'\n | '@opentelemetry/exporter-metrics-otlp-http'\n | '@opentelemetry/exporter-trace-otlp-http'\n | '@opentelemetry/resources'\n | '@opentelemetry/sdk-metrics'\n | '@opentelemetry/sdk-node'\n | '@opentelemetry/sdk-trace-base'\n | '@opentelemetry/semantic-conventions';\n\n/**\n * Module namespaces injected in place of runtime imports (see `OtelSdkConfig.modules`).\n * Single instrumentation packages (`@opentelemetry/instrumentation-pg`) can be\n * injected too; they are used when be-sdk registers its explicit list\n * (`./instrumentations.ts`).\n */\nexport type OtelModules = Partial<Record<OtelPeerPackage | InstrumentationPackage, unknown>>;\n\n/** A single OpenTelemetry instrumentation package. */\nexport type InstrumentationPackage = `@opentelemetry/instrumentation-${string}`;\n\nexport interface OtelSdkHandle {\n shutdown: () => Promise<void>;\n metricsEnabled: boolean;\n metricsDropReason?: string;\n /**\n * Where the configured ratio sampler came from, or `undefined` when no\n * sampler could be built and NodeSDK fell back to its own default sampler.\n */\n samplerSource?: SamplerSource;\n}\n\n/** The module a ratio sampler was built from (see `resolveSampler`). */\nexport type SamplerSource =\n 'injected @opentelemetry/sdk-trace-base' | '@opentelemetry/sdk-node tracing' | '@opentelemetry/sdk-trace-base';\n\ninterface SamplerModule {\n ParentBasedSampler: new (init: Record<string, unknown>) => unknown;\n TraceIdRatioBasedSampler: new (ratio: number) => unknown;\n}\n\nconst isSamplerModule = (mod: unknown): mod is SamplerModule => {\n if (typeof mod !== 'object' || mod === null) return false;\n const candidate = mod as Partial<Record<keyof SamplerModule, unknown>>;\n return typeof candidate.ParentBasedSampler === 'function' && typeof candidate.TraceIdRatioBasedSampler === 'function';\n};\n\nexport interface ResolveSamplerInput {\n /** The loaded `@opentelemetry/sdk-node` namespace. */\n sdkNode: unknown;\n /** An `@opentelemetry/sdk-trace-base` namespace passed in through `OtelSdkConfig.modules`. */\n injectedTraceBase?: unknown;\n /** Loads `@opentelemetry/sdk-trace-base` from the consumer's `node_modules`. */\n loadTraceBase: () => Promise<unknown>;\n sampleRatio: number;\n}\n\nexport interface ResolveSamplerResult {\n sampler: unknown;\n source?: SamplerSource;\n /** One entry per candidate that was missing or could not build a sampler. */\n failures: string[];\n}\n\nconst describeError = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * Builds `ParentBasedSampler(TraceIdRatioBasedSampler(ratio))`.\n *\n * Candidates, first that works wins:\n * 1. an `@opentelemetry/sdk-trace-base` namespace the caller injected;\n * 2. the `tracing` namespace `@opentelemetry/sdk-node` re-exports. It is the\n * sdk-trace copy NodeSDK itself was built against, so its\n * `@opentelemetry/core` always matches;\n * 3. the consumer's top-level `@opentelemetry/sdk-trace-base`.\n *\n * Candidate 3 alone used to be the only path. Services that also depend on\n * `@envelop/opentelemetry` (which asks for sdk-trace-base `^1.11.0`) get the\n * 1.x copy hoisted to the top level, and with `@opentelemetry/core` pinned to\n * 2.x that copy throws at load time (`TracesSamplerValues` is undefined). The\n * configured ratio was then ignored silently (CORE-48).\n *\n * Each candidate is constructed inside its own try, because a module can load\n * and still fail when its classes are instantiated.\n */\nexport async function resolveSampler(input: ResolveSamplerInput): Promise<ResolveSamplerResult> {\n const ratio = Math.min(1, Math.max(0, input.sampleRatio));\n const failures: string[] = [];\n const build = (mod: SamplerModule): unknown =>\n new mod.ParentBasedSampler({ root: new mod.TraceIdRatioBasedSampler(ratio) });\n\n const candidates: Array<{ source: SamplerSource; get: () => unknown }> = [];\n if (input.injectedTraceBase !== undefined) {\n candidates.push({ source: 'injected @opentelemetry/sdk-trace-base', get: () => input.injectedTraceBase });\n }\n candidates.push({\n source: '@opentelemetry/sdk-node tracing',\n get: () => (input.sdkNode as { tracing?: unknown } | null | undefined)?.tracing,\n });\n candidates.push({ source: '@opentelemetry/sdk-trace-base', get: input.loadTraceBase });\n\n for (const candidate of candidates) {\n try {\n const mod = await candidate.get();\n if (!isSamplerModule(mod)) {\n failures.push(`${candidate.source}: no ParentBasedSampler/TraceIdRatioBasedSampler export`);\n continue;\n }\n return { sampler: build(mod), source: candidate.source, failures };\n } catch (error) {\n failures.push(`${candidate.source}: ${describeError(error)}`);\n }\n }\n return { sampler: undefined, failures };\n}\n\n/** Per-instrumentation config handed to `getNodeAutoInstrumentations`, keyed by package name. */\nexport type AutoInstrumentationConfig = Record<string, { enabled: boolean }>;\n\n/** The name `OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS` use for `@opentelemetry/instrumentation-runtime-node`. */\nconst RUNTIME_NODE_INSTRUMENTATION = 'runtime-node';\n\n/** True when a comma-separated `OTEL_NODE_*_INSTRUMENTATIONS` value names `name` (parsed as auto-instrumentations-node does). */\nconst listsInstrumentation = (value: string | undefined, name: string): boolean =>\n value !== undefined && value.split(',').some((entry) => entry.trim() === name);\n\n/**\n * The config be-sdk hands to `getNodeAutoInstrumentations`.\n *\n * - `instrumentation-fs` is always off.\n * - `instrumentation-runtime-node` is off under Bun unless\n * `OTEL_NODE_ENABLED_INSTRUMENTATIONS` names `runtime-node` (BOFF-12287). On\n * every 60 s OTLP metric export it reads `v8.getHeapSpaceStatistics()`,\n * which Bun implements as a synchronous walk of the whole heap: a 0.1–1.4 s\n * block once a minute on the prod gateways, during which no request is\n * served. Event-loop lag stays visible through prom-client's\n * `nodejs_eventloop_lag_*`. Dropped: the OTel `v8js_*`,\n * `nodejs_eventloop_delay_*`, `nodejs_eventloop_utilization_*` and\n * `nodejs_eventloop_time_*` series, which no dashboard or alert reads.\n *\n * auto-instrumentations-node lets a programmatic `enabled: false` win over\n * both env vars, so the opt-in has to be checked here. Under Node nothing\n * changes: the env vars keep their usual meaning.\n */\nexport function autoInstrumentationConfig(\n env: Readonly<Record<string, string | undefined>> = process.env,\n bun: boolean = isBunRuntime()\n): AutoInstrumentationConfig {\n const config: AutoInstrumentationConfig = {\n '@opentelemetry/instrumentation-fs': { enabled: false },\n };\n if (bun && !listsInstrumentation(env['OTEL_NODE_ENABLED_INSTRUMENTATIONS'], RUNTIME_NODE_INSTRUMENTATION)) {\n config['@opentelemetry/instrumentation-runtime-node'] = { enabled: false };\n }\n return config;\n}\n\ntype Thenable = {\n then: (onfulfilled?: (value: void) => void, onrejected?: (reason: unknown) => void) => unknown;\n};\n\nconst isThenable = (value: unknown): value is Thenable => {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n};\n\nconst asyncDisposeMetricReader = async (metricReaderCandidate: unknown): Promise<void> => {\n const shutdown = (metricReaderCandidate as { shutdown?: () => void | Promise<void> }).shutdown;\n if (typeof shutdown === 'function') {\n const result = shutdown.call(metricReaderCandidate) as unknown;\n if (isThenable(result)) await result;\n }\n};\n\nexport async function createOtelSdk(cfg: OtelSdkConfig): Promise<OtelSdkHandle> {\n const load = (name: OtelPeerPackage): Promise<unknown> =>\n cfg.modules?.[name] !== undefined ? Promise.resolve(cfg.modules[name]) : importOptionalPeer(name);\n console.log('[sdk] importing @opentelemetry/sdk-node...');\n const sdkMod = (await load('@opentelemetry/sdk-node')) as {\n NodeSDK: new (init: Record<string, unknown>) => {\n start: () => void;\n shutdown: () => Promise<void>;\n };\n };\n\n console.log('[sdk] importing @opentelemetry/resources...');\n const resources = (await load('@opentelemetry/resources')) as {\n resourceFromAttributes: (attrs: Record<string, string | number>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/semantic-conventions...');\n const sem = (await load('@opentelemetry/semantic-conventions')) as Record<string, string>;\n\n console.log('[sdk] importing @opentelemetry/exporter-trace-otlp-http...');\n const traceExp = (await load('@opentelemetry/exporter-trace-otlp-http')) as {\n OTLPTraceExporter: new (init: Record<string, string>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/exporter-metrics-otlp-http...');\n let metricsExp: { OTLPMetricExporter?: new (init: Record<string, string>) => unknown } | undefined;\n try {\n metricsExp = (await load('@opentelemetry/exporter-metrics-otlp-http')) as typeof metricsExp;\n } catch {\n metricsExp = undefined;\n console.log('[sdk] metrics exporter not available (non-fatal)');\n }\n\n let metricReader: unknown;\n let metricsEnabled = false;\n let metricsDropReason: string | undefined;\n if (metricsExp?.OTLPMetricExporter) {\n try {\n const metricsSdk = (await load('@opentelemetry/sdk-metrics')) as {\n PeriodicExportingMetricReader: new (init: Record<string, unknown>) => unknown;\n };\n const candidate = new metricsSdk.PeriodicExportingMetricReader({\n exporter: new metricsExp.OTLPMetricExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/metrics`,\n }),\n });\n // Pre-flight API compatibility check. Some OTel package version\n // combinations construct `PeriodicExportingMetricReader` successfully\n // but lack `setMetricProducer` on the prototype chain (mixed\n // sdk-metrics versions, or runtime-specific class-inheritance\n // quirks — Bun has surfaced this in the past). Without the check,\n // `NodeSDK.start()` may register the global tracer provider BEFORE\n // it tries to call `setMetricProducer` and throws — leaving the\n // global tracer pointing at a half-initialized provider whose\n // span pipeline never drains. Skipping the metric reader when the\n // API isn't there avoids that whole failure mode in one pass.\n const setProducer = (candidate as { setMetricProducer?: unknown }).setMetricProducer;\n if (typeof setProducer === 'function') {\n metricReader = candidate;\n metricsEnabled = true;\n } else {\n metricsDropReason =\n 'setMetricProducer is not a function on PeriodicExportingMetricReader; skipping metrics path';\n await asyncDisposeMetricReader(candidate);\n metricReader = undefined;\n }\n } catch {\n if (metricsDropReason === undefined) {\n metricsDropReason = 'metric reader construction or compatibility check failed';\n }\n metricReader = undefined;\n }\n }\n\n const samplerResult = await resolveSampler({\n sdkNode: sdkMod,\n injectedTraceBase: cfg.modules?.['@opentelemetry/sdk-trace-base'],\n loadTraceBase: () => importOptionalPeer('@opentelemetry/sdk-trace-base'),\n sampleRatio: cfg.sampleRatio,\n });\n const sampler = samplerResult.sampler;\n if (samplerResult.source) {\n console.log(`[sdk] sampler built from ${samplerResult.source}`);\n } else {\n console.log(`[sdk] sampler not available (non-fatal): ${samplerResult.failures.join('; ')}`);\n }\n\n // Instrumentations: an explicit list by default, the full auto set on request\n // or as the fallback (BOFF-16818, see ./instrumentations.ts). All optional.\n let autoInstrumentations: unknown[] | undefined;\n const plan = planInstrumentations(\n process.env,\n cfg.modules?.['@opentelemetry/auto-instrumentations-node'] !== undefined\n );\n if (plan.mode === 'explicit') {\n const explicit = await loadExplicitInstrumentations(plan.names, (specifier) => {\n // instrumentationPackage() only ever builds `@opentelemetry/instrumentation-<name>`.\n const injected = cfg.modules?.[specifier as InstrumentationPackage];\n return injected !== undefined ? Promise.resolve(injected) : importOptionalPeer(specifier);\n });\n if (explicit.instances.length > 0) {\n autoInstrumentations = explicit.instances;\n console.log(`[sdk] instrumentations (${plan.reason}): ${explicit.loaded.join(',')}`);\n if (explicit.missing.length > 0) console.log(`[sdk] instrumentations skipped: ${explicit.missing.join('; ')}`);\n } else {\n console.log(\n `[sdk] none of the explicit instrumentations could be loaded (${explicit.missing.join('; ')}); ` +\n 'falling back to auto-instrumentations-node'\n );\n }\n } else {\n console.log(`[sdk] full auto-instrumentations set (${plan.reason})`);\n }\n if (autoInstrumentations === undefined) {\n try {\n console.log('[sdk] importing @opentelemetry/auto-instrumentations-node...');\n const auto = (await load('@opentelemetry/auto-instrumentations-node')) as {\n getNodeAutoInstrumentations: (cfg?: Record<string, unknown>) => unknown[];\n };\n const instrumentationConfig = autoInstrumentationConfig();\n autoInstrumentations = auto.getNodeAutoInstrumentations(instrumentationConfig);\n console.log('[sdk] auto-instrumentations loaded');\n if (instrumentationConfig['@opentelemetry/instrumentation-runtime-node']?.enabled === false) {\n console.log(\n '[sdk] runtime-node instrumentation off under Bun (its heap statistics stall the event loop); ' +\n 'list runtime-node in OTEL_NODE_ENABLED_INSTRUMENTATIONS to turn it on'\n );\n }\n } catch {\n autoInstrumentations = undefined;\n console.log('[sdk] auto-instrumentations not available (non-fatal)');\n }\n }\n\n const serviceNamespaceByBoundary: Record<Boundary, string> = {\n wspace: 'workspaces',\n global: 'tenant',\n gateway: 'gateways',\n };\n const resourceAttributes: Record<string, string> = {\n [sem['SEMRESATTRS_SERVICE_NAME'] ?? 'service.name']: cfg.serviceName,\n [sem['SEMRESATTRS_SERVICE_VERSION'] ?? 'service.version']: cfg.serviceVersion,\n [sem['SEMRESATTRS_SERVICE_NAMESPACE'] ?? 'service.namespace']: serviceNamespaceByBoundary[cfg.boundary],\n [sem['SEMRESATTRS_DEPLOYMENT_ENVIRONMENT'] ?? 'deployment.environment']: cfg.env,\n 'burdenoff.boundary': cfg.boundary,\n };\n if (cfg.module) resourceAttributes['burdenoff.module'] = cfg.module;\n const serviceInstanceId = process.env['POD_NAME'] ?? process.env['HOSTNAME'];\n if (serviceInstanceId) resourceAttributes['service.instance.id'] = serviceInstanceId;\n const clusterName = process.env['CLUSTER_NAME'];\n if (clusterName) {\n resourceAttributes['cluster'] = clusterName;\n resourceAttributes['k8s.cluster.name'] = clusterName;\n }\n\n const resource = resources.resourceFromAttributes(resourceAttributes);\n\n const traceExporter = new traceExp.OTLPTraceExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/traces`,\n });\n\n // Single NodeSDK, single start. The pre-flight `setMetricProducer`\n // check above means we never pass an incompatible metric reader into\n // NodeSDK construction — so we no longer need the prior catch+rebuild\n // fallback dance, which had its own side-effect: the failed first\n // NodeSDK could leave the global tracer provider partially registered,\n // and the second NodeSDK's `setGlobalTracerProvider` becomes a no-op\n // — meaning spans flow into the FIRST (broken) provider and never\n // reach the exporter. Eliminating the fallback eliminates that hazard.\n console.log('[sdk] constructing NodeSDK...');\n const nodeSdk = new sdkMod.NodeSDK({\n resource,\n traceExporter,\n ...(metricReader ? { metricReader } : {}),\n ...(sampler ? { sampler } : {}),\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(autoInstrumentations ? { instrumentations: autoInstrumentations } : {}),\n });\n console.log('[sdk] NodeSDK constructed, calling start()...');\n // NodeSDK.start() returns void in modern versions and Promise<void> in older\n // ones. Cast to a permissive thenable shape so awaiting works either way\n // without tripping `@typescript-eslint/await-thenable`.\n const startResult = nodeSdk.start() as unknown;\n if (isThenable(startResult)) {\n await startResult;\n }\n console.log('[sdk] NodeSDK started');\n\n // Stash the @opentelemetry/api reference for pino-logger's mixin.\n try {\n (globalThis as unknown as { __otelApi?: unknown }).__otelApi = await load('@opentelemetry/api');\n console.log('[sdk] @opentelemetry/api stashed for pino mixin');\n } catch {\n console.log('[sdk] @opentelemetry/api stash failed (non-fatal)');\n }\n\n console.log('[sdk] OTel SDK initialization complete');\n return {\n shutdown: async (): Promise<void> => nodeSdk.shutdown(),\n metricsEnabled,\n metricsDropReason,\n ...(samplerResult.source ? { samplerSource: samplerResult.source } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,uBAAuB;;;;;;;AAQpC,MAAa,2BAA8C;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAM,eAAiD;CACrD,MAAM;CACN,QAAQ;CACR,IAAI;CACJ,SAAS;CACT,OAAO;CACP,SAAS;CACT,MAAM;CACN,WAAW;CACX,YAAY;AACd;;AAGA,MAAa,0BAA0B,SAAyB,kCAAkC;AAKlG,MAAM,aAAa,UAA4B,CAC7C,GAA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,SAAS,kBAAkB,EACnD,KAAK,GAAG,IAAI,aAAa,QAAQ,OAAO,EAAE,EAAE,YAC9C,CAAC;CAUD,QAAQ,IAAI,+BAA+B;CAC3C,MAAM,UAAU,IAAI,OAAO,QAAQ;EACjC;EACA;EACA,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;EACvC,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAC7B,GAAI,IAAI,cAAc,EAAE,aAAa,IAAI,YAAY,IAAI,CAAC;EAC1D,GAAI,uBAAuB,EAAE,kBAAkB,qBAAqB,IAAI,CAAC;CAC3E,CAAC;CACD,QAAQ,IAAI,+CAA+C;CAI3D,MAAM,cAAc,QAAQ,MAAM;CAClC,IAAI,WAAW,WAAW,GACxB,MAAM;CAER,QAAQ,IAAI,uBAAuB;CAGnC,IAAI;EACF,AAAC,WAAkD,YAAY,MAAM,KAAK,oBAAoB;EAC9F,QAAQ,IAAI,iDAAiD;CAC/D,QAAQ;EACN,QAAQ,IAAI,mDAAmD;CACjE;CAEA,QAAQ,IAAI,wCAAwC;CACpD,OAAO;EACL,UAAU,YAA2B,QAAQ,SAAS;EACtD;EACA;EACA,GAAI,cAAc,SAAS,EAAE,eAAe,cAAc,OAAO,IAAI,CAAC;CACxE;AACF"}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { r as Logger } from "../index-KlrnELrN.js";
|
|
2
|
-
import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-
|
|
2
|
+
import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-jStzN9rq.js";
|
|
3
3
|
interface TelemetryIdGenerator {
|
|
4
4
|
generateTraceId(): string;
|
|
5
5
|
generateSpanId(): string;
|
|
6
6
|
}
|
|
7
7
|
export declare function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined;
|
|
8
8
|
type OtelPeerPackage = '@opentelemetry/api' | '@opentelemetry/auto-instrumentations-node' | '@opentelemetry/exporter-metrics-otlp-http' | '@opentelemetry/exporter-trace-otlp-http' | '@opentelemetry/resources' | '@opentelemetry/sdk-metrics' | '@opentelemetry/sdk-node' | '@opentelemetry/sdk-trace-base' | '@opentelemetry/semantic-conventions';
|
|
9
|
-
type OtelModules = Partial<Record<OtelPeerPackage, unknown>>;
|
|
9
|
+
type OtelModules = Partial<Record<OtelPeerPackage | InstrumentationPackage, unknown>>;
|
|
10
|
+
type InstrumentationPackage = `@opentelemetry/instrumentation-${string}`;
|
|
10
11
|
interface PrismaLike {
|
|
11
12
|
$queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;
|
|
12
13
|
}
|
package/dist/telemetry/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
|
|
2
2
|
import { a as logger, s as redactSensitiveFields, t as Logger } from "../logger-B6rCpb7D.js";
|
|
3
|
-
import {
|
|
3
|
+
import { D as setActiveTelemetryLogger, n as initializeInstrumentation, o as setupInstrumentation } from "../instrumentation-DKHAGCoz.js";
|
|
4
4
|
import { a as resolveCollectorLayer, i as defaultCollectorTracesEndpoint, n as OTLP_HTTP_PORT, r as defaultCollectorEndpoint, t as COLLECTOR_SERVICE } from "../collector-endpoint-iyQYeI50.js";
|
|
5
5
|
import { t as collectPromDefaultMetrics } from "../bun-runtime-metrics-CPy5D6NT.js";
|
|
6
6
|
|
|
@@ -352,7 +352,7 @@ async function bootstrapTelemetry(cfg) {
|
|
|
352
352
|
if (resolveOtelSdkEnabled()) {
|
|
353
353
|
console.log("[telemetry] OTel SDK bootstrap starting...");
|
|
354
354
|
try {
|
|
355
|
-
const { createOtelSdk } = await import("../sdk-
|
|
355
|
+
const { createOtelSdk } = await import("../sdk-7TBR987n.js");
|
|
356
356
|
otelSdk = await createOtelSdk({
|
|
357
357
|
serviceName: cfg.serviceName,
|
|
358
358
|
serviceVersion,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.1127.2",
|
|
4
4
|
"description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation-C738xDj8.js","names":["instrumentedContext","defaultLogger","getTracerFn","getMetricsFn","getConfig","isConfigInit","isTracerInit","isMetricsInit"],"sources":["../src/instrumentation/tracer.ts","../src/telemetry/logger-state.ts","../src/instrumentation/types.ts","../src/instrumentation/graphql-plugin.ts","../src/instrumentation/decorators.ts","../src/instrumentation/index.ts"],"sourcesContent":["/**\n * Tracer Module\n *\n * OpenTelemetry tracing utilities for distributed tracing across\n * Burdenoff microservices. Provides span creation, context propagation,\n * and trace management.\n *\n * @module instrumentation/tracer\n * @category Observability\n */\n\nimport { logger } from '../logger/index.js';\nimport { getInstrumentationConfig, isFeatureEnabled, isInstrumentationConfigInitialized } from './config.js';\nimport type { OperationContext, SpanAttributes, SpanContext, TraceContext } from './types.js';\n\n/**\n * Span status\n */\nexport enum SpanStatus {\n UNSET = 0,\n OK = 1,\n ERROR = 2,\n}\n\n/**\n * Span kind\n */\nexport enum SpanKind {\n INTERNAL = 0,\n SERVER = 1,\n CLIENT = 2,\n PRODUCER = 3,\n CONSUMER = 4,\n}\n\n/**\n * Span interface for tracing operations\n */\nexport interface Span {\n /** Span name */\n name: string;\n /** Trace ID */\n traceId: string;\n /** Span ID */\n spanId: string;\n /** Parent span ID */\n parentSpanId?: string;\n /** Span kind */\n kind: SpanKind;\n /** Start time in milliseconds */\n startTime: number;\n /** End time in milliseconds */\n endTime?: number;\n /** Span status */\n status: SpanStatus;\n /** Span attributes */\n attributes: SpanAttributes;\n /** Events recorded in this span */\n events: SpanEvent[];\n /** Whether the span is recording */\n isRecording: boolean;\n\n /** Set an attribute on the span */\n setAttribute(key: string, value: string | number | boolean): Span;\n /** Set multiple attributes on the span */\n setAttributes(attributes: SpanAttributes): Span;\n /** Set the span status */\n setStatus(status: SpanStatus, message?: string): Span;\n /** Record an exception */\n recordException(error: Error): Span;\n /** Add an event to the span */\n addEvent(name: string, attributes?: SpanAttributes): Span;\n /** End the span */\n end(): void;\n /** Get span context for propagation */\n getSpanContext(): SpanContext;\n}\n\n/**\n * Span event\n */\nexport interface SpanEvent {\n name: string;\n timestamp: number;\n attributes?: SpanAttributes;\n}\n\n/**\n * Generate a random trace ID (32 hex characters)\n */\nfunction generateTraceId(): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Generate a random span ID (16 hex characters)\n */\nfunction generateSpanId(): string {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * In-memory span implementation\n */\nclass InMemorySpan implements Span {\n name: string;\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n kind: SpanKind;\n startTime: number;\n endTime?: number;\n status: SpanStatus = SpanStatus.UNSET;\n attributes: SpanAttributes = {};\n events: SpanEvent[] = [];\n isRecording = true;\n\n private onEnd?: (span: Span) => void;\n\n constructor(\n name: string,\n kind: SpanKind = SpanKind.INTERNAL,\n parentContext?: SpanContext,\n onEnd?: (span: Span) => void\n ) {\n this.name = name;\n this.kind = kind;\n this.startTime = Date.now();\n this.spanId = generateSpanId();\n this.onEnd = onEnd;\n\n if (parentContext) {\n this.traceId = parentContext.traceId;\n this.parentSpanId = parentContext.spanId;\n } else {\n this.traceId = generateTraceId();\n }\n }\n\n setAttribute(key: string, value: string | number | boolean): Span {\n if (this.isRecording) {\n this.attributes[key] = value;\n }\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): Span {\n if (this.isRecording) {\n Object.assign(this.attributes, attributes);\n }\n return this;\n }\n\n setStatus(status: SpanStatus, message?: string): Span {\n this.status = status;\n if (message) {\n this.attributes['status.message'] = message;\n }\n return this;\n }\n\n recordException(error: Error): Span {\n this.status = SpanStatus.ERROR;\n this.attributes['error'] = true;\n this.attributes['error.type'] = error.name;\n this.attributes['error.message'] = error.message;\n if (error.stack) {\n this.attributes['error.stack'] = error.stack;\n }\n this.addEvent('exception', {\n 'exception.type': error.name,\n 'exception.message': error.message,\n });\n return this;\n }\n\n addEvent(name: string, attributes?: SpanAttributes): Span {\n if (this.isRecording) {\n this.events.push({\n name,\n timestamp: Date.now(),\n attributes,\n });\n }\n return this;\n }\n\n end(): void {\n if (!this.isRecording) return;\n\n this.endTime = Date.now();\n this.isRecording = false;\n\n if (this.onEnd) {\n this.onEnd(this);\n }\n }\n\n getSpanContext(): SpanContext {\n return {\n traceId: this.traceId,\n spanId: this.spanId,\n traceFlags: this.status === SpanStatus.ERROR ? 1 : 0,\n };\n }\n}\n\n/**\n * No-op span for when tracing is disabled\n */\nclass NoOpSpan implements Span {\n name = '';\n traceId = '';\n spanId = '';\n kind = SpanKind.INTERNAL;\n startTime = 0;\n status = SpanStatus.UNSET;\n attributes: SpanAttributes = {};\n events: SpanEvent[] = [];\n isRecording = false;\n\n setAttribute(): Span {\n return this;\n }\n setAttributes(): Span {\n return this;\n }\n setStatus(): Span {\n return this;\n }\n recordException(): Span {\n return this;\n }\n addEvent(): Span {\n return this;\n }\n end(): void {}\n getSpanContext(): SpanContext {\n return { traceId: '', spanId: '', traceFlags: 0 };\n }\n}\n\n/**\n * Tracer class for creating and managing spans\n */\nexport class Tracer {\n private serviceName: string;\n private activeSpans: Map<string, Span> = new Map();\n private currentSpan: Span | null = null;\n private spanListeners: Array<(span: Span) => void> = [];\n\n constructor(serviceName: string) {\n this.serviceName = serviceName;\n }\n\n /**\n * Check if tracing is enabled\n */\n isEnabled(): boolean {\n return isInstrumentationConfigInitialized() && isFeatureEnabled('tracing');\n }\n\n /**\n * Start a new span\n */\n startSpan(name: string, kind: SpanKind = SpanKind.INTERNAL, parentContext?: SpanContext): Span {\n if (!this.isEnabled()) {\n return new NoOpSpan();\n }\n\n const config = getInstrumentationConfig();\n\n // Check if operation should be ignored\n if (config.tracing.ignoredOperations?.includes(name)) {\n return new NoOpSpan();\n }\n\n // Use current span as parent if no parent provided\n const parent = parentContext || this.currentSpan?.getSpanContext();\n\n const span = new InMemorySpan(name, kind, parent, (completedSpan) => {\n this.onSpanEnd(completedSpan);\n });\n\n // Add service attributes\n span.setAttributes({\n 'service.name': this.serviceName,\n 'service.version': config.tracing.serviceVersion || '1.0.0',\n 'deployment.environment': config.tracing.environment || 'development',\n });\n\n // Add custom resource attributes\n if (config.tracing.resourceAttributes) {\n span.setAttributes(config.tracing.resourceAttributes);\n }\n\n // Track active span\n this.activeSpans.set(span.spanId, span);\n this.currentSpan = span;\n\n return span;\n }\n\n /**\n * Start a span from operation context\n */\n startSpanFromContext(context: OperationContext, kind: SpanKind = SpanKind.INTERNAL): Span {\n const span = this.startSpan(context.operationName, kind);\n\n if (span.isRecording) {\n span.setAttributes({\n 'operation.type': context.operationType,\n ...(context.actorId && { 'actor.id': context.actorId }),\n ...(context.tenantId && { 'tenant.id': context.tenantId }),\n ...(context.workspaceId && { 'workspace.id': context.workspaceId }),\n ...(context.requestId && { 'request.id': context.requestId }),\n ...context.attributes,\n });\n }\n\n return span;\n }\n\n /**\n * Get current active span\n */\n getCurrentSpan(): Span | null {\n return this.currentSpan;\n }\n\n /**\n * Get current trace context for logging\n */\n getTraceContext(): TraceContext {\n if (!this.currentSpan || !this.isEnabled()) {\n return {};\n }\n\n const spanContext = this.currentSpan.getSpanContext();\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n parentSpanId: this.currentSpan.parentSpanId,\n };\n }\n\n /**\n * Set current span (for context propagation)\n */\n setCurrentSpan(span: Span): void {\n this.currentSpan = span;\n }\n\n /**\n * Run a function within a span\n */\n async withSpan<T>(\n name: string,\n fn: (span: Span) => Promise<T>,\n kind: SpanKind = SpanKind.INTERNAL,\n parentContext?: SpanContext\n ): Promise<T> {\n const span = this.startSpan(name, kind, parentContext);\n\n try {\n const result = await fn(span);\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }\n\n /**\n * Run a synchronous function within a span\n */\n withSpanSync<T>(\n name: string,\n fn: (span: Span) => T,\n kind: SpanKind = SpanKind.INTERNAL,\n parentContext?: SpanContext\n ): T {\n const span = this.startSpan(name, kind, parentContext);\n\n try {\n const result = fn(span);\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }\n\n /**\n * Add a listener for completed spans\n */\n addSpanListener(listener: (span: Span) => void): void {\n this.spanListeners.push(listener);\n }\n\n /**\n * Remove a span listener\n */\n removeSpanListener(listener: (span: Span) => void): void {\n const index = this.spanListeners.indexOf(listener);\n if (index !== -1) {\n this.spanListeners.splice(index, 1);\n }\n }\n\n /**\n * Handle span completion\n */\n private onSpanEnd(span: Span): void {\n // Remove from active spans\n this.activeSpans.delete(span.spanId);\n\n // Update current span to parent if this was the current span\n if (this.currentSpan?.spanId === span.spanId) {\n if (span.parentSpanId) {\n this.currentSpan = this.activeSpans.get(span.parentSpanId) || null;\n } else {\n this.currentSpan = null;\n }\n }\n\n // Log span if console exporter enabled\n const config = getInstrumentationConfig();\n if (config.tracing.exporterType === 'console') {\n this.logSpan(span);\n }\n\n // Notify listeners\n for (const listener of this.spanListeners) {\n try {\n listener(span);\n } catch (error) {\n logger.error('[Tracer] Error in span listener:', error);\n }\n }\n }\n\n /**\n * Log span to console (for debugging)\n */\n private logSpan(span: Span): void {\n const duration = span.endTime ? span.endTime - span.startTime : 0;\n\n logger.debug('[Tracer] Span completed', {\n name: span.name,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n kind: SpanKind[span.kind],\n status: SpanStatus[span.status],\n duration: `${duration}ms`,\n attributes: span.attributes,\n eventCount: span.events.length,\n });\n }\n\n /**\n * Get active span count\n */\n getActiveSpanCount(): number {\n return this.activeSpans.size;\n }\n\n /**\n * Clear all active spans (for testing)\n */\n clearActiveSpans(): void {\n this.activeSpans.clear();\n this.currentSpan = null;\n }\n}\n\n/**\n * Global tracer instance\n */\nlet globalTracer: Tracer | null = null;\n\n/**\n * Initialize global tracer\n */\nexport function initializeTracer(serviceName: string): Tracer {\n globalTracer = new Tracer(serviceName);\n return globalTracer;\n}\n\n/**\n * Get global tracer instance\n */\nexport function getTracer(): Tracer {\n if (!globalTracer) {\n // Return a default tracer if not initialized\n globalTracer = new Tracer('unknown-service');\n }\n return globalTracer;\n}\n\n/**\n * Check if tracer is initialized\n */\nexport function isTracerInitialized(): boolean {\n return globalTracer !== null;\n}\n\n/**\n * Convenience function to start a span\n */\nexport function startSpan(name: string, kind: SpanKind = SpanKind.INTERNAL, parentContext?: SpanContext): Span {\n return getTracer().startSpan(name, kind, parentContext);\n}\n\n/**\n * Convenience function to run code within a span\n */\nexport async function withSpan<T>(\n name: string,\n fn: (span: Span) => Promise<T>,\n kind: SpanKind = SpanKind.INTERNAL\n): Promise<T> {\n return getTracer().withSpan(name, fn, kind);\n}\n\n/**\n * Convenience function to get current trace context\n */\nexport function getTraceContext(): TraceContext {\n return getTracer().getTraceContext();\n}\n\n/**\n * Extract trace context from HTTP headers (W3C Trace Context format)\n */\nexport function extractTraceContext(headers: Record<string, string | string[] | undefined>): SpanContext | undefined {\n const traceparent = headers['traceparent'];\n if (!traceparent) return undefined;\n\n const value = Array.isArray(traceparent) ? traceparent[0] : traceparent;\n if (!value) return undefined;\n\n // Parse W3C traceparent: version-trace_id-parent_id-trace_flags\n const parts = value.split('-');\n if (parts.length !== 4) return undefined;\n\n const [, traceId, spanId, traceFlags] = parts;\n if (!traceId || !spanId || traceId.length !== 32 || spanId.length !== 16) {\n return undefined;\n }\n\n return {\n traceId,\n spanId,\n traceFlags: parseInt(traceFlags || '0', 16),\n isRemote: true,\n };\n}\n\n/**\n * Inject trace context into HTTP headers (W3C Trace Context format)\n */\nexport function injectTraceContext(headers: Record<string, string>, spanContext?: SpanContext): void {\n const context = spanContext || getTracer().getCurrentSpan()?.getSpanContext();\n if (!context || !context.traceId || !context.spanId) return;\n\n // Format: version-trace_id-parent_id-trace_flags\n headers['traceparent'] =\n `00-${context.traceId}-${context.spanId}-${context.traceFlags.toString(16).padStart(2, '0')}`;\n}\n","import type { Logger } from '../logger/index.js';\n\nlet activeTelemetryLogger: Logger | undefined;\n\nexport function setActiveTelemetryLogger(logger: Logger): void {\n activeTelemetryLogger = logger;\n}\n\nexport function getActiveTelemetryLogger(): Logger | undefined {\n return activeTelemetryLogger;\n}\n","/**\n * Instrumentation Types\n *\n * Type definitions for OpenTelemetry instrumentation configuration\n * and utilities used across all Burdenoff microservices.\n *\n * @module instrumentation/types\n * @category Observability\n */\n\n/**\n * Instrumentation feature flags for conditional enable/disable\n */\nexport interface InstrumentationFeatureFlags {\n /** Enable distributed tracing with spans */\n tracing: boolean;\n /** Enable metrics collection (counters, histograms, gauges) */\n metrics: boolean;\n /** Enable enhanced logging with trace context */\n logging: boolean;\n /** Enable GraphQL resolver instrumentation */\n graphql: boolean;\n /** Enable database query instrumentation */\n database: boolean;\n /** Enable HTTP request/response instrumentation */\n http: boolean;\n /** Enable cache operation instrumentation */\n cache: boolean;\n /** Enable event queue instrumentation */\n eventQueue: boolean;\n}\n\n/**\n * Tracing configuration\n */\nexport interface TracingConfig {\n /** Enable tracing (default: true when instrumentation enabled) */\n enabled: boolean;\n /** Service name for traces */\n serviceName: string;\n /** Service version */\n serviceVersion?: string;\n /** Environment (development, staging, production) */\n environment?: string;\n /** OTLP exporter endpoint (e.g., http://localhost:4318) */\n exporterEndpoint?: string;\n /** Exporter type: 'otlp' | 'console' | 'none' */\n exporterType?: 'otlp' | 'console' | 'none';\n /** Trace sampling rate (0-1, default: 1.0) */\n samplingRate?: number;\n /** Propagation format: 'w3c' | 'b3' | 'jaeger' */\n propagationFormat?: 'w3c' | 'b3' | 'jaeger';\n /** Additional resource attributes */\n resourceAttributes?: Record<string, string>;\n /** Ignored routes (won't create spans) */\n ignoredRoutes?: string[];\n /** Ignored operations (won't create spans) */\n ignoredOperations?: string[];\n}\n\n/**\n * Metrics configuration\n */\nexport interface MetricsConfig {\n /** Enable metrics (default: true when instrumentation enabled) */\n enabled: boolean;\n /** Service name for metrics */\n serviceName: string;\n /** OTLP exporter endpoint */\n exporterEndpoint?: string;\n /** Exporter type: 'otlp' | 'prometheus' | 'console' | 'none' */\n exporterType?: 'otlp' | 'prometheus' | 'console' | 'none';\n /** Prometheus metrics endpoint (default: /metrics) */\n prometheusEndpoint?: string;\n /** Prometheus metrics port (default: 9090) */\n prometheusPort?: number;\n /** Metrics collection interval in ms (default: 60000) */\n collectInterval?: number;\n /** Enable default runtime metrics (CPU, memory, etc.) */\n defaultMetrics?: boolean;\n /** Custom metric prefix */\n metricPrefix?: string;\n /** Maximum distinct label series per metric before bucketing into overflow (default: 500) */\n maxSeriesPerMetric?: number;\n /** Process-level cap on total distinct metric label series across the registry (default: 5000) */\n maxTotalSeries?: number;\n}\n\n/**\n * Logging configuration for instrumentation\n */\nexport interface LoggingConfig {\n /** Enable trace context in logs */\n enabled: boolean;\n /** Include trace ID in logs */\n includeTraceId?: boolean;\n /** Include span ID in logs */\n includeSpanId?: boolean;\n /** Include trace flags in logs */\n includeTraceFlags?: boolean;\n /** Log level for instrumentation messages */\n level?: 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * GraphQL instrumentation configuration\n */\nexport interface GraphQLInstrumentationConfig {\n /** Enable GraphQL instrumentation */\n enabled: boolean;\n /** Include query/mutation in span attributes */\n includeDocument?: boolean;\n /** Include variables in span attributes (be careful with sensitive data) */\n includeVariables?: boolean;\n /** Include result in span attributes */\n includeResult?: boolean;\n /** Depth to which to serialize document */\n documentDepth?: number;\n /** Operations to ignore */\n ignoredOperations?: string[];\n /** Include resolver-level spans */\n includeResolvers?: boolean;\n /** Max depth for resolver spans */\n resolverSpanDepth?: number;\n /**\n * Explicit allowlist of GraphQL operation names permitted as `operation_name`\n * metric labels. Any operation not in this list is bucketed to `'other'`.\n * When omitted, client-controlled operation names are bucketed to `'named'`\n * (or `'anonymous'`) so untrusted input cannot explode metric cardinality.\n */\n allowedMetricOperationNames?: string[];\n /**\n * Opt in to tracking observed GraphQL operation names dynamically up to\n * {@link maxOperationNameCardinality} when no explicit allowlist is set.\n * Defaults to `false` (fail-closed against cardinality exhaustion).\n */\n includeOperationNameInMetrics?: boolean;\n /** Maximum distinct operation_name labels tracked when dynamic tracking is enabled (default: 100) */\n maxOperationNameCardinality?: number;\n}\n\n/**\n * Database instrumentation configuration\n */\nexport interface DatabaseInstrumentationConfig {\n /** Enable database instrumentation */\n enabled: boolean;\n /** Include SQL query in span attributes */\n includeStatement?: boolean;\n /** Include query parameters (be careful with sensitive data) */\n includeParameters?: boolean;\n /** Include row count in span attributes */\n includeRowCount?: boolean;\n /** Slow query threshold in ms (logs warning if exceeded) */\n slowQueryThreshold?: number;\n /** Operations to ignore */\n ignoredOperations?: string[];\n}\n\n/**\n * HTTP instrumentation configuration\n */\nexport interface HTTPInstrumentationConfig {\n /** Enable HTTP instrumentation */\n enabled: boolean;\n /** Include request headers */\n includeRequestHeaders?: boolean;\n /** Include response headers */\n includeResponseHeaders?: boolean;\n /** Include request body (be careful with sensitive data) */\n includeRequestBody?: boolean;\n /** Include response body */\n includeResponseBody?: boolean;\n /** Headers to redact */\n redactedHeaders?: string[];\n /** Routes to ignore */\n ignoredRoutes?: string[];\n /** Request size threshold for body inclusion */\n maxBodySize?: number;\n}\n\n/**\n * Cache instrumentation configuration\n */\nexport interface CacheInstrumentationConfig {\n /** Enable cache instrumentation */\n enabled: boolean;\n /** Include cache key in span attributes */\n includeKey?: boolean;\n /** Include cache value size */\n includeValueSize?: boolean;\n /** Include TTL in span attributes */\n includeTTL?: boolean;\n}\n\n/**\n * Event queue instrumentation configuration\n */\nexport interface EventQueueInstrumentationConfig {\n /** Enable event queue instrumentation */\n enabled: boolean;\n /** Include message payload (be careful with sensitive data) */\n includePayload?: boolean;\n /** Include message headers */\n includeHeaders?: boolean;\n /** Max payload size to include */\n maxPayloadSize?: number;\n}\n\n/**\n * Complete instrumentation configuration\n */\nexport interface InstrumentationConfig {\n /** Enable all instrumentation (master switch) */\n enabled: boolean;\n /** Feature flags for conditional enable/disable */\n features: InstrumentationFeatureFlags;\n /** Tracing configuration */\n tracing: TracingConfig;\n /** Metrics configuration */\n metrics: MetricsConfig;\n /** Logging configuration */\n logging: LoggingConfig;\n /** GraphQL instrumentation configuration */\n graphql: GraphQLInstrumentationConfig;\n /** Database instrumentation configuration */\n database: DatabaseInstrumentationConfig;\n /** HTTP instrumentation configuration */\n http: HTTPInstrumentationConfig;\n /** Cache instrumentation configuration */\n cache: CacheInstrumentationConfig;\n /** Event queue instrumentation configuration */\n eventQueue: EventQueueInstrumentationConfig;\n}\n\n/**\n * Span attributes for consistent naming\n */\nexport interface SpanAttributes {\n /** Service name */\n 'service.name'?: string;\n /** Service version */\n 'service.version'?: string;\n /** Environment */\n 'deployment.environment'?: string;\n /** Operation name */\n 'operation.name'?: string;\n /** Operation type */\n 'operation.type'?: string;\n /** User ID */\n 'user.id'?: string;\n /** Tenant ID */\n 'tenant.id'?: string;\n /** Workspace ID */\n 'workspace.id'?: string;\n /** Request ID */\n 'request.id'?: string;\n /** Error flag */\n error?: boolean;\n /** Error message */\n 'error.message'?: string;\n /** Error type */\n 'error.type'?: string;\n /** Custom attributes */\n [key: string]: string | number | boolean | undefined;\n}\n\n/**\n * Metric types\n */\nexport type MetricType = 'counter' | 'histogram' | 'gauge' | 'upDownCounter';\n\n/**\n * Metric definition\n */\nexport interface MetricDefinition {\n /** Metric name */\n name: string;\n /** Metric description */\n description: string;\n /** Metric type */\n type: MetricType;\n /** Unit of measurement */\n unit?: string;\n /** Label keys */\n labelKeys?: string[];\n /** Histogram boundaries (for histogram type) */\n boundaries?: number[];\n}\n\n/**\n * Predefined metrics for microservices\n */\nexport const STANDARD_METRICS: Record<string, MetricDefinition> = {\n // HTTP metrics\n HTTP_REQUEST_DURATION: {\n name: 'http_request_duration_ms',\n description: 'HTTP request duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['method', 'route', 'status_code'],\n boundaries: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n },\n HTTP_REQUEST_TOTAL: {\n name: 'http_requests_total',\n description: 'Total number of HTTP requests',\n type: 'counter',\n labelKeys: ['method', 'route', 'status_code'],\n },\n HTTP_REQUEST_SIZE: {\n name: 'http_request_size_bytes',\n description: 'HTTP request size in bytes',\n type: 'histogram',\n unit: 'bytes',\n labelKeys: ['method', 'route'],\n boundaries: [100, 1000, 10000, 100000, 1000000],\n },\n HTTP_RESPONSE_SIZE: {\n name: 'http_response_size_bytes',\n description: 'HTTP response size in bytes',\n type: 'histogram',\n unit: 'bytes',\n labelKeys: ['method', 'route'],\n boundaries: [100, 1000, 10000, 100000, 1000000],\n },\n\n // GraphQL metrics\n GRAPHQL_OPERATION_DURATION: {\n name: 'graphql_operation_duration_ms',\n description: 'GraphQL operation duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation_type', 'operation_name'],\n boundaries: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000],\n },\n GRAPHQL_OPERATION_TOTAL: {\n name: 'graphql_operations_total',\n description: 'Total number of GraphQL operations',\n type: 'counter',\n labelKeys: ['operation_type', 'operation_name', 'status'],\n },\n GRAPHQL_RESOLVER_DURATION: {\n name: 'graphql_resolver_duration_ms',\n description: 'GraphQL resolver duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['type_name', 'field_name'],\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500],\n },\n\n // Database metrics\n DB_QUERY_DURATION: {\n name: 'db_query_duration_ms',\n description: 'Database query duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation', 'model'],\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000],\n },\n DB_QUERY_TOTAL: {\n name: 'db_queries_total',\n description: 'Total number of database queries',\n type: 'counter',\n labelKeys: ['operation', 'model', 'status'],\n },\n DB_CONNECTION_POOL_SIZE: {\n name: 'db_connection_pool_size',\n description: 'Database connection pool size',\n type: 'gauge',\n labelKeys: ['state'],\n },\n\n // Cache metrics\n CACHE_OPERATION_DURATION: {\n name: 'cache_operation_duration_ms',\n description: 'Cache operation duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation'],\n boundaries: [0.1, 0.5, 1, 2, 5, 10, 25, 50],\n },\n CACHE_HIT_TOTAL: {\n name: 'cache_hits_total',\n description: 'Total number of cache hits',\n type: 'counter',\n labelKeys: ['cache_type'],\n },\n CACHE_MISS_TOTAL: {\n name: 'cache_misses_total',\n description: 'Total number of cache misses',\n type: 'counter',\n labelKeys: ['cache_type'],\n },\n\n // Business metrics\n OPERATION_DURATION: {\n name: 'operation_duration_ms',\n description: 'Business operation duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation', 'status'],\n boundaries: [10, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n },\n OPERATION_TOTAL: {\n name: 'operations_total',\n description: 'Total number of business operations',\n type: 'counter',\n labelKeys: ['operation', 'status'],\n },\n ACTIVE_OPERATIONS: {\n name: 'active_operations',\n description: 'Number of currently active operations',\n type: 'upDownCounter',\n labelKeys: ['operation'],\n },\n\n // Resource-cap metrics (BOFF-4809)\n RESOURCE_CAPS_PLAN_RESOLUTION: {\n name: 'resource_caps.plan_resolution_total',\n description: 'Total number of billing plan resolutions for resource caps',\n type: 'counter',\n labelKeys: ['result', 'reason'],\n },\n RESOURCE_CAPS_ENFORCEMENT: {\n name: 'resource_caps.enforcement_total',\n description: 'Total number of resource cap enforcement checks',\n type: 'counter',\n labelKeys: ['resource', 'plan_tier', 'result'],\n },\n RESOURCE_CAPS_CLIENTLESS_FALLBACK: {\n name: 'resource_caps.clientless_fallback_total',\n description: 'Total number of times resource caps fell back because no billing source was configured at bootstrap',\n type: 'counter',\n labelKeys: [],\n },\n};\n\n/**\n * Span context for propagation\n */\nexport interface SpanContext {\n traceId: string;\n spanId: string;\n traceFlags: number;\n isRemote?: boolean;\n}\n\n/**\n * Trace context for logging\n */\nexport interface TraceContext {\n traceId?: string;\n spanId?: string;\n traceFlags?: number;\n parentSpanId?: string;\n}\n\n/**\n * Operation context for instrumentation\n */\nexport interface OperationContext {\n /** Operation name */\n operationName: string;\n /** Operation type (query, mutation, subscription, http, db, cache, etc.) */\n operationType: string;\n /** Actor ID */\n actorId?: string;\n /** Tenant ID */\n tenantId?: string;\n /** Workspace ID */\n workspaceId?: string;\n /** Request ID */\n requestId?: string;\n /** Additional attributes */\n attributes?: Record<string, string | number | boolean>;\n}\n","/**\n * GraphQL Instrumentation Plugin\n *\n * Envelop/GraphQL Yoga plugin for comprehensive GraphQL operation\n * instrumentation including tracing, metrics, and logging.\n *\n * Uses Apollo Federation inline trace plugin for automatic resolver/field-level\n * tracing without manual instrumentation code in microservices.\n *\n * @module instrumentation/graphql-plugin\n * @category Observability\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\nimport { getInstrumentationConfig, isFeatureEnabled, isInstrumentationConfigInitialized } from './config.js';\nimport { createCounter, createHistogram, type MetricLabels } from './metrics-collector.js';\nimport { getTracer, SpanKind, SpanStatus, type Span } from './tracer.js';\nimport { STANDARD_METRICS } from './types.js';\n\n// Create a require function for loading optional CommonJS modules in ESM context\nconst require = createRequire(import.meta.url);\n\n// ============================================================================\n// Prometheus Metrics Plugin\n// ============================================================================\n\n/**\n * Cached reference to the Prometheus plugin.\n * Uses lazy loading to avoid top-level await (CJS compatibility).\n */\nlet prometheusPluginFactory: ((options: unknown) => unknown) | null | undefined = undefined;\nlet prometheusLoadAttempted = false;\n\n/**\n * Lazily load the Prometheus plugin.\n * Returns null if not available.\n */\nfunction loadPrometheusPlugin(): ((options: unknown) => unknown) | null {\n if (prometheusLoadAttempted) {\n return prometheusPluginFactory ?? null;\n }\n\n prometheusLoadAttempted = true;\n\n try {\n // Use require for synchronous loading of optional peer dependency\n const module = require('@graphql-yoga/plugin-prometheus');\n prometheusPluginFactory = module.usePrometheus;\n if (prometheusPluginFactory) {\n logger.info('[Instrumentation] Successfully loaded @graphql-yoga/plugin-prometheus');\n } else {\n logger.warn('[Instrumentation] @graphql-yoga/plugin-prometheus loaded but usePrometheus not found');\n }\n return prometheusPluginFactory ?? null;\n } catch (error) {\n // Plugin not installed\n logger.warn('[Instrumentation] Failed to load @graphql-yoga/plugin-prometheus:', error);\n prometheusPluginFactory = null;\n return null;\n }\n}\n\n/**\n * Options for the Prometheus metrics plugin\n */\nexport interface PrometheusPluginOptions {\n /** Endpoint to expose metrics (default: '/metrics') */\n endpoint?: string | false;\n /** Skip introspection queries from metrics (default: true) */\n skipIntrospection?: boolean;\n /** Enable HTTP duration metrics (default: true) */\n httpDuration?: boolean;\n /** Enable request duration histogram (default: true) */\n requestDuration?: boolean;\n /** Enable request count metrics (default: true) */\n requestCount?: boolean;\n /** Enable error count metrics (default: true) */\n errorCount?: boolean;\n /** Enable resolver-level metrics (default: false - has performance overhead) */\n resolverMetrics?: boolean;\n /** Specific resolvers to instrument (e.g., ['Query.*', 'Mutation.*']) */\n instrumentResolvers?: string[];\n /** Enable deprecated field tracking (default: true) */\n deprecatedFields?: boolean;\n /** Enable parse phase metrics (default: true) */\n parsePhase?: boolean;\n /** Enable validate phase metrics (default: true) */\n validatePhase?: boolean;\n /** Enable context phase metrics (default: true) */\n contextPhase?: boolean;\n /** Enable execute phase metrics (default: true) */\n executePhase?: boolean;\n}\n\n/**\n * Create the Prometheus metrics plugin for automatic GraphQL metrics.\n *\n * This plugin automatically tracks all GraphQL operations and provides\n * Prometheus-compatible metrics for monitoring dashboards.\n *\n * Metrics exposed:\n * - graphql_yoga_http_duration - HTTP request duration\n * - graphql_envelop_request_duration - Operation duration histogram\n * - graphql_envelop_request - Operation counter\n * - graphql_envelop_error_result - Error counter\n * - graphql_envelop_deprecated_field - Deprecated field usage\n * - graphql_envelop_phase_* - Execution phase metrics\n * - graphql_envelop_execute_resolver - Resolver metrics (if enabled)\n *\n * @example\n * ```typescript\n * import { createPrometheusPlugin } from '@burdenoff/be-sdk/instrumentation';\n *\n * const yoga = createYoga({\n * plugins: [\n * createPrometheusPlugin({\n * endpoint: '/metrics',\n * resolverMetrics: false,\n * }),\n * ],\n * });\n * ```\n */\nexport function createPrometheusPlugin(options?: PrometheusPluginOptions): unknown | null {\n // Check if metrics is enabled\n if (isInstrumentationConfigInitialized() && !isFeatureEnabled('metrics')) {\n logger.debug('[Instrumentation] Metrics disabled, skipping Prometheus plugin');\n return null;\n }\n\n // Lazily load the plugin\n const pluginFactory = loadPrometheusPlugin();\n\n // Check if the plugin is available\n if (!pluginFactory) {\n logger.debug('[Instrumentation] @graphql-yoga/plugin-prometheus not installed, metrics not available');\n return null;\n }\n\n const config = {\n // Expose metrics endpoint (set to false to disable, e.g., for push mode)\n endpoint: options?.endpoint ?? '/metrics',\n // Skip introspection queries from metrics\n skipIntrospection: options?.skipIntrospection ?? true,\n // Metrics configuration\n metrics: {\n // HTTP-level metrics\n graphql_yoga_http_duration: options?.httpDuration ?? true,\n // Operation-level metrics\n graphql_envelop_request_duration: options?.requestDuration ?? true,\n graphql_envelop_request_time_summary: options?.requestDuration ?? true,\n graphql_envelop_request: options?.requestCount ?? true,\n graphql_envelop_error_result: options?.errorCount ?? true,\n graphql_envelop_deprecated_field: options?.deprecatedFields ?? true,\n // Execution phase metrics\n graphql_envelop_phase_parse: options?.parsePhase ?? true,\n graphql_envelop_phase_validate: options?.validatePhase ?? true,\n graphql_envelop_phase_context: options?.contextPhase ?? true,\n graphql_envelop_phase_execute: options?.executePhase ?? true,\n graphql_envelop_phase_subscribe: true,\n // Schema change tracking\n graphql_envelop_schema_change: true,\n // Resolver-level metrics (disabled by default due to performance overhead)\n graphql_envelop_execute_resolver: options?.resolverMetrics ?? false,\n },\n // If resolver metrics enabled, optionally filter which resolvers to instrument\n ...(options?.instrumentResolvers && { instrumentResolvers: options.instrumentResolvers }),\n };\n\n logger.debug('[Instrumentation] Using Prometheus metrics plugin', {\n endpoint: config.endpoint,\n resolverMetrics: options?.resolverMetrics ?? false,\n });\n\n return pluginFactory(config);\n}\n\n/**\n * Check if Prometheus plugin is available\n */\nexport function isPrometheusAvailable(): boolean {\n return loadPrometheusPlugin() !== null;\n}\n\n// ============================================================================\n// Apollo Federation Inline Trace Plugin\n// ============================================================================\n\n/**\n * Cached reference to the Apollo inline trace plugin.\n * Uses lazy loading to avoid top-level await (CJS compatibility).\n */\nlet apolloInlineTracePluginFactory: (() => unknown) | null | undefined = undefined;\nlet apolloInlineTraceLoadAttempted = false;\n\n/**\n * Lazily load the Apollo inline trace plugin.\n * Returns null if not available.\n */\nfunction loadApolloInlineTracePlugin(): (() => unknown) | null {\n if (apolloInlineTraceLoadAttempted) {\n return apolloInlineTracePluginFactory ?? null;\n }\n\n apolloInlineTraceLoadAttempted = true;\n\n try {\n // Use require for synchronous loading of optional peer dependency\n const module = require('@graphql-yoga/plugin-apollo-inline-trace');\n apolloInlineTracePluginFactory = module.useApolloInlineTrace;\n return apolloInlineTracePluginFactory ?? null;\n } catch {\n // Plugin not installed\n apolloInlineTracePluginFactory = null;\n return null;\n }\n}\n\n/**\n * Options for the Apollo Federation inline trace plugin\n */\nexport interface ApolloInlineTraceOptions {\n /** Include detailed field-level traces (default: true) */\n includeFieldTraces?: boolean;\n /** Include variable values in traces (default: false for security) */\n includeVariables?: boolean;\n /** Operations to exclude from tracing */\n excludeOperations?: string[];\n}\n\n/**\n * Create the Apollo Federation inline trace plugin for automatic tracing.\n *\n * This plugin automatically instruments all GraphQL operations and resolvers\n * without requiring manual tracing code. It's designed to work with Apollo Federation\n * and the API Gateway for distributed tracing.\n *\n * @example\n * ```typescript\n * import { createApolloInlineTracePlugin } from '@burdenoff/be-sdk/instrumentation';\n *\n * const yoga = createYoga({\n * plugins: [\n * createApolloInlineTracePlugin(),\n * ],\n * });\n * ```\n */\nexport function createApolloInlineTracePlugin(_options?: ApolloInlineTraceOptions): unknown | null {\n // Check if tracing is enabled\n if (isInstrumentationConfigInitialized() && !isFeatureEnabled('tracing')) {\n logger.debug('[Instrumentation] Tracing disabled, skipping Apollo inline trace plugin');\n return null;\n }\n\n // Lazily load the plugin\n const pluginFactory = loadApolloInlineTracePlugin();\n\n // Check if the plugin is available\n if (!pluginFactory) {\n logger.debug('[Instrumentation] @graphql-yoga/plugin-apollo-inline-trace not installed, using fallback tracing');\n return null;\n }\n\n logger.debug('[Instrumentation] Using Apollo Federation inline trace plugin');\n return pluginFactory();\n}\n\n/**\n * Check if Apollo inline tracing is available\n */\nexport function isApolloInlineTraceAvailable(): boolean {\n return loadApolloInlineTracePlugin() !== null;\n}\n\n/**\n * GraphQL operation type\n */\nexport type GraphQLOperationType = 'query' | 'mutation' | 'subscription';\n\n/**\n * GraphQL operation info\n */\nexport interface GraphQLOperationInfo {\n operationType: GraphQLOperationType;\n operationName: string | null;\n document?: string;\n variables?: Record<string, unknown>;\n}\n\n/**\n * Context extension for instrumentation\n */\nexport interface InstrumentationContextExtension {\n _instrumentation?: {\n span?: Span;\n startTime?: number;\n operationInfo?: GraphQLOperationInfo;\n };\n}\n\n/**\n * Create GraphQL metrics\n */\nfunction createGraphQLMetrics(): {\n operationDuration: ReturnType<typeof createHistogram>;\n operationTotal: ReturnType<typeof createCounter>;\n operationErrors: ReturnType<typeof createCounter>;\n resolverDuration: ReturnType<typeof createHistogram>;\n resolverTotal: ReturnType<typeof createCounter>;\n} {\n const def = STANDARD_METRICS;\n\n return {\n operationDuration: createHistogram(\n def['GRAPHQL_OPERATION_DURATION']?.name || 'graphql_operation_duration_ms',\n def['GRAPHQL_OPERATION_DURATION']?.description || 'GraphQL operation duration',\n def['GRAPHQL_OPERATION_DURATION']?.boundaries\n ),\n operationTotal: createCounter(\n def['GRAPHQL_OPERATION_TOTAL']?.name || 'graphql_operations_total',\n def['GRAPHQL_OPERATION_TOTAL']?.description || 'Total GraphQL operations'\n ),\n operationErrors: createCounter('graphql_operation_errors_total', 'Total GraphQL operation errors'),\n resolverDuration: createHistogram(\n def['GRAPHQL_RESOLVER_DURATION']?.name || 'graphql_resolver_duration_ms',\n def['GRAPHQL_RESOLVER_DURATION']?.description || 'GraphQL resolver duration',\n def['GRAPHQL_RESOLVER_DURATION']?.boundaries\n ),\n resolverTotal: createCounter('graphql_resolvers_total', 'Total GraphQL resolver calls'),\n };\n}\n\n// Lazy-initialized metrics\nlet graphqlMetrics: ReturnType<typeof createGraphQLMetrics> | null = null;\n\nfunction getGraphQLMetrics(): ReturnType<typeof createGraphQLMetrics> {\n if (!graphqlMetrics) {\n graphqlMetrics = createGraphQLMetrics();\n }\n return graphqlMetrics;\n}\n\n/** Reset cached GraphQL metric handles (for tests after resetting the metrics registry). */\nexport function resetGraphQLMetricsForTests(): void {\n graphqlMetrics = null;\n}\n\nconst VALID_GRAPHQL_OP_NAME_RE = /^[A-Za-z_]\\w{0,63}$/;\n\nexport interface OperationNameLabelOptions {\n /** Explicit allowlist of permitted `operation_name` metric label values. */\n allowedOperationNames?: readonly string[];\n /**\n * When true and no allowlist is configured, allow up to `maxDynamicNames`\n * distinct observed valid GraphQL identifiers before bucketing to `'other'`.\n * Defaults to `false` (bucket all named operations to `'named'`).\n */\n includeOperationNameInMetrics?: boolean;\n /** Cap on dynamically tracked operation names (default: 100). */\n maxDynamicNames?: number;\n}\n\n/**\n * Bound client-controlled GraphQL operation names before using them as metric\n * labels (BOFF-15984).\n *\n * - Missing/empty -> `'anonymous'`\n * - With an explicit allowlist -> exact name if allowlisted, else `'other'`\n * - Without an allowlist and `includeOperationNameInMetrics !== true` -> `'named'`\n * - With `includeOperationNameInMetrics: true` -> valid GraphQL identifier up to\n * `maxDynamicNames` distinct values in `observedNames`, else `'other'`\n */\nexport function normalizeOperationNameForMetric(\n operationName: string | null | undefined,\n options: OperationNameLabelOptions = {},\n observedNames?: Set<string>\n): string {\n const trimmed = operationName?.trim();\n if (!trimmed) return 'anonymous';\n\n if (options.allowedOperationNames && options.allowedOperationNames.length > 0) {\n return options.allowedOperationNames.includes(trimmed) ? trimmed : 'other';\n }\n\n if (!options.includeOperationNameInMetrics) {\n return 'named';\n }\n\n if (!VALID_GRAPHQL_OP_NAME_RE.test(trimmed)) {\n return 'other';\n }\n\n const cap = Math.max(1, Math.floor(options.maxDynamicNames ?? 100));\n if (observedNames) {\n if (observedNames.has(trimmed)) return trimmed;\n if (observedNames.size >= cap) return 'other';\n observedNames.add(trimmed);\n return trimmed;\n }\n return 'named';\n}\n\n/**\n * Extract operation info from GraphQL execution args\n */\nexport function extractOperationInfo(args: {\n document?: { loc?: { source?: { body?: string } }; definitions?: unknown[] };\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n}): GraphQLOperationInfo {\n let operationType: GraphQLOperationType = 'query';\n let operationName: string | null = args.operationName || null;\n\n // Try to extract operation type from document\n const definitions = args.document?.definitions as\n Array<{ kind?: string; operation?: string; name?: { value?: string } }> | undefined;\n if (definitions && definitions.length > 0) {\n for (const def of definitions) {\n if (def.kind === 'OperationDefinition') {\n operationType = (def.operation as GraphQLOperationType) || 'query';\n if (!operationName && def.name?.value) {\n operationName = def.name.value;\n }\n break;\n }\n }\n }\n\n return {\n operationType,\n operationName,\n document: args.document?.loc?.source?.body,\n variables: args.variableValues,\n };\n}\n\n/**\n * Check if operation should be ignored\n */\nfunction shouldIgnoreOperation(operationName: string | null): boolean {\n if (!isInstrumentationConfigInitialized()) return false;\n\n const config = getInstrumentationConfig();\n const ignoredOps = config.graphql.ignoredOperations || [];\n\n return operationName ? ignoredOps.includes(operationName) : false;\n}\n\n/**\n * GraphQL Yoga plugin for instrumentation\n *\n * @example\n * ```typescript\n * import { createYoga } from 'graphql-yoga';\n * import { createGraphQLInstrumentationPlugin } from '@burdenoff/be-sdk/instrumentation';\n *\n * const yoga = createYoga({\n * plugins: [\n * createGraphQLInstrumentationPlugin(),\n * ],\n * });\n * ```\n */\nexport function createGraphQLInstrumentationPlugin(options?: OperationNameLabelOptions): {\n onExecute: (args: {\n args: {\n document?: unknown;\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n contextValue?: unknown;\n };\n }) =>\n | {\n onExecuteDone: (args: { result: unknown; setResult?: (result: unknown) => void }) => void;\n }\n | undefined;\n onSubscribe?: (args: { args: unknown }) => void;\n} {\n const observedOperationNames = new Set<string>();\n\n return {\n onExecute({\n args,\n }): { onExecuteDone: (args: { result: unknown; setResult?: (result: unknown) => void }) => void } | undefined {\n // Check if GraphQL instrumentation is enabled\n if (!isFeatureEnabled('graphql')) {\n return undefined;\n }\n\n const operationInfo = extractOperationInfo(\n args as {\n document?: { loc?: { source?: { body?: string } }; definitions?: unknown[] };\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n }\n );\n\n // Check if this operation should be ignored\n if (shouldIgnoreOperation(operationInfo.operationName)) {\n return undefined;\n }\n\n const startTime = Date.now();\n const config = getInstrumentationConfig();\n const metrics = getGraphQLMetrics();\n\n // Start span for tracing\n let span: Span | undefined;\n if (isFeatureEnabled('tracing')) {\n const tracer = getTracer();\n const spanName = operationInfo.operationName\n ? `GraphQL ${operationInfo.operationType} ${operationInfo.operationName}`\n : `GraphQL ${operationInfo.operationType}`;\n\n span = tracer.startSpan(spanName, SpanKind.SERVER);\n\n span.setAttributes({\n 'graphql.operation.type': operationInfo.operationType,\n 'graphql.operation.name': operationInfo.operationName || 'anonymous',\n });\n\n // Include document if configured\n if (config.graphql.includeDocument && operationInfo.document) {\n span.setAttribute('graphql.document', operationInfo.document.substring(0, 2000));\n }\n\n // Include variables if configured (be careful with sensitive data)\n if (config.graphql.includeVariables && operationInfo.variables) {\n try {\n span.setAttribute('graphql.variables', JSON.stringify(operationInfo.variables).substring(0, 500));\n } catch {\n // Ignore serialization errors\n }\n }\n }\n\n // Log operation start\n if (isFeatureEnabled('logging')) {\n logger.debug('[GraphQL] Operation started', {\n type: operationInfo.operationType,\n name: operationInfo.operationName || 'anonymous',\n });\n }\n\n // Store instrumentation context\n const context = args.contextValue as InstrumentationContextExtension | undefined;\n if (context) {\n context._instrumentation = {\n span,\n startTime,\n operationInfo,\n };\n }\n\n return {\n onExecuteDone({ result }): void {\n const duration = Date.now() - startTime;\n const hasErrors =\n result &&\n typeof result === 'object' &&\n 'errors' in result &&\n Array.isArray((result as { errors?: unknown[] }).errors) &&\n (result as { errors: unknown[] }).errors.length > 0;\n\n // Record metrics with bounded operation_name cardinality (BOFF-15984)\n if (isFeatureEnabled('metrics')) {\n const metricOperationName = normalizeOperationNameForMetric(\n operationInfo.operationName,\n {\n allowedOperationNames: options?.allowedOperationNames ?? config.graphql.allowedMetricOperationNames,\n includeOperationNameInMetrics:\n options?.includeOperationNameInMetrics ?? config.graphql.includeOperationNameInMetrics,\n maxDynamicNames: options?.maxDynamicNames ?? config.graphql.maxOperationNameCardinality,\n },\n observedOperationNames\n );\n const labels: MetricLabels = {\n operation_type: operationInfo.operationType,\n operation_name: metricOperationName,\n };\n\n metrics.operationDuration.record(duration, labels);\n metrics.operationTotal.inc({ ...labels, status: hasErrors ? 'error' : 'success' });\n\n if (hasErrors) {\n metrics.operationErrors.inc(labels);\n }\n }\n\n // Update span\n if (span) {\n span.setAttribute('graphql.duration_ms', duration);\n\n if (hasErrors) {\n span.setStatus(SpanStatus.ERROR, 'GraphQL operation had errors');\n const errors = (result as { errors?: Array<{ message?: string }> }).errors;\n if (errors && errors.length > 0) {\n span.setAttribute('graphql.error_count', errors.length);\n span.addEvent('graphql.errors', {\n errors: errors.map((e) => e.message || 'Unknown error').join('; '),\n });\n }\n } else {\n span.setStatus(SpanStatus.OK);\n }\n\n // Include result if configured\n if (config.graphql.includeResult) {\n try {\n span.setAttribute('graphql.result', JSON.stringify(result).substring(0, 500));\n } catch {\n // Ignore\n }\n }\n\n span.end();\n }\n\n // Log completion\n if (isFeatureEnabled('logging')) {\n if (hasErrors) {\n logger.warn('[GraphQL] Operation completed with errors', {\n type: operationInfo.operationType,\n name: operationInfo.operationName || 'anonymous',\n duration: `${duration}ms`,\n errorCount: ((result as { errors?: unknown[] }).errors || []).length,\n });\n } else {\n logger.debug('[GraphQL] Operation completed', {\n type: operationInfo.operationType,\n name: operationInfo.operationName || 'anonymous',\n duration: `${duration}ms`,\n });\n }\n }\n },\n };\n },\n };\n}\n\n/**\n * Resolver instrumentation wrapper\n *\n * Use this to wrap individual resolvers for detailed tracing and metrics.\n *\n * @example\n * ```typescript\n * const resolvers = {\n * Query: {\n * getUser: instrumentResolver('Query.getUser', async (parent, args, context) => {\n * // resolver logic\n * }),\n * },\n * };\n * ```\n */\nexport function instrumentResolver<TArgs extends unknown[], TResult>(\n name: string,\n resolver: (...args: TArgs) => Promise<TResult>,\n options?: {\n /** Include resolver arguments in span */\n includeArgs?: boolean;\n /** Include resolver result in span */\n includeResult?: boolean;\n /** Custom span attributes */\n attributes?: Record<string, string | number | boolean>;\n }\n): (...args: TArgs) => Promise<TResult> {\n const [typeName, fieldName] = name.includes('.') ? name.split('.', 2) : ['Unknown', name];\n\n return async (...args: TArgs): Promise<TResult> => {\n // Check if GraphQL instrumentation is enabled\n if (!isFeatureEnabled('graphql')) {\n return resolver(...args);\n }\n\n const config = getInstrumentationConfig();\n\n // Check resolver depth limit\n // (This is a simplified check - in production you'd track nesting level)\n const startTime = Date.now();\n const metrics = getGraphQLMetrics();\n\n // Start span\n let span: Span | undefined;\n if (isFeatureEnabled('tracing') && config.graphql.includeResolvers) {\n const tracer = getTracer();\n span = tracer.startSpan(`Resolver: ${name}`, SpanKind.INTERNAL);\n\n span.setAttributes({\n 'graphql.resolver.type': typeName || 'Unknown',\n 'graphql.resolver.field': fieldName || name,\n ...options?.attributes,\n });\n\n if (options?.includeArgs && args.length > 1) {\n try {\n // args[1] is typically the resolver arguments\n span.setAttribute('graphql.resolver.args', JSON.stringify(args[1]).substring(0, 500));\n } catch {\n // Ignore\n }\n }\n }\n\n try {\n const result = await resolver(...args);\n\n if (span) {\n span.setStatus(SpanStatus.OK);\n if (options?.includeResult) {\n try {\n span.setAttribute('graphql.resolver.result', JSON.stringify(result).substring(0, 500));\n } catch {\n // Ignore\n }\n }\n }\n\n return result;\n } catch (error) {\n if (span && error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n\n if (span) {\n span.end();\n }\n\n // Record metrics\n if (isFeatureEnabled('metrics')) {\n metrics.resolverDuration.record(duration, {\n type_name: typeName || 'Unknown',\n field_name: fieldName || name,\n });\n metrics.resolverTotal.inc({\n type_name: typeName || 'Unknown',\n field_name: fieldName || name,\n });\n }\n }\n };\n}\n\n/**\n * Create instrumented resolvers from a resolver map\n *\n * @example\n * ```typescript\n * const resolvers = instrumentResolverMap({\n * Query: {\n * getUser: async (parent, args, context) => { ... },\n * getUsers: async (parent, args, context) => { ... },\n * },\n * Mutation: {\n * createUser: async (parent, args, context) => { ... },\n * },\n * });\n * ```\n */\nexport function instrumentResolverMap<\n T extends Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>>,\n>(\n resolverMap: T,\n options?: {\n /** Types to include (default: all) */\n includeTypes?: string[];\n /** Types to exclude */\n excludeTypes?: string[];\n /** Fields to exclude (format: \"TypeName.fieldName\") */\n excludeFields?: string[];\n }\n): T {\n const result: Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>> = {};\n\n for (const [typeName, fields] of Object.entries(resolverMap)) {\n // Check if type should be included\n if (options?.excludeTypes?.includes(typeName)) {\n result[typeName] = fields;\n continue;\n }\n if (options?.includeTypes && !options.includeTypes.includes(typeName)) {\n result[typeName] = fields;\n continue;\n }\n\n result[typeName] = {};\n\n for (const [fieldName, resolver] of Object.entries(fields)) {\n const fullName = `${typeName}.${fieldName}`;\n\n // Check if field should be excluded\n if (options?.excludeFields?.includes(fullName)) {\n result[typeName][fieldName] = resolver;\n continue;\n }\n\n // Wrap resolver with instrumentation\n result[typeName][fieldName] = instrumentResolver(fullName, resolver);\n }\n }\n\n return result as T;\n}\n\n/**\n * Get current GraphQL operation info from context\n */\nexport function getGraphQLOperationFromContext(context: unknown): GraphQLOperationInfo | undefined {\n const instrumentedContext = context as InstrumentationContextExtension | undefined;\n return instrumentedContext?._instrumentation?.operationInfo;\n}\n\n/**\n * Get current GraphQL span from context\n */\nexport function getGraphQLSpanFromContext(context: unknown): Span | undefined {\n const instrumentedContext = context as InstrumentationContextExtension | undefined;\n return instrumentedContext?._instrumentation?.span;\n}\n","/**\n * Instrumentation Decorators\n *\n * TypeScript decorators for easy method instrumentation with\n * tracing, metrics, and logging.\n *\n * @module instrumentation/decorators\n * @category Observability\n */\n\nimport { logger } from '../logger/index.js';\nimport { isFeatureEnabled } from './config.js';\nimport { createCounter, createHistogram, type MetricLabels } from './metrics-collector.js';\nimport { getTracer, SpanKind, SpanStatus, type Span } from './tracer.js';\n\n/**\n * Type for span attributes (primitive values only)\n */\nexport type SpanAttributes = Record<string, string | number | boolean>;\n\n/**\n * Options for the @Trace decorator\n */\nexport interface TraceOptions {\n /** Custom span name (default: className.methodName) */\n name?: string;\n /** Span kind */\n kind?: SpanKind;\n /** Additional span attributes */\n attributes?: SpanAttributes;\n /** Include method arguments in span (be careful with sensitive data) */\n includeArgs?: boolean;\n /** Include result in span */\n includeResult?: boolean;\n /** Extract attributes from method arguments */\n extractAttributes?: (args: unknown[]) => SpanAttributes;\n /** Skip tracing for this method */\n skip?: boolean | ((args: unknown[]) => boolean);\n}\n\n/**\n * Options for the @Metric decorator\n */\nexport interface MetricOptions {\n /** Custom metric name (default: operation_duration) */\n name?: string;\n /** Additional labels */\n labels?: MetricLabels | ((args: unknown[], result?: unknown) => MetricLabels);\n /** Record count metric */\n recordCount?: boolean;\n /** Record duration metric */\n recordDuration?: boolean;\n /** Custom histogram boundaries */\n boundaries?: number[];\n}\n\n/**\n * Options for the @Log decorator\n */\nexport interface LogOptions {\n /** Log level */\n level?: 'debug' | 'info' | 'warn' | 'error';\n /** Include method arguments */\n includeArgs?: boolean;\n /** Include result */\n includeResult?: boolean;\n /** Log on entry */\n logEntry?: boolean;\n /** Log on exit */\n logExit?: boolean;\n /** Log on error */\n logError?: boolean;\n /** Custom message */\n message?: string;\n}\n\n/**\n * Combined options for the @Instrument decorator\n */\nexport interface InstrumentOptions {\n /** Operation name */\n operationName?: string;\n /** Operation type */\n operationType?: string;\n /** Tracing options */\n trace?: TraceOptions | boolean;\n /** Metrics options */\n metrics?: MetricOptions | boolean;\n /** Logging options */\n log?: LogOptions | boolean;\n /** Skip instrumentation condition */\n skip?: boolean | ((args: unknown[]) => boolean);\n}\n\n/**\n * @Trace decorator - adds tracing to a method\n *\n * @example\n * ```typescript\n * class UserService {\n * @Trace({ name: 'getUserById', kind: SpanKind.INTERNAL })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Trace(options: TraceOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const spanName = options.name || `${className}.${methodName}`;\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check if tracing is enabled\n if (!isFeatureEnabled('tracing')) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n // Check skip condition\n if (options.skip) {\n const shouldSkip = typeof options.skip === 'function' ? options.skip(args) : options.skip;\n if (shouldSkip) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n }\n\n const tracer = getTracer();\n const span = tracer.startSpan(spanName, options.kind || SpanKind.INTERNAL);\n\n // Add base attributes\n span.setAttributes({\n 'code.function': methodName,\n 'code.namespace': className,\n ...options.attributes,\n });\n\n // Extract custom attributes from arguments\n if (options.extractAttributes) {\n try {\n const extractedAttrs = options.extractAttributes(args);\n span.setAttributes(extractedAttrs);\n } catch {\n // Ignore extraction errors\n }\n }\n\n // Include args if configured\n if (options.includeArgs) {\n try {\n span.setAttribute('method.args', JSON.stringify(args).substring(0, 1000));\n } catch {\n // Ignore serialization errors\n }\n }\n\n try {\n const result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n\n // Include result if configured\n if (options.includeResult) {\n try {\n span.setAttribute('method.result', JSON.stringify(result).substring(0, 1000));\n } catch {\n // Ignore serialization errors\n }\n }\n\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * @Metric decorator - adds metrics to a method\n *\n * @example\n * ```typescript\n * class UserService {\n * @Metric({ name: 'user_fetch', recordCount: true, recordDuration: true })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Metric(options: MetricOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const baseName = options.name || `${className.toLowerCase()}_${methodName.toLowerCase()}`;\n\n // Create metrics (they will be no-ops if metrics are disabled)\n const durationHistogram = createHistogram(\n `${baseName}_duration_ms`,\n `Duration of ${className}.${methodName} in milliseconds`,\n options.boundaries\n );\n const totalCounter = createCounter(`${baseName}_total`, `Total calls to ${className}.${methodName}`);\n const errorCounter = createCounter(`${baseName}_errors_total`, `Total errors in ${className}.${methodName}`);\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check if metrics are enabled\n if (!isFeatureEnabled('metrics')) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n const startTime = Date.now();\n let result: unknown;\n let hasError = false;\n\n try {\n result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n return result;\n } catch (error) {\n hasError = true;\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n\n // Get labels\n let labels: MetricLabels = {};\n if (options.labels) {\n labels = typeof options.labels === 'function' ? options.labels(args, result) : options.labels;\n }\n\n // Record metrics\n if (options.recordDuration !== false) {\n durationHistogram.record(duration, labels);\n }\n\n if (options.recordCount !== false) {\n totalCounter.inc({ ...labels, status: hasError ? 'error' : 'success' });\n }\n\n if (hasError) {\n errorCounter.inc(labels);\n }\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * @Log decorator - adds logging to a method\n *\n * @example\n * ```typescript\n * class UserService {\n * @Log({ level: 'info', logEntry: true, logExit: true })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Log(options: LogOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const level = options.level || 'debug';\n const logEntry = options.logEntry !== false;\n const logExit = options.logExit !== false;\n const logError = options.logError !== false;\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check if logging instrumentation is enabled\n if (!isFeatureEnabled('logging')) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n const baseMessage = options.message || `${className}.${methodName}`;\n\n // Log entry\n if (logEntry) {\n const entryData: Record<string, unknown> = {\n class: className,\n method: methodName,\n };\n if (options.includeArgs) {\n entryData['args'] = args;\n }\n logger[level](`[Enter] ${baseMessage}`, entryData);\n }\n\n const startTime = Date.now();\n\n try {\n const result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n\n // Log exit\n if (logExit) {\n const duration = Date.now() - startTime;\n const exitData: Record<string, unknown> = {\n class: className,\n method: methodName,\n duration: `${duration}ms`,\n };\n if (options.includeResult) {\n exitData['result'] = result;\n }\n logger[level](`[Exit] ${baseMessage}`, exitData);\n }\n\n return result;\n } catch (error) {\n // Log error\n if (logError) {\n const duration = Date.now() - startTime;\n logger.error(`[Error] ${baseMessage}`, {\n class: className,\n method: methodName,\n duration: `${duration}ms`,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n throw error;\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * Helper: Check if instrumentation should be skipped\n */\nfunction shouldSkipInstrumentation(\n skipOption: boolean | ((args: unknown[]) => boolean) | undefined,\n args: unknown[]\n): boolean {\n if (!skipOption) {\n return false;\n }\n return typeof skipOption === 'function' ? skipOption(args) : skipOption;\n}\n\n/**\n * Helper: Start and configure tracing span\n */\nfunction startInstrumentationSpan(\n traceOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n methodName: string,\n className: string,\n args: unknown[]\n): Span | null {\n if (traceOpts === null || !isFeatureEnabled('tracing')) {\n return null;\n }\n\n const tracer = getTracer();\n const span = tracer.startSpan(\n (traceOpts?.['name'] as string | undefined) || operationName,\n (traceOpts?.['kind'] as SpanKind | undefined) || SpanKind.INTERNAL\n );\n\n span.setAttributes({\n 'operation.type': operationType,\n 'code.function': methodName,\n 'code.namespace': className,\n ...(traceOpts?.['attributes'] as SpanAttributes | undefined),\n });\n\n if (traceOpts?.['extractAttributes']) {\n try {\n const extractFn = traceOpts['extractAttributes'] as (args: unknown[]) => SpanAttributes;\n span.setAttributes(extractFn(args));\n } catch {\n // Ignore extraction errors\n }\n }\n\n return span;\n}\n\n/**\n * Helper: Log method entry\n */\nfunction logInstrumentationEntry(\n logOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n args: unknown[]\n): void {\n if (logOpts === null || !isFeatureEnabled('logging')) {\n return;\n }\n\n if (logOpts?.['logEntry'] === false) {\n return;\n }\n\n const level = (logOpts?.['level'] as 'debug' | 'info' | 'warn' | 'error' | undefined) || 'debug';\n logger[level](`[Enter] ${operationName}`, {\n operation: operationName,\n type: operationType,\n ...(logOpts?.['includeArgs'] ? { args } : {}),\n });\n}\n\n/**\n * Helper: Handle successful method execution\n */\nfunction handleInstrumentationSuccess(\n span: Span | null,\n traceOpts: Record<string, unknown> | null,\n result: unknown\n): void {\n if (!span) {\n return;\n }\n\n span.setStatus(SpanStatus.OK);\n\n if (traceOpts?.['includeResult']) {\n try {\n span.setAttribute('result', JSON.stringify(result).substring(0, 500));\n } catch {\n // Ignore serialization errors\n }\n }\n}\n\n/**\n * Helper: Handle method error\n */\nfunction handleInstrumentationError(\n span: Span | null,\n logOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n error: unknown,\n startTime: number\n): void {\n if (span && error instanceof Error) {\n span.recordException(error);\n }\n\n if (logOpts !== null && isFeatureEnabled('logging') && logOpts?.['logError'] !== false) {\n logger.error(`[Error] ${operationName}`, {\n operation: operationName,\n type: operationType,\n error: error instanceof Error ? error.message : String(error),\n duration: `${Date.now() - startTime}ms`,\n });\n }\n}\n\n/**\n * Helper: Record metrics in finally block\n */\nfunction recordInstrumentationMetrics(\n metricOpts: Record<string, unknown> | null,\n durationHistogram: ReturnType<typeof createHistogram> | null,\n totalCounter: ReturnType<typeof createCounter> | null,\n errorCounter: ReturnType<typeof createCounter> | null,\n duration: number,\n args: unknown[],\n result: unknown,\n hasError: boolean\n): void {\n if (metricOpts === null || !isFeatureEnabled('metrics')) {\n return;\n }\n\n const labelsFn = metricOpts?.['labels'] as ((args: unknown[], result?: unknown) => MetricLabels) | undefined;\n const labelsObj = metricOpts?.['labels'] as MetricLabels | undefined;\n const labels = typeof metricOpts?.['labels'] === 'function' ? labelsFn?.(args, result) : labelsObj || {};\n\n if (durationHistogram && metricOpts?.['recordDuration'] !== false) {\n durationHistogram.record(duration, labels);\n }\n\n if (totalCounter && metricOpts?.['recordCount'] !== false) {\n totalCounter.inc({ ...labels, status: hasError ? 'error' : 'success' });\n }\n\n if (errorCounter && hasError) {\n errorCounter.inc(labels);\n }\n}\n\n/**\n * Helper: Log method exit in finally block\n */\nfunction logInstrumentationExit(\n logOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n duration: number,\n result: unknown,\n hasError: boolean\n): void {\n if (logOpts === null || !isFeatureEnabled('logging')) {\n return;\n }\n\n if (logOpts?.['logExit'] === false || hasError) {\n return;\n }\n\n const level = (logOpts?.['level'] as 'debug' | 'info' | 'warn' | 'error' | undefined) || 'debug';\n logger[level](`[Exit] ${operationName}`, {\n operation: operationName,\n type: operationType,\n duration: `${duration}ms`,\n ...(logOpts?.['includeResult'] ? { result } : {}),\n });\n}\n\n/**\n * @Instrument decorator - combines tracing, metrics, and logging\n *\n * @example\n * ```typescript\n * class UserService {\n * @Instrument({\n * operationName: 'getUser',\n * operationType: 'query',\n * trace: true,\n * metrics: true,\n * log: { level: 'debug' }\n * })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Instrument(options: InstrumentOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const operationName = options.operationName || `${className}.${methodName}`;\n const operationType = options.operationType || 'internal';\n\n // Parse options\n let traceOpts: Record<string, unknown> | null;\n if (options.trace === true) {\n traceOpts = {};\n } else if (options.trace === false || options.trace === undefined) {\n traceOpts = null;\n } else {\n traceOpts = options.trace as Record<string, unknown>;\n }\n\n let metricOpts: Record<string, unknown> | null;\n if (options.metrics === true) {\n metricOpts = {};\n } else if (options.metrics === false || options.metrics === undefined) {\n metricOpts = null;\n } else {\n metricOpts = options.metrics as Record<string, unknown>;\n }\n\n let logOpts: Record<string, unknown> | null;\n if (options.log === true) {\n logOpts = {};\n } else if (options.log === false || options.log === undefined) {\n logOpts = null;\n } else {\n logOpts = options.log as Record<string, unknown>;\n }\n\n // Create metrics if enabled\n let durationHistogram: ReturnType<typeof createHistogram> | null = null;\n let totalCounter: ReturnType<typeof createCounter> | null = null;\n let errorCounter: ReturnType<typeof createCounter> | null = null;\n\n if (metricOpts !== null) {\n const baseName =\n (metricOpts?.['name'] as string | undefined) || `${className.toLowerCase()}_${methodName.toLowerCase()}`;\n durationHistogram = createHistogram(`${baseName}_duration_ms`, `Duration of ${operationName} in ms`);\n totalCounter = createCounter(`${baseName}_total`, `Total calls to ${operationName}`);\n errorCounter = createCounter(`${baseName}_errors_total`, `Total errors in ${operationName}`);\n }\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check skip condition\n if (shouldSkipInstrumentation(options.skip, args)) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n const startTime = Date.now();\n let hasError = false;\n let result: unknown;\n\n // Start span and log entry\n const span = startInstrumentationSpan(traceOpts, operationName, operationType, methodName, className, args);\n logInstrumentationEntry(logOpts, operationName, operationType, args);\n\n try {\n result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n handleInstrumentationSuccess(span, traceOpts, result);\n return result;\n } catch (error) {\n hasError = true;\n handleInstrumentationError(span, logOpts, operationName, operationType, error, startTime);\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n\n if (span) {\n span.end();\n }\n\n recordInstrumentationMetrics(\n metricOpts,\n durationHistogram,\n totalCounter,\n errorCounter,\n duration,\n args,\n result,\n hasError\n );\n\n logInstrumentationExit(logOpts, operationName, operationType, duration, result, hasError);\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * Helper function to create a traced function without decorators\n */\nexport function traced<T extends (...args: unknown[]) => Promise<unknown>>(\n name: string,\n fn: T,\n options?: TraceOptions\n): T {\n return (async (...args: unknown[]) => {\n if (!isFeatureEnabled('tracing')) {\n return fn(...args);\n }\n\n const tracer = getTracer();\n const span = tracer.startSpan(name, options?.kind || SpanKind.INTERNAL);\n\n if (options?.attributes) {\n span.setAttributes(options.attributes);\n }\n\n try {\n const result = await fn(...args);\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }) as T;\n}\n\n/**\n * Helper function to create an instrumented function without decorators\n */\nexport function instrumented<T extends (...args: unknown[]) => Promise<unknown>>(\n name: string,\n fn: T,\n options?: InstrumentOptions\n): T {\n const operationType = options?.operationType || 'internal';\n\n // Create metrics\n const durationHistogram =\n options?.metrics !== false\n ? createHistogram(`${name.toLowerCase()}_duration_ms`, `Duration of ${name} in ms`)\n : null;\n const totalCounter =\n options?.metrics !== false ? createCounter(`${name.toLowerCase()}_total`, `Total calls to ${name}`) : null;\n\n return (async (...args: unknown[]) => {\n const startTime = Date.now();\n let span: Span | null = null;\n let hasError = false;\n\n // Start span\n if (options?.trace !== false && isFeatureEnabled('tracing')) {\n span = getTracer().startSpan(name, SpanKind.INTERNAL);\n span.setAttribute('operation.type', operationType);\n }\n\n // Log entry\n if (options?.log !== false && isFeatureEnabled('logging')) {\n logger.debug(`[Enter] ${name}`, { operation: name, type: operationType });\n }\n\n try {\n const result = await fn(...args);\n if (span) span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n hasError = true;\n if (span && error instanceof Error) span.recordException(error);\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n if (span) span.end();\n\n // Record metrics\n if (durationHistogram && isFeatureEnabled('metrics')) {\n durationHistogram.record(duration, { status: hasError ? 'error' : 'success' });\n }\n if (totalCounter && isFeatureEnabled('metrics')) {\n totalCounter.inc({ status: hasError ? 'error' : 'success' });\n }\n\n // Log exit/error\n if (options?.log !== false && isFeatureEnabled('logging')) {\n if (hasError) {\n logger.error(`[Error] ${name}`, { operation: name, duration: `${duration}ms` });\n } else {\n logger.debug(`[Exit] ${name}`, { operation: name, duration: `${duration}ms` });\n }\n }\n }\n }) as T;\n}\n","/**\n * Instrumentation Module\n *\n * Comprehensive OpenTelemetry instrumentation utilities for\n * Burdenoff microservices including tracing, metrics, and logging.\n *\n * @module instrumentation\n * @category Observability\n *\n * @example\n * ```typescript\n * import {\n * initializeInstrumentation,\n * getTracer,\n * createCounter,\n * createGraphQLInstrumentationPlugin,\n * Trace,\n * Instrument,\n * } from '@burdenoff/be-sdk/instrumentation';\n *\n * // Initialize instrumentation\n * const { tracer, metrics } = initializeInstrumentation('my-service');\n *\n * // Create a span\n * await tracer.withSpan('operation', async (span) => {\n * span.setAttribute('key', 'value');\n * // ... operation logic\n * });\n *\n * // Use decorators\n * class MyService {\n * @Trace()\n * async myMethod() { ... }\n *\n * @Instrument({ tracing: true, metrics: true, logging: true })\n * async trackedMethod() { ... }\n * }\n * ```\n */\n\n// Internal imports for initialization functions\nimport {\n getInstrumentationConfig as getConfig,\n initializeInstrumentationConfig as initConfig,\n isInstrumentationConfigInitialized as isConfigInit,\n resetInstrumentationConfig as resetConfig,\n} from './config.js';\nimport {\n getMetricsRegistry as getMetricsFn,\n initializeMetricsRegistry as initMetrics,\n isMetricsRegistryInitialized as isMetricsInit,\n resetMetricsRegistry as resetMetrics,\n} from './metrics-collector.js';\nimport {\n getTracer as getTracerFn,\n initializeTracer as initTracer,\n isTracerInitialized as isTracerInit,\n} from './tracer.js';\nimport { logger as defaultLogger, type Logger } from '../logger/index.js';\nimport { getActiveTelemetryLogger } from '../telemetry/logger-state.js';\n\n// ============================================================================\n// Simplified Setup API\n// ============================================================================\n\nimport {\n createApolloInlineTracePlugin,\n createPrometheusPlugin,\n type PrometheusPluginOptions,\n} from './graphql-plugin.js';\n\n// Configuration exports\nexport {\n buildDatabaseConfig,\n buildFeatureFlags,\n buildGraphQLConfig,\n buildInstrumentationConfig,\n buildMetricsConfig,\n buildTracingConfig,\n DEFAULT_CACHE_CONFIG,\n DEFAULT_DATABASE_CONFIG,\n DEFAULT_EVENT_QUEUE_CONFIG,\n DEFAULT_FEATURE_FLAGS,\n DEFAULT_GRAPHQL_CONFIG,\n DEFAULT_HTTP_CONFIG,\n DEFAULT_LOGGING_CONFIG,\n DEFAULT_METRICS_CONFIG,\n DEFAULT_TRACING_CONFIG,\n ENV_VARS,\n getInstrumentationConfig,\n initializeInstrumentationConfig,\n isFeatureEnabled,\n isInstrumentationConfigInitialized,\n resetInstrumentationConfig,\n updateInstrumentationConfig,\n} from './config.js';\n\n// Tracer exports\nexport {\n extractTraceContext,\n getTraceContext,\n getTracer,\n initializeTracer,\n injectTraceContext,\n isTracerInitialized,\n type Span,\n type SpanEvent,\n SpanKind,\n SpanStatus,\n startSpan,\n Tracer,\n withSpan,\n} from './tracer.js';\n\n// Metrics exports\nexport {\n type Counter,\n createCounter,\n createGauge,\n createHistogram,\n createUpDownCounter,\n DEFAULT_MAX_SERIES_PER_METRIC,\n DEFAULT_MAX_TOTAL_SERIES,\n type Gauge,\n getMetricsRegistry,\n type Histogram,\n initializeMetricsRegistry,\n isMetricsRegistryInitialized,\n type MetricLabels,\n MetricsRegistry,\n type MetricsRegistryOptions,\n OVERFLOW_LABEL_KEY,\n resetMetricsRegistry,\n type UpDownCounter,\n} from './metrics-collector.js';\n\n// Decorator exports\nexport { Instrument, instrumented, Log, Metric, Trace, traced } from './decorators.js';\n\n// GraphQL plugin exports\nexport {\n type ApolloInlineTraceOptions,\n createApolloInlineTracePlugin,\n createGraphQLInstrumentationPlugin,\n createPrometheusPlugin,\n extractOperationInfo,\n getGraphQLOperationFromContext,\n getGraphQLSpanFromContext,\n type GraphQLOperationInfo,\n type GraphQLOperationType,\n instrumentResolver,\n instrumentResolverMap,\n type InstrumentationContextExtension,\n isApolloInlineTraceAvailable,\n isPrometheusAvailable,\n normalizeOperationNameForMetric,\n type OperationNameLabelOptions,\n type PrometheusPluginOptions,\n} from './graphql-plugin.js';\n\n// Type exports\nexport type {\n CacheInstrumentationConfig,\n DatabaseInstrumentationConfig,\n EventQueueInstrumentationConfig,\n GraphQLInstrumentationConfig,\n HTTPInstrumentationConfig,\n InstrumentationConfig,\n InstrumentationFeatureFlags,\n LoggingConfig,\n MetricDefinition,\n MetricsConfig,\n OperationContext,\n SpanAttributes,\n SpanContext,\n TraceContext,\n TracingConfig,\n} from './types.js';\n\nexport { STANDARD_METRICS } from './types.js';\n\n// Re-export logger for convenience\nexport { logger } from '../logger/index.js';\n\nexport function getLogger(): Logger {\n return getActiveTelemetryLogger() ?? defaultLogger;\n}\n\n/**\n * Options for initializing instrumentation\n */\nexport interface InitializeInstrumentationOptions {\n features?: Partial<import('./types.js').InstrumentationFeatureFlags>;\n tracing?: Partial<import('./types.js').TracingConfig>;\n metrics?: Partial<import('./types.js').MetricsConfig>;\n logging?: Partial<import('./types.js').LoggingConfig>;\n graphql?: Partial<import('./types.js').GraphQLInstrumentationConfig>;\n database?: Partial<import('./types.js').DatabaseInstrumentationConfig>;\n http?: Partial<import('./types.js').HTTPInstrumentationConfig>;\n cache?: Partial<import('./types.js').CacheInstrumentationConfig>;\n eventQueue?: Partial<import('./types.js').EventQueueInstrumentationConfig>;\n}\n\n/**\n * Initialize all instrumentation components\n *\n * This is a convenience function that initializes the tracer, metrics registry,\n * and instrumentation configuration in one call.\n *\n * @param serviceName - Name of the service for tracing and metrics\n * @param options - Optional configuration overrides\n * @returns Initialized instrumentation components\n *\n * @example\n * ```typescript\n * const { tracer, metrics, config } = initializeInstrumentation('my-service', {\n * features: { tracing: true, metrics: true, logging: true },\n * tracing: { samplingRate: 0.5 },\n * });\n * ```\n */\nexport function initializeInstrumentation(\n serviceName: string,\n options?: InitializeInstrumentationOptions\n): {\n tracer: import('./tracer.js').Tracer;\n metrics: import('./metrics-collector.js').MetricsRegistry;\n config: import('./types.js').InstrumentationConfig;\n} {\n // Initialize configuration - cast options to the expected type\n // The buildInstrumentationConfig function handles merging with defaults\n initConfig(serviceName, options as unknown as Partial<import('./types.js').InstrumentationConfig>);\n\n // Initialize tracer\n initTracer(serviceName);\n\n // Initialize metrics registry with configured cardinality bounds\n initMetrics(serviceName, options?.metrics?.metricPrefix ?? '', {\n maxSeriesPerMetric: options?.metrics?.maxSeriesPerMetric,\n maxTotalSeries: options?.metrics?.maxTotalSeries,\n });\n\n return {\n tracer: getTracerFn(),\n metrics: getMetricsFn(),\n config: getConfig(),\n };\n}\n\n/**\n * Check if instrumentation is fully initialized\n */\nexport function isInstrumentationInitialized(): boolean {\n return isConfigInit() && isTracerInit() && isMetricsInit();\n}\n\n/**\n * Reset all instrumentation state (useful for testing)\n */\nexport function resetInstrumentation(): void {\n resetConfig();\n resetMetrics();\n}\n\n/**\n * Options for simplified instrumentation setup\n */\nexport interface SetupInstrumentationOptions extends InitializeInstrumentationOptions {\n /**\n * Use Apollo Federation inline tracing for automatic resolver/field-level tracing.\n * This is the recommended approach for microservices in a federated architecture.\n * @default true\n */\n useApolloInlineTrace?: boolean;\n\n /**\n * Use Prometheus metrics plugin for automatic GraphQL operation metrics.\n * This provides comprehensive metrics including:\n * - HTTP request duration\n * - GraphQL operation duration\n * - Error counts\n * - Execution phase metrics\n * - Optional resolver-level metrics\n * @default true\n */\n usePrometheus?: boolean;\n\n /**\n * Prometheus plugin configuration options.\n * Only used if usePrometheus is true.\n */\n prometheus?: PrometheusPluginOptions;\n}\n\n/**\n * Result of instrumentation setup\n */\nexport interface InstrumentationSetupResult {\n /** Initialized tracer instance */\n tracer: import('./tracer.js').Tracer;\n /** Initialized metrics registry */\n metrics: import('./metrics-collector.js').MetricsRegistry;\n /** Full instrumentation configuration */\n config: import('./types.js').InstrumentationConfig;\n /**\n * GraphQL Yoga plugins to add to your server.\n * These provide automatic tracing and metrics without manual instrumentation.\n */\n plugins: unknown[];\n}\n\n/**\n * Set up complete instrumentation for a microservice with minimal configuration.\n *\n * This is the recommended way to set up instrumentation in Burdenoff microservices.\n * It automatically configures:\n * - OpenTelemetry tracing with Apollo Federation inline traces\n * - Metrics collection\n * - GraphQL operation logging\n *\n * All you need to do is pass the returned plugins to your GraphQL Yoga server.\n *\n * @param serviceName - Name of your service (e.g., 'module-tags')\n * @param options - Optional overrides for defaults\n * @returns Instrumentation components and GraphQL plugins\n *\n * @example\n * ```typescript\n * import { setupInstrumentation } from '@burdenoff/be-sdk/instrumentation';\n * import { createYoga } from 'graphql-yoga';\n *\n * // Simple setup with all defaults\n * const { plugins, tracer, metrics } = setupInstrumentation('module-tags');\n *\n * // Create Yoga server with automatic tracing\n * const yoga = createYoga({\n * schema,\n * plugins: [...plugins, ...otherPlugins],\n * });\n *\n * // With custom overrides\n * const { plugins } = setupInstrumentation('module-tags', {\n * tracing: { samplingRate: 0.5 },\n * metrics: { metricPrefix: 'tags' },\n * });\n * ```\n */\nexport function setupInstrumentation(\n serviceName: string,\n options?: SetupInstrumentationOptions\n): InstrumentationSetupResult {\n // Initialize core instrumentation\n const { tracer, metrics, config } = initializeInstrumentation(serviceName, options);\n\n // Build plugin list\n const plugins: unknown[] = [];\n\n // Add Apollo inline trace plugin for automatic resolver/field-level tracing\n // This provides distributed tracing across federated services\n const useApollo = options?.useApolloInlineTrace ?? true;\n if (useApollo) {\n const apolloPlugin = createApolloInlineTracePlugin();\n if (apolloPlugin) {\n plugins.push(apolloPlugin);\n }\n }\n\n // Add Prometheus metrics plugin for automatic GraphQL metrics\n // This provides comprehensive metrics without manual instrumentation\n const usePrometheus = options?.usePrometheus ?? true;\n if (usePrometheus) {\n const prometheusPlugin = createPrometheusPlugin(options?.prometheus);\n if (prometheusPlugin) {\n plugins.push(prometheusPlugin);\n }\n }\n\n return {\n tracer,\n metrics,\n config,\n plugins,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,IAAY,aAAL;CACL;CACA;CACA;;AACF;;;;AAKA,IAAY,WAAL;CACL;CACA;CACA;CACA;CACA;;AACF;;;;AAyDA,SAAS,kBAA0B;CACjC,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,OAAO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