Skip to content

Commit

Permalink
[data.search.aggs] Remove date histogram dependency on timefilter (el…
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeelmers authored and Bamieh committed Jul 1, 2020
1 parent b3bc03d commit b4d0967
Show file tree
Hide file tree
Showing 27 changed files with 149 additions and 66 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) &gt; [getTime](./kibana-plugin-plugins-data-server.gettime.md)

## getTime() function

<b>Signature:</b>

```typescript
export declare function getTime(indexPattern: IIndexPattern | undefined, timeRange: TimeRange, options?: {
forceNow?: Date;
fieldName?: string;
}): import("../..").RangeFilter | undefined;
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| indexPattern | <code>IIndexPattern &#124; undefined</code> | |
| timeRange | <code>TimeRange</code> | |
| options | <code>{</code><br/><code> forceNow?: Date;</code><br/><code> fieldName?: string;</code><br/><code>}</code> | |

<b>Returns:</b>

`import("../..").RangeFilter | undefined`

Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
| Function | Description |
| --- | --- |
| [getDefaultSearchParams(config)](./kibana-plugin-plugins-data-server.getdefaultsearchparams.md) | |
| [getTime(indexPattern, timeRange, options)](./kibana-plugin-plugins-data-server.gettime.md) | |
| [parseInterval(interval)](./kibana-plugin-plugins-data-server.parseinterval.md) | |
| [plugin(initializerContext)](./kibana-plugin-plugins-data-server.plugin.md) | Static code to be shared externally |
| [shouldReadFieldFromDocValues(aggregatable, esType)](./kibana-plugin-plugins-data-server.shouldreadfieldfromdocvalues.md) | |
Expand Down
1 change: 0 additions & 1 deletion src/plugins/data/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,5 @@ export * from './kbn_field_types';
export * from './query';
export * from './search';
export * from './search/aggs';
export * from './timefilter';
export * from './types';
export * from './utils';
1 change: 1 addition & 0 deletions src/plugins/data/common/query/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
*/

export * from './filter_manager';
export * from './timefilter';
export * from './types';
export * from './is_query';
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@
*/

import dateMath from '@elastic/datemath';
import { IIndexPattern } from '../..';
import { TimeRange, buildRangeFilter } from '../../../common';
import { buildRangeFilter, IIndexPattern, TimeRange, TimeRangeBounds } from '../..';

interface CalculateBoundsOptions {
forceNow?: Date;
}

export function calculateBounds(timeRange: TimeRange, options: CalculateBoundsOptions = {}) {
export function calculateBounds(
timeRange: TimeRange,
options: CalculateBoundsOptions = {}
): TimeRangeBounds {
return {
min: dateMath.parse(timeRange.from, { forceNow: options.forceNow }),
max: dateMath.parse(timeRange.to, { roundUp: true, forceNow: options.forceNow }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@
* under the License.
*/

export { isTimeRange } from './is_time_range';
export * from './get_time';
export * from './is_time_range';
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* under the License.
*/

import { Moment } from 'moment';

export interface RefreshInterval {
pause: boolean;
value: number;
Expand All @@ -27,3 +29,8 @@ export interface TimeRange {
to: string;
mode?: 'absolute' | 'relative';
}

export interface TimeRangeBounds {
min: Moment | undefined;
max: Moment | undefined;
}
2 changes: 2 additions & 0 deletions src/plugins/data/common/query/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* under the License.
*/

export * from './timefilter/types';

export interface Query {
query: string | { [key: string]: any };
language: string;
Expand Down
1 change: 0 additions & 1 deletion src/plugins/data/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
* under the License.
*/

export * from './timefilter/types';
export * from './query/types';
export * from './kbn_field_types/types';
export * from './index_patterns/types';
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/data/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,6 @@ export {
connectToQueryState,
syncQueryStateWithUrl,
QueryState,
getTime,
getQueryLog,
getDefaultQuery,
FilterManager,
Expand All @@ -435,6 +434,7 @@ export {
} from './query';

export {
getTime,
// kbn field types
castEsToKbnFieldTypeName,
getKbnTypeNames,
Expand Down
1 change: 0 additions & 1 deletion src/plugins/data/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ export class DataPublicPlugin implements Plugin<DataPublicPluginSetup, DataPubli
expressions,
getInternalStartServices,
packageInfo: this.packageInfo,
query: queryService,
}),
fieldFormats: this.fieldFormatsService.setup(core),
query: queryService,
Expand Down
1 change: 0 additions & 1 deletion src/plugins/data/public/query/timefilter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,5 @@ export { TimefilterService, TimefilterSetup } from './timefilter_service';
export * from './types';
export { Timefilter, TimefilterContract } from './timefilter';
export { TimeHistory, TimeHistoryContract } from './time_history';
export { getTime, calculateBounds } from './get_time';
export { changeTimeFilter, convertRangeFilterToTimeRangeString } from './lib/change_time_filter';
export { extractTimeFilter } from './lib/extract_time_filter';
34 changes: 34 additions & 0 deletions src/plugins/data/public/query/timefilter/lib/get_force_now.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* 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 { parseQueryString } from './parse_querystring';

/** @internal */
export function getForceNow() {
const forceNow = parseQueryString().forceNow as string;
if (!forceNow) {
return;
}

const ticks = Date.parse(forceNow);
if (isNaN(ticks)) {
throw new Error(`forceNow query parameter, ${forceNow}, can't be parsed by Date.parse`);
}
return new Date(ticks);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
import { parse } from 'query-string';

