Skip to content

parsec ​

@c9up/parsec: metrics: counters, gauges and histograms behind one driver contract, with a zero-dependency Prometheus driver, an OpenTelemetry driver, an HTTP middleware and a protected scrape endpoint. Guide: Metrics.

Installation ​

bash
pnpm add @c9up/parsec

ream configure @c9up/parsec registers the provider and the HTTP middleware (server tier), writes config/metrics.ts and start/metrics.ts (the /__metrics route), and adds METRICS_EXPORTER and a random METRICS_TOKEN to .env. The OpenTelemetry driver needs @opentelemetry/api (an optional peer) and a meter from the application's SDK.

Entry points ​

ImportContents
@c9up/parsecMetricsManager, defineConfig, drivers, the three drivers, metricsHandler, collectDefaultMetrics, instrumentHealthChecks, errors, types
@c9up/parsec/providerParsecProvider (default export)
@c9up/parsec/services/mainThe booted MetricsManager (default export), setMetrics, getMetrics, clearMetrics
@c9up/parsec/httpThe HTTP middleware (default export ParsecHttpMiddleware, and parsecHttpMiddleware) and its label helpers
@c9up/parsec/endpointmetricsHandler and its types
@c9up/parsec/prometheusPrometheusDriver, PROMETHEUS_CONTENT_TYPE
@c9up/parsec/otelOtelDriver, OtelDriverOptions, OtelMeter
@c9up/parsec/diagnosticsinstrumentHealthChecks, HEALTH_CHANNEL
@c9up/parsec/testingfakeMetrics
@c9up/parsec/configureconfigure(codemods), run by ream configure

Exports ​

@c9up/parsec ​

ExportKindDescription
MetricsManagerclassThe configured exporters, built on first use; declares instruments on the default one.
defineConfigfunctiondefineConfig(config: MetricsConfig): MetricsConfig.
driversconstExporter factories: prometheus(options?: DriverOptions), otel(options: OtelDriverOptions), noop().
PrometheusDriverclassHolds series in memory and renders the Prometheus text format on scrape(). new PrometheusDriver(options?: DriverOptions).
OtelDriverclassRecords through an OpenTelemetry meter; scrape() answers null. new OtelDriver(options: OtelDriverOptions).
NoopDriverclassMeasures nothing. The exporter of a manager built without config.
PROMETHEUS_CONTENT_TYPEconst'text/plain; version=0.0.4; charset=utf-8'.
metricsHandlerfunctionmetricsHandler(metrics: MetricsManager, options?: MetricsEndpointOptions): a route handler serving the scrape body.
collectDefaultMetricsfunctioncollectDefaultMetrics(metrics: InstrumentFactory, options?: DefaultMetricsOptions): () => void: declares the process and Node.js baseline and starts its monitors; returns the stop.
instrumentHealthChecksfunctioninstrumentHealthChecks(metrics: MetricsManager): () => void: times each health check run from ream's tracing channel; returns the unsubscribe.
HEALTH_CHANNELconst'ream.health.check'.
errorsnamespaceThe package's errors, one class per code, see Errors
MetricsRecordertypeWhat use(name?) returns: one exporter's counter, gauge, histogram, scrape(): Promise<string | null>, shutdown() and getDriver(). Type only: the manager builds it.
MetricsConfiginterface{ default: string; exporters: Record<string, () => MetricsDriver> }.
MetricsDriverinterfaceThe driver contract: createCounter, createGauge, createHistogram, optional scrape() and shutdown().
DriverOptionsinterface{ maxSeries?: number; collectTimeout?: number }.
OtelDriverOptionsinterfaceDriverOptions & { meter: OtelMeter }.
OtelMeterinterfaceThe meter methods the OpenTelemetry driver calls (createCounter, createGauge, createHistogram, optional observable variants).
Counterinterfaceincrement(value?: number, labels?: Labels): void, plus remove and reset.
Gaugeinterfaceset, increment, decrement, startTimer(labels?): EndTimer, plus remove and reset.
Histograminterfaceobserve(value, labels?), time<T>(work: () => Promise<T>, labels?): Promise<T>, startTimer(labels?), plus remove and reset.
SeriesLifecycleinterface{ remove(labels?: Labels): void; reset(): void }.
EndTimertype(labels?: Labels) => number: records and returns the elapsed seconds.
LabelstypeReadonly<Record<string, string | number>>.
InstrumentOptionsinterface{ name: string; help: string; labelNames?: readonly string[]; unit?: string }.
CounterOptionsinterfaceInstrumentOptions & { collect?: Collect<Counter> }.
GaugeOptionsinterfaceInstrumentOptions & { collect?: Collect<Gauge> }.
HistogramOptionsinterfaceInstrumentOptions & { buckets?: readonly number[] }.
Collecttype(instrument: T) => void | Promise<void>: computes values when they are read.
InstrumentFactoryinterface{ counter; gauge; histogram }: a MetricsManager or one of its recorders.
DefaultMetricsOptionsinterface{ prefix?: string; eventLoopMonitoringPrecision?: number; gcDurationBuckets?: readonly number[] }.
MetricsEndpointOptionsinterface{ token?: string | ReleasableSecret; public?: boolean }.
MetricsEndpointContextinterfaceThe slice of the HTTP context the handler reads and writes.
ReleasableSecretinterface{ release(): string }.

