diff --git a/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.test.ts b/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.test.ts index 94daa0030cd600..15f5a37edb910e 100644 --- a/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.test.ts +++ b/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.test.ts @@ -33,6 +33,10 @@ describe('wrapScopedClusterClient', () => { jest.useRealTimers(); }); + afterEach(() => { + jest.resetAllMocks(); + }); + test('searches with asInternalUser when specified', async () => { const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); const childClient = elasticsearchServiceMock.createElasticsearchClient(); @@ -119,6 +123,35 @@ describe('wrapScopedClusterClient', () => { ).rejects.toThrowErrorMatchingInlineSnapshot(`"something went wrong!"`); }); + test('handles empty search result object', async () => { + const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const childClient = elasticsearchServiceMock.createElasticsearchClient(); + + ( + scopedClusterClient.asInternalUser as unknown as jest.Mocked + ).child.mockReturnValue(childClient as unknown as Client); + const asInternalUserWrappedSearchFn = childClient.search; + // @ts-ignore incomplete return type + asInternalUserWrappedSearchFn.mockResolvedValue({}); + + const wrappedSearchClientFactory = createWrappedScopedClusterClientFactory({ + scopedClusterClient, + rule, + logger, + }); + + const wrappedSearchClient = wrappedSearchClientFactory.client(); + await wrappedSearchClient.asInternalUser.search(esQuery); + + expect(asInternalUserWrappedSearchFn).toHaveBeenCalledTimes(1); + expect(scopedClusterClient.asInternalUser.search).not.toHaveBeenCalled(); + expect(scopedClusterClient.asCurrentUser.search).not.toHaveBeenCalled(); + + const stats = wrappedSearchClientFactory.getMetrics(); + expect(stats.numSearches).toEqual(1); + expect(stats.esSearchDurationMs).toEqual(0); + }); + test('keeps track of number of queries', async () => { const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); const childClient = elasticsearchServiceMock.createElasticsearchClient(); diff --git a/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.ts b/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.ts index 00ee3302c88c51..dfe32a48ce4384 100644 --- a/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.ts +++ b/x-pack/plugins/alerting/server/lib/wrap_scoped_cluster_client.ts @@ -158,7 +158,7 @@ function getWrappedSearchFn(opts: WrapEsClientOpts) { took = (result as SearchResponse).took; } - opts.logMetricsFn({ esSearchDuration: took, totalSearchDuration: durationMs }); + opts.logMetricsFn({ esSearchDuration: took ?? 0, totalSearchDuration: durationMs }); return result; } catch (e) { throw e;