From a2f86d169b0b61e21a34eba5a254932c1170e7d1 Mon Sep 17 00:00:00 2001 From: Zacqary Xeper Date: Wed, 4 Aug 2021 12:42:55 -0500 Subject: [PATCH] [Metrics UI] Fix metric threshold preview regression --- .../metric_threshold/lib/evaluate_alert.ts | 10 +++---- .../metric_threshold/lib/metric_query.test.ts | 26 +++++++++++++++++++ .../metric_threshold/lib/metric_query.ts | 13 +++++----- 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts index d3fa983ff9e84..88d135fd1681b 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts @@ -96,8 +96,6 @@ export const evaluateAlert = { ); }); }); + + describe('when passed a timeframe of 1 hour', () => { + const testTimeframe = { + start: moment().subtract(1, 'hour').valueOf(), + end: moment().valueOf(), + }; + const searchBodyWithoutGroupBy = getElasticsearchMetricQuery( + expressionParams, + timefield, + testTimeframe + ); + const searchBodyWithGroupBy = getElasticsearchMetricQuery( + expressionParams, + timefield, + testTimeframe, + groupBy + ); + test("generates 1 hour's worth of buckets", () => { + // @ts-ignore + expect(searchBodyWithoutGroupBy.aggs.aggregatedIntervals.date_range.ranges.length).toBe(60); + expect( + // @ts-ignore + searchBodyWithGroupBy.aggs.groupings.aggs.aggregatedIntervals.date_range.ranges.length + ).toBe(60); + }); + }); }); diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts index cde84b217be95..66e112640c357 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts @@ -76,12 +76,13 @@ export const getElasticsearchMetricQuery = ( aggregatedIntervals: { date_range: { field: timefield, - ranges: [ - { - from: to - intervalAsMS - deliveryDelay, - to: to - deliveryDelay, - }, - ], + // Generate an array of buckets, starting at `from` and ending at `to` + // This is usually only necessary for alert previews or rate aggs. Most alert evaluations + // will generate only one bucket from this logic. + ranges: Array.from(Array(Math.floor((to - from) / intervalAsMS)), (_, i) => ({ + from: from + intervalAsMS * i - deliveryDelay, + to: from + intervalAsMS * (i + 1) - deliveryDelay, + })), }, aggregations, },