@c9up/parsec/provider ​

ExportKindDescription
default (ParsecProvider)providerregister() binds the MetricsManager (a no-op one without config/metrics.ts); boot() seats it on services/main; ready() calls instrumentHealthChecks; shutdown() unsubscribes and shuts the exporters down.
ParsecAppContextinterface{ container; config }: the host the provider needs.

@c9up/parsec/services/main ​

ExportKindDescription
defaultconstThe booted MetricsManager; a member read before boot throws.
setMetricsfunctionsetMetrics(value: MetricsManager): void.
getMetricsfunctiongetMetrics(): MetricsManager | undefined.
clearMetricsfunctionclearMetrics(): void.

@c9up/parsec/http ​

ExportKindDescription
default (ParsecHttpMiddleware)classMiddleware class, handle(ctx, next). Register it with server.use, so unmatched requests are counted.
parsecHttpMiddlewarefunctionparsecHttpMiddleware(ctx: ReamContext, next: () => Promise<void> | void): Promise<void>. Records http_server_requests_total, http_server_request_duration_seconds (labels method, route, status) and http_server_requests_in_flight (label method).
PARSEC_KEYconst'parsec.metrics': the token the middleware resolves through ctx.containerResolver.
methodLabelfunctionmethodLabel(method: string): string: the HTTP method, or OTHER for one outside the standard list.
routeLabelfunctionrouteLabel(ctx: ReamContext): string: the matched route pattern, or <unmatched>; never the URL.
instrumentsForfunctioninstrumentsFor(metrics: MetricsManager): the three HTTP instruments, declared once per manager.
statusOfErrorfunctionstatusOfError(error: unknown): number: the error's HTTP status, else 500.
ReamContextinterfaceThe slice of the HTTP context the middleware reads.

@c9up/parsec/testing ​

ExportKindDescription
fakeMetricsfunctionfakeMetrics(): { metrics: MetricsManager; restore: () => void }. Seats a Prometheus-backed manager on services/main; restore() puts the previous one back.

MetricsManager ​

new MetricsManager(config?: MetricsConfig); without a config, a single noop exporter. Throws E_PARSEC_UNKNOWN_EXPORTER when default is not declared.

MemberSignatureDescription
useuse(name?: string): MetricsRecorderThe recorder of an exporter (default one without a name), built once. It has the same counter, gauge, histogram, scrape, shutdown and getDriver().
countercounter(options: CounterOptions): CounterDeclare or fetch a counter on the default exporter. The same name returns the same instrument.
gaugegauge(options: GaugeOptions): GaugeDeclare or fetch a gauge.
histogramhistogram(options: HistogramOptions): HistogramDeclare or fetch a histogram.
scrapescrape(): Promise<string | null>The default exporter's body; null for a pushing driver.
shutdownshutdown(): Promise<void>Shut down every built exporter.

