From eb8e1683fb489bc8bb075c1a979518219f563f13 Mon Sep 17 00:00:00 2001 From: txix Date: Fri, 24 Jan 2025 09:48:42 +0300 Subject: [PATCH] 2025-01-24 09:48:42: merge [main:cf1209562ae3ac7c0754e92b429b52c9a126d004]; --- Dockerfile | 7 +- ...-admin-ui.conf => 8002_isp-stress-ui.conf} | 5 +- package-lock.json | 4 +- src/components/App.tsx | 2 +- src/components/Layout/index.tsx | 140 ++++---- src/components/Layout/layout.type.ts | 13 +- src/components/app.scss | 1 - src/constants/api/apiPaths.ts | 29 +- .../stress-ui/ObjectFieldRenderer/index.tsx | 130 ++++++++ .../object-field-renderer.scss | 46 +++ .../stress-ui/ProjectEditor/ProjectEditor.tsx | 100 ++++++ .../stress-ui/ProjectsPage/ProjectsPage.tsx | 90 +++++ src/pages/stress-ui/ProjectsPage/project.ts | 9 + src/pages/stress-ui/TestEditor/TestEditor.tsx | 119 +++++++ .../stress-ui/TestEditor/TestEditorForm.tsx | 313 ++++++++++++++++++ src/pages/stress-ui/TestsPage/TestsPage.tsx | 266 +++++++++++++++ src/pages/stress-ui/TestsPage/tests.scss | 10 + src/pages/stress-ui/TestsPage/tests.ts | 58 ++++ src/routes/Routers/index.tsx | 242 +++++++------- src/routes/routePaths.ts | 10 +- src/services/projectService.ts | 62 ++++ src/services/testsService.ts | 84 +++++ src/stores/index.tsx | 10 +- src/utils/apiUtils.ts | 16 +- 24 files changed, 1574 insertions(+), 192 deletions(-) rename cfg/{80_isp-admin-ui.conf => 8002_isp-stress-ui.conf} (97%) create mode 100644 src/pages/stress-ui/ObjectFieldRenderer/index.tsx create mode 100644 src/pages/stress-ui/ObjectFieldRenderer/object-field-renderer.scss create mode 100644 src/pages/stress-ui/ProjectEditor/ProjectEditor.tsx create mode 100644 src/pages/stress-ui/ProjectsPage/ProjectsPage.tsx create mode 100644 src/pages/stress-ui/ProjectsPage/project.ts create mode 100644 src/pages/stress-ui/TestEditor/TestEditor.tsx create mode 100644 src/pages/stress-ui/TestEditor/TestEditorForm.tsx create mode 100644 src/pages/stress-ui/TestsPage/TestsPage.tsx create mode 100644 src/pages/stress-ui/TestsPage/tests.scss create mode 100644 src/pages/stress-ui/TestsPage/tests.ts create mode 100644 src/services/projectService.ts create mode 100644 src/services/testsService.ts diff --git a/Dockerfile b/Dockerfile index 44c1610..bfc94ea 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,13 +3,12 @@ ARG NODE_VERSION=lts FROM node:${NODE_VERSION}-alpine as base WORKDIR /usr/src/app - FROM base as deps RUN --mount=type=bind,source=package.json,target=package.json \ --mount=type=bind,source=package-lock.json,target=package-lock.json \ --mount=type=cache,target=/root/.npm \ - npm ci --omit=dev + npm ci --legacy-peer-deps --omit=dev FROM deps as build @@ -23,6 +22,6 @@ RUN npm run build FROM nginx:alpine-slim as final RUN rm -f /etc/nginx/conf.d/default.conf -COPY cfg/80_isp-admin-ui.conf /etc/nginx/conf.d/80_isp-admin-ui.conf -COPY --from=build /usr/src/app/build /opt/msp/isp-admin-ui +COPY cfg/8002_isp-stress-ui.conf /etc/nginx/conf.d/8002_isp-stress-ui.conf +COPY --from=build /usr/src/app/build /opt/msp/isp-stress-ui diff --git a/cfg/80_isp-admin-ui.conf b/cfg/8002_isp-stress-ui.conf similarity index 97% rename from cfg/80_isp-admin-ui.conf rename to cfg/8002_isp-stress-ui.conf index 0bbe130..fb71127 100644 --- a/cfg/80_isp-admin-ui.conf +++ b/cfg/8002_isp-stress-ui.conf @@ -1,7 +1,8 @@ server { - listen 8001; + listen 8002; server_name localhost; - root /opt/msp/isp-admin-ui/; + + root /opt/msp/isp-stress-ui/; location / { add_header Cache-Control "no-cache, no-store, must-revalidate"; diff --git a/package-lock.json b/package-lock.json index 770e47e..f491747 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "isp-admin-ui", - "version": "0.18.8", + "version": "0.18.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "isp-admin-ui", - "version": "0.18.8", + "version": "0.18.9", "dependencies": { "@apidevtools/json-schema-ref-parser": "^9.0.6", "@monaco-editor/react": "^4.6.0", diff --git a/src/components/App.tsx b/src/components/App.tsx index 99831d4..0f5c3c2 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -40,7 +40,7 @@ const App = () => { return (
- + diff --git a/src/components/Layout/index.tsx b/src/components/Layout/index.tsx index 3746313..677eb9c 100644 --- a/src/components/Layout/index.tsx +++ b/src/components/Layout/index.tsx @@ -68,62 +68,80 @@ const LayoutComponent = () => { return hasPermission(permission) ? '' : 'hide-item' } const menuItems: MenuItemType[] = [ + // { + // label: firstName || '', + // key: 'profile', + // className: 'user-item', + // icon: + // }, + // { + // label: 'Приложения', + // key: 'applications_group', + // className: hideItem([PermissionKeysType.read]), + // icon: + // }, + // { + // label: 'Доступы приложений', + // key: 'appAccess', + // className: hideItem([PermissionKeysType.read]), + // icon: + // }, + // { + // label: 'Модули', + // key: 'modules', + // className: hideItem(PermissionKeysType.read), + // icon: + // }, + // { + // label: 'Пользователи и роли', + // key: 'sessionManagement', + // className: hideItem([ + // PermissionKeysType.user_view, + // PermissionKeysType.session_view, + // PermissionKeysType.role_view + // ]), + // icon: , + // children: [ + // { + // label: 'Пользователи', + // key: 'users', + // className: hideItem(PermissionKeysType.user_view) + // }, + // { + // label: 'Пользовательские сессии', + // key: 'sessions', + // className: hideItem(PermissionKeysType.session_view) + // }, + // { + // label: 'Просмотр журналов ИБ', + // key: 'securityLog', + // className: hideItem(PermissionKeysType.security_log_view) + // }, + // { + // label: 'Роли', + // key: 'roles', + // className: hideItem(PermissionKeysType.role_view) + // } + // ] + // }, { - label: firstName || '', - key: 'profile', - className: 'user-item', - icon: - }, - { - label: 'Приложения', - key: 'applications_group', - className: hideItem([PermissionKeysType.read]), - icon: - }, - { - label: 'Доступы приложений', - key: 'appAccess', - className: hideItem([PermissionKeysType.read]), - icon: - }, - { - label: 'Модули', - key: 'modules', - className: hideItem(PermissionKeysType.read), - icon: - }, - { - label: 'Пользователи и роли', - key: 'sessionManagement', - className: hideItem([ - PermissionKeysType.user_view, - PermissionKeysType.session_view, - PermissionKeysType.role_view - ]), - icon: , - children: [ + label: 'Stress-ui', + key: 'stress', + className: '', + icon: , + children:[ { - label: 'Пользователи', - key: 'users', - className: hideItem(PermissionKeysType.user_view) + label: 'Tests', + key: 'tests', + className: '' }, { - label: 'Пользовательские сессии', - key: 'sessions', - className: hideItem(PermissionKeysType.session_view) + label: 'Projects', + key: 'projects', + className: '' }, - { - label: 'Просмотр журналов ИБ', - key: 'securityLog', - className: hideItem(PermissionKeysType.security_log_view) - }, - { - label: 'Роли', - key: 'roles', - className: hideItem(PermissionKeysType.role_view) - } ] - } + }, ] useEffect(() => { @@ -155,7 +173,6 @@ const LayoutComponent = () => { const menuKey = location.pathname.split('/')[1] as MenuItemKeysType const selectedKey = selectedMenuKeys[0] || '' const menuItem = menuKeys[menuKey] - if (menuItem && menuKey !== selectedKey) { setSelectedMenuKeys([menuItem.key]) if (selectedKey) { @@ -191,17 +208,23 @@ const LayoutComponent = () => { case MenuItemKeysType.applicationsGroup: navigate(routePaths.applicationsGroup) break + case 'tests': + navigate(routePaths.tests) + break + case 'projects': + navigate(routePaths.projects) + break default: } } - if (loading || status === StateProfileStatus.pending) { - return - } - - if (status === StateProfileStatus.rejected) { - return - } + // if (loading || status === StateProfileStatus.pending) { + // return + // } + // + // if (status === StateProfileStatus.rejected) { + // return + // } return (
@@ -217,7 +240,6 @@ const LayoutComponent = () => { setCollapsed(value) }} > -
setOpenKeys(keys)} openKeys={openKeys} diff --git a/src/components/Layout/layout.type.ts b/src/components/Layout/layout.type.ts index ec02f84..b7aebbb 100644 --- a/src/components/Layout/layout.type.ts +++ b/src/components/Layout/layout.type.ts @@ -9,8 +9,11 @@ export enum MenuItemKeysType { logout = 'logout', profile = 'profile', modules = 'modules', - applicationsGroup = 'applications_group' + applicationsGroup = 'applications_group', + stressUITests = 'tests', + stressUIProjects = 'projects' } + export enum MenuItemLabelsType { users = 'Пользователи', sessions = 'Пользовательские сессии', @@ -64,6 +67,14 @@ export const menuKeys: Record = { [MenuItemKeysType.applicationsGroup]: { key: MenuItemKeysType.applicationsGroup, parent: ['applicationsGroup'] + }, + [MenuItemKeysType.stressUITests]: { + key: MenuItemKeysType.stressUITests, + parent: ['stress'] + }, + [MenuItemKeysType.stressUIProjects]: { + key: MenuItemKeysType.stressUIProjects, + parent: ['stress'] } } diff --git a/src/components/app.scss b/src/components/app.scss index 8947f80..07b9c91 100644 --- a/src/components/app.scss +++ b/src/components/app.scss @@ -7,7 +7,6 @@ } .app{ - overflow: hidden; height: 100vh; min-height: 0; min-width: 500px; diff --git a/src/constants/api/apiPaths.ts b/src/constants/api/apiPaths.ts index 1a5fba4..9afcac1 100644 --- a/src/constants/api/apiPaths.ts +++ b/src/constants/api/apiPaths.ts @@ -54,6 +54,19 @@ type PathKeys = | 'getUI' | 'getByModuleId' | 'changePassword' + | 'baseStressUrl' + | 'getAllProject' + | 'createProject' + | 'updateProject' + | 'deleteProject' + | 'getOneProject' + | 'getAllTests' + | 'createTest' + | 'runTest' + | 'stopTest' + | 'updateTest' + | 'deleteTest' + | 'getOneTest' export const apiPaths: Record = { baseUrl: '/api/kkd-configuration-service', @@ -122,5 +135,19 @@ export const apiPaths: Record = { createUpdateConfig: '/config/create_update_config', deleteVersion: '/config/delete_version', deleteConfig: '/config/delete_config', - markConfigAsActive: '/config/mark_config_as_active' + markConfigAsActive: '/config/mark_config_as_active', + // ======= STRESS-UI ====== + baseStressUrl: '/api/isp-stress-service', + getAllProject: 'project/all', + createProject: 'project/create', + updateProject: 'project/update', + deleteProject: 'project/delete', + getOneProject: 'project/get', + getAllTests: 'test/all', + createTest: 'test/create', + runTest: 'test/run', + stopTest: 'test/stop', + updateTest: 'test/update', + deleteTest: 'test/delete', + getOneTest: 'test/get' } diff --git a/src/pages/stress-ui/ObjectFieldRenderer/index.tsx b/src/pages/stress-ui/ObjectFieldRenderer/index.tsx new file mode 100644 index 0000000..4bd0b80 --- /dev/null +++ b/src/pages/stress-ui/ObjectFieldRenderer/index.tsx @@ -0,0 +1,130 @@ +import { DeleteOutlined } from '@ant-design/icons' +import { Button, Input } from 'antd' +import { useEffect, useState } from 'react' +import { Control, Controller, useController } from 'react-hook-form' + +import './object-field-renderer.scss' + +export interface ObjectFieldRendererPropsType { + name: string + control: Control + readOnly: boolean +} + +export type FieldEsiPropsType = string[][] + +export interface ObjectEntriesValueType { + [key: string]: string +} + +export const ObjectFieldRenderer = ({ + name, + control, + readOnly +}: ObjectFieldRendererPropsType) => { + const [entries, setEntries] = useState([]) + const { + field: { value } + } = useController({ name, control }) + + useEffect(() => { + if (value && entries.length === 0) { + setEntries(Object.entries(value)) + } + }, [value]) + const entriesToObject = (entries: FieldEsiPropsType) => + entries.reduce( + (obj, [key, value]) => (key ? { ...obj, [key]: value } : obj), + {} + ) + + const handleAddField = () => { + const updatedEntries = [...entries, ['', '']] + setEntries(updatedEntries) + } + + const handleRemoveField = ( + index: number, + onChange: (el: ObjectEntriesValueType) => void + ) => { + const updatedEntries = entries.filter((_, i) => i !== index) + setEntries(updatedEntries) + onChange(entriesToObject(updatedEntries)) + } + + const getUpdatedEntries = (index: number, newValue: string, order: number) => + entries.map((entry, i) => { + if (order === 0) { + return i === index ? [newValue, entry[1]] : entry + } + return i === index ? [entry[0], newValue] : entry + }) + + const handleChangeKey = ( + index: number, + newKey: string, + onChange: (el: ObjectEntriesValueType) => void + ) => { + const updatedEntries = getUpdatedEntries(index, newKey, 0) + setEntries(updatedEntries) + onChange(entriesToObject(updatedEntries)) + } + + const handleChangeValue = ( + index: number, + newValue: string, + onChange: (el: ObjectEntriesValueType) => void + ) => { + const updatedEntries = getUpdatedEntries(index, newValue, 1) + setEntries(updatedEntries) + onChange(entriesToObject(updatedEntries)) + } + const renderConditionFields = ( + onChange: (el: ObjectEntriesValueType) => void + ) => ( + <> + {entries.map(([key, value], index) => ( +
+ handleChangeKey(index, e.target.value, onChange)} + /> + handleChangeValue(index, e.target.value, onChange)} + /> +
+ ))} + + ) + return ( + ( +
+
+ {renderConditionFields(field.onChange)} +
+
+ +
+
+ )} + /> + ) +} diff --git a/src/pages/stress-ui/ObjectFieldRenderer/object-field-renderer.scss b/src/pages/stress-ui/ObjectFieldRenderer/object-field-renderer.scss new file mode 100644 index 0000000..57adc15 --- /dev/null +++ b/src/pages/stress-ui/ObjectFieldRenderer/object-field-renderer.scss @@ -0,0 +1,46 @@ +.object-component { + width: 100%; + position: relative; + padding-top: 15px; + + &__content { + overflow: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + width: 0; + height: 0; + } + } + + &__empty-field { + display: flex; + justify-content: center; + } + + &__field { + width: 100%; + display: flex; + gap: 16px; + padding-bottom: 10px; + + div { + min-width: 190px; + flex-grow: 1; + } + + &__remove-btn { + flex-shrink: 0; + } + } + + &__add-btn { + bottom: 16px; + right: 16px; + margin-top: 8px; + display: flex; + align-self: flex-end; + align-items: center; + gap: 8px; + } +} diff --git a/src/pages/stress-ui/ProjectEditor/ProjectEditor.tsx b/src/pages/stress-ui/ProjectEditor/ProjectEditor.tsx new file mode 100644 index 0000000..14c9b7c --- /dev/null +++ b/src/pages/stress-ui/ProjectEditor/ProjectEditor.tsx @@ -0,0 +1,100 @@ +import { Button, message, Space, Spin } from 'antd' +import { FormComponents } from 'isp-ui-kit' +import { useEffect } from 'react' +import { useForm } from 'react-hook-form' +import { useNavigate, useParams } from 'react-router-dom' + +import { ValidationRules } from '@constants/form/validationRules.ts' + +import { ProjectType } from '@pages/stress-ui/ProjectsPage/project.ts' + +import projectApi from '@services/projectService.ts' + +import { routePaths } from '@routes/routePaths.ts' + +const { FormInput } = FormComponents + +const ProjectEditor = () => { + const { id } = useParams() + const navigate = useNavigate() + const validatedId = id && id !== 'new' ? id : '' + const [getOneProject, { data, error, isLoading }] = + projectApi.useGetOneProjectMutation() + const [updateProject] = projectApi.useUpdateProjectMutation() + const [createProject] = projectApi.useCreateProjectMutation() + + const isNew = id === 'new' + + useEffect(() => { + const handleFetchProject = async () => { + try { + await getOneProject(validatedId).unwrap() + } catch (err) { + console.error('Error fetching project:', err) + } + } + handleFetchProject().then() + }, []) + + const { handleSubmit, control, reset } = useForm({ + mode: 'onChange', + defaultValues: isNew ? {} : data + }) + + useEffect(() => { + reset(data) + }, [data]) + + if (isLoading) return + if (!isNew && error) return

Error

+ + const handleSubmitForm = (data: ProjectType) => { + console.log('handleSubmitForm') + if (isNew) { + const newData = { + name: data.name + } + createProject(newData) + .unwrap() + .then(() => { + message.success('Проект создан') + navigate(routePaths.projects) + }) + .catch(() => message.error('Ошибка создания проекта')) + } else { + const updateData = { + ...data, + name: data.name + } + updateProject(updateData as ProjectType) + .unwrap() + .then(() => { + message.success('Проект изменен') + navigate(routePaths.projects) + }) + .catch(() => message.error('Ошибка изменения проекта')) + } + } + + return ( +
+
+ + + + + + +
+ ) +} + +export default ProjectEditor diff --git a/src/pages/stress-ui/ProjectsPage/ProjectsPage.tsx b/src/pages/stress-ui/ProjectsPage/ProjectsPage.tsx new file mode 100644 index 0000000..d9a13bc --- /dev/null +++ b/src/pages/stress-ui/ProjectsPage/ProjectsPage.tsx @@ -0,0 +1,90 @@ +import { FormOutlined, DeleteOutlined } from '@ant-design/icons' +import { Button, Space, Spin, Table, message } from 'antd' +import { ColumnsType } from 'antd/es/table' +import dayjs from 'dayjs' +import { useNavigate } from 'react-router-dom' +import { ProjectType } from '@pages/stress-ui/ProjectsPage/project.ts' +import projectApi from '@services/projectService.ts' +import { dateFormats } from '@constants/date.ts' +import { routePaths } from '@routes/routePaths.ts' + +const ProjectsPage = () => { + const navigate = useNavigate() + const { data, isLoading, isError } = projectApi.useGetAllProjectsQuery() + const [deleteProject] = projectApi.useDeleteProjectMutation() + + if (isLoading) return + if (isError) return

Error

+ + const columns: ColumnsType = [ + { + key: 'id', + title: 'Id', + dataIndex: 'id', + + }, + { + key: 'name', + title: 'Наименование', + dataIndex: 'name' + }, + { + key: 'createdAt', + title: 'Дата создания', + dataIndex: 'createdAt', + render: (value: string) => { + return dayjs(value).format(dateFormats.fullFormat) + } + }, + { + key: 'updatedAt', + title: ' Дата обновления', + dataIndex: 'updatedAt', + render: (value: string) => { + return dayjs(value).format(dateFormats.fullFormat) + } + }, + { + key: 'control', + render: (record) => { + return ( + + + record.id} + /> + + ) +} + +export default ProjectsPage diff --git a/src/pages/stress-ui/ProjectsPage/project.ts b/src/pages/stress-ui/ProjectsPage/project.ts new file mode 100644 index 0000000..6bf5d86 --- /dev/null +++ b/src/pages/stress-ui/ProjectsPage/project.ts @@ -0,0 +1,9 @@ +export interface ProjectType { + createdAt: string + id: string + name: string + updatedAt: string +} +export interface NewProjectType { + name: string +} \ No newline at end of file diff --git a/src/pages/stress-ui/TestEditor/TestEditor.tsx b/src/pages/stress-ui/TestEditor/TestEditor.tsx new file mode 100644 index 0000000..21c6f90 --- /dev/null +++ b/src/pages/stress-ui/TestEditor/TestEditor.tsx @@ -0,0 +1,119 @@ +import { message, Spin } from 'antd' +import { useEffect, useState } from 'react' +import { useNavigate, useParams } from 'react-router-dom' +import testApi from '@services/testsService.ts' +import { TestType } from '@pages/stress-ui/TestsPage/tests.ts' +import { routePaths } from '@routes/routePaths.ts' +import TestForm from '@pages/stress-ui/TestEditor/TestEditorForm.tsx' + +const TestEditor = ({readOnly, propsId} :{readOnly?: boolean, propsId?: string} ) => { + const { id: urlId } = useParams() + const id = urlId || propsId + const navigate = useNavigate() + const validatedId = id && id !== 'new' ? id : '' + const [updateTest] = testApi.useUpdateTestMutation() + const [createTest] = testApi.useCreateTestMutation() + const [getOneTest, { data: test, isLoading: isLoadingTest}] = testApi.useGetOneTestMutation() + const [currentTest, setCurrentTest] = useState() + + const defaultTest = { + comment: '', + name: '', + projectId: localStorage.getItem('selectedProject') ?? undefined, + scenario: { + globalHeaders: {}, + pool: { + dialTimeout: '1s', + enableHttp2: true, + enableKeepalive: true, + maxIdleCons: 100, + }, + requests: [ + { + ammo: { + endpoint: { + method: '', + url: '', + }, + file: '', + headers: {}, + iterable: false, + templatedBody: false, + type: 'http', + }, + baseUrl: '', + debug: false, + discardResponseBody: false, + name: '', + timeout: '0s', + type: 'basic', + }, + ], + rps: { + steps: [ + { + duration: '30s', + from: 1, + step: 0, + to: 100, + type: 'linear', + }, + ], + workers: 10, + }, + }, + } + + useEffect(() => { + const handleFetchTest = async () => { + if (validatedId) { + try { + await getOneTest(validatedId).unwrap() + } catch (err) { + console.error('Error fetching test:', err) + } + } else { + setCurrentTest(defaultTest as TestType) + } + } + handleFetchTest().then() + }, [validatedId]) + + const isNew = id === 'new' + + useEffect(() => { + setCurrentTest(test ? test : defaultTest as TestType) + }, [test]) + + if (!isNew && isLoadingTest) return + + const handleSubmitForm = (data: TestType) => { + if (isNew) { + createTest(data) + .unwrap() + .then(() => { + message.success('Тест создан') + navigate(routePaths.tests) + }) + .catch(() => message.error('Ошибка создания теста')) + } else { + updateTest(data).unwrap() + .then(() => { + message.success('Тест изменен') + navigate(routePaths.tests) + }) + .catch(() => message.error('Ошибка изменения теста')) + } + } + + return ( +
+ + {currentTest && + + } +
+ ) +} + +export default TestEditor diff --git a/src/pages/stress-ui/TestEditor/TestEditorForm.tsx b/src/pages/stress-ui/TestEditor/TestEditorForm.tsx new file mode 100644 index 0000000..fbf202b --- /dev/null +++ b/src/pages/stress-ui/TestEditor/TestEditorForm.tsx @@ -0,0 +1,313 @@ +import { Button, Card, Space } from 'antd' +import { FormComponents } from 'isp-ui-kit' +import { useEffect } from 'react' +import { useForm, useFieldArray } from 'react-hook-form' +import { useNavigate } from 'react-router-dom' + +import { ValidationRules } from '@constants/form/validationRules.ts' + +import { ObjectFieldRenderer } from '@pages/stress-ui/ObjectFieldRenderer' +import { TestType } from '@pages/stress-ui/TestsPage/tests.ts' + +import { routePaths } from '@routes/routePaths.ts' + +const { FormInput, FormInputNumber, FormCheckbox } = FormComponents + +export interface TestFormProps { + initialValues: TestType + onSubmit: (data: TestType) => void + readOnly?: boolean + isNew?: boolean +} + +const TestForm = ({ + initialValues = {} as TestType, + onSubmit, + readOnly = false, + isNew +}: TestFormProps) => { + const navigate = useNavigate() + const { handleSubmit, control, reset } = useForm({ + mode: 'onChange', + defaultValues: initialValues + }) + + const { + fields: requestFields, + append, + remove + } = useFieldArray({ + control, + name: 'scenario.requests' + }) + + const { + fields: rpsStepsFields, + append: appendStep, + remove: removeStep + } = useFieldArray({ + control, + name: 'scenario.rps.steps' + }) + + useEffect(() => { + reset(initialValues) + }, [initialValues]) + + return ( +
+ + {!readOnly && ( + <> + + + + + )} + + + + + + + +

Global Headers

+ +
+ +

Пул

+ + + + +
+ + +

Запросы

+ {requestFields.map((field, index) => ( + +

ammo

+ + + + +

Заголовки

+ +
+ + + + + + + + + + + + + +
+ ))} +
+ +

RPS

+ {rpsStepsFields.map((field, index) => ( + + + + + + + + + ))} + + + +
+ + ) +} + +export default TestForm diff --git a/src/pages/stress-ui/TestsPage/TestsPage.tsx b/src/pages/stress-ui/TestsPage/TestsPage.tsx new file mode 100644 index 0000000..18db3a7 --- /dev/null +++ b/src/pages/stress-ui/TestsPage/TestsPage.tsx @@ -0,0 +1,266 @@ +import { DeleteOutlined, FormOutlined, PlayCircleOutlined, StopOutlined } from '@ant-design/icons' +import { Button, message, Modal, Popconfirm, Select, Space, Spin, Table, Tag } from 'antd' +import { ColumnGroupType, ColumnType } from 'antd/es/table' +import { FormComponents } from 'isp-ui-kit' +import { useEffect, useState } from 'react' +import { useForm } from 'react-hook-form' +import { useNavigate } from 'react-router-dom' +import projectApi from '@services/projectService.ts' +import testApi from '@services/testsService.ts' +import './tests.scss' +import { PlayTestType, TestType } from '@pages/stress-ui/TestsPage/tests.ts' +import { ValidationRules } from '@constants/form/validationRules.ts' +import { ProjectType } from '@pages/stress-ui/ProjectsPage/project.ts' +import { routePaths } from '@routes/routePaths.ts' +import TestEditor from '@pages/stress-ui/TestEditor/TestEditor.tsx' +import ErrorWrapperPage from '@pages/ErrorWrapperPage' +const { FormTextArea, FormInputNumber } = FormComponents + + +const TestsPage = () => { + const navigate = useNavigate() + const [selectedProject, setSelectedProject] = useState('') + const { + data: allProjects, + isLoading: isLoadingAllProjects, + isError: isErrorAllProjects + } = projectApi.useGetAllProjectsQuery() + + const [deleteTest] = testApi.useDeleteTestMutation() + const [runTest] = testApi.useRunTestMutation() + const [stopTest] = testApi.useStopTestMutation() + + const [isScenarioModalOpen, setIsScenarioModalOpen] = useState(false) + const [isLaunchesModalOpen, setIsLaunchesModalOpen] = useState(false) + const [selectedScenario, setSelectedScenario] = useState() + + + const [tests, setTests] = useState([]) + + const { handleSubmit, control } = useForm({ + mode: 'onChange', + defaultValues: {} + }) + + + useEffect(() => { + setSelectedProject(localStorage.getItem('selectedProject') || '') + }, []) + + + const { data: testsFromServer, isLoading: isLoadingTests } = + testApi.useGetAllTestsQuery(selectedProject ? selectedProject : '', { + skip: !selectedProject, + pollingInterval: 3000 + }) + + useEffect(() => { + if (testsFromServer) { + setTests(testsFromServer) + } + }, [testsFromServer]) + + const handleOpenScenarioModal = (scenario: TestType) => { + setSelectedScenario(scenario) + setIsScenarioModalOpen(true) + } + + const handlePlay = (record: PlayTestType) => { + const modal = Modal.confirm({ + title: 'Запустить тест', + footer: false, + content: ( +
+ + + + + + + + ), + }) + } + + const handleStop = (record: PlayTestType) => { + stopTest(record.id) + .unwrap() + .then(() => { + message.success('Тест остановлен') + setTests((prev) => + prev.map((test) => + test.id === record.id ? { ...test, status: 'READY' } : test + ) + ) + }) + .catch(() => message.error('Ошибка остановки теста')) + } + + const handleChange = (value: string) => { + setSelectedProject(value) + localStorage.setItem('selectedProject', value) + } + + const transformToSelectOptions = (data: ProjectType[] | []) => { + if (data.length) { + return data.map((item) => ({ + value: item.id, + label: item.name + })) + } + } + + const columns: (ColumnGroupType | ColumnType)[] = [ + { + title: 'Наименование', + dataIndex: 'name', + key: 'name', + }, + { + title: 'Описание', + dataIndex: 'description', + key: 'description', + }, + { + title: 'Сценарий', + dataIndex: 'scenario', + key: 'scenario', + render: (_, record) => ( + handleOpenScenarioModal(record)}>Смотреть сценарий + ), + }, + { + title: 'Статус', + dataIndex: 'status', + key: 'status', + render: (status: 'READY' | 'RUNNING') => ( + {status} + ), + }, + { + title: 'Действия', + key: 'actions', + render: (_, record) => ( + +
record.id} + /> + setIsScenarioModalOpen(false)} + footer={null} + > + {selectedScenario?.id && ( + + )} + + setIsLaunchesModalOpen(false)} + footer={null} + > +

Таблица с запусками

+
+ + )} + + ) +} + +export default TestsPage diff --git a/src/pages/stress-ui/TestsPage/tests.scss b/src/pages/stress-ui/TestsPage/tests.scss new file mode 100644 index 0000000..4d99e78 --- /dev/null +++ b/src/pages/stress-ui/TestsPage/tests.scss @@ -0,0 +1,10 @@ +.tests-page { + margin: 8px; +} +.test-editor { + margin: 8px; +} + +.tests-select { + min-width: 200px; +} diff --git a/src/pages/stress-ui/TestsPage/tests.ts b/src/pages/stress-ui/TestsPage/tests.ts new file mode 100644 index 0000000..f4ea41b --- /dev/null +++ b/src/pages/stress-ui/TestsPage/tests.ts @@ -0,0 +1,58 @@ +export interface TestType { + comment?: string; + createdAt: string; + id: string; + lastRunAt: string; + name: string; + description: string; + projectId: string; + scenario: ScenarioType + status: string; + updatedAt: string; +} + +export interface ScenarioType { + globalHeaders: Record; + pool: { + dialTimeout: string; + enableHttp2: boolean; + enableKeepalive: boolean; + maxIdleCons: number; + }; + requests: { + ammo: { + endpoint: { + method: string; + url: string; + }; + file: string; + headers: Record; + iterable: boolean; + templatedBody: boolean; + type: string; + }; + baseUrl: string; + debug: boolean; + discardResponseBody: boolean; + name: string; + timeout: string; + type: string; + }[]; + rps: { + steps: { + duration: string; + from: number; + step: number; + to: number; + type: string; + }[]; + workers: number; + }; +} +export interface NewTestType { + name: string +} + +export interface PlayTestType extends Omit { + dataOffset?: number; +} \ No newline at end of file diff --git a/src/routes/Routers/index.tsx b/src/routes/Routers/index.tsx index b9bbdd7..ff8b796 100644 --- a/src/routes/Routers/index.tsx +++ b/src/routes/Routers/index.tsx @@ -8,8 +8,11 @@ import LayoutComponent from '@components/Layout' import Configurations from '@pages/ConfigurationsPage' import Connections from '@pages/ConnectionsPage' import ErrorWrapperPage from '@pages/ErrorWrapperPage' +import ProjectEditor from '@pages/stress-ui/ProjectEditor/ProjectEditor.tsx' +import ProjectsPage from '@pages/stress-ui/ProjectsPage/ProjectsPage.tsx' +import TestEditor from '@pages/stress-ui/TestEditor/TestEditor.tsx' +import TestsPage from '@pages/stress-ui/TestsPage/TestsPage.tsx' -import PrivateRoute from '@routes/PrivateRoute' import { routePaths } from '@routes/routePaths.ts' const LoginPage = lazy(() => import('@pages/LoginPage')) @@ -31,59 +34,73 @@ const NotFound = lazy(() => import('@pages/NotFound')) const Routers = () => { return ( - }> - }> + }> + }> + + + } + /> + } /> + + } /> + + } /> + + } /> + }> + + + } + /> + }> + + + } + /> + }> + + + } + /> + }> + + + } + > }> - - - } - /> - }> - - - } - /> - }> - - - } - /> - }> - - - } - /> - }> } - > - }> - - - } - /> - + /> + + }> + + + } + > }> @@ -91,7 +108,7 @@ const Routers = () => { } > }> @@ -99,101 +116,92 @@ const Routers = () => { } > }> } - > - }> - - - } - /> - + /> + + }> + + + } + /> + }> + + + } + /> + }> + + + } + > }> - - - } - /> - }> - - - } - /> - }> } - > + /> + + }> + + + } + > + }> + + + } + > + }> - + } - /> - - }> - - - } - > - }> - - - } - > - + > }> - - - } - > - }> - - - } - /> - - }> - + } /> + }> + + + } + /> diff --git a/src/routes/routePaths.ts b/src/routes/routePaths.ts index 241d468..9fe5ff2 100644 --- a/src/routes/routePaths.ts +++ b/src/routes/routePaths.ts @@ -17,6 +17,10 @@ type RoutePaths = | 'configurations' | 'allVersions' | 'configEditor' + | 'projects' + | 'project' + | 'test' + | 'tests' export const routePaths: Record = { home: '/', @@ -36,5 +40,9 @@ export const routePaths: Record = { connections: 'connections', configurations: 'configurations', allVersions: ':configId/all_versions', - configEditor: 'configEditor' + configEditor: 'configEditor', + projects: '/projects', + project: '/project', + test: '/test', + tests: '/tests' } diff --git a/src/services/projectService.ts b/src/services/projectService.ts new file mode 100644 index 0000000..8ef3256 --- /dev/null +++ b/src/services/projectService.ts @@ -0,0 +1,62 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { baseQuery } from '@utils/apiUtils' +import { getConfigProperty } from '@utils/configUtils' +import { NewProjectType, ProjectType } from '@pages/stress-ui/ProjectsPage/project.ts' +import { apiPaths } from '@constants/api/apiPaths.ts' + +const projectApi = createApi({ + reducerPath: 'projectApi', + refetchOnFocus: true, + tagTypes: ['Project'], + baseQuery: baseQuery(apiPaths.baseStressUrl, { + 'X-APPLICATION-TOKEN': getConfigProperty( + 'APP_TOKEN', + import.meta.env.VITE_APP_TOKEN + ) + }), + endpoints: (builder) => ({ + getAllProjects: builder.query({ + query: () => ({ + url: apiPaths.getAllProject, + method: 'POST', + body: {} + }), + providesTags: () => ['Project'] + }), + createProject: builder.mutation({ + query: (newProject) => ({ + url: apiPaths.createProject, + method: 'POST', + body: newProject + }), + invalidatesTags: ['Project'] + }), + updateProject: builder.mutation({ + query: (project) => ({ + url: apiPaths.updateProject, + method: 'POST', + body: project + }), + invalidatesTags: ['Project'] + }), + getOneProject: builder.mutation({ + query: (id) => ({ + url: apiPaths.getOneProject, + method: 'POST', + body: { id } + }), + invalidatesTags: ['Project'] + }), + deleteProject: builder.mutation({ + query: (id) => ({ + url: apiPaths.deleteProject, + method: 'POST', + body: { id } + }), + invalidatesTags: ['Project'] + }) + }) +}) + +export default projectApi diff --git a/src/services/testsService.ts b/src/services/testsService.ts new file mode 100644 index 0000000..5d9c279 --- /dev/null +++ b/src/services/testsService.ts @@ -0,0 +1,84 @@ +import { createApi } from '@reduxjs/toolkit/query/react' + +import { apiPaths } from '@constants/api/apiPaths.ts' + +import { + NewTestType, + PlayTestType, + TestType +} from '@pages/stress-ui/TestsPage/tests.ts' + +import { baseQuery } from '@utils/apiUtils.ts' +import { getConfigProperty } from '@utils/configUtils' + +const testApi = createApi({ + reducerPath: 'testApi', + refetchOnFocus: true, + tagTypes: ['Test'], + baseQuery: baseQuery(apiPaths.baseStressUrl, { + 'X-APPLICATION-TOKEN': getConfigProperty( + 'APP_TOKEN', + import.meta.env.VITE_APP_TOKEN + ) + }), + endpoints: (builder) => ({ + getAllTests: builder.query({ + query: (projectId) => ({ + url: apiPaths.getAllTests, + method: 'POST', + body: { projectId } + }), + providesTags: () => ['Test'] + }), + createTest: builder.mutation({ + query: (newTest) => ({ + url: apiPaths.createTest, + method: 'POST', + body: newTest + }), + invalidatesTags: ['Test'] + }), + runTest: builder.mutation({ + query: (test) => ({ + url: apiPaths.runTest, + method: 'POST', + body: test + }), + invalidatesTags: ['Test'] + }), + stopTest: builder.mutation({ + query: (id) => ({ + url: apiPaths.getOneTest, + method: 'POST', + body: { id } + }), + invalidatesTags: ['Test'] + }), + updateTest: builder.mutation({ + query: (test) => ({ + url: apiPaths.updateTest, + method: 'POST', + body: test + }), + invalidatesTags: ['Test'] + }), + getOneTest: builder.mutation({ + query: (id) => ({ + url: apiPaths.getOneTest, + method: 'POST', + body: { id } + }), + invalidatesTags: ['Test'] + }), + deleteTest: builder.mutation({ + query: (id) => ({ + url: apiPaths.deleteTest, + method: 'POST', + body: { id } + }), + invalidatesTags: ['Test'] + }) + }) +}) + +export default testApi diff --git a/src/stores/index.tsx b/src/stores/index.tsx index ceffc60..191cf3e 100644 --- a/src/stores/index.tsx +++ b/src/stores/index.tsx @@ -9,10 +9,12 @@ import applicationsGroupApi from '@services/applicationsGroupService.ts' import applicationsApi from '@services/applicationsService.ts' import configServiceApi from '@services/configService.ts' import modulesServiceApi from '@services/modulesService.ts' +import projectService from '@services/projectService.ts' import roleApi from '@services/roleService.ts' import routeApi from '@services/routeService.ts' import securityLogServiceApi from '@services/securityLogService.ts' import sessionServiceApi from '@services/sessionService.ts' +import testsService from '@services/testsService.ts' import tokensApi from '@services/tokensService.ts' import userServiceApi from '@services/userService.ts' @@ -51,7 +53,9 @@ const rootReducer = combineReducers({ [applicationsGroupApi.reducerPath]: applicationsGroupApi.reducer, [applicationsApi.reducerPath]: applicationsApi.reducer, [configServiceApi.reducerPath]: configServiceApi.reducer, - [tokensApi.reducerPath]: tokensApi.reducer + [tokensApi.reducerPath]: tokensApi.reducer, + [projectService.reducerPath]: projectService.reducer, + [testsService.reducerPath]: testsService.reducer }) export const setupStore = () => @@ -71,7 +75,9 @@ export const setupStore = () => applicationsGroupApi.middleware, applicationsApi.middleware, tokensApi.middleware, - configServiceApi.middleware + configServiceApi.middleware, + projectService.middleware, + testsService.middleware ) }) diff --git a/src/utils/apiUtils.ts b/src/utils/apiUtils.ts index dd5f6ee..c76fbfe 100644 --- a/src/utils/apiUtils.ts +++ b/src/utils/apiUtils.ts @@ -1,10 +1,24 @@ -import { BaseQueryFn, retry } from '@reduxjs/toolkit/query/react' +import { BaseQueryFn, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react' import { AxiosError, AxiosRequestConfig } from 'axios' import { apiService } from '@services/apiService.ts' import { MSPError } from '@type/index.ts' +export const baseQuery = ( + baseUrl: string, + customHeaders: { [key: string]: string } +) => + fetchBaseQuery({ + baseUrl, + prepareHeaders: (headers) => { + Object.keys(customHeaders).forEach((key) => { + headers.set(key, customHeaders[key]) + }) + return headers + } + }) + export const axiosBaseQuery = ( { baseUrl }: { baseUrl: string } = { baseUrl: '' }