diff --git a/observability/observe.ts b/observability/observe.ts index a4c1518ac..298f2685d 100644 --- a/observability/observe.ts +++ b/observability/observe.ts @@ -2,36 +2,44 @@ import { isWrappedError } from "../blocks/loader.ts"; import { ValueType } from "../deps.ts"; import { meter, OTEL_ENABLE_EXTRA_METRICS } from "./otel/metrics.ts"; -const operationDuration = meter.createHistogram("block_op_duration", { - description: "operation duration", - unit: "ms", - valueType: ValueType.DOUBLE, -}); +const observeWithMetrics = (() => { + const operationDuration = meter.createHistogram("block_op_duration", { + description: "operation duration", + unit: "ms", + valueType: ValueType.DOUBLE, + }); -/** - * Observe function durations based on the provided labels - */ -export const observe = async ( - op: string, - f: () => Promise, -): Promise => { - const start = performance.now(); - let isError = "false"; - try { - const result = await f(); - if (isWrappedError(result)) { + return async ( + op: string, + f: () => Promise, + ): Promise => { + const start = performance.now(); + let isError = "false"; + try { + const result = await f(); + if (isWrappedError(result)) { + isError = "true"; + } + return result; + } catch (error) { isError = "true"; - } - return result; - } catch (error) { - isError = "true"; - throw error; - } finally { - if (OTEL_ENABLE_EXTRA_METRICS) { + throw error; + } finally { operationDuration.record(performance.now() - start, { "operation.name": op, "operation.is_error": isError, }); } - } -}; + }; +})(); + +/** + * When metrics are disabled, pass through directly to avoid async wrapper + * overhead (performance.now, try/catch, isWrappedError check). + */ +export const observe: ( + op: string, + f: () => Promise, +) => Promise = OTEL_ENABLE_EXTRA_METRICS + ? observeWithMetrics + : (_op, f) => f();