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

Add Notifications for Log Viewer #2502

Merged
merged 8 commits into from
Dec 5, 2023
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

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion locust/webui/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<meta name="theme-color" content="#000000" />

<title>Locust</title>
<script type="module" crossorigin src="/assets/index-5727afdb.js"></script>
<script type="module" crossorigin src="/assets/index-d0af3b25.js"></script>
</head>
<body>
<div id="root"></div>
Expand Down
2 changes: 2 additions & 0 deletions locust/webui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ThemeProvider } from '@mui/material/styles';
import { connect } from 'react-redux';

import Layout from 'components/Layout/Layout';
import useLogViewer from 'components/LogViewer/useLogViewer';
import SwarmForm from 'components/SwarmForm/SwarmForm';
import Tabs from 'components/Tabs/Tabs';
import { SWARM_STATE } from 'constants/swarm';
Expand All @@ -21,6 +22,7 @@ interface IApp {

function App({ isDarkMode, swarmState }: IApp) {
useSwarmUi();
useLogViewer();

const theme = useMemo(
() => createTheme(isDarkMode ? THEME_MODE.DARK : THEME_MODE.LIGHT),
Expand Down
31 changes: 0 additions & 31 deletions locust/webui/src/components/LogViewer/LogViewer.test.tsx
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

(Moved, not deleted)

This file was deleted.

14 changes: 6 additions & 8 deletions locust/webui/src/components/LogViewer/LogViewer.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import { Box, Typography } from '@mui/material';

import { SWARM_STATE } from 'constants/swarm';
import useInterval from 'hooks/useInterval';
import { useGetLogsQuery } from 'redux/api/swarm';
import { useSelector } from 'redux/hooks';

export default function LogViewer() {
const swarm = useSelector(({ swarm }) => swarm);
const { data, refetch: refetchLogs } = useGetLogsQuery();

useInterval(refetchLogs, 5000, { shouldRunInterval: swarm.state !== SWARM_STATE.STOPPED });
const logs = useSelector(({ logViewer: { logs } }) => logs);

return (
<Box>
<Typography component='h2' variant='h4'>
Logs
</Typography>

<ul>{data && data.logs.map((log, index) => <li key={`log-${index}`}>{log}</li>)}</ul>
<ul>
{logs.map((log, index) => (
<li key={`log-${index}`}>{log}</li>
))}
</ul>
</Box>
);
}
20 changes: 20 additions & 0 deletions locust/webui/src/components/LogViewer/tests/LogViewer.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, test } from 'vitest';

import LogViewer from 'components/LogViewer/LogViewer';
import { swarmStateMock } from 'test/mocks/swarmState.mock';
import { renderWithProvider } from 'test/testUtils';

describe('LogViewer', () => {
test('should render host, status, RPS, and failures on first load', async () => {
const { getByText } = renderWithProvider(<LogViewer />, {
swarm: swarmStateMock,
logViewer: {
logs: ['Log 1', 'Log 2', 'Log 3'],
},
});

expect(getByText('Log 1')).toBeTruthy();
expect(getByText('Log 2')).toBeTruthy();
expect(getByText('Log 3')).toBeTruthy();
});
});
38 changes: 38 additions & 0 deletions locust/webui/src/components/LogViewer/tests/useLogViewer.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { waitFor } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';

import useLogViewer from 'components/LogViewer/useLogViewer';
import { TEST_BASE_API } from 'test/constants';
import { swarmStateMock } from 'test/mocks/swarmState.mock';
import { renderWithProvider } from 'test/testUtils';

const mockLogs = ['Log 1', 'Log 2', 'Log 3'];

const server = setupServer(
http.get(`${TEST_BASE_API}/logs`, () => HttpResponse.json({ logs: mockLogs })),
);

function MockHook() {
const logs = useLogViewer();

return <span data-testid='logs'>{JSON.stringify(logs)}</span>;
}

describe('useLogViewer', () => {
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('should fetch logs from server and store them in state', async () => {
const { store, getByTestId } = renderWithProvider(<MockHook />, {
swarm: swarmStateMock,
});

await waitFor(() => {
expect(getByTestId('logs').textContent).toBe(JSON.stringify(mockLogs));
expect(store.getState().logViewer.logs).toEqual(mockLogs);
});
});
});
35 changes: 35 additions & 0 deletions locust/webui/src/components/LogViewer/useLogViewer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useCallback, useEffect } from 'react';

import { SWARM_STATE } from 'constants/swarm';
import useInterval from 'hooks/useInterval';
import useNotifications from 'hooks/useNotifications';
import { useGetLogsQuery } from 'redux/api/swarm';
import { useAction, useSelector } from 'redux/hooks';
import { logViewerActions } from 'redux/slice/logViewer.slice';

const isImportantLog = (log: string) =>
log.includes('WARNING') || log.includes('ERROR') || log.includes('CRITICAL');

export default function useLogViewer() {
const swarm = useSelector(({ swarm }) => swarm);
const setLogs = useAction(logViewerActions.setLogs);
const { data, refetch: refetchLogs } = useGetLogsQuery();

const logs = data ? data.logs : [];

const shouldNotifyLogsUpdate = useCallback(
() => logs.slice(localStorage['logViewer']).some(isImportantLog),
[logs],
);

useInterval(refetchLogs, 5000, {
shouldRunInterval: swarm.state === SWARM_STATE.SPAWNING || swarm.state == SWARM_STATE.RUNNING,
});
useNotifications(logs, { key: 'logViewer', shouldNotify: shouldNotifyLogsUpdate });

useEffect(() => {
setLogs({ logs });
}, [logs]);

return logs;
}
2 changes: 1 addition & 1 deletion locust/webui/src/components/Tabs/Tabs.constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const baseTabs = [
},
{
component: LogViewer,
key: 'log_viewer',
key: 'logViewer',
title: 'Logs',
},
];
Expand Down
35 changes: 32 additions & 3 deletions locust/webui/src/components/Tabs/Tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
import { useState } from 'react';
import PriorityHighIcon from '@mui/icons-material/PriorityHigh';
import { Box, Tabs as MuiTabs, Tab as MuiTab, Container } from '@mui/material';
import { connect } from 'react-redux';

