import type { TPromsterOptions , TDefaultedPromsterOptions , TLabelValues , THttpMetrics , } from '@promster/types' ; import merge from 'merge-options' ; import { skipMetricsInEnvironment } from '../environment' ; import { sortLabels } from '../sort-labels' ; import { endMeasurementFrom } from '../end-measurement-from' ; import { Timing } from '../timing' ; type TRecordingOptions = { labels : TLabelValues ; requestContentLength ? : number ; responseContentLength ? : number ; } ; type TLegacyTiming = [ number , number ] ; export type TRequestRecorder = ( timing : Timing | TLegacyTiming , recordingOptions : TRecordingOptions ) => void ; const defaultOptions = { skip : ( ) => false , detectKubernetes : false , } ; function isTiming ( timing ) { return ! Array . isArray ( timing ) ; } const createRequestRecorder = ( metrics , options = defaultOptions ) : TRequestRecorder => { const defaultedRecorderOptions = merge ( defaultOptions , options ) ; const shouldSkipMetricsByEnvironment = skipMetricsInEnvironment ( defaultedRecorderOptions ) ; return ( timing , recordingOptions ) => { const durationS = isTiming ( timing ) ? timing . end ( ) . value ( ) . seconds : endMeasurementFrom ( timing ) . durationS ; const labels = sortLabels ( recordingOptions . labels ) ; if ( ! shouldSkipMetricsByEnvironment && durationS !== undefined ) { metrics . httpRequestDurationInSeconds ?. forEach ( ( httpRequestDurationInSecondsMetricType ) => { httpRequestDurationInSecondsMetricType . observe ( labels , durationS ) ; } ) ; } if ( ! shouldSkipMetricsByEnvironment && durationS !== undefined ) { metrics . httpRequestDurationPerPercentileInSeconds ?. forEach ( ( httpRequestDurationPerPercentileInSecondsMetricType ) => { httpRequestDurationPerPercentileInSecondsMetricType . observe ( labels , durationS ) ; } ) ; } if ( ! shouldSkipMetricsByEnvironment && durationS !== undefined ) { metrics . httpRequestsTotal ?. forEach ( ( httpRequestsTotalMetricType ) => { httpRequestsTotalMetricType . inc ( labels ) ; } ) ; } if ( recordingOptions . requestContentLength ) { metrics . httpRequestContentLengthInBytes ?. forEach ( ( httpRequestContentLengthInBytesMetricType ) => { httpRequestContentLengthInBytesMetricType . observe ( labels , recordingOptions . requestContentLength ) ; } ) ; } if ( recordingOptions . responseContentLength ) { metrics . httpResponseContentLengthInBytes ?. forEach ( ( httpResponseContentLengthInBytesMetricType ) => { httpResponseContentLengthInBytesMetricType . observe ( labels , recordingOptions . responseContentLength ) ; } ) ; } } ; } ; createRequestRecorder . defaultOptions = defaultOptions ; export { createRequestRecorder , sortLabels , endMeasurementFrom } ;