import { scaleLog } from 'd3-scale' ; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey' ; import type { ElasticsearchClient } from 'src/core/server' ; import { TRANSACTION_DURATION } from '../../../../common/elasticsearch_fieldnames' ; import type { CorrelationsParams } from '../../../../common/correlations/types' ; import { getQueryWithParams } from './get_query_with_params' ; import { getRequestBase } from './get_request_base' ; export const getHistogramRangeSteps = ( min , max , steps ) => { const logFn = scaleLog ( ) . domain ( [ min , max ] ) . range ( [ 1 , steps ] ) ; return [ ... Array ( steps ) . keys ( ) ] . map ( logFn . invert ) . map ( ( d ) => ( isNaN ( d ) ? 0 : Math . round ( d ) ) ) ; } ; interface Aggs extends estypes . AggregationsRateAggregate { value : number ; } export const getHistogramIntervalRequest = ( params ) : estypes . SearchRequest => ( { ... getRequestBase ( params ) , body : { query : getQueryWithParams ( { params } ) , size : 0 , aggs : { transaction_duration_min : { min : { field : TRANSACTION_DURATION } } , transaction_duration_max : { max : { field : TRANSACTION_DURATION } } , } , } , } ) ; export const fetchTransactionDurationHistogramRangeSteps = async ( esClient , params ) : Promise < number [ ] > => { const steps = 100 ; const resp = await esClient . search < unknown , { transaction_duration_min : Aggs ; transaction_duration_max : Aggs ; } > ( getHistogramIntervalRequest ( params ) ) ; if ( ( resp . body . hits . total as estypes . SearchTotalHits ) . value === 0 ) { return getHistogramRangeSteps ( 0 , 1 , 100 ) ; } if ( resp . body . aggregations === undefined ) { throw new Error ( 'fetchTransactionDurationHistogramRangeSteps failed, did not return aggregations.' ) ; } const min = resp . body . aggregations . transaction_duration_min . value ; const max = resp . body . aggregations . transaction_duration_max . value * 2 ; return getHistogramRangeSteps ( min , max , steps ) ; } ;