{"version":3,"sources":["../../src/tracing/direct-instrumentation.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 {\n  SpanStatusCode,\n  trace,\n  TraceFlags,\n  type Span as ApiSpan,\n  type SpanAttributes,\n} from '@opentelemetry/api';\nimport { randomBytes } from 'node:crypto';\nimport { performance } from 'node:perf_hooks';\nimport { getAsyncContext } from '../async-context.mjs';\nimport { logger } from '../logging.mjs';\nimport { postToTelemetryServer } from './exporter.mjs';\nimport {\n  getErrorMessage,\n  isDisableRootSpanDetection,\n  metadataToAttributes,\n  toSpanAttributes,\n  type GenkitLogRecord,\n  type GenkitSpanContext,\n  type Instrumentation,\n  type InstrumentationNext,\n  type InstrumentationSpanInfo,\n  type LogRecordingInstrumentation,\n} from './instrumentation-api.mjs';\nimport type { SpanData, TraceData } from './types.mjs';\n\nconst directAlsKey = 'core.tracing.direct.span';\nconst INSTRUMENTATION_LIBRARY = { name: 'genkit-tracer', version: 'v1' };\n\ninterface DirectParent {\n  traceId: string;\n  spanId: string;\n}\n\n/**\n * A self-contained instrumentation that feeds the Developer UI directly, with\n * no OpenTelemetry SDK. It mints its own ids, tracks parentage via Genkit's\n * async context, builds the same `SpanData`/`TraceData` shape the OTel-backed\n * `TraceServerExporter` produced, and POSTs to `${server}/api/traces`.\n *\n * Auto-prepended in dev when a telemetry server is configured.\n *\n * @hidden\n */\nexport class DirectTelemetryInstrumentation\n  implements Instrumentation, LogRecordingInstrumentation\n{\n  async runInNewSpan<T>(\n    info: InstrumentationSpanInfo,\n    next: InstrumentationNext<T>\n  ): Promise<T> {\n    // An explicit root starts a new trace even under an active parent, matching\n    // OTelInstrumentation (`spanOptions.root`).\n    const isRoot = info.metadata.isRoot && !isDisableRootSpanDetection();\n    const parent = isRoot\n      ? undefined\n      : getAsyncContext().getStore<DirectParent>(directAlsKey);\n    const traceId = parent?.traceId ?? genId(16);\n    const spanId = genId(8);\n    const startTime = Date.now();\n    const startPerf = performance.now();\n\n    // Custom attributes written via the callback span; picked up by every\n    // subsequent export of this span.\n    const customAttributes: SpanAttributes = {};\n\n    // Ids surfaced to the composite and to log correlation.\n    const spanCtx: GenkitSpanContext = {\n      traceId,\n      spanId,\n      setMetadata(values) {\n        Object.assign(customAttributes, toSpanAttributes(values));\n      },\n    };\n    // Non-recording OTel span carrying our ids, for providers/callbacks that\n    // read `.spanContext()`. Never booted through the SDK.\n    const otSpan: ApiSpan = trace.wrapSpanContext({\n      traceId,\n      spanId,\n      traceFlags: TraceFlags.SAMPLED,\n    });\n\n    const exceptions: Array<Record<string, string>> = [];\n    let status: { code: number; message?: string } = {\n      code: SpanStatusCode.UNSET,\n    };\n\n    const exportSpan = (final: boolean) => {\n      // In-progress spans report endTime 0. This matches the old OTel realtime\n      // path (an open span's endTime is [0,0], and hrTimeToMilliseconds([0,0])\n      // is 0). The telemetry server and Dev UI treat a falsy endTime as \"still\n      // running\"; a real endTime here would render the span as already complete\n      // and suppress the pending state.\n      const endTime = final ? startTime + (performance.now() - startPerf) : 0;\n      const spanData = buildSpanData({\n        info,\n        customAttributes,\n        traceId,\n        spanId,\n        parentSpanId: parent?.spanId,\n        startTime,\n        endTime,\n        status,\n        exceptions,\n      });\n      const traceData: TraceData = {\n        traceId,\n        spans: { [spanId]: spanData },\n      };\n      if (!spanData.parentSpanId) {\n        traceData.displayName = spanData.displayName;\n        traceData.startTime = spanData.startTime;\n        // Leave the trace endTime unset until the root span finishes.\n        if (final) {\n          traceData.endTime = spanData.endTime;\n        }\n      }\n      // Fire-and-forget; telemetry must never block or fail the operation.\n      postToTelemetryServer('/api/traces', traceData).catch((e) =>\n        logger.debug(`Failed to save trace ${traceId}`, e)\n      );\n    };\n\n    // Real-time updates: export the in-progress span on start too, so the Dev\n    // UI can show running traces. Gated on GENKIT_ENABLE_REALTIME_TELEMETRY;\n    // the on-end export below is unconditional.\n    if (process.env.GENKIT_ENABLE_REALTIME_TELEMETRY === 'true') {\n      exportSpan(false);\n    }\n\n    try {\n      const output = await getAsyncContext().run(\n        directAlsKey,\n        { traceId, spanId } as DirectParent,\n        () => next(otSpan, spanCtx)\n      );\n      exportSpan(true);\n      return output;\n    } catch (e) {\n      status = { code: SpanStatusCode.ERROR, message: getErrorMessage(e) };\n      if (e instanceof Error) {\n        const exception = toExceptionAttributes(e);\n        if (exception) exceptions.push(exception);\n      }\n      exportSpan(true);\n      throw e;\n    }\n  }\n\n  /**\n   * Correlates via Genkit async context (the span the Dev UI actually shows),\n   * lowers to the OTLP-log shape, and POSTs to `${server}/api/otlp`.\n   */\n  recordLog(record: GenkitLogRecord): void {\n    const parent = getAsyncContext().getStore<DirectParent>(directAlsKey);\n    const attributes: any[] = [];\n    for (const [k, v] of Object.entries(record.attributes ?? {})) {\n      if (typeof v === 'string')\n        attributes.push({ key: k, value: { stringValue: v } });\n      else if (typeof v === 'number')\n        attributes.push({ key: k, value: { intValue: v } });\n      else if (typeof v === 'boolean')\n        attributes.push({ key: k, value: { boolValue: v } });\n    }\n    let bodyValue: Record<string, unknown>;\n    if (typeof record.body === 'string')\n      bodyValue = { stringValue: record.body };\n    else if (typeof record.body === 'number')\n      bodyValue = { intValue: record.body };\n    else if (typeof record.body === 'boolean')\n      bodyValue = { boolValue: record.body };\n    else {\n      // A circular body would make JSON.stringify throw; keep the log record\n      // rather than dropping it.\n      try {\n        bodyValue = { stringValue: JSON.stringify(record.body) };\n      } catch {\n        bodyValue = { stringValue: '[unserializable log body]' };\n      }\n    }\n\n    const payload = {\n      resourceLogs: [\n        {\n          resource: { attributes: [], droppedAttributesCount: 0 },\n          scopeLogs: [\n            {\n              scope: {\n                name: INSTRUMENTATION_LIBRARY.name,\n                version: INSTRUMENTATION_LIBRARY.version,\n              },\n              logRecords: [\n                {\n                  timeUnixNano: (Date.now() * 1_000_000).toString(),\n                  severityNumber: toSeverityNumber(record.severity),\n                  severityText: record.severity.toUpperCase(),\n                  body: bodyValue,\n                  attributes,\n                  ...(parent\n                    ? { traceId: parent.traceId, spanId: parent.spanId }\n                    : {}),\n                },\n              ],\n            },\n          ],\n        },\n      ],\n    };\n    postToTelemetryServer('/api/otlp', payload).catch(() => {\n      // Best-effort; log shipping must never throw on the caller thread.\n    });\n  }\n}\n\ninterface BuildSpanDataArgs {\n  info: InstrumentationSpanInfo;\n  customAttributes: SpanAttributes;\n  traceId: string;\n  spanId: string;\n  parentSpanId?: string;\n  startTime: number;\n  endTime: number;\n  status: { code: number; message?: string };\n  exceptions: Array<Record<string, string>>;\n}\n\n/**\n * Reproduces the `SpanData` shape `TraceServerExporter._exportInfo` produced,\n * so before/after Dev UI traces are structurally identical.\n */\nfunction buildSpanData(args: BuildSpanDataArgs): SpanData {\n  const { info, exceptions } = args;\n  // Genkit's own attributes win over custom writes, as they did when\n  // OTelInstrumentation applied metadataToAttributes last (at span end).\n  const attributes: Record<string, any> = {\n    ...info.labels,\n    ...args.customAttributes,\n    ...metadataToAttributes(info.metadata),\n  };\n  const spanData: SpanData = {\n    spanId: args.spanId,\n    traceId: args.traceId,\n    startTime: args.startTime,\n    endTime: args.endTime,\n    attributes,\n    displayName: info.metadata.name,\n    links: (info.links ?? []) as any,\n    instrumentationLibrary: { ...INSTRUMENTATION_LIBRARY },\n    spanKind: 'INTERNAL',\n    sameProcessAsParentSpan: { value: true },\n    status: args.status.message\n      ? { code: args.status.code, message: args.status.message }\n      : { code: args.status.code },\n    timeEvents: {\n      timeEvent: exceptions.map((attrs) => ({\n        time: args.endTime,\n        annotation: { attributes: attrs, description: 'exception' },\n      })),\n    },\n  };\n  if (args.parentSpanId) {\n    spanData.parentSpanId = args.parentSpanId;\n  }\n  return spanData;\n}\n\n/**\n * Mirrors OTel's `Span.recordException`: type prefers `code` over `name`, empty\n * fields are omitted, and nothing is recorded without a type or message. The\n * omission matters: the Dev UI titles interrupts \"Interrupted\" only when\n * `exception.message` is missing (`ToolInterruptError` has an empty message).\n */\nfunction toExceptionAttributes(\n  e: Error & { code?: unknown }\n): Record<string, string> | undefined {\n  const attrs: Record<string, string> = {};\n  if (e.code) {\n    attrs['exception.type'] = String(e.code);\n  } else if (e.name) {\n    attrs['exception.type'] = e.name;\n  }\n  if (e.message) attrs['exception.message'] = e.message;\n  if (e.stack) attrs['exception.stacktrace'] = e.stack;\n  if (!attrs['exception.type'] && !attrs['exception.message']) return undefined;\n  return attrs;\n}\n\nfunction genId(bytes: number): string {\n  return randomBytes(bytes).toString('hex');\n}\n\nfunction toSeverityNumber(level: string): number {\n  switch (level) {\n    case 'debug':\n      return 5;\n    case 'info':\n      return 9;\n    case 'warn':\n      return 13;\n    case 'error':\n      return 17;\n    default:\n      return 0;\n  }\n}\n"],"mappings":"AAgBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAGP,MAAM,eAAe;AACrB,MAAM,0BAA0B,EAAE,MAAM,iBAAiB,SAAS,KAAK;AAiBhE,MAAM,+BAEb;AAAA,EACE,MAAM,aACJ,MACA,MACY;AAGZ,UAAM,SAAS,KAAK,SAAS,UAAU,CAAC,2BAA2B;AACnE,UAAM,SAAS,SACX,SACA,gBAAgB,EAAE,SAAuB,YAAY;AACzD,UAAM,UAAU,QAAQ,WAAW,MAAM,EAAE;AAC3C,UAAM,SAAS,MAAM,CAAC;AACtB,UAAM,YAAY,KAAK,IAAI;AAC3B,UAAM,YAAY,YAAY,IAAI;AAIlC,UAAM,mBAAmC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