Skip to content

Commit

Permalink
Simplify log api log download (#906)
Browse files Browse the repository at this point in the history
* simplify error handling when saving

* simplify logapi log download

* allow empty logs
  • Loading branch information
Pespiri authored Dec 22, 2023
1 parent 16f4ff1 commit c3a623b
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 108 deletions.
18 changes: 9 additions & 9 deletions src/components/code/log-helper.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { BaseQueryFn, QueryDefinition } from '@reduxjs/toolkit/query';
import { UseLazyQuery } from '@reduxjs/toolkit/dist/query/react/buildHooks';
import { LazyQueryTrigger } from '@reduxjs/toolkit/dist/query/react/buildHooks';

import { errorToast } from '../global-top-nav/styled-toaster';
import { getFetchErrorMessage } from '../../store/utils';
import { copyToTextFile } from '../../utils/string';

export type LazyQueryTriggerPlain<Args extends Record<string, unknown>> =
LazyQueryTrigger<QueryDefinition<Args, BaseQueryFn, string, string>>;

export function downloadLazyLogCb<
T extends ReturnType<
UseLazyQuery<QueryDefinition<unknown, BaseQueryFn, string, string>>
>[0],
T extends LazyQueryTriggerPlain<Record<string, unknown>>,
>(filename: string, func: T, ...args: Parameters<T>): () => Promise<void> {
return async () => {
const { data, error, isError, isSuccess } = await func(
args?.[0],
args?.[1]
);
const { data, error, isError, isSuccess } = await (
func as unknown as (...args: Parameters<T>) => ReturnType<T>
)(...((args || []) as Parameters<T>));

if (isSuccess && data) {
if (isSuccess) {
copyToTextFile(filename, data);
} else if (isError) {
const message = getFetchErrorMessage(error);
Expand Down
16 changes: 4 additions & 12 deletions src/components/environment-variables/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,19 +113,11 @@ export const EnvironmentVariables: FunctionComponent<{
.filter((x) => x.value !== x.original.value)
.map<EnvVarParameter>((x) => ({ name: x.original.name, value: x.value }));
if (body.length > 0) {
const response = await saveFunc({
appName,
envName,
componentName,
body,
});

if ('error' in response) {
errorToast(
`Failed to save variables. ${getFetchErrorMessage(response.error)}`
);
} else {
try {
await saveFunc({ appName, envName, componentName, body }).unwrap();
refetchEnvVars();
} catch (error) {
errorToast(`Failed to save variables. ${getFetchErrorMessage(error)}`);
}
}
setInEditMode(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from 'react';

import AsyncResource from '../async-resource/another-async-resource';
import { errorToast } from '../global-top-nav/styled-toaster';
import { LazyQueryTriggerPlain, downloadLazyLogCb } from '../code/log-helper';
import { Duration } from '../time/duration';
import { RelativeToNow } from '../time/relative-to-now';
import {
Expand All @@ -27,18 +27,12 @@ import {
logApi,
useGetComponentInventoryQuery,
} from '../../store/log-api';
import { FetchQueryResult } from '../../store/types';
import { getFetchErrorData } from '../../store/utils';
import {
dataSorter,
sortCompareDate,
sortDirection,
} from '../../utils/sort-utils';
import {
copyToTextFile,
smallGithubCommitHash,
smallReplicaName,
} from '../../utils/string';
import { smallGithubCommitHash, smallReplicaName } from '../../utils/string';
import { TableSortIcon, getNewSortDir } from '../../utils/table-sort-utils';

interface ComponentNameProps {
Expand Down Expand Up @@ -66,19 +60,6 @@ const LogDownloadButton: FunctionComponent<{
</Button>
);

function saveLog(
query: Pick<FetchQueryResult, 'data' | 'error' | 'isError' | 'isSuccess'>,
filename: string,
errMsg = 'Failed to download log'
): void {
if (query.isSuccess) {
copyToTextFile(filename, query.data as string);
} else if (query.isError) {
const { code, message } = getFetchErrorData(query.error);
errorToast(`${errMsg}: ${code && `[${code}] `}${message}`);
}
}

export const ComponentReplicaLogAccordion: FunctionComponent<
ComponentReplicaLogAccordionProps
> = ({ appName, envName, componentName, title, isExpanded }) => {
Expand Down Expand Up @@ -228,17 +209,11 @@ const ReplicaLogTableRow: FunctionComponent<
<Table.Cell className={`fitwidth padding-right-0`} variant="icon">
<LogDownloadButton
title="Download Replica log"
onClick={async () => {
const response = await getLog({
appName,
envName,
componentName,
replicaName: name,
});

const filename = `${appName}_${envName}_${componentName}_${name}.txt`;
saveLog(response, filename);
}}
onClick={downloadLazyLogCb(
`${appName}_${envName}_${componentName}_${name}.txt`,
getLog as LazyQueryTriggerPlain<Parameters<typeof getLog>[0]>,
{ appName, envName, componentName, replicaName: name }
)}
disabled={isFetching}
/>
</Table.Cell>
Expand Down Expand Up @@ -290,18 +265,11 @@ const ReplicaContainerTableRow: FunctionComponent<
<Table.Cell className={`fitwidth padding-right-0`} variant="icon">
<LogDownloadButton
title="Download Container log"
onClick={async () => {
const response = await getLog({
appName,
envName,
componentName,
replicaName,
containerId: id,
});

const filename = `${appName}_${envName}_${componentName}_${replicaName}_${id}.txt`;
saveLog(response, filename);
}}
onClick={downloadLazyLogCb(
`${appName}_${envName}_${componentName}_${replicaName}_${id}.txt`,
getLog as LazyQueryTriggerPlain<Parameters<typeof getLog>[0]>,
{ appName, envName, componentName, replicaName, containerId: id }
)}
disabled={isFetching}
/>
</Table.Cell>
Expand Down
65 changes: 22 additions & 43 deletions src/components/page-scheduled-job/replica-log-accordion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
} from 'react';

import AsyncResource from '../async-resource/another-async-resource';
import { errorToast } from '../global-top-nav/styled-toaster';
import { LazyQueryTriggerPlain, downloadLazyLogCb } from '../code/log-helper';
import { Duration } from '../time/duration';
import { RelativeToNow } from '../time/relative-to-now';
import { RawModel } from '../../models/model-types';
Expand All @@ -28,18 +28,12 @@ import {
logApi,
useGetJobInventoryQuery,
} from '../../store/log-api';
import { FetchQueryResult } from '../../store/types';
import { getFetchErrorData } from '../../store/utils';
import {
dataSorter,
sortCompareDate,
sortDirection,
} from '../../utils/sort-utils';
import {
copyToTextFile,
smallGithubCommitHash,
smallReplicaName,
} from '../../utils/string';
import { smallGithubCommitHash, smallReplicaName } from '../../utils/string';
import { TableSortIcon, getNewSortDir } from '../../utils/table-sort-utils';

interface JobNameProps {
Expand Down Expand Up @@ -80,19 +74,6 @@ function getTimespan(
};
}

function saveLog(
query: Pick<FetchQueryResult, 'data' | 'error' | 'isError' | 'isSuccess'>,
filename: string,
errMsg = 'Failed to download log'
): void {
if (query.isSuccess) {
copyToTextFile(filename, query.data as string);
} else if (query.isError) {
const { code, message } = getFetchErrorData(query.error);
errorToast(`${errMsg}: ${code && `[${code}] `}${message}`);
}
}

export const JobReplicaLogAccordion: FunctionComponent<
JobReplicaLogAccordionProps
> = ({
Expand Down Expand Up @@ -256,20 +237,13 @@ const ReplicaLogTableRow: FunctionComponent<
<Table.Cell className={`fitwidth padding-right-0`} variant="icon">
<LogDownloadButton
title="Download Replica log"
onClick={async () => {
const response = await getLog({
appName,
envName,
jobComponentName,
jobName,
replicaName: name,
});

const filename = `${appName}_${envName}_${jobComponentName}_${jobName}_${smallReplicaName(
onClick={downloadLazyLogCb(
`${appName}_${envName}_${jobComponentName}_${jobName}_${smallReplicaName(
name
)}.txt`;
saveLog(response, filename);
}}
)}.txt`,
getLog as LazyQueryTriggerPlain<Parameters<typeof getLog>[0]>,
{ appName, envName, jobComponentName, jobName, replicaName: name }
)}
disabled={isFetching}
/>
</Table.Cell>
Expand Down Expand Up @@ -322,21 +296,20 @@ const ReplicaContainerTableRow: FunctionComponent<
<Table.Cell className={`fitwidth padding-right-0`} variant="icon">
<LogDownloadButton
title="Download Container log"
onClick={async () => {
const response = await getLog({
onClick={downloadLazyLogCb(
`${appName}_${envName}_${jobComponentName}_${jobName}_${smallReplicaName(
replicaName
)}_${id}.txt`,
getLog as LazyQueryTriggerPlain<Parameters<typeof getLog>[0]>,
{
appName,
envName,
jobComponentName,
jobName,
replicaName,
containerId: id,
});

const filename = `${appName}_${envName}_${jobComponentName}_${jobName}_${smallReplicaName(
replicaName
)}_${id}.txt`;
saveLog(response, filename);
}}
}
)}
disabled={isFetching}
/>
</Table.Cell>
Expand All @@ -351,4 +324,10 @@ JobReplicaLogAccordion.propTypes = {
jobComponentName: PropTypes.string.isRequired,
jobName: PropTypes.string.isRequired,
isExpanded: PropTypes.bool,
timeSpan: PropTypes.shape<
PropTypes.ValidationMap<JobReplicaLogAccordionProps['timeSpan']>
>({
start: PropTypes.instanceOf(Date).isRequired,
end: PropTypes.instanceOf(Date),
}) as PropTypes.Validator<JobReplicaLogAccordionProps['timeSpan']>,
};

0 comments on commit c3a623b

Please sign in to comment.