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

Refactor async calls and minor bug fixes #274

Merged
merged 9 commits into from
Feb 28, 2024
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
37 changes: 0 additions & 37 deletions common/toast/index.tsx

This file was deleted.

22 changes: 21 additions & 1 deletion common/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,14 @@
formErrors: FormErrorsType;
}

export enum AsyncQueryLoadingStatus {
export enum AsyncQueryStatus {
Pending = 'pending',
Success = 'success',
Failed = 'failed',
Running = 'running',
Scheduled = 'scheduled',
Cancelled = 'cancelled',
Waiting = 'waiting',
}

export type TreeItemType =
Expand All @@ -115,3 +117,21 @@
flag: boolean;
status: string;
}

interface AsyncApiDataResponse {
status: string;
schema?: Array<{ name: string; type: string }>;
datarows?: any;

Check warning on line 124 in common/types/index.ts

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
total?: number;
size?: number;
error?: string;
}

export interface AsyncApiResponse {
data: {
ok: boolean;
resp: AsyncApiDataResponse;
};
}

export type PollingCallback = (statusObj: AsyncApiResponse) => void;
174 changes: 125 additions & 49 deletions common/utils/async_query_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
* SPDX-License-Identifier: Apache-2.0
*/

import _ from 'lodash';
import { CoreStart } from '../../../../src/core/public';
import { coreRefs } from '../../public/framework/core_refs';
import {
ASYNC_QUERY_ENDPOINT,
ASYNC_QUERY_JOB_ENDPOINT,
ASYNC_QUERY_SESSION_ID,
POLL_INTERVAL_MS,
} from '../constants';
import { AsyncApiResponse, AsyncQueryStatus, PollingCallback } from '../types';
import { RaiseErrorToast } from './toast_helper';

