Skip to content
File

Blob: src/cloudflare/internal/tracing-helpers.ts

typescript43 lines
1// Copyright (c) 2025 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import tracing, { type Span } from 'cloudflare-internal:tracing';
6 
7export type { Span };
8 
9/**
10 * Helper function to wrap operations with tracing spans.
11 * Automatically handles span lifecycle for both sync and async operations via
12 * the underlying `enterSpan` primitive, which also pushes the new span onto
13 * the async context so that any spans (or async continuations) created inside
14 * `fn` nest correctly beneath it.
15 *
16 * @param name - The operation name for the span
17 * @param fn - The function to execute within the span context
18 * @returns The result of the function
19 *
20 * @example
21 * // Synchronous usage
22 * const result = withSpan('prepare', (span) => {
23 * span.setAttribute('query', sql);
24 * return new PreparedStatement(sql);
25 * });
26 *
27 * @example
28 * // Asynchronous usage
29 * const result = await withSpan('exec', async (span) => {
30 * span.setAttribute('query', sql);
31 * return await database.execute(sql);
32 * });
33 *
34 * @note Generator functions are not currently supported and will have their
35 * spans ended immediately after the generator object is returned, not when
36 * the generator is exhausted.
37 */
38export function withSpan<T>(name: string, fn: (span: Span) => T): T {
39 // `enterSpan` already handles sync vs. promise return (and sync-throw /
40 // promise-reject) auto-ending, so this is a pure passthrough.
41 return tracing.enterSpan(name, fn);
42}