aboutsummaryrefslogtreecommitdiffstats
path: root/apps/workers/workerTracing.ts
blob: 3ff16d1caa029acb17beb78065eeea266016d24e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import type { DequeuedJob } from "@karakeep/shared/queueing";
import { getTracer, withSpan } from "@karakeep/shared-server";

const tracer = getTracer("@karakeep/workers");

type WorkerRunFn<TData, TResult = void> = (
  job: DequeuedJob<TData>,
) => Promise<TResult>;

/**
 * Wraps a worker run function with OpenTelemetry tracing.
 * Creates a span for each job execution and automatically handles error recording.
 *
 * @param name - The name of the span (e.g., "feedWorker.run", "crawlerWorker.run")
 * @param fn - The worker run function to wrap
 * @returns A wrapped function that executes within a traced span
 *
 * @example
 * ```ts
 * const run = withWorkerTracing("feedWorker.run", async (job) => {
 *   // Your worker logic here
 * });
 * ```
 */
export function withWorkerTracing<TData, TResult = void>(
  name: string,
  fn: WorkerRunFn<TData, TResult>,
): WorkerRunFn<TData, TResult> {
  return async (job: DequeuedJob<TData>): Promise<TResult> => {
    return await withSpan(
      tracer,
      name,
      {
        attributes: {
          "job.id": job.id,
          "job.priority": job.priority,
          "job.runNumber": job.runNumber,
        },
      },
      () => fn(job),
    );
  };
}