refactor: 前后端目录结构模块化 + v2 优化移植与缺陷修复
前端: - src/srv/api → src/api,按域分文件夹(auth/cluster/host/storage/deployment/collector) - 新增 http.ts 引擎(http.get/post/put/delete),域模块改用语义化调用 - index.html 增加 favicon(匹配应用 logo 的 emerald + Activity 脉冲) 后端分层增强(保留包名): - 新增 repository/:从 models 拆出 JsonDB 持久化层(InitDB/GetDB/Shutdown/RequestSave) - 新增 dto/:从 controllers 抽出各域请求契约(带 binding 校验) - 新增 pkg/crypto、pkg/jwt:从 utils 拆出安全原语(外部 jwt 别名 jwtv5 避免冲突) - models 只留领域实体 + sanitizer;utils 只留 gin/应用相关(response/errors) v2 优化移植与缺陷修复: - 移植密钥分离/SSH TOFU/并发写安全/Loki 生产级配置/Docker 加固 - 修复 deployment.go 并发丢更新、Helm values 重复键、EncryptField 哨兵、loki-gateway 端点等审计缺陷 - 实现真正的优雅关停(main.go http.Server + signal + repository.Shutdown) - 修复登录契约:后端返回 accessToken,前端 auth.ts/Login.tsx 对齐 - 补 crypto/jwt/repository 单元测试(含并发写回归) 验证: go build/vet/test 全绿;npm run build 通过;登录→鉴权→优雅关停冒烟通过 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
fb8d10231a
commit
327e282356
93 files changed
+8433
-3089
No files matched your search
@@ -0,0 +1,29 @@
|
||||
// 认证域 API
|
||||
import { http } from '../http';
|
||||
import type { User } from '@/types';
|
||||
|
||||
// 登录响应:后端 AuthController.Login 返回 TokenPair + 用户信息。
|
||||
export interface LoginResponse {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
login: (username: string, password: string) =>
|
||||
http.post<LoginResponse>('/auth/login', { username, password }),
|
||||
|
||||
register: (username: string, password: string, nickname: string, role?: string) =>
|
||||
http.post<User>('/auth/register', {
|
||||
username,
|
||||
password,
|
||||
nickname,
|
||||
role: role || 'user',
|
||||
}),
|
||||
|
||||
getCurrentUser: () => http.get<User>('/auth/user'),
|
||||
|
||||
changePassword: (oldPassword: string, newPassword: string) =>
|
||||
http.post<{ message: string }>('/auth/password', { oldPassword, newPassword }),
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
// 集群域 API
|
||||
import { http } from '../http';
|
||||
import type { PageData, Cluster, ClusterInfo } from '@/types';
|
||||
|
||||
export const clusterApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<Cluster>>(`/clusters?page=${page}&pageSize=${pageSize}`),
|
||||
|
||||
get: (id: number) => http.get<Cluster>(`/clusters/${id}`),
|
||||
|
||||
create: (data: {
|
||||
name: string; description?: string; configType?: string;
|
||||
apiServer?: string; kubeconfig?: string; token?: string; context?: string;
|
||||
}) => http.post<Cluster>('/clusters', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
http.put<{ message: string }>(`/clusters/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/clusters/${id}`),
|
||||
|
||||
validate: (id: number) =>
|
||||
http.post<{ message: string }>(`/clusters/${id}/validate`),
|
||||
|
||||
getInfo: (id: number) => http.get<ClusterInfo>(`/clusters/${id}/info`),
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
// 采集器域 API
|
||||
import { http } from '../http';
|
||||
import type { PageData, Collector, CreateCollectorRequest } from '@/types';
|
||||
|
||||
export const collectorApi = {
|
||||
list: (page = 1, pageSize = 100) =>
|
||||
http.get<PageData<Collector>>(`/collectors?page=${page}&pageSize=${pageSize}`),
|
||||
|
||||
get: (id: number) => http.get<Collector>(`/collectors/${id}`),
|
||||
|
||||
create: (data: CreateCollectorRequest) => http.post<Collector>('/collectors', data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/collectors/${id}`),
|
||||
|
||||
install: (id: number) => http.post<{ message: string }>(`/collectors/${id}/install`),
|
||||
|
||||
uninstall: (id: number) => http.post<{ message: string }>(`/collectors/${id}/uninstall`),
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
// Loki 部署域 API
|
||||
import { http } from '../http';
|
||||
import type {
|
||||
PageData,
|
||||
LokiDeployment,
|
||||
DeploymentLog,
|
||||
DashboardStats,
|
||||
CreateDeploymentRequest,
|
||||
} from '@/types';
|
||||
|
||||
export const deploymentApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<LokiDeployment>>(`/deployments?page=${page}&pageSize=${pageSize}`),
|
||||
|
||||
get: (id: number) => http.get<LokiDeployment>(`/deployments/${id}`),
|
||||
|
||||
create: (data: CreateDeploymentRequest) => http.post<LokiDeployment>('/deployments', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
http.put<{ message: string }>(`/deployments/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/deployments/${id}`),
|
||||
|
||||
deploy: (id: number) => http.post<{ message: string }>(`/deployments/${id}/deploy`),
|
||||
|
||||
stop: (id: number) => http.post<{ message: string }>(`/deployments/${id}/stop`),
|
||||
|
||||
restart: (id: number) => http.post<{ message: string }>(`/deployments/${id}/restart`),
|
||||
|
||||
logs: (id: number, page = 1, pageSize = 50) =>
|
||||
http.get<PageData<DeploymentLog>>(
|
||||
`/deployments/${id}/logs?page=${page}&pageSize=${pageSize}`
|
||||
),
|
||||
|
||||
stats: () => http.get<DashboardStats>('/deployments/stats'),
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
// 主机域 API
|
||||
import { http } from '../http';
|
||||
import type { PageData, Host, HostInfo } from '@/types';
|
||||
|
||||
export const hostApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<Host>>(`/hosts?page=${page}&pageSize=${pageSize}`),
|
||||
|
||||
get: (id: number) => http.get<Host>(`/hosts/${id}`),
|
||||
|
||||
create: (data: {
|
||||
name: string; hostIP: string; port?: number; user: string;
|
||||
authType: 'password' | 'key'; password?: string; privateKey?: string;
|
||||
keyPhrase?: string; os?: string; arch?: string; labels?: string;
|
||||
}) => http.post<Host>('/hosts', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
http.put<{ message: string }>(`/hosts/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/hosts/${id}`),
|
||||
|
||||
validate: (id: number) => http.post<{ message: string }>(`/hosts/${id}/validate`),
|
||||
|
||||
getInfo: (id: number) => http.get<HostInfo>(`/hosts/${id}/info`),
|
||||
|
||||
execute: (id: number, command: string) =>
|
||||
http.post<{ stdout: string; stderr: string }>(`/hosts/${id}/execute`, { command }),
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
// HTTP 请求引擎 — 统一的 fetch 封装,提供 request<T> 与 http.get/post/put/delete 两种用法。
|
||||
// 参考 aiops 的 @/utils/request 模式:超时/取消、token 注入、401 自动登出、统一错误处理。
|
||||
import type { ApiResponse } from '@/types';
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL || '';
|
||||
const DEFAULT_TIMEOUT = 30000; // 30秒默认超时
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('token');
|
||||
}
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
timeout?: number;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* 核心请求函数:带超时与取消支持,自动注入 Authorization,统一处理 401。
|
||||
*/
|
||||
export async function request<T>(
|
||||
url: string,
|
||||
options: RequestOptions = {}
|
||||
): Promise<T> {
|
||||
const { timeout = DEFAULT_TIMEOUT, signal, ...fetchOptions } = options;
|
||||
|
||||
const token = getToken();
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...((fetchOptions.headers as Record<string, string>) || {}),
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const fullUrl = `${API_BASE}/api/v1${url}`;
|
||||
|
||||
// 超时控制
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
// 外部 signal 联动
|
||||
const externalSignal = signal;
|
||||
const onExternalAbort = () => {
|
||||
controller.abort();
|
||||
};
|
||||
if (externalSignal) {
|
||||
externalSignal.addEventListener('abort', onExternalAbort);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(fullUrl, {
|
||||
...fetchOptions,
|
||||
headers,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (response.status === 401) {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
window.location.href = '/login';
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (!contentType || !contentType.includes('application/json')) {
|
||||
const text = await response.text();
|
||||
throw new Error(
|
||||
`Server returned non-JSON (${response.status}): ${text.substring(0, 200)}`
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ApiResponse<T>;
|
||||
if (data.code !== 0) {
|
||||
throw new Error(data.message || 'Request failed');
|
||||
}
|
||||
return data.data;
|
||||
} catch (err) {
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'AbortError') {
|
||||
if (controller.signal.aborted && !externalSignal?.aborted) {
|
||||
throw new Error(`Request timeout after ${timeout}ms`);
|
||||
}
|
||||
throw new Error('Request was cancelled');
|
||||
}
|
||||
if (err instanceof TypeError && err.message.includes('fetch')) {
|
||||
throw new Error(
|
||||
'Cannot connect to backend server. Please ensure the API server is running.'
|
||||
);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
if (externalSignal) {
|
||||
externalSignal.removeEventListener('abort', onExternalAbort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 语义化 HTTP 助手:自动处理 method 与 JSON 序列化,减少调用样板。
|
||||
* @example
|
||||
* http.get<Cluster[]>('/clusters')
|
||||
* http.post<Cluster>('/clusters', { name, ... })
|
||||
* http.put(`/clusters/${id}`, updates)
|
||||
* http.delete(`/clusters/${id}`)
|
||||
*/
|
||||
export const http = {
|
||||
get: <T>(url: string, options?: RequestOptions) =>
|
||||
request<T>(url, { ...options, method: 'GET' }),
|
||||
post: <T>(url: string, body?: unknown, options?: RequestOptions) =>
|
||||
request<T>(url, {
|
||||
...options,
|
||||
method: 'POST',
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}),
|
||||
put: <T>(url: string, body?: unknown, options?: RequestOptions) =>
|
||||
request<T>(url, {
|
||||
...options,
|
||||
method: 'PUT',
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
}),
|
||||
delete: <T>(url: string, options?: RequestOptions) =>
|
||||
request<T>(url, { ...options, method: 'DELETE' }),
|
||||
};
|
||||
|
||||
/**
|
||||
* 创建可取消的请求辅助函数
|
||||
*/
|
||||
export function createCancelableRequest() {
|
||||
const controller = new AbortController();
|
||||
|
||||
return {
|
||||
request: async <T>(url: string, options: Omit<RequestOptions, 'signal'> = {}) => {
|
||||
return request<T>(url, { ...options, signal: controller.signal });
|
||||
},
|
||||
cancel: () => controller.abort(),
|
||||
get signal() {
|
||||
return controller.signal;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 带自动重试的请求函数(不重试 401/取消/超时)
|
||||
*/
|
||||
export async function requestWithRetry<T>(
|
||||
url: string,
|
||||
options: RequestOptions = {},
|
||||
retries = 3,
|
||||
delay = 1000
|
||||
): Promise<T> {
|
||||
let lastError: Error | unknown;
|
||||
|
||||
for (let i = 0; i < retries; i++) {
|
||||
try {
|
||||
return await request<T>(url, options);
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
|
||||
if (err instanceof Error) {
|
||||
if (
|
||||
err.message === 'Unauthorized' ||
|
||||
err.message === 'Request was cancelled' ||
|
||||
err.message.startsWith('Request timeout')
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (i === retries - 1) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, delay * (i + 1)));
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// API 统一出口 — 按域组织,各域为独立文件夹(含 index.ts 桶)。
|
||||
// 用法:`import { clusterApi, hostApi, http } from '@/api'`。
|
||||
export * from './http';
|
||||
export * from './auth';
|
||||
export * from './cluster';
|
||||
export * from './host';
|
||||
export * from './storage';
|
||||
export * from './deployment';
|
||||
export * from './collector';
|
||||
@@ -0,0 +1,24 @@
|
||||
// 存储域 API
|
||||
import { http } from '../http';
|
||||
import type { PageData, StorageConfig } from '@/types';
|
||||
|
||||
export const storageApi = {
|
||||
list: (page = 1, pageSize = 10) =>
|
||||
http.get<PageData<StorageConfig>>(`/storages?page=${page}&pageSize=${pageSize}`),
|
||||
|
||||
get: (id: number) => http.get<StorageConfig>(`/storages/${id}`),
|
||||
|
||||
create: (data: {
|
||||
name: string; storageType: 's3' | 'oss' | 'minio' | 'rustfs';
|
||||
endpoint?: string; bucket: string; region?: string;
|
||||
accessKey?: string; secretKey?: string; pathPrefix?: string;
|
||||
insecure?: boolean; isDefault?: boolean;
|
||||
}) => http.post<StorageConfig>('/storages', data),
|
||||
|
||||
update: (id: number, data: Record<string, unknown>) =>
|
||||
http.put<{ message: string }>(`/storages/${id}`, data),
|
||||
|
||||
remove: (id: number) => http.delete<{ message: string }>(`/storages/${id}`),
|
||||
|
||||
getDefault: () => http.get<StorageConfig>('/storages/default'),
|
||||
};
|
||||
Reference in new issue
Block a user