Instrument options ​

OptionTypeDefaultDescription
namestring—[a-zA-Z_:][a-zA-Z0-9_:]*.
helpstring—One line, rendered as HELP.
labelNamesreadonly string[][]The only labels a measurement may carry.
unitstringnone; s for a histogram on the default bucketsOpenTelemetry-style unit (s, By, 1).
bucketsreadonly number[]0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10Histogram bucket bounds, ascending.
collectCollect<T>noneCounter or gauge computed when read.

Configuration ​

config/metrics.ts, read under the metrics key.

OptionTypeDefaultDescription
defaultstring'noop' without configThe exporter instruments are declared on. The generated config reads METRICS_EXPORTER (prometheus when unset).
exportersRecord<string, () => MetricsDriver>{ noop } without configNamed exporters, built on first use.
drivers.prometheus({ maxSeries })number1000Label combinations one instrument may hold; past it, series are dropped and counted.
drivers.prometheus({ collectTimeout })number (ms)5000Time one collect callback may take during a scrape.

metricsHandler options:

OptionTypeDefaultDescription
tokenstring | ReleasableSecret—Required Authorization: Bearer token; a wrong or missing one gets 404.
publicbooleanfalseServe without a token. Neither option set is an error.

Container bindings ​

TokenResolves to
MetricsManager (class)The MetricsManager built from config/metrics.ts
'parsec.metrics'The same manager
'metrics'The same manager

The two string tokens are typed on ContainerBindings once @c9up/parsec is imported.

Errors ​

CodeRaised when
E_PARSEC_INVALID_NAMEA metric or label name is not valid.
E_PARSEC_INVALID_INSTRUMENTAn instrument is declared with options it cannot have.
E_PARSEC_INSTRUMENT_CONFLICTA name is already declared with another type, help or label set.
E_PARSEC_INVALID_MEASUREMENTA measurement is not a finite number, or is negative where it must not be.
E_PARSEC_INVALID_LABEL_VALUEA label value is neither a string nor a finite number.
E_PARSEC_UNDECLARED_LABELA measurement carries a label the instrument does not declare.
E_PARSEC_UNKNOWN_EXPORTERdefault or use(name) names an exporter that is not declared.
E_PARSEC_UNPROTECTED_ENDPOINTmetricsHandler has no token and no public: true, or both.
E_PARSEC_EMPTY_TOKENThe endpoint token is empty or blank.
E_PARSEC_INVALID_CONFIGconfig/metrics.ts does not export defineConfig({ default, exporters }).
E_PARSEC_INVALID_BINDINGThe container answers something other than a MetricsManager for the MetricsManager token.
E_PARSEC_NOT_BOOTEDThe metrics service or the HTTP middleware is used before ParsecProvider bound the manager, or before setMetrics().

Each one is a class of the errors namespace and a @c9up/flare Exception with status 500: branch on error.code or on error instanceof errors.E_PARSEC_*.

Migration ​

  • ParsecError is gone: test error.code, or error instanceof errors.E_PARSEC_* with import { errors } from '@c9up/parsec'.
  • The error classes are renamed after their code and live in the errors namespace: InvalidMetricNameError becomes errors.E_PARSEC_INVALID_NAME, InvalidInstrumentError errors.E_PARSEC_INVALID_INSTRUMENT, InstrumentConflictError errors.E_PARSEC_INSTRUMENT_CONFLICT, InvalidMeasurementError errors.E_PARSEC_INVALID_MEASUREMENT, InvalidLabelValueError errors.E_PARSEC_INVALID_LABEL_VALUE, UndeclaredLabelError errors.E_PARSEC_UNDECLARED_LABEL, UnknownExporterError errors.E_PARSEC_UNKNOWN_EXPORTER, UnprotectedEndpointError errors.E_PARSEC_UNPROTECTED_ENDPOINT, EmptyTokenError errors.E_PARSEC_EMPTY_TOKEN.

See also ​