2025-01-24 10:37:12: merge [main:49411ff93c78a55478e3432737bab9a499b0066d];

This commit is contained in:
txix committed 2025-01-24 10:37:12 +03:00
1 parent 0b6f6cb8fa
commit e730b5ace3
24 files changed
+196 -1578

No files matched your search

+4 -3
View File
@@ -3,12 +3,13 @@ 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 --legacy-peer-deps --omit=dev
npm ci --omit=dev
FROM deps as build
@@ -22,6 +23,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
@@ -1,8 +1,7 @@
server {
listen 8002;
listen 8001;
server_name localhost;
root /opt/msp/isp-stress-ui/;
root /opt/msp/isp-admin-ui/;
location / {
add_header Cache-Control "no-cache, no-store, must-revalidate";
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "isp-admin-ui",
"version": "0.18.9",
"version": "0.18.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "isp-admin-ui",
"version": "0.18.9",
"version": "0.18.8",
"dependencies": {
"@apidevtools/json-schema-ref-parser": "^9.0.6",
"@monaco-editor/react": "^4.6.0",
+1 -1
View File
@@ -40,7 +40,7 @@ const App = () => {
return (
<div className="app">
<Context.Provider value={{ setTheme, setChangeTheme, changeTheme }}>
<ConfigProvider locale={ruRu}>
<ConfigProvider theme={themes} locale={ruRu}>
<Routers />
</ConfigProvider>
</Context.Provider>
+63 -85
View File
@@ -68,80 +68,62 @@ const LayoutComponent = () => {
return hasPermission(permission) ? '' : 'hide-item'
}
const menuItems: MenuItemType[] = [
// {
// label: firstName || '',
// key: 'profile',
// className: 'user-item',
// icon: <DefaultUser />
// },
// {
// label: 'Приложения',
// key: 'applications_group',
// className: hideItem([PermissionKeysType.read]),
// icon: <AppstoreAddOutlined />
// },
// {
// label: 'Доступы приложений',
// key: 'appAccess',
// className: hideItem([PermissionKeysType.read]),
// icon: <FileProtectOutlined />
// },
// {
// label: 'Модули',
// key: 'modules',
// className: hideItem(PermissionKeysType.read),
// icon: <ProductOutlined />
// },
// {
// label: 'Пользователи и роли',
// key: 'sessionManagement',
// className: hideItem([
// PermissionKeysType.user_view,
// PermissionKeysType.session_view,
// PermissionKeysType.role_view
// ]),
// icon: <ProfileOutlined />,
// 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: 'Stress-ui',
key: 'stress',
className: '',
icon: <AppstoreAddOutlined />,
children:[
{
label: 'Tests',
key: 'tests',
className: ''
},
{
label: 'Projects',
key: 'projects',
className: ''
},
]
label: firstName || '',
key: 'profile',
className: 'user-item',
icon: <DefaultUser />
},
{
label: 'Приложения',
key: 'applications_group',
className: hideItem([PermissionKeysType.read]),
icon: <AppstoreAddOutlined />
},
{
label: 'Доступы приложений',
key: 'appAccess',
className: hideItem([PermissionKeysType.read]),
icon: <FileProtectOutlined />
},
{
label: 'Модули',
key: 'modules',
className: hideItem(PermissionKeysType.read),
icon: <ProductOutlined />
},
{
label: 'Пользователи и роли',
key: 'sessionManagement',
className: hideItem([
PermissionKeysType.user_view,
PermissionKeysType.session_view,
PermissionKeysType.role_view
]),
icon: <ProfileOutlined />,
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)
}
]
}
]
useEffect(() => {
@@ -173,6 +155,7 @@ 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) {
@@ -208,23 +191,17 @@ 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 <Spin size="large" fullscreen />
// }
//
// if (status === StateProfileStatus.rejected) {
// return <Navigate to={routePaths.error} replace />
// }
if (loading || status === StateProfileStatus.pending) {
return <Spin size="large" fullscreen />
}
if (status === StateProfileStatus.rejected) {
return <Navigate to={routePaths.error} replace />
}
return (
<section>
@@ -240,6 +217,7 @@ const LayoutComponent = () => {
setCollapsed(value)
}}
>
<Header collapsed={collapsed} />
<Menu
onOpenChange={(keys) => setOpenKeys(keys)}
openKeys={openKeys}
+1 -12
View File
@@ -9,11 +9,8 @@ export enum MenuItemKeysType {
logout = 'logout',
profile = 'profile',
modules = 'modules',
applicationsGroup = 'applications_group',
stressUITests = 'tests',
stressUIProjects = 'projects'
applicationsGroup = 'applications_group'
}
export enum MenuItemLabelsType {
users = 'Пользователи',
sessions = 'Пользовательские сессии',
@@ -67,14 +64,6 @@ export const menuKeys: Record<MenuItemKeysType, MenuItem> = {
[MenuItemKeysType.applicationsGroup]: {
key: MenuItemKeysType.applicationsGroup,
parent: ['applicationsGroup']
},
[MenuItemKeysType.stressUITests]: {
key: MenuItemKeysType.stressUITests,
parent: ['stress']
},
[MenuItemKeysType.stressUIProjects]: {
key: MenuItemKeysType.stressUIProjects,
parent: ['stress']
}
}
+1
View File
@@ -7,6 +7,7 @@
}
.app{
overflow: hidden;
height: 100vh;
min-height: 0;
min-width: 500px;
+1 -28
View File
@@ -54,19 +54,6 @@ type PathKeys =
| 'getUI'
| 'getByModuleId'
| 'changePassword'
| 'baseStressUrl'
| 'getAllProject'
| 'createProject'
| 'updateProject'
| 'deleteProject'
| 'getOneProject'
| 'getAllTests'
| 'createTest'
| 'runTest'
| 'stopTest'
| 'updateTest'
| 'deleteTest'
| 'getOneTest'
export const apiPaths: Record<PathKeys, string> = {
baseUrl: '/api/kkd-configuration-service',
@@ -135,19 +122,5 @@ export const apiPaths: Record<PathKeys, string> = {
createUpdateConfig: '/config/create_update_config',
deleteVersion: '/config/delete_version',
deleteConfig: '/config/delete_config',
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'
markConfigAsActive: '/config/mark_config_as_active'
}
@@ -1,130 +0,0 @@
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<any>
readOnly: boolean
}
export type FieldEsiPropsType = string[][]
export interface ObjectEntriesValueType {
[key: string]: string
}
export const ObjectFieldRenderer = ({
name,
control,
readOnly
}: ObjectFieldRendererPropsType) => {
const [entries, setEntries] = useState<FieldEsiPropsType>([])
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) => (
<div key={index} className="object-component__field">
<Input
disabled={readOnly}
style={{ maxWidth: 185 }}
placeholder="Ключ"
value={key}
onChange={(e) => handleChangeKey(index, e.target.value, onChange)}
/>
<Input
disabled={readOnly}
style={{ maxWidth: 185 }}
placeholder="Значение"
value={value}
onChange={(e) => handleChangeValue(index, e.target.value, onChange)}
/>
<Button
disabled={readOnly}
className="object-component__field__remove-btn"
danger
type="primary"
onClick={() => handleRemoveField(index, onChange)}
icon={<DeleteOutlined />}
/>
</div>
))}
</>
)
return (
<Controller
name={name}
control={control}
render={({ field }) => (
<div className="object-component">
<div className="object-component__content">
{renderConditionFields(field.onChange)}
</div>
<div className="object-component__add-btn">
<Button disabled={readOnly} onClick={handleAddField}>Добавить заголовок</Button>
</div>
</div>
)}
/>
)
}
@@ -1,46 +0,0 @@
.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;
}
}
@@ -1,100 +0,0 @@
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<ProjectType>({
mode: 'onChange',
defaultValues: isNew ? {} : data
})
useEffect(() => {
reset(data)
}, [data])
if (isLoading) return <Spin />
if (!isNew && error) return <p>Error</p>
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 (
<section className="project-editor">
<form onSubmit={handleSubmit(handleSubmitForm)}>
<FormInput
style={{ maxWidth: 185 }}
control={control}
name="name"
label="Наименование"
rules={{ required: ValidationRules.required }}
/>
<Space>
<Button onClick={() => navigate(routePaths.projects)}>Назад</Button>
<Button type="primary" htmlType="submit">
{isNew ? 'Создать' : 'Сохранить'}
</Button>
</Space>
</form>
</section>
)
}
export default ProjectEditor
@@ -1,90 +0,0 @@
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 <Spin />
if (isError) return <p>Error</p>
const columns: ColumnsType<ProjectType> = [
{
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 (
<Space>
<Button
type="primary"
icon={ <FormOutlined />}
onClick={() => navigate(`${routePaths.project}/${record.id}`)} />
<Button
danger
onClick={() => {
deleteProject(record.id)
.unwrap()
.then(() => message.success('Проект удален'))
.catch(() => message.error('Ошибка удаления проекта'))
}}
icon={<DeleteOutlined />}
/>
</Space>
)
}
}
]
return (
<section className="project-page" style={{margin: '8px'}}>
<Button style={{marginBottom: '8px'}} type="primary" onClick={() => navigate(`${routePaths.project}/new`)}>
Создать
</Button>
<Table
size="small"
columns={columns}
pagination={{ pageSize: 30 }}
dataSource={data}
rowKey={(record) => record.id}
/>
</section>
)
}
export default ProjectsPage
@@ -1,9 +0,0 @@
export interface ProjectType {
createdAt: string
id: string
name: string
updatedAt: string
}
export interface NewProjectType {
name: string
}
@@ -1,119 +0,0 @@
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<TestType>()
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 <Spin />
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 (
<section className="test-editor">
{currentTest &&
<TestForm initialValues={currentTest} onSubmit={handleSubmitForm} readOnly={readOnly} isNew={isNew}/>
}
</section>
)
}
export default TestEditor
@@ -1,313 +0,0 @@
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 (
<form onSubmit={handleSubmit(onSubmit)}>
<Space style={{ marginBottom: 8 }}>
{!readOnly && (
<>
<Button onClick={() => navigate(routePaths.tests)}>Назад</Button>
<Button type="primary" htmlType="submit" disabled={readOnly}>
{isNew ? 'Создать' : 'Сохранить'}
</Button>
</>
)}
</Space>
<Card>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name="name"
label="Наименование теста"
rules={{ required: ValidationRules.required }}
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name="description"
label="Описание"
rules={{ required: ValidationRules.required }}
/>
</Card>
<Card>
<h4>Global Headers</h4>
<ObjectFieldRenderer
readOnly={readOnly}
control={control}
name={'scenario.globalHeaders'}
/>
</Card>
<Card>
<h4>Пул</h4>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name="scenario.pool.dialTimeout"
label="Тайм-аут подключения"
/>
<FormCheckbox
disabled={readOnly}
control={control}
name="scenario.pool.enableHttp2"
label="Включить HTTP/2"
/>
<FormCheckbox
disabled={readOnly}
control={control}
name="scenario.pool.enableKeepalive"
label="Включить Keepalive"
/>
<FormInputNumber
disabled={readOnly}
control={control}
name="scenario.pool.maxIdleCons"
label="Максимальное количество соединений"
/>
</Card>
<Card>
<h4>Запросы</h4>
{requestFields.map((field, index) => (
<Card key={field.id}>
<h4>ammo</h4>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.endpoint.method`}
label="Метод"
rules={{ required: ValidationRules.required }}
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.endpoint.url`}
label="URL"
rules={{ required: ValidationRules.required }}
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.file`}
label="Файл"
rules={{ required: ValidationRules.required }}
/>
<Card>
<h4>Заголовки</h4>
<ObjectFieldRenderer
readOnly={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.headers`}
/>
</Card>
<FormCheckbox
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.iterable`}
label="iterable"
/>
<FormCheckbox
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.templatedBody`}
label="templatedBody"
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.ammo.type`}
label="Тип"
rules={{ required: ValidationRules.required }}
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.baseUrl`}
label="Базовый URL"
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.discardResponseBody`}
label="discardResponseBody"
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.name`}
label="Имя запроса"
rules={{ required: ValidationRules.required }}
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.timeout`}
label="Тайм-аут"
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.requests.${index}.type`}
label="Тип"
rules={{ required: ValidationRules.required }}
/>
<Space>
<Button danger disabled={readOnly} onClick={() => remove(index)}>
Удалить запрос
</Button>
<Button
disabled={readOnly}
onClick={() =>
append({
name: '',
baseUrl: '',
timeout: '',
ammo: {
endpoint: { method: '', url: '' },
headers: {},
file: '',
iterable: false,
templatedBody: false,
type: ''
},
debug: false,
discardResponseBody: false,
type: ''
})
}
>
Добавить запрос
</Button>
</Space>
</Card>
))}
</Card>
<Card>
<h4>RPS</h4>
{rpsStepsFields.map((field, index) => (
<Card key={field.id}>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.rps.steps.${index}.duration`}
label="Длительность"
/>
<FormInputNumber
disabled={readOnly}
control={control}
name={`scenario.rps.steps.${index}.from`}
label="От"
/>
<FormInputNumber
disabled={readOnly}
control={control}
name={`scenario.rps.steps.${index}.step`}
label="step"
/>
<FormInputNumber
disabled={readOnly}
control={control}
name={`scenario.rps.steps.${index}.to`}
label="До"
/>
<FormInput
style={{ maxWidth: 185 }}
disabled={readOnly}
control={control}
name={`scenario.rps.steps.${index}.type`}
label="Тип"
/>
<Button
danger
disabled={readOnly}
onClick={() => removeStep(index)}
>
Удалить шаг
</Button>
</Card>
))}
<Space direction="vertical">
<Button
style={{ marginTop: 8 }}
disabled={readOnly}
onClick={() =>
appendStep({ duration: '', from: 0, to: 0, step: 0, type: '' })
}
>
Добавить шаг
</Button>
</Space>
</Card>
</form>
)
}
export default TestForm
-266
View File
@@ -1,266 +0,0 @@
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<TestType>()
const [tests, setTests] = useState<TestType[]>([])
const { handleSubmit, control } = useForm<TestType | PlayTestType>({
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: (
<form>
<FormTextArea
control={control}
name="comment"
label="Комментарий"
rules={{ required: ValidationRules.required }}
/>
<FormInputNumber control={control} name="dataOffset" label="dataOffset" />
<Space>
<Button onClick={() => modal.destroy()} danger>
Закрыть
</Button>
<Button
type="primary"
onClick={handleSubmit((data) => {
const newData = { ...record, ...data }
runTest(newData)
.unwrap()
.then(() => {
message.success('Тест запущен')
setTests((prev) =>
prev.map((test) =>
test.id === record.id ? { ...test, status: 'RUNNING' } : test
)
)
})
.catch(() => message.error('Ошибка запуска теста'))
modal.destroy()
})}
>
Запустить
</Button>
</Space>
</form>
),
})
}
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<TestType> | ColumnType<TestType>)[] = [
{
title: 'Наименование',
dataIndex: 'name',
key: 'name',
},
{
title: 'Описание',
dataIndex: 'description',
key: 'description',
},
{
title: 'Сценарий',
dataIndex: 'scenario',
key: 'scenario',
render: (_, record) => (
<a onClick={() => handleOpenScenarioModal(record)}>Смотреть сценарий</a>
),
},
{
title: 'Статус',
dataIndex: 'status',
key: 'status',
render: (status: 'READY' | 'RUNNING') => (
<Tag color={status === 'READY' ? 'green' : 'orange'}>{status}</Tag>
),
},
{
title: 'Действия',
key: 'actions',
render: (_, record) => (
<Space>
<Button
onClick={() => handlePlay(record)}
disabled={record.status === 'RUNNING'}
icon={<PlayCircleOutlined />}
/>
<Button
danger
onClick={() => handleStop(record)}
disabled={record.status === 'READY'}
icon={<StopOutlined />}
/>
<Button
type="primary"
onClick={() => navigate(`${routePaths.test}/${record.id}`)}
icon={<FormOutlined />}
/>
<Popconfirm
title="Удалить этот тест?"
onConfirm={() => {
deleteTest(record.id)
.unwrap()
.then(() => message.success('Тест удален'))
.catch(() => message.error('Ошибка удаления теста'))
}}
>
<Button danger icon={<DeleteOutlined />} />
</Popconfirm>
</Space>
),
},
]
if (isLoadingAllProjects) return <Spin />
if (isErrorAllProjects) return <ErrorWrapperPage />
const projectName =
allProjects &&
allProjects.find((project) => project.id === selectedProject)?.name
return (
<section className="tests-page">
{allProjects && (
<div style={{ marginBottom: 8 }}>
<Select
style={{ marginRight: 8 }}
value={projectName}
onChange={handleChange}
placeholder="Выберите проект"
className="tests-select"
options={transformToSelectOptions(allProjects)}
/>
<Button
type="primary"
onClick={() => navigate(`${routePaths.test}/new`)}
>
Создать
</Button>
</div>
)}
{}
{isLoadingTests ? (
<Spin />
) : (
<>
<Table
columns={columns}
dataSource={tests}
rowKey={(record) => record.id}
/>
<Modal
title="Сценарий"
open={isScenarioModalOpen}
onCancel={() => setIsScenarioModalOpen(false)}
footer={null}
>
{selectedScenario?.id && (
<TestEditor readOnly={true} propsId={selectedScenario.id} />
)}
</Modal>
<Modal
title="Запуски"
open={isLaunchesModalOpen}
onCancel={() => setIsLaunchesModalOpen(false)}
footer={null}
>
<p>Таблица с запусками</p>
</Modal>
</>
)}
</section>
)
}
export default TestsPage
-10
View File
@@ -1,10 +0,0 @@
.tests-page {
margin: 8px;
}
.test-editor {
margin: 8px;
}
.tests-select {
min-width: 200px;
}
-58
View File
@@ -1,58 +0,0 @@
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<string, string>;
pool: {
dialTimeout: string;
enableHttp2: boolean;
enableKeepalive: boolean;
maxIdleCons: number;
};
requests: {
ammo: {
endpoint: {
method: string;
url: string;
};
file: string;
headers: Record<string, string>;
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<TestType, 'projectId'> {
dataOffset?: number;
}
+117 -125
View File
@@ -8,11 +8,8 @@ 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'))
@@ -34,73 +31,59 @@ const NotFound = lazy(() => import('@pages/NotFound'))
const Routers = () => {
return (
<Routes>
<Route path={routePaths.home} element={<LayoutComponent />}>
<Route
index
element={
<Suspense fallback={<Spin />}>
<Navigate to={routePaths.tests} replace={true} />
</Suspense>
}
/>
<Route path={routePaths.tests} element={<TestsPage />} />
<Route path={`${routePaths.test}/:id`} element={<TestEditor />} />
<Route path={routePaths.projects} element={<ProjectsPage />} />
<Route path={`${routePaths.project}/:id`} element={<ProjectEditor />} />
<Route
path={`${routePaths.profile}`}
element={
<Suspense fallback={<Spin />}>
<ProfilePage />
</Suspense>
}
/>
<Route
path={routePaths.users}
element={
<Suspense fallback={<Spin />}>
<UsersPage />
</Suspense>
}
/>
<Route
path={`${routePaths.users}/:id`}
element={
<Suspense fallback={<Spin />}>
<UserEditor />
</Suspense>
}
/>
<Route
path={routePaths.roles}
element={
<Suspense fallback={<Spin />}>
<RolesPage />
</Suspense>
}
>
<Route element={<PrivateRoute />}>
<Route path={routePaths.home} element={<LayoutComponent />}>
<Route
path=":id"
index
element={
<Suspense fallback={<Spin />}>
<Navigate to={routePaths.modules} replace={true} />
</Suspense>
}
/>
<Route
path={`${routePaths.profile}`}
element={
<Suspense fallback={<Spin />}>
<ProfilePage />
</Suspense>
}
/>
<Route
path={routePaths.users}
element={
<Suspense fallback={<Spin />}>
<UsersPage />
</Suspense>
}
/>
<Route
path={`${routePaths.users}/:id`}
element={
<Suspense fallback={<Spin />}>
<UserEditor />
</Suspense>
}
/>
<Route
path={routePaths.roles}
element={
<Suspense fallback={<Spin />}>
<RolesPage />
</Suspense>
}
/>
</Route>
<Route
path={routePaths.applicationsGroup}
element={
<Suspense fallback={<Spin />}>
<ApplicationsPage />
</Suspense>
}
>
>
<Route
path=":id"
element={
<Suspense fallback={<Spin />}>
<RolesPage />
</Suspense>
}
/>
</Route>
<Route
path=":id"
path={routePaths.applicationsGroup}
element={
<Suspense fallback={<Spin />}>
<ApplicationsPage />
@@ -108,7 +91,7 @@ const Routers = () => {
}
>
<Route
path={routePaths.application}
path=":id"
element={
<Suspense fallback={<Spin />}>
<ApplicationsPage />
@@ -116,92 +99,101 @@ const Routers = () => {
}
>
<Route
path=":appId"
path={routePaths.application}
element={
<Suspense fallback={<Spin />}>
<ApplicationsPage />
</Suspense>
}
/>
>
<Route
path=":appId"
element={
<Suspense fallback={<Spin />}>
<ApplicationsPage />
</Suspense>
}
/>
</Route>
</Route>
</Route>
</Route>
<Route
path={routePaths.sessions}
element={
<Suspense fallback={<Spin />}>
<SessionsPage />
</Suspense>
}
/>
<Route
path={routePaths.securityLog}
element={
<Suspense fallback={<Spin />}>
<SecurityLogPage />
</Suspense>
}
/>
<Route
path={`${routePaths.appAccess}`}
element={
<Suspense fallback={<Spin />}>
<AppAccessPage />
</Suspense>
}
>
<Route
path=":id"
path={routePaths.sessions}
element={
<Suspense fallback={<Spin />}>
<SessionsPage />
</Suspense>
}
/>
<Route
path={routePaths.securityLog}
element={
<Suspense fallback={<Spin />}>
<SecurityLogPage />
</Suspense>
}
/>
<Route
path={`${routePaths.appAccess}`}
element={
<Suspense fallback={<Spin />}>
<AppAccessPage />
</Suspense>
}
/>
</Route>
<Route
path={`:moduleId/${routePaths.configEditor}/:id`}
element={
<Suspense fallback={<Spin />}>
<ConfigurationEditorPage />
</Suspense>
}
></Route>
<Route
path={routePaths.modules}
element={
<Suspense fallback={<Spin />}>
<ModulesPage />
</Suspense>
}
>
<Route path=":id">
>
<Route
path={routePaths.configurations}
path=":id"
element={
<Suspense fallback={<Spin />}>
<Configurations />
<AppAccessPage />
</Suspense>
}
>
/>
</Route>
<Route
path={`:moduleId/${routePaths.configEditor}/:id`}
element={
<Suspense fallback={<Spin />}>
<ConfigurationEditorPage />
</Suspense>
}
></Route>
<Route
path={routePaths.modules}
element={
<Suspense fallback={<Spin />}>
<ModulesPage />
</Suspense>
}
>
<Route path=":id">
<Route
path={routePaths.allVersions}
path={routePaths.configurations}
element={
<Suspense fallback={<Spin />}>
<AllVersionsPage />
<Configurations />
</Suspense>
}
>
<Route
path={routePaths.allVersions}
element={
<Suspense fallback={<Spin />}>
<AllVersionsPage />
</Suspense>
}
/>
</Route>
<Route
path={routePaths.connections}
element={
<Suspense fallback={<Spin />}>
<Connections />
</Suspense>
}
/>
</Route>
<Route
path={routePaths.connections}
element={
<Suspense fallback={<Spin />}>
<Connections />
</Suspense>
}
/>
</Route>
</Route>
</Route>
+1 -9
View File
@@ -17,10 +17,6 @@ type RoutePaths =
| 'configurations'
| 'allVersions'
| 'configEditor'
| 'projects'
| 'project'
| 'test'
| 'tests'
export const routePaths: Record<RoutePaths, string> = {
home: '/',
@@ -40,9 +36,5 @@ export const routePaths: Record<RoutePaths, string> = {
connections: 'connections',
configurations: 'configurations',
allVersions: ':configId/all_versions',
configEditor: 'configEditor',
projects: '/projects',
project: '/project',
test: '/test',
tests: '/tests'
configEditor: 'configEditor'
}
-62
View File
@@ -1,62 +0,0 @@
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<ProjectType[], void>({
query: () => ({
url: apiPaths.getAllProject,
method: 'POST',
body: {}
}),
providesTags: () => ['Project']
}),
createProject: builder.mutation<ProjectType, NewProjectType>({
query: (newProject) => ({
url: apiPaths.createProject,
method: 'POST',
body: newProject
}),
invalidatesTags: ['Project']
}),
updateProject: builder.mutation<void, ProjectType>({
query: (project) => ({
url: apiPaths.updateProject,
method: 'POST',
body: project
}),
invalidatesTags: ['Project']
}),
getOneProject: builder.mutation<ProjectType, string>({
query: (id) => ({
url: apiPaths.getOneProject,
method: 'POST',
body: { id }
}),
invalidatesTags: ['Project']
}),
deleteProject: builder.mutation<void, string>({
query: (id) => ({
url: apiPaths.deleteProject,
method: 'POST',
body: { id }
}),
invalidatesTags: ['Project']
})
})
})
export default projectApi
-84
View File
@@ -1,84 +0,0 @@
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<TestType[], string>({
query: (projectId) => ({
url: apiPaths.getAllTests,
method: 'POST',
body: { projectId }
}),
providesTags: () => ['Test']
}),
createTest: builder.mutation<TestType, NewTestType>({
query: (newTest) => ({
url: apiPaths.createTest,
method: 'POST',
body: newTest
}),
invalidatesTags: ['Test']
}),
runTest: builder.mutation<void, PlayTestType>({
query: (test) => ({
url: apiPaths.runTest,
method: 'POST',
body: test
}),
invalidatesTags: ['Test']
}),
stopTest: builder.mutation<void, string>({
query: (id) => ({
url: apiPaths.getOneTest,
method: 'POST',
body: { id }
}),
invalidatesTags: ['Test']
}),
updateTest: builder.mutation<void, TestType>({
query: (test) => ({
url: apiPaths.updateTest,
method: 'POST',
body: test
}),
invalidatesTags: ['Test']
}),
getOneTest: builder.mutation<TestType, string>({
query: (id) => ({
url: apiPaths.getOneTest,
method: 'POST',
body: { id }
}),
invalidatesTags: ['Test']
}),
deleteTest: builder.mutation<void, string>({
query: (id) => ({
url: apiPaths.deleteTest,
method: 'POST',
body: { id }
}),
invalidatesTags: ['Test']
})
})
})
export default testApi
+2 -8
View File
@@ -9,12 +9,10 @@ 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'
@@ -53,9 +51,7 @@ const rootReducer = combineReducers({
[applicationsGroupApi.reducerPath]: applicationsGroupApi.reducer,
[applicationsApi.reducerPath]: applicationsApi.reducer,
[configServiceApi.reducerPath]: configServiceApi.reducer,
[tokensApi.reducerPath]: tokensApi.reducer,
[projectService.reducerPath]: projectService.reducer,
[testsService.reducerPath]: testsService.reducer
[tokensApi.reducerPath]: tokensApi.reducer
})
export const setupStore = () =>
@@ -75,9 +71,7 @@ export const setupStore = () =>
applicationsGroupApi.middleware,
applicationsApi.middleware,
tokensApi.middleware,
configServiceApi.middleware,
projectService.middleware,
testsService.middleware
configServiceApi.middleware
)
})
+1 -15
View File
@@ -1,24 +1,10 @@
import { BaseQueryFn, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
import { BaseQueryFn, 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: '' }