Skip to content

Commit

Permalink
Improve inspector adapter typings.
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeelmers committed Nov 11, 2020
1 parent 0476f73 commit 17715c7
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 87 deletions.
4 changes: 2 additions & 2 deletions src/plugins/data/common/search/aggs/agg_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export interface AggTypeConfig<
aggConfigs: IAggConfigs,
aggConfig: TAggConfig,
searchSource: ISearchSource,
inspectorRequestAdapter: RequestAdapter,
inspectorRequestAdapter?: RequestAdapter,
abortSignal?: AbortSignal
) => Promise<any>;
getSerializedFormat?: (agg: TAggConfig) => SerializedFieldFormat;
Expand Down Expand Up @@ -189,7 +189,7 @@ export class AggType<
aggConfigs: IAggConfigs,
aggConfig: TAggConfig,
searchSource: ISearchSource,
inspectorRequestAdapter: RequestAdapter,
inspectorRequestAdapter?: RequestAdapter,
abortSignal?: AbortSignal
) => Promise<any>;
/**
Expand Down
42 changes: 24 additions & 18 deletions src/plugins/data/common/search/aggs/buckets/terms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import { noop } from 'lodash';
import { i18n } from '@kbn/i18n';
import type { RequestAdapter } from 'src/plugins/inspector/common';

import { BucketAggType, IBucketAggConfig } from './bucket_agg_type';
import { BUCKET_TYPES } from './bucket_agg_types';
Expand Down Expand Up @@ -111,27 +112,32 @@ export const getTermsBucketAgg = () =>

nestedSearchSource.setField('aggs', filterAgg);

const request = inspectorRequestAdapter.start(
i18n.translate('data.search.aggs.buckets.terms.otherBucketTitle', {
defaultMessage: 'Other bucket',
}),
{
description: i18n.translate('data.search.aggs.buckets.terms.otherBucketDescription', {
defaultMessage:
'This request counts the number of documents that fall ' +
'outside the criterion of the data buckets.',
let request: ReturnType<RequestAdapter['start']> | undefined;
if (inspectorRequestAdapter) {
request = inspectorRequestAdapter.start(
i18n.translate('data.search.aggs.buckets.terms.otherBucketTitle', {
defaultMessage: 'Other bucket',
}),
}
);
nestedSearchSource.getSearchRequestBody().then((body) => {
request.json(body);
});
request.stats(getRequestInspectorStats(nestedSearchSource));
{
description: i18n.translate('data.search.aggs.buckets.terms.otherBucketDescription', {
defaultMessage:
'This request counts the number of documents that fall ' +
'outside the criterion of the data buckets.',
}),
}
);
nestedSearchSource.getSearchRequestBody().then((body) => {
request!.json(body);
});
request.stats(getRequestInspectorStats(nestedSearchSource));
}

const response = await nestedSearchSource.fetch({ abortSignal });
request
.stats(getResponseInspectorStats(response, nestedSearchSource))
.ok({ json: response });
if (request) {
request
.stats(getResponseInspectorStats(response, nestedSearchSource))
.ok({ json: response });
}
resp = mergeOtherBucketAggResponse(aggConfigs, resp, response, aggConfig, filterAgg());
}
if (aggConfig.params.missingBucket) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ import { createFilter } from '../create_filter';
export async function buildTabularInspectorData(
table: TabbedTable,
{
addFilters,
deserializeFieldFormat,
queryFilter,
}: {
addFilters?: FilterManager['addFilters'];
deserializeFieldFormat: FormatFactory;
queryFilter?: Pick<FilterManager, 'addFilters'>;
}
): Promise<TabularData> {
const aggConfigs = table.columns.map((column) => column.aggConfig);
Expand Down Expand Up @@ -71,7 +71,7 @@ export async function buildTabularInspectorData(
name: col.name,
field: `col-${colIndex}-${col.aggConfig.id}`,
filter:
queryFilter &&
addFilters &&
isCellContentFilterable &&
((value: TabularDataValue) => {
const rowIndex = rows.findIndex(
Expand All @@ -80,11 +80,11 @@ export async function buildTabularInspectorData(
const filter = createFilter(aggConfigs, table, colIndex, rowIndex, value.raw);

if (filter) {
queryFilter.addFilters(filter);
addFilters(filter);
}
}),
filterOut:
queryFilter &&
addFilters &&
isCellContentFilterable &&
((value: TabularDataValue) => {
const rowIndex = rows.findIndex(
Expand All @@ -100,7 +100,7 @@ export async function buildTabularInspectorData(
} else {
set(filter, 'meta.negate', notOther && notMissing);
}
queryFilter.addFilters(filter);
addFilters(filter);
}
}),
};
Expand Down
17 changes: 9 additions & 8 deletions src/plugins/data/public/search/expressions/esaggs/esaggs_fn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,19 +90,20 @@ export const esaggs = (): EsaggsExpressionFunctionDefinition => ({
const resolvedTimeRange = input?.timeRange && calculateBounds(input.timeRange);

const response = await handleRequest({
searchSource,
abortSignal: (abortSignal as unknown) as AbortSignal,
addFilters: filterManager.addFilters,
aggs,
indexPattern,
timeRange: get(input, 'timeRange', undefined),
query: get(input, 'query', undefined) as any,
deserializeFieldFormat: getFieldFormats().deserialize,
filters: get(input, 'filters', undefined),
timeFields: args.timeFields,
indexPattern,
inspectorAdapters: inspectorAdapters as Adapters,
metricsAtAllLevels: args.metricsAtAllLevels,
partialRows: args.partialRows,
inspectorAdapters: inspectorAdapters as Adapters,
filterManager,
abortSignal: (abortSignal as unknown) as AbortSignal,
query: get(input, 'query', undefined) as any,
searchSessionId: getSearchSessionId(),
searchSource,
timeFields: args.timeFields,
timeRange: get(input, 'timeRange', undefined),
});

const table: Datatable = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { buildTabularInspectorData } from './build_tabular_inspector_data';

interface RequestHandlerParams {
abortSignal?: AbortSignal;
addFilters?: FilterManager['addFilters'];
aggs: IAggConfigs;
deserializeFieldFormat: FormatFactory;
filters?: Filter[];
Expand All @@ -51,7 +52,6 @@ interface RequestHandlerParams {
metricsAtAllLevels?: boolean;
partialRows?: boolean;
query?: Query;
queryFilter?: Pick<FilterManager, 'addFilters'>;
searchSessionId?: string;
searchSource: ISearchSource;
timeFields?: string[];
Expand All @@ -60,6 +60,7 @@ interface RequestHandlerParams {

export const handleRequest = async ({
abortSignal,
addFilters,
aggs,
deserializeFieldFormat,
filters,
Expand All @@ -68,7 +69,6 @@ export const handleRequest = async ({
metricsAtAllLevels,
partialRows,
query,
queryFilter,
searchSessionId,
searchSource,
timeFields,
Expand Down Expand Up @@ -124,37 +124,46 @@ export const handleRequest = async ({
requestSearchSource.setField('filter', filters);
requestSearchSource.setField('query', query);

inspectorAdapters.requests.reset();
const request = inspectorAdapters.requests.start(
i18n.translate('data.functions.esaggs.inspector.dataRequest.title', {
defaultMessage: 'Data',
}),
{
description: i18n.translate('data.functions.esaggs.inspector.dataRequest.description', {
defaultMessage:
'This request queries Elasticsearch to fetch the data for the visualization.',
let request;
if (inspectorAdapters.requests) {
inspectorAdapters.requests.reset();
request = inspectorAdapters.requests.start(
i18n.translate('data.functions.esaggs.inspector.dataRequest.title', {
defaultMessage: 'Data',
}),
searchSessionId,
}
);
request.stats(getRequestInspectorStats(requestSearchSource));
{
description: i18n.translate('data.functions.esaggs.inspector.dataRequest.description', {
defaultMessage:
'This request queries Elasticsearch to fetch the data for the visualization.',
}),
searchSessionId,
}
);
request.stats(getRequestInspectorStats(requestSearchSource));
}

try {
const response = await requestSearchSource.fetch({
abortSignal,
sessionId: searchSessionId,
});

request.stats(getResponseInspectorStats(response, searchSource)).ok({ json: response });
if (request) {
request.stats(getResponseInspectorStats(response, searchSource)).ok({ json: response });
}

(searchSource as any).rawResponse = response;
} catch (e) {
// Log any error during request to the inspector
request.error({ json: e });
if (request) {
request.error({ json: e });
}
throw e;
} finally {
// Add the request body no matter if things went fine or not
request.json(await requestSearchSource.getSearchRequestBody());
if (request) {
request.json(await requestSearchSource.getSearchRequestBody());
}
}

// Note that rawResponse is not deeply cloned here, so downstream applications using courier
Expand Down Expand Up @@ -185,14 +194,16 @@ export const handleRequest = async ({

const tabifiedResponse = tabifyAggResponse(aggs, response, tabifyParams);

inspectorAdapters.data.setTabularLoader(
() =>
buildTabularInspectorData(tabifiedResponse, {
queryFilter,
deserializeFieldFormat,
}),
{ returnsFormattedValues: true }
);
if (inspectorAdapters.data) {
inspectorAdapters.data.setTabularLoader(
() =>
buildTabularInspectorData(tabifiedResponse, {
addFilters,
deserializeFieldFormat,
}),
{ returnsFormattedValues: true }
);
}

return tabifiedResponse;
};
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export class SearchEmbeddable
private readonly savedSearch: SavedSearch;
private $rootScope: ng.IRootScopeService;
private $compile: ng.ICompileService;
private inspectorAdaptors: Adapters;
private inspectorAdapters: Adapters;
private searchScope?: SearchScope;
private panelTitle: string = '';
private filtersSearchSource?: ISearchSource;
Expand Down Expand Up @@ -131,7 +131,7 @@ export class SearchEmbeddable
this.savedSearch = savedSearch;
this.$rootScope = $rootScope;
this.$compile = $compile;
this.inspectorAdaptors = {
this.inspectorAdapters = {
requests: new RequestAdapter(),
};
this.initializeSearchScope();
Expand All @@ -150,7 +150,7 @@ export class SearchEmbeddable
}

public getInspectorAdapters() {
return this.inspectorAdaptors;
return this.inspectorAdapters;
}

public getSavedSearch() {
Expand Down Expand Up @@ -195,7 +195,7 @@ export class SearchEmbeddable
const searchScope: SearchScope = (this.searchScope = this.$rootScope.$new());

searchScope.description = this.savedSearch.description;
searchScope.inspectorAdapters = this.inspectorAdaptors;
searchScope.inspectorAdapters = this.inspectorAdapters;

const { searchSource } = this.savedSearch;
const indexPattern = (searchScope.indexPattern = searchSource.getField('index'))!;
Expand Down Expand Up @@ -287,15 +287,15 @@ export class SearchEmbeddable
);

// Log request to inspector
this.inspectorAdaptors.requests.reset();
this.inspectorAdapters.requests!.reset();
const title = i18n.translate('discover.embeddable.inspectorRequestDataTitle', {
defaultMessage: 'Data',
});
const description = i18n.translate('discover.embeddable.inspectorRequestDescription', {
defaultMessage: 'This request queries Elasticsearch to fetch the data for the search.',
});

const inspectorRequest = this.inspectorAdaptors.requests.start(title, {
const inspectorRequest = this.inspectorAdapters.requests!.start(title, {
description,
searchSessionId,
});
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/inspector/common/adapters/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import type { RequestAdapter } from './request';
* The interface that the adapters used to open an inspector have to fullfill.
*/
export interface Adapters {
data: DataAdapter;
requests: RequestAdapter;
data?: DataAdapter;
requests?: RequestAdapter;
[key: string]: any;
}
3 changes: 1 addition & 2 deletions src/plugins/inspector/public/test/is_available.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
*/

