{"version":3,"sources":["../../src/tracing/instrumentation-api.ts"],"sourcesContent":["/**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  Span as ApiSpan,\n  Link,\n  SpanAttributes,\n  SpanAttributeValue,\n} from '@opentelemetry/api';\nimport type { SpanMetadata } from './types.mjs';\n\n/**\n * The genkit attribute namespace, e.g. `genkit:name`, `genkit:path`.\n * @hidden\n */\nexport const ATTR_PREFIX = 'genkit';\n/** @hidden */\nexport const SPAN_TYPE_ATTR = ATTR_PREFIX + ':type';\n/** @hidden */\nexport const TRACER_NAME = 'genkit-tracer';\n/** @hidden */\nexport const TRACER_VERSION = 'v1';\n\n/** ALS key under which the dispatcher stores the current span context. */\nexport const spanMetadataAlsKey = 'core.tracing.instrumentation.span';\n\n/**\n * A backend-independent view of the span handed to the wrapped function.\n *\n * `traceId` / `spanId` are the composite-resolved ids (first non-empty across\n * the active instrumentation chain); both are '' when nothing is instrumented.\n *\n * `setMetadata` receives custom attribute writes made on the span handed to the\n * `runInNewSpan` callback (`span.setAttribute(s)`).\n *\n * @hidden\n */\nexport interface GenkitSpanContext {\n  readonly traceId: string;\n  readonly spanId: string;\n  setMetadata(values: Record<string, unknown>): void;\n}\n\n/**\n * Everything an {@link Instrumentation} provider needs to open a span. The\n * dispatcher owns Genkit semantics (path, isRoot, custom metadata); providers\n * only encode this into their backend.\n *\n * @hidden\n */\nexport interface InstrumentationSpanInfo {\n  metadata: SpanMetadata;\n  labels?: Record<string, string>;\n  links?: Link[];\n}\n\n/**\n * Continuation passed to a provider's `runInNewSpan`. Providers must call it\n * exactly once and return its result.\n *\n * @hidden\n */\nexport type InstrumentationNext<T> = (\n  span: ApiSpan,\n  ctx: GenkitSpanContext\n) => Promise<T>;\n\n/**\n * A pluggable telemetry instrumentation provider. Middleware over span\n * creation: implementations open a backend span, call `next`, and finalize.\n *\n * @hidden\n */\nexport interface Instrumentation {\n  runInNewSpan<T>(\n    info: InstrumentationSpanInfo,\n    next: InstrumentationNext<T>\n  ): Promise<T>;\n}\n\n/**\n * A correlation-free log record. Each provider attaches trace/span correlation\n * from its own context source (OTel active context vs Genkit ALS).\n *\n * @hidden\n */\nexport interface GenkitLogRecord {\n  severity: 'debug' | 'info' | 'warn' | 'error';\n  body: unknown;\n  attributes?: Record<string, unknown>;\n}\n\n/**\n * Optional capability: a provider that also records logs (mirrors span\n * recording). `logging.ts` fans out to providers implementing this.\n *\n * @hidden\n */\nexport interface LogRecordingInstrumentation {\n  recordLog(record: GenkitLogRecord): void;\n}\n\n/** @hidden */\nexport function hasRecordLog(\n  p: Instrumentation\n): p is Instrumentation & LogRecordingInstrumentation {\n  return (\n    typeof (p as Partial<LogRecordingInstrumentation>).recordLog === 'function'\n  );\n}\n\n/** An OTel id made entirely of zeros is the no-op / unknown id. */\nexport function isValidId(id: string | undefined): id is string {\n  return !!id && !/^0+$/.test(id);\n}\n\n/** First valid (non-empty, non-zero) id across the chain, or ''. */\nexport function firstNonEmpty(ids: (string | undefined)[]): string {\n  for (const id of ids) {\n    if (isValidId(id)) return id;\n  }\n  return '';\n}\n\n/**\n * Maps SpanMetadata to the flat `genkit:*` attribute set persisted on a span.\n * Shared by all providers so encodings stay identical.\n *\n * @hidden\n */\nexport function metadataToAttributes(\n  metadata: SpanMetadata\n): Record<string, string> {\n  const out = {} as Record<string, string>;\n  Object.keys(metadata).forEach((key) => {\n    if (\n      key === 'metadata' &&\n      typeof metadata[key] === 'object' &&\n      metadata.metadata\n    ) {\n      Object.entries(metadata.metadata).forEach(([metaKey, value]) => {\n        out[ATTR_PREFIX + ':metadata:' + metaKey] = value;\n      });\n    } else if (\n      key === 'input' ||\n      key === 'init' ||\n      typeof metadata[key] === 'object'\n    ) {\n      out[ATTR_PREFIX + ':' + key] = JSON.stringify(metadata[key]);\n    } else {\n      out[ATTR_PREFIX + ':' + key] = metadata[key];\n    }\n  });\n  return out;\n}\n\n/**\n * Normalizes custom attribute writes (`GenkitSpanContext.setMetadata`) into\n * valid OTel attribute values. Primitives and homogeneous primitive arrays pass\n * through as-is, matching what `span.setAttribute` would record; anything else\n * is JSON-encoded. undefined/null are dropped.\n *\n * @hidden\n */\nexport function toSpanAttributes(\n  values: Record<string, unknown>\n): SpanAttributes {\n  const attrs: SpanAttributes = {};\n  for (const [k, v] of Object.entries(values)) {\n    if (v === undefined || v === null) continue;\n    attrs[k] = isAttributeValue(v) ? v : JSON.stringify(v);\n  }\n  return attrs;\n}\n\nfunction isPrimitiveAttribute(v: unknown): v is string | number | boolean {\n  return (\n    typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'\n  );\n}\n\nfunction isAttributeValue(v: unknown): v is SpanAttributeValue {\n  if (isPrimitiveAttribute(v)) return true;\n  if (!Array.isArray(v)) return false;\n  const present = v.filter((x) => x !== null && x !== undefined);\n  return (\n    present.every(isPrimitiveAttribute) &&\n    new Set(present.map((x) => typeof x)).size <= 1\n  );\n}\n\n/** @hidden */\nexport function getErrorMessage(e: any): string {\n  if (e instanceof Error) {\n    return e.message;\n  }\n  return `${e}`;\n}\n\nconst rootSpanDetectionKey = '__genkit_disableRootSpanDetection';\n\n/** @hidden */\nexport function isDisableRootSpanDetection(): boolean {\n  return global[rootSpanDetectionKey] === true;\n}\n\n/**\n * Disables Genkit's custom root span detection and leaves default Otel root span.\n *\n * This function attempts to control Genkit's internal OTel instrumentation behaviour,\n * since internal implementation details are subject to change at any time consider\n * this function \"unstable\" and subject to breaking changes as well.\n *\n * @hidden\n */\nexport function disableOTelRootSpanDetection() {\n  global[rootSpanDetectionKey] = true;\n}\n"],"mappings":"AA4BO,MAAM,cAAc;AAEpB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