Skip to content

Commit

Permalink
Added tests and logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Liza K committed Feb 15, 2021
1 parent 5fdf18e commit e973a79
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 29 deletions.
94 changes: 94 additions & 0 deletions x-pack/plugins/data_enhanced/server/collectors/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import {
SharedGlobalConfig,
ElasticsearchClient,
SavedObjectsErrorHelpers,
Logger,
} from '../../../../../src/core/server';
import { BehaviorSubject } from 'rxjs';
import { fetchProvider } from './fetch';
import { elasticsearchServiceMock } from '../../../../../src/core/server/mocks';

describe('fetchProvider', () => {
let fetchFn: any;
let esClient: jest.Mocked<ElasticsearchClient>;
let mockLogger: Logger;

beforeEach(async () => {
const config$ = new BehaviorSubject<SharedGlobalConfig>({
kibana: {
index: '123',
},
} as any);
mockLogger = {
warn: jest.fn(),
debug: jest.fn(),
} as any;
esClient = elasticsearchServiceMock.createElasticsearchClient();
fetchFn = fetchProvider(config$, mockLogger);
});

test('returns when ES returns no results', async () => {
esClient.search.mockResolvedValue({
statusCode: 200,
body: {
aggregations: {
persisted: {
buckets: [],
},
},
},
} as any);

const collRes = await fetchFn({ esClient });
expect(collRes.transientCount).toBe(0);
expect(collRes.persistedCount).toBe(0);
expect(collRes.totalCount).toBe(0);
expect(mockLogger.warn).not.toBeCalled();
});

test('returns when ES throws an error', async () => {
esClient.search.mockRejectedValue(
SavedObjectsErrorHelpers.createTooManyRequestsError('a', 'b')
);

const collRes = await fetchFn({ esClient });
expect(collRes.transientCount).toBe(0);
expect(collRes.persistedCount).toBe(0);
expect(collRes.totalCount).toBe(0);
expect(mockLogger.warn).toBeCalledTimes(1);
});

test('returns when ES returns full buckets', async () => {
esClient.search.mockResolvedValue({
statusCode: 200,
body: {
aggregations: {
persisted: {
buckets: [
{
key_as_string: 'true',
doc_count: 10,
},
{
key_as_string: 'false',
doc_count: 7,
},
],
},
},
},
} as any);

const collRes = await fetchFn({ esClient });
expect(collRes.transientCount).toBe(7);
expect(collRes.persistedCount).toBe(10);
expect(collRes.totalCount).toBe(17);
});
});
56 changes: 31 additions & 25 deletions x-pack/plugins/data_enhanced/server/collectors/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
import { SearchResponse } from 'elasticsearch';
import { SharedGlobalConfig } from 'kibana/server';
import { SharedGlobalConfig, Logger } from 'kibana/server';
import { CollectorFetchContext } from '../../../../../src/plugins/usage_collection/server';
import { SEARCH_SESSION_TYPE } from '../../common';
import { ReportedUsage } from './register';
Expand All @@ -18,36 +18,42 @@ interface SessionPersistedTermsBucket {
doc_count: number;
}

export function fetchProvider(config$: Observable<SharedGlobalConfig>) {
export function fetchProvider(config$: Observable<SharedGlobalConfig>, logger: Logger) {
return async ({ esClient }: CollectorFetchContext): Promise<ReportedUsage> => {
const config = await config$.pipe(first()).toPromise();
const { body: esResponse } = await esClient.search<SearchResponse<unknown>>({
index: config.kibana.index,
body: {
size: 0,
aggs: {
persisted: {
terms: {
field: `${SEARCH_SESSION_TYPE}.persisted`,
try {
const config = await config$.pipe(first()).toPromise();
const { body: esResponse } = await esClient.search<SearchResponse<unknown>>({
index: config.kibana.index,
body: {
size: 0,
aggs: {
persisted: {
terms: {
field: `${SEARCH_SESSION_TYPE}.persisted`,
},
},
},
},
},
});
});

const { buckets } = esResponse.aggregations.persisted;
if (!buckets.length) {
const { buckets } = esResponse.aggregations.persisted;
if (!buckets.length) {
return { transientCount: 0, persistedCount: 0, totalCount: 0 };
}

const { transientCount = 0, persistedCount = 0 } = buckets.reduce(
(usage: Partial<ReportedUsage>, bucket: SessionPersistedTermsBucket) => {
const key = bucket.key_as_string === 'false' ? 'transientCount' : 'persistedCount';
return { ...usage, [key]: bucket.doc_count };
},
{}
);
const totalCount = transientCount + persistedCount;
logger.debug(`fetchProvider | ${persistedCount} persisted | ${transientCount} transient`);
return { transientCount, persistedCount, totalCount };
} catch (e) {
logger.warn(`fetchProvider | error | ${e.message}`);
return { transientCount: 0, persistedCount: 0, totalCount: 0 };
}

const { transientCount = 0, persistedCount = 0 } = buckets.reduce(
(usage: Partial<ReportedUsage>, bucket: SessionPersistedTermsBucket) => {
const key = bucket.key_as_string === 'false' ? 'transientCount' : 'persistedCount';
return { ...usage, [key]: bucket.doc_count };
},
{}
);
const totalCount = transientCount + persistedCount;
return { transientCount, persistedCount, totalCount };
};
}
7 changes: 4 additions & 3 deletions x-pack/plugins/data_enhanced/server/collectors/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { PluginInitializerContext } from 'kibana/server';
import { PluginInitializerContext, Logger } from 'kibana/server';
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { fetchProvider } from './fetch';

Expand All @@ -17,13 +17,14 @@ export interface ReportedUsage {

export async function registerUsageCollector(
usageCollection: UsageCollectionSetup,
context: PluginInitializerContext
context: PluginInitializerContext,
logger: Logger
) {
try {
const collector = usageCollection.makeUsageCollector<ReportedUsage>({
type: 'search-session',
isReady: () => true,
fetch: fetchProvider(context.config.legacy.globalConfig$),
fetch: fetchProvider(context.config.legacy.globalConfig$, logger),
schema: {
transientCount: { type: 'long' },
persistedCount: { type: 'long' },
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/data_enhanced/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export class EnhancedDataServerPlugin
});

if (deps.usageCollection) {
registerUsageCollector(deps.usageCollection, this.initializerContext);
registerUsageCollector(deps.usageCollection, this.initializerContext, this.logger);
}
}

Expand Down

0 comments on commit e973a79

Please sign in to comment.