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

remove unneeded usages of isErrorResponse #164609

Merged
merged 23 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
8 changes: 0 additions & 8 deletions examples/search_examples/public/search/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
DataPublicPluginStart,
IKibanaSearchResponse,
isCompleteResponse,
isErrorResponse,
} from '@kbn/data-plugin/public';
import { SearchResponseWarning } from '@kbn/data-plugin/public/search/types';
import type { DataView, DataViewField } from '@kbn/data-views-plugin/public';
Expand Down Expand Up @@ -247,9 +246,6 @@ export const SearchExamplesApp = ({
text: toMountPoint(res.warning),
});
}
} else if (isErrorResponse(res)) {
// TODO: Make response error status clearer
notifications.toasts.addDanger('An error has occurred');
}
},
error: (e) => {
Expand Down Expand Up @@ -401,10 +397,6 @@ export const SearchExamplesApp = ({
title: 'Query result',
text: 'Query finished',
});
} else if (isErrorResponse(res)) {
setIsLoading(false);
// TODO: Make response error status clearer
notifications.toasts.addWarning('An error has occurred');
}
},
error: (e) => {
Expand Down
3 changes: 0 additions & 3 deletions examples/search_examples/public/search_sessions/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import {
IEsSearchRequest,
IEsSearchResponse,
isCompleteResponse,
isErrorResponse,
QueryState,
SearchSessionState,
} from '@kbn/data-plugin/public';
Expand Down Expand Up @@ -724,8 +723,6 @@ function doSearch(
title: 'Query result',
text: mountReactNode(message),
});
} else if (isErrorResponse(res)) {
notifications.toasts.addWarning('An error has occurred');
}
}),
map((res) => ({ response: res, request: req, tookMs: performance.now() - startTs })),
Expand Down
5 changes: 0 additions & 5 deletions examples/search_examples/public/sql_search/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import {
DataPublicPluginStart,
IKibanaSearchResponse,
isCompleteResponse,
isErrorResponse,
} from '@kbn/data-plugin/public';
import {
SQL_SEARCH_STRATEGY,
Expand Down Expand Up @@ -70,10 +69,6 @@ export const SqlSearchExampleApp = ({ notifications, data }: SearchExamplesAppDe
if (isCompleteResponse(res)) {
setIsLoading(false);
setResponse(res);
} else if (isErrorResponse(res)) {
setIsLoading(false);
setResponse(res);
notifications.toasts.addDanger('An error has occurred');
}
},
error: (e) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ import { getRequestInspectorStats, getResponseInspectorStats } from './inspect';
import {
getEsQueryConfig,
IKibanaSearchResponse,
isErrorResponse,
isPartialResponse,
isCompleteResponse,
UI_SETTINGS,
Expand Down Expand Up @@ -547,9 +546,7 @@ export class SearchSource {
// For testing timeout messages in UI, uncomment the next line
// response.rawResponse.timed_out = true;
return new Observable<IKibanaSearchResponse<unknown>>((obs) => {
if (isErrorResponse(response)) {
obs.error(response);
} else if (isPartialResponse(response)) {
if (isPartialResponse(response)) {
obs.next(this.postFlightTransform(response));
} else {
if (!this.hasPostFlightRequests()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { cloneDeep, get } from 'lodash';
import { useRef, useCallback, useMemo } from 'react';
import { isCompleteResponse, isErrorResponse } from '@kbn/data-plugin/public';
import { isCompleteResponse } from '@kbn/data-plugin/public';
import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types';

import { createRandomSamplerWrapper } from '@kbn/ml-random-sampler-utils';
Expand Down Expand Up @@ -110,8 +110,6 @@ export function useCategorizeRequest() {
next: (result) => {
if (isCompleteResponse(result)) {
resolve(processCategoryResults(result, field, unwrap));
} else if (isErrorResponse(result)) {
reject(result);
} else {
// partial results
// Ignore partial results for now.
Expand Down
8 changes: 1 addition & 7 deletions x-pack/plugins/aiops/public/hooks/use_cancellable_search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@
*/

import { useCallback, useRef, useState } from 'react';
import {
type IKibanaSearchResponse,
isCompleteResponse,
isErrorResponse,
} from '@kbn/data-plugin/common';
import { type IKibanaSearchResponse, isCompleteResponse } from '@kbn/data-plugin/common';
import { tap } from 'rxjs/operators';
import { useAiopsAppContext } from './use_aiops_app_context';

Expand Down Expand Up @@ -38,8 +34,6 @@ export function useCancellableSearch() {
if (isCompleteResponse(result)) {
setIsFetching(false);
resolve(result);
} else if (isErrorResponse(result)) {
reject(result);
} else {
// partial results
// Ignore partial results for now.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { useDispatch } from 'react-redux';
import { Subscription } from 'rxjs';
import type { DataView } from '@kbn/data-views-plugin/public';
import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
import { isCompleteResponse, isErrorResponse } from '@kbn/data-plugin/common';
import { isCompleteResponse } from '@kbn/data-plugin/common';
import type {
Inspect,
PaginationInputPaginated,
Expand All @@ -32,8 +32,6 @@ import type { RunTimeMappings } from '../../store/sourcerer/model';
import { TimelineEventsQueries } from '../../../../common/search_strategy';
import type { KueryFilterQueryKind } from '../../../../common/types';
import type { ESQuery } from '../../../../common/typed_json';
import { useAppToasts } from '../../hooks/use_app_toasts';
import { ERROR_TIMELINE_EVENTS } from './translations';
import type { AlertWorkflowStatus } from '../../types';
import { getSearchTransactionName, useStartTransaction } from '../../lib/apm/use_start_transaction';
export type InspectResponse = Inspect & { response: string[] };
Expand Down Expand Up @@ -220,7 +218,6 @@ export const useTimelineEventsHandler = ({
loadPage: wrappedLoadPage,
updatedAt: 0,
});
const { addWarning } = useAppToasts();

const timelineSearch = useCallback(
(request: TimelineRequest<typeof language> | null, onNextHandler?: OnNextResponseHandler) => {
Expand All @@ -233,7 +230,7 @@ export const useTimelineEventsHandler = ({
abortCtrl.current = new AbortController();
setLoading(true);
if (data && data.search) {
const { endTracking } = startTracking();
startTracking();
const abortSignal = abortCtrl.current.signal;
searchSubscription$.current = data.search
.search<TimelineRequest<typeof language>, TimelineResponse<typeof language>>(
Expand Down Expand Up @@ -270,11 +267,6 @@ export const useTimelineEventsHandler = ({
setFilterStatus(request.filterStatus);
setLoading(false);

searchSubscription$.current.unsubscribe();
} else if (isErrorResponse(response)) {
setLoading(false);
endTracking('invalid');
addWarning(ERROR_TIMELINE_EVENTS);
searchSubscription$.current.unsubscribe();
}
},
Expand All @@ -292,7 +284,7 @@ export const useTimelineEventsHandler = ({
asyncSearch();
refetch.current = asyncSearch;
},
[skip, data, entityType, dataViewId, addWarning, startTracking, dispatch, id, prevFilterStatus]
[skip, data, entityType, dataViewId, startTracking, dispatch, id, prevFilterStatus]
);

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
import { isErrorResponse, isCompleteResponse } from '@kbn/data-plugin/common';
import { isCompleteResponse } from '@kbn/data-plugin/common';
import type {
CtiEventEnrichmentRequestOptions,
CtiEventEnrichmentStrategyResponse,
Expand Down Expand Up @@ -46,6 +46,4 @@ export const getEventEnrichment = ({
export const getEventEnrichmentComplete = (
props: GetEventEnrichmentProps
): Observable<CtiEventEnrichmentStrategyResponse> =>
getEventEnrichment(props).pipe(
filter((response) => isErrorResponse(response) || isCompleteResponse(response))
);
getEventEnrichment(props).pipe(filter((response) => isCompleteResponse(response)));
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { noop } from 'lodash/fp';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Subscription } from 'rxjs';

import { isCompleteResponse, isErrorResponse } from '@kbn/data-plugin/common';
import { isCompleteResponse } from '@kbn/data-plugin/common';
import type { inputsModel } from '../../../store';
import { useKibana } from '../../../lib/kibana';
import type {
Expand Down Expand Up @@ -59,7 +59,7 @@ export const useTimelineLastEventTime = ({
refetch: refetch.current,
errorMessage: undefined,
});
const { addError, addWarning } = useAppToasts();
const { addError } = useAppToasts();

const timelineLastEventTimeSearch = useCallback(
(request: TimelineEventsLastEventTimeRequestOptions) => {
Expand All @@ -85,9 +85,6 @@ export const useTimelineLastEventTime = ({
lastSeen: response.lastSeen,
refetch: refetch.current,
}));
} else if (isErrorResponse(response)) {
setLoading(false);
addWarning(i18n.ERROR_LAST_EVENT_TIME);
nreese marked this conversation as resolved.
Show resolved Hide resolved
}
},
error: (msg) => {
Expand All @@ -107,7 +104,7 @@ export const useTimelineLastEventTime = ({
asyncSearch();
refetch.current = asyncSearch;
},
[data.search, addError, addWarning]
[data.search, addError]
);

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,19 +190,6 @@ describe('useMatrixHistogram', () => {
expect(mockEndTracking).toHaveBeenCalledWith('success');
});

it('should end tracking error when the partial request is invalid', () => {
(useKibana().services.data.search.search as jest.Mock).mockReturnValueOnce({
subscribe: ({ next }: { next: Function }) => next(null),
});

renderHook(useMatrixHistogram, {
initialProps: props,
wrapper: TestProviders,
});

expect(mockEndTracking).toHaveBeenCalledWith('invalid');
});

it('should end tracking error when the request fails', () => {
(useKibana().services.data.search.search as jest.Mock).mockReturnValueOnce({
subscribe: ({ error }: { error: Function }) => error('some error'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { getOr, noop } from 'lodash/fp';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Subscription } from 'rxjs';

import { isErrorResponse, isCompleteResponse } from '@kbn/data-plugin/common';
import { isCompleteResponse } from '@kbn/data-plugin/common';
import type { MatrixHistogramQueryProps } from '../../components/matrix_histogram/types';
import type { inputsModel } from '../../store';
import { createFilter } from '../helpers';
Expand Down Expand Up @@ -92,7 +92,7 @@ export const useMatrixHistogram = ({
...(isPtrIncluded != null ? { isPtrIncluded } : {}),
...(includeMissingData != null ? { includeMissingData } : {}),
});
const { addError, addWarning } = useAppToasts();
const { addError } = useAppToasts();

const [matrixHistogramResponse, setMatrixHistogramResponse] = useState<UseMatrixHistogramArgs>({
data: [],
Expand Down Expand Up @@ -138,11 +138,6 @@ export const useMatrixHistogram = ({
}));
endTracking('success');
searchSubscription$.current.unsubscribe();
} else if (isErrorResponse(response)) {
setLoading(false);
addWarning(i18n.ERROR_MATRIX_HISTOGRAM);
endTracking('invalid');
searchSubscription$.current.unsubscribe();
}
},
error: (msg) => {
Expand All @@ -160,7 +155,7 @@ export const useMatrixHistogram = ({
asyncSearch();
refetch.current = asyncSearch;
},
[data.search, histogramType, addWarning, addError, errorMessage, startTracking]
[data.search, histogramType, addError, errorMessage, startTracking]
);

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,14 +273,18 @@ describe('useSearchStrategy', () => {
expect(mockEndTracking).toBeCalledWith('success');
});

it('should track invalid search result', () => {
mockResponse.mockReturnValueOnce({}); // mock invalid empty response
it('should handle search error', () => {
mockResponse.mockImplementation(() => {
throw new Error(
'simulated search response error, which could be 1) undefined response, 2) response without rawResponse, or 3) partial response'
);
});

const { result } = renderHook(() => useSearch<FactoryQueryTypes>(factoryQueryType));
result.current({ request, abortSignal: new AbortController().signal });

expect(mockStartTracking).toBeCalledTimes(1);
expect(mockEndTracking).toBeCalledWith('invalid');
expect(mockEndTracking).toBeCalledWith('error');
});

it('should track error search result', () => {
Expand Down Expand Up @@ -310,14 +314,5 @@ describe('useSearchStrategy', () => {
expect(mockEndTracking).toBeCalledTimes(1);
expect(mockEndTracking).toBeCalledWith('aborted');
});

it('should show toast warning when the API returns partial invalid response', () => {
mockResponse.mockReturnValueOnce({}); // mock invalid empty response

const { result } = renderHook(() => useSearch<FactoryQueryTypes>(factoryQueryType));
result.current({ request, abortSignal: new AbortController().signal });

expect(mockAddToastWarning).toBeCalled();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ export const useSearch = <QueryType extends FactoryQueryTypes>(
factoryQueryType: QueryType
): UseSearchFunction<QueryType> => {
const { data } = useKibana().services;
const { addWarning } = useAppToasts();
const { startTracking } = useTrackHttpRequest();

const search = useCallback<UseSearchFunction<QueryType>>(
Expand All @@ -65,16 +64,11 @@ export const useSearch = <QueryType extends FactoryQueryTypes>(
abortSignal,
}
)
.pipe(filter((response) => isErrorResponse(response) || isCompleteResponse(response)));
.pipe(filter((response) => isCompleteResponse(response)));

observable.subscribe({
next: (response) => {
if (isErrorResponse(response)) {
addWarning(i18n.INVALID_RESPONSE_WARNING_SEARCH_STRATEGY(factoryQueryType));
endTracking('invalid');
} else {
endTracking('success');
}
endTracking('success');
},
error: () => {
endTracking(abortSignal.aborted ? 'aborted' : 'error');
Expand All @@ -83,7 +77,7 @@ export const useSearch = <QueryType extends FactoryQueryTypes>(

return observable;
},
[addWarning, data.search, factoryQueryType, startTracking]
[data.search, factoryQueryType, startTracking]
);

return search;
Expand Down
Loading