export const setAsyncSessionId = (dataSource: string, value: string | null) => {
if (value !== null) {
Expand All @@ -22,55 +23,130 @@ export const getAsyncSessionId = (dataSource: string) => {
return sessionStorage.getItem(`${ASYNC_QUERY_SESSION_ID}_${dataSource}`);
};

export const getJobId = (
export const executeAsyncQuery = (
currentDataSource: string,
query: {},
http: CoreStart['http'],
callback
pollingCallback: PollingCallback,
onErrorCallback?: (errorMessage: string) => void
) => {
http
.post(ASYNC_QUERY_ENDPOINT, {
body: JSON.stringify({
...query,
sessionId: getAsyncSessionId(currentDataSource) ?? undefined,
}),
})
.then((res) => {
const id = res.data.resp.queryId;
setAsyncSessionId(currentDataSource, _.get(res.data.resp, 'sessionId', null));
if (id === undefined) {
console.error(JSON.parse(res.data.body));
}
callback(id);
})
.catch((err) => {
console.error(err);
});
};
let jobId: string | undefined;
let isQueryFulfilled = false;
const http = coreRefs.http!;

const getJobId = () => {
http
.post(ASYNC_QUERY_ENDPOINT, {
body: JSON.stringify({
...query,
sessionId: getAsyncSessionId(currentDataSource) ?? undefined,
}),
})
.then((res) => {
const responseData = res.data.resp;
jobId = responseData?.queryId;
if (jobId === undefined || !res.data.ok) {
console.error('Recieved an invalid query id:', res.data);
RaiseErrorToast({
errorToastMessage: 'Recieved an invalid query id: ' + res.data.resp,
errorDetailsMessage: res.data.body,
});

if (onErrorCallback) {
onErrorCallback(res.data.body);
}
return;
}
setAsyncSessionId(currentDataSource, responseData?.sessionId ?? null);
pollQueryStatus(jobId, pollingCallback);
})
.catch((err) => {
console.error('Error occurred while getting query id:', err);
RaiseErrorToast({
errorToastMessage: 'Error occurred while getting query id',
errorDetailsMessage: err,
});
isQueryFulfilled = true;
if (onErrorCallback) {
onErrorCallback(err);
}
});
};

const pollQueryStatus = (id: string, callback: PollingCallback) => {
http
.get(ASYNC_QUERY_JOB_ENDPOINT + id)
.then((res: AsyncApiResponse) => {
const status = res.data.resp.status.toLowerCase();
const errorDetailsMessage = res.data.resp.error ?? '';
switch (status) {
case AsyncQueryStatus.Pending:
case AsyncQueryStatus.Running:
case AsyncQueryStatus.Scheduled:
case AsyncQueryStatus.Waiting:
callback({ ...res });
setTimeout(() => pollQueryStatus(id, callback), POLL_INTERVAL_MS);
break;

case AsyncQueryStatus.Failed:
case AsyncQueryStatus.Cancelled:
isQueryFulfilled = true;
Copy link
Collaborator

@sumukhswamy sumukhswamy Feb 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had a question about this isQueryFulfilled this is set as true here so that the loading stops?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isQueryFulfilled is an internal flag that keeps a check for cancelQuery. If query is fulfilled either with success or failed status then we will not run cancel query.


if (status === AsyncQueryStatus.Failed) {
RaiseErrorToast({
errorToastMessage: 'Query failed',
errorDetailsMessage,
});
}
if (onErrorCallback) {
onErrorCallback(errorDetailsMessage);
}
callback({ ...res });
break;

case AsyncQueryStatus.Success:
isQueryFulfilled = true;
callback({ ...res });
break;

default:
console.error('Unrecognized status:', status);
RaiseErrorToast({
errorToastMessage: 'Unrecognized status recieved',
errorDetailsMessage: 'Unrecognized status recieved - ' + errorDetailsMessage,
});
if (onErrorCallback) {
onErrorCallback(errorDetailsMessage);
}
callback({ ...res });
}
})
.catch((err) => {
console.error('Error occurred while polling query status:', err);
isQueryFulfilled = true;
callback({
data: {
ok: true,
resp: { status: AsyncQueryStatus.Failed, error: 'Failed to query status' },
},
});
});
};

const cancelQuery = () => {
if (jobId && !isQueryFulfilled) {
http.delete(ASYNC_QUERY_JOB_ENDPOINT + jobId).catch((err) => {
console.error('Error occurred while cancelling query:', err);
RaiseErrorToast({
errorToastMessage: 'Query cancellation failed',
errorDetailsMessage: 'Query cancellation failed for queryId: ' + err,
});
});
}
};

// Start executing the query
getJobId();

export const pollQueryStatus = (id: string, http: CoreStart['http'], callback) => {
http
.get(ASYNC_QUERY_JOB_ENDPOINT + id)
.then((res) => {
const status = res.data.resp.status.toLowerCase();
if (
status === 'pending' ||
status === 'running' ||
status === 'scheduled' ||
status === 'waiting'
) {
callback({ status });
setTimeout(() => pollQueryStatus(id, http, callback), POLL_INTERVAL_MS);
} else if (status === 'failed') {
const results = res.data.resp;
callback({ status: 'FAILED', error: results.error });
} else if (status === 'success') {
const results = _.get(res.data.resp, 'datarows');
callback({ status: 'SUCCESS', results });
}
})
.catch((err) => {
console.error(err);
callback({ status: 'FAILED', error: 'Failed to fetch data' });
});
// Return a function to cancel the query
return cancelQuery;
};
90 changes: 90 additions & 0 deletions common/utils/toast_helper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import {
EuiButton,
EuiCodeBlock,
EuiModal,
EuiModalBody,
EuiModalFooter,
EuiModalHeader,
EuiModalHeaderTitle,
} from '@elastic/eui';
import React from 'react';
import { MountPoint, ToastInputFields } from '../../../../src/core/public';
import { toMountPoint } from '../../../../src/plugins/opensearch_dashboards_react/public';
import { coreRefs } from '../../public/framework/core_refs';

type Color = 'success' | 'primary' | 'warning' | 'danger' | undefined;

export const useToast = () => {
const toasts = coreRefs.toasts!;

const setToast = (title: string, color: Color = 'success', text?: string | MountPoint) => {
const newToast: ToastInputFields = {
id: new Date().toISOString(),
title,
text,
};
switch (color) {
case 'danger': {
toasts.addDanger(newToast);
break;
}
case 'warning': {
toasts.addWarning(newToast);
break;
}
default: {
toasts.addSuccess(newToast);
break;
}
}
};

return { setToast };
};

const loadErrorModal = (errorDetailsMessage: string) => {
const openModal = coreRefs.overlays?.openModal!;
const modal = openModal(
toMountPoint(
<EuiModal onClose={() => modal.close()}>
<EuiModalHeader>
<EuiModalHeaderTitle>Error details</EuiModalHeaderTitle>
</EuiModalHeader>
<EuiModalBody>
<EuiCodeBlock language="json" fontSize="m" paddingSize="m" isCopyable>
{errorDetailsMessage}
</EuiCodeBlock>
</EuiModalBody>
<EuiModalFooter>
<EuiButton onClick={() => modal.close()}>Close</EuiButton>
</EuiModalFooter>
</EuiModal>
)
);
};

export const RaiseErrorToast = ({
errorToastMessage,
errorDetailsMessage,
}: {
errorToastMessage: string;
errorDetailsMessage: string;
}) => {
const { setToast } = useToast();
setToast(
errorToastMessage,
'danger',
toMountPoint(
<EuiButton color="danger" size="s" onClick={() => loadErrorModal(errorDetailsMessage)}>
Error details
</EuiButton>
)
);

return <></>;
};
Loading
Loading