/** @internal */
export function parseQueryString() {
// window.location.search is an empty string
// get search from href
Expand Down
16 changes: 3 additions & 13 deletions src/plugins/data/public/query/timefilter/timefilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ import _ from 'lodash';
import { Subject, BehaviorSubject } from 'rxjs';
import moment from 'moment';
import { areRefreshIntervalsDifferent, areTimeRangesDifferent } from './lib/diff_time_picker_vals';
import { parseQueryString } from './lib/parse_querystring';
import { calculateBounds, getTime } from './get_time';
import { getForceNow } from './lib/get_force_now';
import { TimefilterConfig, InputTimeRange, TimeRangeBounds } from './types';
import { RefreshInterval, TimeRange } from '../../../common';
import { calculateBounds, getTime, RefreshInterval, TimeRange } from '../../../common';
import { TimeHistoryContract } from './time_history';
import { IndexPattern } from '../../index_patterns';

Expand Down Expand Up @@ -224,16 +223,7 @@ export class Timefilter {
}

private getForceNow = () => {
const forceNow = parseQueryString().forceNow as string;
if (!forceNow) {
return;
}

const ticks = Date.parse(forceNow);
if (isNaN(ticks)) {
throw new Error(`forceNow query parameter, ${forceNow}, can't be parsed by Date.parse`);
}
return new Date(ticks);
return getForceNow();
};
}

Expand Down
7 changes: 3 additions & 4 deletions src/plugins/data/public/query/timefilter/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/

import { Moment } from 'moment';

import { TimeRange, RefreshInterval } from '../../../common';

export interface TimefilterConfig {
Expand All @@ -32,7 +34,4 @@ export type InputTimeRange =
to: Moment;
};

export interface TimeRangeBounds {
min: Moment | undefined;
max: Moment | undefined;
}
export { TimeRangeBounds } from '../../../common';
15 changes: 7 additions & 8 deletions src/plugins/data/public/search/aggs/agg_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
*/

import { IUiSettingsClient } from 'src/core/public';
import { QuerySetup } from '../../query/query_service';
import { TimeRange, TimeRangeBounds } from '../../../common';
import { GetInternalStartServicesFn } from '../../types';

import { getCountMetricAgg } from './metrics/count';
import { getAvgMetricAgg } from './metrics/avg';
Expand Down Expand Up @@ -54,18 +55,16 @@ import { getBucketAvgMetricAgg } from './metrics/bucket_avg';
import { getBucketMinMetricAgg } from './metrics/bucket_min';
import { getBucketMaxMetricAgg } from './metrics/bucket_max';

import { GetInternalStartServicesFn } from '../../types';

export interface AggTypesDependencies {
uiSettings: IUiSettingsClient;
query: QuerySetup;
calculateBounds: (timeRange: TimeRange) => TimeRangeBounds;
getInternalStartServices: GetInternalStartServicesFn;
uiSettings: IUiSettingsClient;
}

