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

Refactoring overview host to use useSearchStrategy #136206

Merged
merged 3 commits into from
Jul 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,68 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { TestProviders } from '../../../common/mock';
import { useHostOverview } from '.';
import { useSearchStrategy } from '../../../common/containers/use_search_strategy';

jest.mock('../../../common/containers/use_search_strategy', () => ({
useSearchStrategy: jest.fn(),
}));
const mockUseSearchStrategy = useSearchStrategy as jest.Mock;
const mockSearch = jest.fn();

const defaultProps = {
endDate: '2020-07-08T08:20:18.966Z',
hostName: 'my-macbook',
indexNames: ['fakebeat-*'],
skip: false,
startDate: '2020-07-07T08:20:18.966Z',
};

describe('useHostOverview', () => {
beforeEach(() => {
jest.clearAllMocks();
mockUseSearchStrategy.mockReturnValue({
loading: false,
result: {
hostDetails: {},
},
search: mockSearch,
refetch: jest.fn(),
inspect: {},
});
});

it('runs search', () => {
renderHook(() => useHostOverview(defaultProps), {
wrapper: TestProviders,
});

expect(mockSearch).toHaveBeenCalled();
});

it('does not run search when skip = true', () => {
const props = {
...defaultProps,
skip: true,
};
renderHook(() => useHostOverview(props), {
wrapper: TestProviders,
});

expect(mockSearch).not.toHaveBeenCalled();
});
it('skip = true will cancel any running request', () => {
const abortSpy = jest.spyOn(AbortController.prototype, 'abort');
const localProps = {
startDate: '2020-07-07T08:20:18.966Z',
endDate: '2020-07-08T08:20:18.966Z',
indexNames: ['cool'],
skip: false,
const props = {
...defaultProps,
};
const { rerender } = renderHook(() => useHostOverview(localProps), {
const { rerender } = renderHook(() => useHostOverview(props), {
wrapper: TestProviders,
});
localProps.skip = true;
props.skip = true;
act(() => rerender());
expect(abortSpy).toHaveBeenCalledTimes(4);
expect(mockUseSearchStrategy).toHaveBeenCalledTimes(2);
expect(mockUseSearchStrategy.mock.calls[1][0].abort).toEqual(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,16 @@
* 2.0.
*/

import { noop } from 'lodash/fp';
import { useCallback, useEffect, useRef, useState } from 'react';
import deepEqual from 'fast-deep-equal';
import { Subscription } from 'rxjs';
import { useEffect, useMemo } from 'react';

import { isCompleteResponse, isErrorResponse } from '@kbn/data-plugin/common';
import type {
HostOverviewRequestOptions,
HostsOverviewStrategyResponse,
} from '../../../../common/search_strategy/security_solution';
import type { HostsOverviewStrategyResponse } from '../../../../common/search_strategy/security_solution';
import { HostsQueries } from '../../../../common/search_strategy/security_solution';
import { useKibana } from '../../../common/lib/kibana';
import type { inputsModel } from '../../../common/store/inputs';
import { createFilter } from '../../../common/containers/helpers';
import type { ESQuery } from '../../../../common/typed_json';
import { getInspectResponse } from '../../../helpers';
import type { InspectResponse } from '../../../types';
import * as i18n from './translations';
import { useAppToasts } from '../../../common/hooks/use_app_toasts';
import { useSearchStrategy } from '../../../common/containers/use_search_strategy';

export const ID = 'overviewHostQuery';

Expand All @@ -50,108 +41,53 @@ export const useHostOverview = ({
skip = false,
startDate,
}: UseHostOverview): [boolean, HostOverviewArgs] => {
const { data } = useKibana().services;
const refetch = useRef<inputsModel.Refetch>(noop);
const abortCtrl = useRef(new AbortController());
const searchSubscription$ = useRef(new Subscription());
const [loading, setLoading] = useState(false);
const [overviewHostRequest, setHostRequest] = useState<HostOverviewRequestOptions | null>(null);

const [overviewHostResponse, setHostOverviewResponse] = useState<HostOverviewArgs>({
overviewHost: {},
id: ID,
inspect: {
dsl: [],
response: [],
const {
loading,
result: response,
search,
refetch,
inspect,
} = useSearchStrategy<HostsQueries.overview>({
factoryQueryType: HostsQueries.overview,
initialResult: {
overviewHost: {},
},
isInspected: false,
refetch: refetch.current,
errorMessage: i18n.FAIL_HOST_OVERVIEW,
abort: skip,
});
const { addError, addWarning } = useAppToasts();

const overviewHostSearch = useCallback(
(request: HostOverviewRequestOptions | null) => {
if (request == null || skip) {
return;
}

const asyncSearch = async () => {
abortCtrl.current = new AbortController();
setLoading(true);

searchSubscription$.current = data.search
.search<HostOverviewRequestOptions, HostsOverviewStrategyResponse>(request, {
strategy: 'securitySolutionSearchStrategy',
abortSignal: abortCtrl.current.signal,
})
.subscribe({
next: (response) => {
if (isCompleteResponse(response)) {
setLoading(false);
setHostOverviewResponse((prevResponse) => ({
...prevResponse,
overviewHost: response.overviewHost,
inspect: getInspectResponse(response, prevResponse.inspect),
refetch: refetch.current,
}));
searchSubscription$.current.unsubscribe();
} else if (isErrorResponse(response)) {
setLoading(false);
addWarning(i18n.ERROR_HOST_OVERVIEW);
searchSubscription$.current.unsubscribe();
}
},
error: (msg) => {
setLoading(false);
addError(msg, {
title: i18n.FAIL_HOST_OVERVIEW,
});
searchSubscription$.current.unsubscribe();
},
});
};
searchSubscription$.current.unsubscribe();
abortCtrl.current.abort();
asyncSearch();
refetch.current = asyncSearch;
},
[data.search, addError, addWarning, skip]
const overviewHostResponse = useMemo(
() => ({
endDate,
overviewHost: response.overviewHost,
id: ID,
inspect,
isInspected: false,
refetch,
startDate,
}),
[endDate, inspect, refetch, response.overviewHost, startDate]
);

useEffect(() => {
setHostRequest((prevRequest) => {
const myRequest = {
...(prevRequest ?? {}),
defaultIndex: indexNames,
factoryQueryType: HostsQueries.overview,
filterQuery: createFilter(filterQuery),
timerange: {
interval: '12h',
from: startDate,
to: endDate,
},
};
if (!deepEqual(prevRequest, myRequest)) {
return myRequest;
}
return prevRequest;
});
}, [indexNames, endDate, filterQuery, startDate]);

useEffect(() => {
overviewHostSearch(overviewHostRequest);
return () => {
searchSubscription$.current.unsubscribe();
abortCtrl.current.abort();
};
}, [overviewHostRequest, overviewHostSearch]);
const overviewHostRequest = useMemo(
() => ({
defaultIndex: indexNames,
factoryQueryType: HostsQueries.overview,
filterQuery: createFilter(filterQuery),
timerange: {
interval: '12h',
from: startDate,
to: endDate,
},
}),
[endDate, filterQuery, indexNames, startDate]
);

useEffect(() => {
if (skip) {
searchSubscription$.current.unsubscribe();
abortCtrl.current.abort();
if (!skip) {
search(overviewHostRequest);
}
}, [skip]);
}, [overviewHostRequest, search, skip]);

return [loading, overviewHostResponse];
};