3.1 KiB
3.1 KiB
Validation OTel Instrumentation
(no submodules)
Purpose
validation-otel.ts provides OpenTelemetry instrumentation for parse operations in @suaveplan/validation. It exposes two counter instruments (validation.parse.success and validation.parse.failure) and one histogram (validation.parse.duration_ms) through the OTel metrics API. All instruments are labelled with a schema.type attribute so dashboards can break down metrics per schema class.
Instruments are lazily initialised on first use and cached as module-level singletons, avoiding meter lookup overhead on the hot parse path.
Features
- Counter
validation.parse.successincremented per successful parse - Counter
validation.parse.failureincremented per failed parse - Histogram
validation.parse.duration_msrecords duration in milliseconds schema.typeattribute on all instruments for per-schema breakdown_resetInstruments()for test isolation
Usage: Basic Example
import { recordParseSuccess, recordParseFailure } from "@suaveplan/validation";
const start = performance.now();
const result = mySchema.safeParse(input);
const duration = performance.now() - start;
if (result.success) {
recordParseSuccess({ schemaType: "ObjectSchema" }, duration);
} else {
recordParseFailure({ schemaType: "ObjectSchema" }, duration);
}
Usage: Advanced Example
import { recordParseSuccess, recordParseFailure } from "@suaveplan/validation";
// Wrap any schema with automatic OTel instrumentation
function instrumentedParse<T>(schema: { safeParse: (v: unknown) => { success: boolean; data?: T } }, input: unknown, schemaType: string) {
const start = performance.now();
const result = schema.safeParse(input);
const duration = performance.now() - start;
if (result.success) {
recordParseSuccess({ schemaType }, duration);
} else {
recordParseFailure({ schemaType }, duration);
}
return result;
}
API Reference
recordParseSuccess(opts: ParseObservabilityOptions, durationMs: number): void
Increments the success counter and records the duration histogram.
recordParseFailure(opts: ParseObservabilityOptions, durationMs: number): void
Increments the failure counter and records the duration histogram.
_resetInstruments(): void
Clears cached instrument singletons. For test use only.
ParseObservabilityOptions
interface ParseObservabilityOptions {
schemaType: string; // e.g. "ObjectSchema", "StringSchema"
}
Implementation Notes
- Instruments are lazily created via
metrics.getMeter()on first call to eitherrecordParseSuccessorrecordParseFailure. This avoids OTel initialisation at module import time. - The OTel
metricsglobal (@opentelemetry/api) is a no-op by default unless a real metrics provider is configured, so these calls are safe in environments without OTel. _resetInstruments()sets all singletons toundefined, causing the next call to re-create them — useful for testing multiple instrumentation scenarios in the same process.