export const getAggTypes = ({
uiSettings,
query,
calculateBounds,
getInternalStartServices,
uiSettings,
}: AggTypesDependencies) => ({
metrics: [
getCountMetricAgg({ getInternalStartServices }),
Expand All @@ -91,7 +90,7 @@ export const getAggTypes = ({
getGeoCentroidMetricAgg({ getInternalStartServices }),
],
buckets: [
getDateHistogramBucketAgg({ uiSettings, query, getInternalStartServices }),
getDateHistogramBucketAgg({ calculateBounds, uiSettings, getInternalStartServices }),
getHistogramBucketAgg({ uiSettings, getInternalStartServices }),
getRangeBucketAgg({ getInternalStartServices }),
getDateRangeBucketAgg({ uiSettings, getInternalStartServices }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
import { BUCKET_TYPES } from '../bucket_agg_types';
import { RangeFilter } from '../../../../../common';
import { coreMock, notificationServiceMock } from '../../../../../../../core/public/mocks';
import { queryServiceMock } from '../../../../query/mocks';
import { fieldFormatsServiceMock } from '../../../../field_formats/mocks';
import { InternalStartServices } from '../../../../types';

Expand All @@ -46,13 +45,13 @@ describe('AggConfig Filters', () => {
const { uiSettings } = coreMock.createSetup();

aggTypesDependencies = {
uiSettings,
query: queryServiceMock.createSetupContract(),
calculateBounds: jest.fn(),
getInternalStartServices: () =>
(({
fieldFormats: fieldFormatsServiceMock.createStartContract(),
notifications: notificationServiceMock.createStartContract(),
} as unknown) as InternalStartServices),
uiSettings,
};

mockDataServices();
Expand Down
34 changes: 18 additions & 16 deletions src/plugins/data/public/search/aggs/buckets/date_histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,38 +27,40 @@ import { BucketAggType, IBucketAggConfig } from './bucket_agg_type';
import { BUCKET_TYPES } from './bucket_agg_types';
import { createFilterDateHistogram } from './create_filter/date_histogram';
import { intervalOptions } from './_interval_options';
import { dateHistogramInterval, TimeRange } from '../../../../common';
import { writeParams } from '../agg_params';
import { isMetricAggType } from '../metrics/metric_agg_type';

import { KBN_FIELD_TYPES, UI_SETTINGS } from '../../../../common';
import { TimefilterContract } from '../../../query';
import { QuerySetup } from '../../../query/query_service';
import {
dateHistogramInterval,
KBN_FIELD_TYPES,
TimeRange,
TimeRangeBounds,
UI_SETTINGS,
} from '../../../../common';
import { GetInternalStartServicesFn } from '../../../types';
import { BaseAggParams } from '../types';
import { ExtendedBounds } from './lib/extended_bounds';

const detectedTimezone = moment.tz.guess();
const tzOffset = moment().format('Z');
type CalculateBoundsFn = (timeRange: TimeRange) => TimeRangeBounds;

const updateTimeBuckets = (
agg: IBucketDateHistogramAggConfig,
timefilter: TimefilterContract,
calculateBounds: CalculateBoundsFn,
customBuckets?: IBucketDateHistogramAggConfig['buckets']
) => {
const bounds =
agg.params.timeRange && (agg.fieldIsTimeField() || agg.params.interval === 'auto')
? timefilter.calculateBounds(agg.params.timeRange)
? calculateBounds(agg.params.timeRange)
: undefined;
const buckets = customBuckets || agg.buckets;
buckets.setBounds(bounds);
buckets.setInterval(agg.params.interval);
};

export interface DateHistogramBucketAggDependencies {
uiSettings: IUiSettingsClient;
query: QuerySetup;
calculateBounds: CalculateBoundsFn;
getInternalStartServices: GetInternalStartServicesFn;
uiSettings: IUiSettingsClient;
}

export interface IBucketDateHistogramAggConfig extends IBucketAggConfig {
Expand All @@ -83,9 +85,9 @@ export interface AggParamsDateHistogram extends BaseAggParams {
}

export const getDateHistogramBucketAgg = ({
uiSettings,
query,
calculateBounds,
getInternalStartServices,
uiSettings,
}: DateHistogramBucketAggDependencies) =>
new BucketAggType<IBucketDateHistogramAggConfig>(
{
Expand Down Expand Up @@ -123,14 +125,13 @@ export const getDateHistogramBucketAgg = ({
get() {
if (buckets) return buckets;

const { timefilter } = query.timefilter;
buckets = new TimeBuckets({
'histogram:maxBars': uiSettings.get(UI_SETTINGS.HISTOGRAM_MAX_BARS),
'histogram:barTarget': uiSettings.get(UI_SETTINGS.HISTOGRAM_BAR_TARGET),
dateFormat: uiSettings.get('dateFormat'),
'dateFormat:scaled': uiSettings.get('dateFormat:scaled'),
});
updateTimeBuckets(this, timefilter, buckets);
updateTimeBuckets(this, calculateBounds, buckets);

return buckets;
},
Expand Down Expand Up @@ -195,8 +196,7 @@ export const getDateHistogramBucketAgg = ({
default: 'auto',
options: intervalOptions,
write(agg, output, aggs) {
const { timefilter } = query.timefilter;
updateTimeBuckets(agg, timefilter);
updateTimeBuckets(agg, calculateBounds);

const { useNormalizedEsInterval, scaleMetricValues } = agg.params;
const interval = agg.buckets.getInterval(useNormalizedEsInterval);
Expand Down Expand Up @@ -257,6 +257,8 @@ export const getDateHistogramBucketAgg = ({
if (!tz) {
// If the index pattern typeMeta data, didn't had a time zone assigned for the selected field use the configured tz
const isDefaultTimezone = uiSettings.isDefault('dateFormat:tz');
const detectedTimezone = moment.tz.guess();
const tzOffset = moment().format('Z');
tz = isDefaultTimezone
? detectedTimezone || tzOffset
: uiSettings.get('dateFormat:tz');
Expand Down
Loading

0 comments on commit b4d0967

Please sign in to comment.