Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[data.search.aggs]: Clean up TimeBuckets implementation #62123

Merged
1 change: 1 addition & 0 deletions src/plugins/data/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ export {
EsQuerySortValue,
SortDirection,
FetchOptions,
Bounds,
// tabify
TabbedAggColumn,
TabbedAggRow,
Expand Down
23 changes: 10 additions & 13 deletions src/plugins/data/public/search/aggs/buckets/date_histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import moment from 'moment-timezone';
import { i18n } from '@kbn/i18n';
import { IUiSettingsClient } from 'src/core/public';

import { TimeBuckets } from './lib/time_buckets';
import { TimeBuckets, Bounds } from './lib/time_buckets';
import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type';
import { BUCKET_TYPES } from './bucket_agg_types';
import { createFilterDateHistogram } from './create_filter/date_histogram';
Expand All @@ -46,25 +46,21 @@ const updateTimeBuckets = (
) => {
const bounds = agg.params.timeRange ? timefilter.calculateBounds(agg.params.timeRange) : null;
const buckets = customBuckets || agg.buckets;
buckets.setBounds(agg.fieldIsTimeField() && bounds);
if (agg.fieldIsTimeField()) {
buckets.setBounds(bounds as Bounds);
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
} else {
buckets.setBounds();
}
buckets.setInterval(agg.params.interval);
};

// TODO: Need to incorporate these properly into TimeBuckets
interface ITimeBuckets {
setBounds: Function;
getScaledDateFormat: TimeBuckets['getScaledDateFormat'];
setInterval: Function;
getInterval: Function;
}

export interface DateHistogramBucketAggDependencies {
uiSettings: IUiSettingsClient;
query: QuerySetup;
}

export interface IBucketDateHistogramAggConfig extends IBucketAggConfig {
buckets: ITimeBuckets;
buckets: TimeBuckets;
}

export function isDateHistogramBucketAggConfig(agg: any): agg is IBucketDateHistogramAggConfig {
Expand Down Expand Up @@ -202,7 +198,8 @@ export const getDateHistogramBucketAgg = ({
...dateHistogramInterval(interval.expression),
};

const scaleMetrics = scaleMetricValues && interval.scaled && interval.scale < 1;
const scaleMetrics =
scaleMetricValues && interval.scaled && interval.scale && interval.scale < 1;
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
if (scaleMetrics && aggs) {
const metrics = aggs.aggs.filter(a => isMetricAggType(a.type));
const all = every(metrics, (a: IBucketAggConfig) => {
Expand All @@ -214,7 +211,7 @@ export const getDateHistogramBucketAgg = ({
});
if (all) {
output.metricScale = interval.scale;
output.metricScaleText = interval.preScaled.description;
output.metricScaleText = interval.preScaled ? interval.preScaled.description : '';
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
}
}
},
Expand Down
1 change: 1 addition & 0 deletions src/plugins/data/public/search/aggs/buckets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ export * from './ip_range';
export * from './lib/cidr_mask';
export * from './lib/date_range';
export * from './lib/ip_range';
export { Bounds } from './lib/time_buckets';
export * from './migrate_include_exclude_format';
export * from './terms';
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
* under the License.
*/

export { TimeBuckets } from './time_buckets';
export { TimeBuckets, Bounds } from './time_buckets';
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import moment from 'moment';
import { coreMock } from '../../../../../../../../../src/core/public/mocks';

import { TimeBuckets, Bounds } from './time_buckets';

describe('TimeBuckets', () => {
const { uiSettings } = coreMock.createSetup();
uiSettings.get.mockImplementation((key: string) => {
if (key === 'histogram:maxBars') {
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
return 4;
} else if (key === 'histogram:barTarget') {
return 2;
} else if (key === 'dateFormat:scaled') {
return [
['', 'HH:mm:ss.SSS'],
['PT1S', 'HH:mm:ss'],
['PT1M', 'HH:mm'],
['PT1H', 'YYYY-MM-DD HH:mm'],
['P1DT', 'YYYY-MM-DD'],
['P1YT', 'YYYY'],
];
}
});

test('setBounds/getBounds - bounds is correct', () => {
const timeBuckets = new TimeBuckets({ uiSettings });
const bounds: Bounds = {
min: moment('2020-03-25'),
max: moment('2020-03-31'),
};
timeBuckets.setBounds(bounds);
const timeBucketsBounds = timeBuckets.getBounds();

expect(timeBucketsBounds).toEqual(bounds);
});

test('setBounds/getBounds - bounds is undefined', () => {
const timeBuckets = new TimeBuckets({ uiSettings });
const bounds: Bounds = {
min: moment('2020-03-25'),
max: moment('2020-03-31'),
};
timeBuckets.setBounds(bounds);
let timeBucketsBounds = timeBuckets.getBounds();

expect(timeBucketsBounds).toEqual(bounds);

timeBuckets.setBounds();
timeBucketsBounds = timeBuckets.getBounds();

expect(timeBucketsBounds).toBeUndefined();
});

test('setInterval/getInterval - intreval is a string', () => {
const timeBuckets = new TimeBuckets({ uiSettings });
timeBuckets.setInterval('20m');
const interval = timeBuckets.getInterval();

expect(interval.description).toEqual('20 minutes');
expect(interval.esValue).toEqual(20);
expect(interval.esUnit).toEqual('m');
expect(interval.expression).toEqual('20m');
});

test('setInterval/getInterval - intreval is a string and bounds is defined', () => {
const timeBuckets = new TimeBuckets({ uiSettings });
const bounds: Bounds = {
min: moment('2020-03-25'),
max: moment('2020-03-31'),
};
timeBuckets.setBounds(bounds);
timeBuckets.setInterval('20m');
const interval = timeBuckets.getInterval();

expect(interval.description).toEqual('day');
expect(interval.esValue).toEqual(1);
expect(interval.esUnit).toEqual('d');
expect(interval.expression).toEqual('1d');
expect(interval.scaled).toBeTruthy();
expect(interval.scale).toEqual(0.013888888888888888);

if (interval.preScaled) {
expect(interval.preScaled.description).toEqual('20 minutes');
expect(interval.preScaled.esValue).toEqual(20);
expect(interval.preScaled.esUnit).toEqual('m');
expect(interval.preScaled.expression).toEqual('20m');
}
});

test('setInterval/getInterval - intreval is a "auto"', () => {
const timeBuckets = new TimeBuckets({ uiSettings });
timeBuckets.setInterval('auto');
const interval = timeBuckets.getInterval();

expect(interval.description).toEqual('0 milliseconds');
expect(interval.esValue).toEqual(0);
expect(interval.esUnit).toEqual('ms');
expect(interval.expression).toEqual('0ms');
});

test('getScaledDateFormat', () => {
const timeBuckets = new TimeBuckets({ uiSettings });
timeBuckets.setInterval('20m');
timeBuckets.getScaledDateFormat();
const format = timeBuckets.getScaledDateFormat();
expect(format).toEqual('HH:mm');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/

import _ from 'lodash';
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
import moment from 'moment';
import moment, { Moment } from 'moment';

import { IUiSettingsClient } from 'src/core/public';
import { parseInterval } from '../../../../../../common';
Expand All @@ -29,9 +29,9 @@ import {
EsInterval,
} from './calc_es_interval';

interface Bounds {
min: Date | number | null;
max: Date | number | null;
export interface Bounds {
min: Moment | Date | number | null;
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
max: Moment | Date | number | null;
}

interface TimeBucketsInterval extends moment.Duration {
Expand All @@ -40,8 +40,7 @@ interface TimeBucketsInterval extends moment.Duration {
esValue: EsInterval['value'];
esUnit: EsInterval['unit'];
expression: EsInterval['expression'];
overflow: moment.Duration | boolean;
preScaled?: moment.Duration;
preScaled?: TimeBucketsInterval;
scale?: number;
scaled?: boolean;
}
Expand Down Expand Up @@ -70,8 +69,6 @@ interface TimeBucketsConfig {
* @param {[type]} display [description]
*/
export class TimeBuckets {
private getConfig: (key: string) => any;

private _lb: Bounds['min'] = null;
private _ub: Bounds['max'] = null;
private _originalInterval: string | null = null;
Expand Down Expand Up @@ -170,7 +167,7 @@ export class TimeBuckets {
}

constructor({ uiSettings }: TimeBucketsConfig) {
this.getConfig = (key: string) => uiSettings.get(key);
this.uiSettings = uiSettings;
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
return TimeBuckets.__cached__(this);
}

Expand Down Expand Up @@ -278,11 +275,10 @@ export class TimeBuckets {
* - Any object from src/legacy/ui/agg_types.js
* - "auto"
* - Pass a valid moment unit
* - a moment.duration object.
*
* @param {object|string|moment.duration} input - see desc
*/
setInterval(input: null | string | Record<string, any> | moment.Duration) {
setInterval(input: null | string | Record<string, any>) {
let interval = input;

// selection object -> val
Expand Down Expand Up @@ -351,7 +347,7 @@ export class TimeBuckets {
const readInterval = () => {
const interval = this._i;
if (moment.isDuration(interval)) return interval;
return calcAutoIntervalNear(this.getConfig('histogram:barTarget'), Number(duration));
return calcAutoIntervalNear(this.uiSettings.get('histogram:barTarget'), Number(duration));
};

const parsedInterval = readInterval();
Expand All @@ -362,7 +358,7 @@ export class TimeBuckets {
return interval;
}

const maxLength: number = this.getConfig('histogram:maxBars');
const maxLength: number = this.uiSettings.get('histogram:maxBars');
const approxLen = Number(duration) / Number(interval);

let scaled;
Expand Down Expand Up @@ -396,10 +392,6 @@ export class TimeBuckets {
esValue: esInterval.value,
esUnit: esInterval.unit,
expression: esInterval.expression,
overflow:
Number(duration) > Number(interval)
? moment.duration(Number(interval) - Number(duration))
: false,
});
};

Expand All @@ -423,7 +415,7 @@ export class TimeBuckets {
*/
getScaledDateFormat() {
const interval = this.getInterval();
const rules = this.getConfig('dateFormat:scaled');
const rules = this.uiSettings.get('dateFormat:scaled');

for (let i = rules.length - 1; i >= 0; i--) {
const rule = rules[i];
Expand All @@ -432,6 +424,6 @@ export class TimeBuckets {
}
}

return this.getConfig('dateFormat');
return this.uiSettings.get('dateFormat');
}
}
3 changes: 2 additions & 1 deletion src/plugins/visualizations/public/legacy/build_pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
fieldFormats,
search,
TimefilterContract,
Bounds,
} from '../../../../plugins/data/public';
import { Vis, VisParams } from '../types';
const { isDateHistogramBucketAggConfig } = search.aggs;
Expand Down Expand Up @@ -95,7 +96,7 @@ const getSchemas = (
if (isDateHistogramBucketAggConfig(agg)) {
agg.params.timeRange = timeRange;
const bounds = agg.params.timeRange ? timefilter.calculateBounds(agg.params.timeRange) : null;
agg.buckets.setBounds(agg.fieldIsTimeField() && bounds);
agg.buckets.setBounds(agg.fieldIsTimeField() ? (bounds as Bounds) : undefined);
VladLasitsa marked this conversation as resolved.
Show resolved Hide resolved
agg.buckets.setInterval(agg.params.interval);
}

Expand Down