Open History to see the last commit
1// Tracing with the OpenTelemetry API. `@opentelemetry/api` is an optional
2// peer: the types are type-only imports, and the runtime is loaded only when a
3// host has a tracer (see `OperationTracing.ready`).
4import { addCounts, emptyCounts } from './usage'
5import type {
6 Attributes,
7 Context,
8 ContextAPI,
9 Span,
10 SpanContext,
11 SpanOptions,
12 TraceAPI,
13 Tracer,
14} from '@opentelemetry/api'
15import type { OperationKind, OperationStatus } from './types'
16import type { UsageCall, UsageCounts } from './usage'
17
18/** What `onOperation` gets, once when an operation starts and once when it settles. */
19export interface OperationReport {
20 phase: 'started' | 'settled'
21 operation: {
22 id: string
23 kind: OperationKind
24 agent?: string
25 threadId: string
26 tenantId?: string
27 parentRunId?: string
28 status: OperationStatus
29 /** Only when `phase` is `'settled'`. */
30 durationMs?: number
31 error?: { message: string; code?: string }
32 usage?: UsageCounts
33 }
34}
35
36/** The `observability` option of a host. */
37export interface ObservabilityOptions {
38 /**
39 * An OpenTelemetry tracer, for example `trace.getTracer('my-app')`.
40 * Without a tracer, the harness writes no spans.
41 */
42 tracer?: Tracer
43 /** A listener that throws is logged and ignored. */
44 onOperation?: (report: OperationReport) => void | Promise<void>
45}
46
47/** The `SpanStatusCode` values, without a runtime import of the enum. */
48const OK = 1
49const ERROR = 2
50
51const NOOP_CONTEXT: SpanContext = {
52 traceId: '0'.repeat(32),
53 spanId: '0'.repeat(16),
54 traceFlags: 0,
55}
56
57// One shared span, so a host without a tracer allocates nothing per span.
58const noopSpan: Span = {
59 setAttribute: () => noopSpan,
60 setAttributes: () => noopSpan,
61 addEvent: () => noopSpan,
62 addLink: () => noopSpan,
63 addLinks: () => noopSpan,
64 setStatus: () => noopSpan,
65 updateName: () => noopSpan,
66 end: () => {},
67 isRecording: () => false,
68 recordException: () => {},
69 spanContext: () => NOOP_CONTEXT,
70}
71
72/** The tracer of a host without `observability.tracer`. It does nothing. */
73export const noopTracer: Pick<Tracer, 'startSpan'> = {
74 startSpan: () => noopSpan,
75}
76
77let otel: { trace: TraceAPI; context: ContextAPI } | undefined
78
79/**
80 * Load `@opentelemetry/api` once, for a host with a tracer. The harness
81 * needs it only to make the context of a parent span. Without the package,
82 * spans have no parent on this host.
83 */
84async function loadOpenTelemetry(): Promise<void> {
85 otel ??= await import('@opentelemetry/api').catch(() => undefined)
86}
87
88/**
89 * Run `fn` in a span. The span ends when `fn` settles. When `fn` throws, the
90 * span records the error and gets the error status, and the error goes on.
91 *
92 * @example
93 * ```ts
94 * const result = await withSpan({ tracer, name: 'harness.recovery' }, () =>
95 * recover(),
96 * )
97 * ```
98 */
99export async function withSpan<T>(
100 {
101 tracer,
102 name,
103 ...options
104 }: { tracer: Pick<Tracer, 'startSpan'>; name: string } & SpanOptions,
105 fn: (span: Span) => T | PromiseLike<T>,
106): Promise<T> {
107 const span = tracer.startSpan(name, options)
108 try {
109 return await fn(span)
110 } catch (error) {
111 const message = error instanceof Error ? error.message : String(error)
112 span.recordException(error instanceof Error ? error : message)
113 span.setStatus({ code: ERROR, message })
114 throw error
115 } finally {
116 span.end()
117 }
118}
119
120const TRACEPARENT =
121 /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/
122
123/**
124 * Read a W3C `traceparent` header value. Returns `undefined` for a value
125 * that is not valid, as the W3C rules say: the caller then starts a new
126 * trace.
127 *
128 * @example
129 * ```ts
130 * parseTraceparent('00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01')
131 * // { traceId: '4bf9…', spanId: '00f0…', traceFlags: 1, isRemote: true }
132 * ```
133 */
134export function parseTraceparent(value: unknown): SpanContext | undefined {
135 if (typeof value !== 'string') return undefined
136 const match = TRACEPARENT.exec(value)
137 if (!match) return undefined
138 const [, version, traceId = '', spanId = '', flags = '', rest] = match
139 // Version `ff` is not valid. Version `00` has exactly four fields. A later
140 // version can add fields after the four that we read.
141 if (version === 'ff' || (version === '00' && rest !== undefined))
142 return undefined
143 if (/^0+$/.test(traceId) || /^0+$/.test(spanId)) return undefined
144 return {
145 traceId: traceId,
146 spanId: spanId,
147 traceFlags: parseInt(flags, 16),
148 isRemote: true,
149 }
150}
151
152/** A context whose span is `span`: a span started in it is its child. */
153const parentContext = (span: Span | undefined): Context | undefined =>
154 span && otel ? otel.trace.setSpan(otel.context.active(), span) : undefined
155
156/** What {@link OperationTracing} reads of an operation. */
157interface TracedOperation {
158 id: string
159 kind: OperationKind
160 agent?: string | undefined
161 status: () => OperationStatus
162 then: (
163 onfulfilled: (value: unknown) => void,
164 onrejected: (reason: unknown) => void,
165 ) => unknown
166}
167
168/** An operation of this host that did not settle yet. */
169interface OpenOperation {
170 span: Span
171 startedAt: number
172 usage: UsageCounts
173}
174
175/** The message and the `code` of an error, when it has a string code. */
176function errorOf(error: unknown): { message: string; code?: string } {
177 const message = error instanceof Error ? error.message : String(error)
178 const code =
179 typeof error === 'object' &&
180 error !== null &&
181 'code' in error &&
182 typeof error.code === 'string'
183 ? error.code
184 : undefined
185 return code === undefined ? { message } : { message, code }
186}
187
188/**
189 * @internal The spans and the `onOperation` reports of one session. A
190 * session of a host without `observability` has none, so it allocates
191 * nothing.
192 */
193export class OperationTracing {
194 private readonly tracer: Pick<Tracer, 'startSpan'>
195 private readonly open = new Map<string, OpenOperation>()
196
197 constructor(
198 private readonly options: ObservabilityOptions & {
199 threadId: string
200 tenantId?: string
201 /** Logs a listener or a tracer that throws. */
202 warn: (error: unknown) => void
203 },
204 ) {
205 this.tracer = options.tracer ?? noopTracer
206 }
207
208 /** Load what the tracer needs. A session awaits it before its first span. */
209 async ready(): Promise<void> {
210 if (this.options.tracer) await loadOpenTelemetry()
211 }
212
213 /**
214 * Run the tracer or span calls `fn`. A tracer that throws is logged, so a
215 * tracing bug never fails a run or the host.
216 */
217 safely(fn: () => void): void {
218 try {
219 fn()
220 } catch (error) {
221 this.options.warn(error)
222 }
223 }
224
225 /** Start a span. A tracer that throws gives a span that does nothing. */
226 private startSpan(name: string, options: SpanOptions, parent?: Span): Span {
227 let span = noopSpan
228 this.safely(() => {
229 span = this.tracer.startSpan(name, options, parentContext(parent))
230 })
231 return span
232 }
233
234 /** The attributes of every span of this session, and `extra`. */
235 private attributes(extra: Attributes) {
236 const attributes: Attributes = {
237 'harness.thread_id': this.options.threadId,
238 }
239 if (this.options.tenantId !== undefined) {
240 attributes['harness.tenant_id'] = this.options.tenantId
241 }
242 for (const [key, value] of Object.entries(extra)) {
243 if (value !== undefined) attributes[key] = value
244 }
245 return attributes
246 }
247
248 /**
249 * Start a span `name` of this session. `runId`: the run that it belongs
250 * to. When that run is open on this host, the span is its child.
251 */
252 span(
253 name: string,
254 extra: Attributes,
255 options: { runId?: string | undefined; startTime?: number } = {},
256 ): Span {
257 const parent =
258 options.runId === undefined ? undefined : this.open.get(options.runId)
259 return this.startSpan(
260 name,
261 {
262 attributes: this.attributes(extra),
263 ...(options.startTime !== undefined
264 ? { startTime: options.startTime }
265 : {}),
266 },
267 parent?.span,
268 )
269 }
270
271 /**
272 * An operation started on this host. Its `harness.operation` span is a
273 * child of the span of its parent run when that run is open on this host.
274 * A valid `traceparent` of the caller becomes a link, never the parent:
275 * it can come from another machine. The span ends, and `onOperation`
276 * gets the report, when the operation settles.
277 */
278 started(
279 operation: TracedOperation,
280 run: { parentRunId: string | undefined; traceparent: string | undefined },
281 ): void {
282 if (this.open.has(operation.id)) return
283 const { parentRunId } = run
284 const parent =
285 parentRunId === undefined ? undefined : this.open.get(parentRunId)
286 const caller = parseTraceparent(run.traceparent)
287 const startedAt = Date.now()
288 const span = this.startSpan(
289 'harness.operation',
290 {
291 attributes: this.attributes({
292 'harness.run_id': operation.id,
293 'harness.parent_run_id': parentRunId,
294 'harness.operation.kind': operation.kind,
295 'harness.agent': operation.agent,
296 }),
297 ...(caller ? { links: [{ context: caller }] } : {}),
298 startTime: startedAt,
299 },
300 parent?.span,
301 )
302 const open: OpenOperation = { span, startedAt, usage: emptyCounts() }
303 this.open.set(operation.id, open)
304 const report = (): OperationReport['operation'] => ({
305 id: operation.id,
306 kind: operation.kind,
307 ...(operation.agent !== undefined ? { agent: operation.agent } : {}),
308 threadId: this.options.threadId,
309 ...(this.options.tenantId !== undefined
310 ? { tenantId: this.options.tenantId }
311 : {}),
312 ...(parentRunId !== undefined ? { parentRunId } : {}),
313 status: operation.status(),
314 })
315 this.report({ phase: 'started', operation: report() })
316 const settle = (error?: unknown) => {
317 this.open.delete(operation.id)
318 const status = operation.status()
319 const failure = error === undefined ? undefined : errorOf(error)
320 const endedAt = Date.now()
321 this.safely(() => {
322 span.setAttribute('harness.operation.status', status)
323 if (status === 'failed' && failure) {
324 span.recordException(error instanceof Error ? error : failure.message)
325 span.setStatus({ code: ERROR, message: failure.message })
326 } else if (status !== 'cancelled') {
327 span.setStatus({ code: OK })
328 }
329 span.end(endedAt)
330 })
331 this.report({
332 phase: 'settled',
333 operation: {
334 ...report(),
335 durationMs: endedAt - startedAt,
336 ...(failure ? { error: failure } : {}),
337 usage: open.usage,
338 },
339 })
340 }
341 operation.then(
342 () => settle(),
343 (error: unknown) => settle(error),
344 )
345 }
346
347 /**
348 * One model call of the run `call.runId`. It counts for that run and for
349 * each run above it that is open on this host, as the run usage of the
350 * log does. `parentOf` gives the parent run of a run.
351 */
352 usage(call: UsageCall, parentOf: (runId: string) => string | undefined) {
353 const seen = new Set<string>()
354 let runId = call.runId
355 while (runId !== undefined && !seen.has(runId)) {
356 seen.add(runId)
357 const open = this.open.get(runId)
358 if (open) addCounts(open.usage, call.usage)
359 runId = parentOf(runId)
360 }
361 }
362
363 /** Call `onOperation`. A listener that throws is logged and ignored. */
364 private report(report: OperationReport) {
365 const listener = this.options.onOperation
366 if (!listener) return
367 try {
368 const done = listener(report)
369 if (done) done.then(undefined, this.options.warn)
370 } catch (error) {
371 this.options.warn(error)
372 }
373 }
374}