Skip to content

Commit

Permalink
[ML] Refactor to use state handler
Browse files Browse the repository at this point in the history
  • Loading branch information
qn895 committed Aug 17, 2021
1 parent 014b5cd commit 6bbb68c
Show file tree
Hide file tree
Showing 4 changed files with 166 additions and 152 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,6 @@ export interface FailedTransactionsCorrelationValue {
fieldValue: string;
}

export interface BaseSearchStrategyResponse {
took: number;
log: string[];
ccsWarning: boolean;
error?: Error;
isComplete: boolean;
isRunning: boolean;
progress: number;
timeTook: number;
startFetch: () => void;
cancelFetch: () => void;
}

export type FailureCorrelationImpactThreshold = typeof FAILED_TRANSACTIONS_IMPACT_THRESHOLD[keyof typeof FAILED_TRANSACTIONS_IMPACT_THRESHOLD];

export interface CorrelationsTerm {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,54 +32,50 @@ import { enableInspectEsQueries } from '../../../../../observability/public';
import { asPreciseDecimal } from '../../../../common/utils/formatters';
import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context';
import { FailedTransactionsCorrelationsHelpPopover } from './failed_transactions_correlations_help_popover';
import { useFailedTransactionsCorrelationsSearchStrategy } from './use_failed_transactions_correlations_search_strategy';
import {
BaseSearchStrategyResponse,
FailedTransactionsCorrelationValue,
} from '../../../../common/search_strategies/failure_correlations/types';
import { FailedTransactionsCorrelationValue } from '../../../../common/search_strategies/failure_correlations/types';
import { ImpactBar } from '../../shared/ImpactBar';
import { FAILED_TRANSACTIONS_CORRELATION_SEARCH_STRATEGY } from '../../../../common/search_strategies/failure_correlations/constants';
import { isErrorMessage } from './utils/is_error_message';
import { Summary } from '../../shared/Summary';
import { FETCH_STATUS } from '../../../hooks/use_fetcher';
import { getFailedTransactionsCorrelationImpactLabel } from './utils/get_failed_transactions_correlation_impact_label';
import { createHref, push } from '../../shared/Links/url_helpers';
import { useUiTracker } from '../../../../../observability/public';
import { useFailedTransactionsCorrelationsFetcher } from '../../../hooks/use_failed_transactions_correlations_fetcher';
import { SearchServiceParams } from '../../../../common/search_strategies/correlations/types';
import { useApmParams } from '../../../hooks/use_apm_params';

interface Props {
onClose: () => void;
}

interface FailedTransactionsCorrelationsSearchStrategyResult
extends BaseSearchStrategyResponse {
values: FailedTransactionsCorrelationValue[];
}

export function FailedTransactionsCorrelations({ onClose }: Props) {
const {
core: { notifications, uiSettings },
} = useApmPluginContext();
const trackApmEvent = useUiTracker({ app: 'apm' });

const { serviceName, transactionType } = useApmServiceContext();
const { urlParams } = useUrlParams();

const { environment, kuery, transactionName, start, end } = urlParams;
const {
query: { kuery, environment },
} = useApmParams('/services/:serviceName');

const { urlParams } = useUrlParams();
const { transactionName, start, end } = urlParams;

const displayLog = uiSettings.get<boolean>(enableInspectEsQueries);

const result = useFailedTransactionsCorrelationsSearchStrategy<FailedTransactionsCorrelationsSearchStrategyResult>(
{
environment,
kuery,
serviceName,
transactionName,
transactionType,
start,
end,
},
FAILED_TRANSACTIONS_CORRELATION_SEARCH_STRATEGY
);
const searchServicePrams: SearchServiceParams = {
environment,
kuery,
serviceName,
transactionName,
transactionType,
start,
end,
};

const result = useFailedTransactionsCorrelationsFetcher(searchServicePrams);

const {
ccsWarning,
Expand Down Expand Up @@ -110,10 +106,10 @@ export function FailedTransactionsCorrelations({ onClose }: Props) {

const selectedTerm = useMemo(() => {
if (selectedSignificantTerm) return selectedSignificantTerm;
return result?.response?.values &&
Array.isArray(result.response.values) &&
result.response.values.length > 0
? result.response?.values[0]
return result?.values &&
Array.isArray(result.values) &&
result.values.length > 0
? result?.values[0]
: undefined;
}, [selectedSignificantTerm, result]);

Expand Down Expand Up @@ -348,7 +344,7 @@ export function FailedTransactionsCorrelations({ onClose }: Props) {
) : null}
<CorrelationsTable<FailedTransactionsCorrelationValue>
columns={failedTransactionsCorrelationsColumns}
significantTerms={result?.response?.values}
significantTerms={result?.values}
status={FETCH_STATUS.SUCCESS}
setSelectedSignificantTerm={setSelectedSignificantTerm}
selectedTerm={selectedTerm}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* 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 { useRef, useState } from 'react';
import type { Subscription } from 'rxjs';
import {
IKibanaSearchRequest,
IKibanaSearchResponse,
isCompleteResponse,
isErrorResponse,
} from '../../../../../src/plugins/data/public';
import type { SearchServiceParams } from '../../common/search_strategies/correlations/types';
import { useKibana } from '../../../../../src/plugins/kibana_react/public';
import { ApmPluginStartDeps } from '../plugin';
import { FailedTransactionsCorrelationValue } from '../../common/search_strategies/failure_correlations/types';
import { FAILED_TRANSACTIONS_CORRELATION_SEARCH_STRATEGY } from '../../common/search_strategies/failure_correlations/constants';

interface RawResponse {
took: number;
values: FailedTransactionsCorrelationValue[];
log: string[];
ccsWarning: boolean;
}

interface FailedTransactionsCorrelationsFetcherState {
error?: Error;
isComplete: boolean;
isRunning: boolean;
loaded: number;
ccsWarning: RawResponse['ccsWarning'];
values: RawResponse['values'];
log: RawResponse['log'];
timeTook?: number;
total: number;
}

export const useFailedTransactionsCorrelationsFetcher = (
params: Omit<SearchServiceParams, 'analyzeCorrelations'>
) => {
const {
services: { data },
} = useKibana<ApmPluginStartDeps>();

const [
fetchState,
setFetchState,
] = useState<FailedTransactionsCorrelationsFetcherState>({
isComplete: false,
isRunning: false,
loaded: 0,
ccsWarning: false,
values: [],
log: [],
total: 100,
});

const abortCtrl = useRef(new AbortController());
const searchSubscription$ = useRef<Subscription>();

function setResponse(response: IKibanaSearchResponse<RawResponse>) {
setFetchState((prevState) => ({
...prevState,
isRunning: response.isRunning || false,
ccsWarning: response.rawResponse?.ccsWarning ?? false,
values: response.rawResponse?.values ?? [],
log: response.rawResponse?.log ?? [],
loaded: response.loaded!,
total: response.total!,
timeTook: response.rawResponse.took,
}));
}

const startFetch = () => {
setFetchState((prevState) => ({
...prevState,
error: undefined,
isComplete: false,
}));
searchSubscription$.current?.unsubscribe();
abortCtrl.current.abort();
abortCtrl.current = new AbortController();

const req = { params };

// Submit the search request using the `data.search` service.
searchSubscription$.current = data.search
.search<IKibanaSearchRequest, IKibanaSearchResponse<RawResponse>>(req, {
strategy: FAILED_TRANSACTIONS_CORRELATION_SEARCH_STRATEGY,
abortSignal: abortCtrl.current.signal,
})
.subscribe({
next: (res: IKibanaSearchResponse<RawResponse>) => {
setResponse(res);
if (isCompleteResponse(res)) {
searchSubscription$.current?.unsubscribe();
setFetchState((prevState) => ({
...prevState,
isRunnning: false,
isComplete: true,
}));
} else if (isErrorResponse(res)) {
searchSubscription$.current?.unsubscribe();
setFetchState((prevState) => ({
...prevState,
error: (res as unknown) as Error,
setIsRunning: false,
}));
}
},
error: (error: Error) => {
setFetchState((prevState) => ({
...prevState,
error,
setIsRunning: false,
}));
},
});
};

const cancelFetch = () => {
searchSubscription$.current?.unsubscribe();
searchSubscription$.current = undefined;
abortCtrl.current.abort();
setFetchState((prevState) => ({
...prevState,
setIsRunning: false,
}));
};

return {
...fetchState,
progress: fetchState.loaded / fetchState.total,
startFetch,
cancelFetch,
};
};

0 comments on commit 6bbb68c

Please sign in to comment.