import { inspectorPluginMock } from '../mocks';
import { DataAdapter } from '../../common/adapters/data/data_adapter';
import { RequestAdapter } from '../../common/adapters/request/request_adapter';
import { DataAdapter, RequestAdapter } from '../../common/adapters';

const adapter1 = new DataAdapter();
const adapter2 = new RequestAdapter();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class DataViewComponent extends Component<DataViewComponentProps, DataViewCompon
adapters: nextProps.adapters,
tabularData: null,
tabularOptions: {},
tabularPromise: nextProps.adapters.data.getTabular(),
tabularPromise: nextProps.adapters.data!.getTabular(),
};
}

Expand All @@ -82,7 +82,7 @@ class DataViewComponent extends Component<DataViewComponentProps, DataViewCompon
this.setState({
tabularData: null,
tabularOptions: {},
tabularPromise: this.props.adapters.data.getTabular(),
tabularPromise: this.props.adapters.data!.getTabular(),
});
}
};
Expand All @@ -105,13 +105,13 @@ class DataViewComponent extends Component<DataViewComponentProps, DataViewCompon

componentDidMount() {
this._isMounted = true;
this.props.adapters.data.on('change', this.onUpdateData);
this.props.adapters.data!.on('change', this.onUpdateData);
this.finishLoadingData();
}

componentWillUnmount() {
this._isMounted = false;
this.props.adapters.data.removeListener('change', this.onUpdateData);
this.props.adapters.data!.removeListener('change', this.onUpdateData);
}

componentDidUpdate() {
Expand Down
Loading

0 comments on commit 17715c7

Please sign in to comment.