import DataTable from 'components/DataTable/DataTable';
import { baseTabs, conditionalTabs } from 'components/Tabs/Tabs.constants';
import { INotificationState, notificationActions } from 'redux/slice/notification.slice';
import { IUrlState, urlActions } from 'redux/slice/url.slice';
import { IRootState } from 'redux/store';
import { ITab } from 'types/tab.types';
import { pushQuery } from 'utils/url';

interface ITabs {
currentTabIndexFromQuery: number;
notification: INotificationState;
setNotification: (payload: INotificationState) => void;
setUrl: (payload: IUrlState) => void;
tabs: ITab[];
}

function Tabs({ currentTabIndexFromQuery, setUrl, tabs }: ITabs) {
interface ITabLabel {
hasNotification?: boolean;
title: string;
}

function TabLabel({ hasNotification, title }: ITabLabel) {
return (
<Box sx={{ display: 'flex', alignItems: 'center' }}>
{hasNotification && <PriorityHighIcon color='secondary' />}
<span>{title}</span>
</Box>
);
}

function Tabs({ currentTabIndexFromQuery, notification, setNotification, setUrl, tabs }: ITabs) {
const [currentTabIndex, setCurrentTabIndex] = useState(currentTabIndexFromQuery);

const onTabChange = (_: React.SyntheticEvent, index: number) => {
const tab = tabs[index].key;

if (notification[tab]) {
setNotification({ [tab]: false });
}

pushQuery({ tab });
setUrl({ query: { tab } });
setCurrentTabIndex(index);
Expand All @@ -29,8 +52,11 @@ function Tabs({ currentTabIndexFromQuery, setUrl, tabs }: ITabs) {
<Container maxWidth='xl'>
<Box sx={{ mb: 2 }}>
<MuiTabs onChange={onTabChange} value={currentTabIndex}>
{tabs.map(({ title }, index) => (
<MuiTab key={`tab-${index}`} label={title} />
{tabs.map(({ key: tabKey, title }, index) => (
<MuiTab
key={`tab-${index}`}
label={<TabLabel hasNotification={notification[tabKey]} title={title} />}
/>
))}
</MuiTabs>
</Box>
Expand All @@ -44,6 +70,7 @@ function Tabs({ currentTabIndexFromQuery, setUrl, tabs }: ITabs) {

const storeConnector = (state: IRootState) => {
const {
notification,
swarm: { extendedTabs = [] },
url: { query: urlQuery },
} = state;
Expand All @@ -55,13 +82,15 @@ const storeConnector = (state: IRootState) => {
const tabs = [...baseTabs, ...conditionalTabsToDisplay, ...extendedTabs];

return {
notification,
tabs,
currentTabIndexFromQuery:
urlQuery && urlQuery.tab ? tabs.findIndex(({ key }) => key === urlQuery.tab) : 0,
};
};

const actionCreator = {
setNotification: notificationActions.setNotification,
setUrl: urlActions.setUrl,
};

Expand Down
Loading