feat: 接入真实登录与成员权限
- auth/members/messages: 新增超级管理员登录、成员权限和密码消息流程 - agent-config/agent: 支持服务端保存 Agent 配置并取消未配置 mock 成功结果 - projects/deploy-runs/settings: 按当前用户权限保护真实接口 - prisma: 新增用户、项目权限和平台消息表结构
This commit is contained in:
@@ -17,11 +17,13 @@ export const createDeployRunSchema = z.object({
|
||||
projectKey: z.string().trim().min(1).max(80),
|
||||
environment: z.enum(['test', 'production']),
|
||||
ref: z.string().trim().min(1).max(200),
|
||||
operator: z.string().trim().min(1).max(120),
|
||||
operator: optionalTrimmedString(120),
|
||||
remark: optionalTrimmedString(500),
|
||||
idempotencyKey: optionalTrimmedString(260),
|
||||
});
|
||||
|
||||
export type CreateDeployRunRequestInput = z.infer<typeof createDeployRunSchema>;
|
||||
|
||||
export class CreateDeployRunDto {
|
||||
@ApiProperty({ example: 'access-manage' })
|
||||
projectKey!: string;
|
||||
@@ -32,8 +34,11 @@ export class CreateDeployRunDto {
|
||||
@ApiProperty({ example: 'develop' })
|
||||
ref!: string;
|
||||
|
||||
@ApiProperty({ example: 'operator@example.com' })
|
||||
operator!: string;
|
||||
@ApiPropertyOptional({
|
||||
example: 'operator@example.com',
|
||||
description: '兼容旧前端字段;后端会优先使用当前登录账号',
|
||||
})
|
||||
operator?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Manual test deploy before release.' })
|
||||
remark?: string;
|
||||
|
||||
@@ -121,10 +121,10 @@ describe('DeployExecutionService', () => {
|
||||
};
|
||||
}
|
||||
|
||||
function createRun(
|
||||
async function createRun(
|
||||
repository: DeployRunRepository,
|
||||
idempotencyKey: string,
|
||||
): DeployRunSummary {
|
||||
): Promise<DeployRunSummary> {
|
||||
return repository.create({
|
||||
...input,
|
||||
idempotencyKey,
|
||||
@@ -143,7 +143,7 @@ describe('DeployExecutionService', () => {
|
||||
},
|
||||
notificationStatus: 'skipped',
|
||||
});
|
||||
const run = createRun(repository, 'run_dry_001');
|
||||
const run = await createRun(repository, 'run_dry_001');
|
||||
|
||||
const result = await service.execute(run, project);
|
||||
|
||||
@@ -169,7 +169,7 @@ describe('DeployExecutionService', () => {
|
||||
notificationStatus: 'sent',
|
||||
queueId: 'jenkins_queue_42',
|
||||
});
|
||||
const run = createRun(repository, 'run_queue_001');
|
||||
const run = await createRun(repository, 'run_queue_001');
|
||||
|
||||
const result = await service.execute(run, project);
|
||||
|
||||
@@ -207,7 +207,10 @@ describe('DeployExecutionService', () => {
|
||||
queueBuildNumber: 18,
|
||||
buildResult: 'SUCCESS',
|
||||
});
|
||||
const run = await service.execute(createRun(repository, 'run_success_001'), project);
|
||||
const run = await service.execute(
|
||||
await createRun(repository, 'run_success_001'),
|
||||
project,
|
||||
);
|
||||
|
||||
const result = await service.syncJenkinsRun(run, project);
|
||||
|
||||
@@ -234,15 +237,18 @@ describe('DeployExecutionService', () => {
|
||||
buildResult: 'FAILURE',
|
||||
logText: ['install ok', 'build failed', 'token=secret-value'].join('\n'),
|
||||
});
|
||||
const run = await service.execute(createRun(repository, 'run_failure_001'), project);
|
||||
const run = await service.execute(
|
||||
await createRun(repository, 'run_failure_001'),
|
||||
project,
|
||||
);
|
||||
|
||||
const result = await service.syncJenkinsRun(run, project);
|
||||
|
||||
expect(result.status).toBe('failed');
|
||||
expect(result.failureSummary).toBe('Jenkins build #19 FAILURE');
|
||||
expect(result.failureSummary).toBe('Jenkins 构建 #19 FAILURE');
|
||||
expect(step(result, 'jenkins-build')?.status).toBe('failed');
|
||||
expect(step(result, 'jenkins-build')?.errorSummary).toBe(
|
||||
'Jenkins build #19 FAILURE',
|
||||
'Jenkins 构建 #19 FAILURE',
|
||||
);
|
||||
expect(step(result, 'jenkins-build')?.logExcerpt).toContain('build failed');
|
||||
expect(step(result, 'notify-wecom')?.status).toBe('skipped');
|
||||
|
||||
@@ -194,7 +194,7 @@ export class DeployExecutionService {
|
||||
currentRun.id,
|
||||
'jenkins-build',
|
||||
'running',
|
||||
`Jenkins build #${queueItem.buildNumber} is running.`,
|
||||
`Jenkins 构建 #${queueItem.buildNumber} 正在运行。`,
|
||||
);
|
||||
|
||||
await this.auditService.record({
|
||||
@@ -236,7 +236,7 @@ export class DeployExecutionService {
|
||||
currentRun.id,
|
||||
'jenkins-build',
|
||||
'running',
|
||||
`Jenkins build #${buildStatus.buildNumber} is running.`,
|
||||
`Jenkins 构建 #${buildStatus.buildNumber} 正在运行。`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -261,7 +261,7 @@ export class DeployExecutionService {
|
||||
if (health.status === 'not_configured') {
|
||||
const reason =
|
||||
health.message ??
|
||||
'Jenkins is not configured; simulated build completed.';
|
||||
'Jenkins 尚未配置,已完成本地模拟构建。';
|
||||
const currentRun = await this.completeStep(
|
||||
run.id,
|
||||
'jenkins-build',
|
||||
@@ -286,7 +286,7 @@ export class DeployExecutionService {
|
||||
if (!environment.jenkinsJobPath) {
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Project ${project.key} ${run.environment} Jenkins job path is empty`,
|
||||
`项目 ${project.key} 的 ${run.environment} 环境 Jenkins Job 路径为空`,
|
||||
400,
|
||||
{ projectKey: project.key, environment: run.environment },
|
||||
);
|
||||
@@ -312,8 +312,8 @@ export class DeployExecutionService {
|
||||
'jenkins-build',
|
||||
nextStatus,
|
||||
queueItem.buildNumber
|
||||
? `Jenkins build #${queueItem.buildNumber} is running.`
|
||||
: `Jenkins queue ${queueItem.queueId} accepted.`,
|
||||
? `Jenkins 构建 #${queueItem.buildNumber} 正在运行。`
|
||||
: `Jenkins 队列 ${queueItem.queueId} 已受理。`,
|
||||
);
|
||||
|
||||
await this.auditService.record({
|
||||
@@ -414,7 +414,7 @@ export class DeployExecutionService {
|
||||
jobPath: string,
|
||||
): Promise<DeployRunSummary> {
|
||||
const logExcerpt = await this.readFailureLogExcerpt(run, jobPath);
|
||||
const failureSummary = `Jenkins build #${run.jenkinsBuildNumber ?? '-'} ${result}`;
|
||||
const failureSummary = `Jenkins 构建 #${run.jenkinsBuildNumber ?? '-'} ${result}`;
|
||||
let currentRun =
|
||||
(await this.deployRunRepository.updateStep(run.id, 'jenkins-build', {
|
||||
status: 'failed',
|
||||
@@ -481,7 +481,7 @@ export class DeployExecutionService {
|
||||
if (!environment) {
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Project ${project.key} does not expose ${run.environment} environment`,
|
||||
`项目 ${project.key} 未配置 ${run.environment} 环境`,
|
||||
400,
|
||||
{ projectKey: project.key, environment: run.environment },
|
||||
);
|
||||
@@ -558,7 +558,7 @@ export class DeployExecutionService {
|
||||
if (!run) {
|
||||
throw new AppError(
|
||||
'RESOURCE_NOT_FOUND',
|
||||
`Deploy run ${id} not found`,
|
||||
`发布记录不存在:${id}`,
|
||||
404,
|
||||
{
|
||||
id,
|
||||
@@ -574,6 +574,6 @@ export class DeployExecutionService {
|
||||
return redactSensitive({ message: error.message }).message;
|
||||
}
|
||||
|
||||
return 'Unknown deploy execution error';
|
||||
return '未知发布执行错误';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,7 +405,7 @@ export class DeployRunRepository {
|
||||
|
||||
if (!project || !environment) {
|
||||
throw new Error(
|
||||
`Project ${input.projectKey} ${input.environment} is not seeded in database`,
|
||||
`数据库未初始化项目 ${input.projectKey} 的 ${input.environment} 环境`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
ApiBody,
|
||||
ApiCreatedResponse,
|
||||
@@ -8,62 +8,95 @@ import {
|
||||
import { ZodValidationPipe } from '../common/pipes/zod-validation.pipe';
|
||||
import {
|
||||
CreateDeployRunDto,
|
||||
CreateDeployRunRequestInput,
|
||||
createDeployRunSchema,
|
||||
} from './create-deploy-run.dto';
|
||||
import { AdminOnlyMessage } from '../auth/admin-only-message.decorator';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { AuthenticatedUser } from '../auth/auth.types';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { PasswordChangeGuard } from '../auth/password-change.guard';
|
||||
import { SuperAdminGuard } from '../auth/super-admin.guard';
|
||||
import {
|
||||
CreateDeployRunInput,
|
||||
DeployRunJenkinsSyncSummary,
|
||||
DeployRunSummary,
|
||||
} from './deploy-run.types';
|
||||
import { DeployRunsService } from './deploy-runs.service';
|
||||
|
||||
@ApiTags('deploy-runs')
|
||||
@ApiTags('发布记录')
|
||||
@Controller('deploy-runs')
|
||||
@UseGuards(AuthGuard, PasswordChangeGuard)
|
||||
export class DeployRunsController {
|
||||
constructor(private readonly deployRunsService: DeployRunsService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOkResponse({ description: 'Latest deploy runs.' })
|
||||
async listRuns(): Promise<DeployRunSummary[]> {
|
||||
return this.deployRunsService.listRuns();
|
||||
@ApiOkResponse({ description: '查询当前账号可访问项目的发布记录。' })
|
||||
async listRuns(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary[]> {
|
||||
return this.deployRunsService.listRuns(user);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOkResponse({ description: 'Deploy run detail.' })
|
||||
async getRun(@Param('id') id: string): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.getRun(id);
|
||||
@ApiOkResponse({ description: '查询发布记录详情。' })
|
||||
async getRun(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.getRun(id, user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiBody({ type: CreateDeployRunDto })
|
||||
@ApiCreatedResponse({ description: 'Create a deploy run draft.' })
|
||||
@ApiCreatedResponse({ description: '创建发布单并触发构建。' })
|
||||
async createRun(
|
||||
@Body(new ZodValidationPipe(createDeployRunSchema)) body: CreateDeployRunInput,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Body(new ZodValidationPipe(createDeployRunSchema))
|
||||
body: CreateDeployRunRequestInput,
|
||||
): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.createRun(body);
|
||||
return this.deployRunsService.createRun(
|
||||
{
|
||||
...body,
|
||||
operator: user.account,
|
||||
},
|
||||
user,
|
||||
);
|
||||
}
|
||||
|
||||
@Post(':id/cancel')
|
||||
@ApiOkResponse({ description: 'Cancel a deploy run.' })
|
||||
async cancelRun(@Param('id') id: string): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.cancelRun(id);
|
||||
@ApiOkResponse({ description: '取消发布单。' })
|
||||
async cancelRun(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.cancelRun(id, user);
|
||||
}
|
||||
|
||||
@Post(':id/retry')
|
||||
@ApiCreatedResponse({ description: 'Retry a deploy run.' })
|
||||
async retryRun(@Param('id') id: string): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.retryRun(id);
|
||||
@ApiCreatedResponse({ description: '重试发布单。' })
|
||||
async retryRun(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.retryRun(id, user);
|
||||
}
|
||||
|
||||
@Post('sync-jenkins')
|
||||
@ApiOkResponse({ description: 'Synchronize all queued/running Jenkins runs.' })
|
||||
async syncJenkinsRuns(): Promise<DeployRunJenkinsSyncSummary> {
|
||||
return this.deployRunsService.syncJenkinsRuns();
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@AdminOnlyMessage('无权限同步全部 Jenkins 状态')
|
||||
@ApiOkResponse({ description: '同步全部队列中或运行中的 Jenkins 发布状态。' })
|
||||
async syncJenkinsRuns(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunJenkinsSyncSummary> {
|
||||
return this.deployRunsService.syncJenkinsRuns(user);
|
||||
}
|
||||
|
||||
@Post(':id/sync-jenkins')
|
||||
@ApiOkResponse({ description: 'Synchronize Jenkins queue/build state.' })
|
||||
async syncJenkinsRun(@Param('id') id: string): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.syncJenkinsRun(id);
|
||||
@ApiOkResponse({ description: '同步单个发布单的 Jenkins 队列或构建状态。' })
|
||||
async syncJenkinsRun(
|
||||
@Param('id') id: string,
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
return this.deployRunsService.syncJenkinsRun(id, user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { JenkinsModule } from '../integrations/jenkins/jenkins.module';
|
||||
import { WeComModule } from '../notifications/wecom/wecom.module';
|
||||
import { ProjectsModule } from '../projects/projects.module';
|
||||
@@ -10,7 +11,7 @@ import { DeployRunsService } from './deploy-runs.service';
|
||||
import { JenkinsSyncSchedulerService } from './jenkins-sync-scheduler.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuditModule, JenkinsModule, ProjectsModule, WeComModule],
|
||||
imports: [AuditModule, AuthModule, JenkinsModule, ProjectsModule, WeComModule],
|
||||
controllers: [DeployRunsController],
|
||||
providers: [
|
||||
DeployExecutionService,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { DeployNotificationService } from '../notifications/wecom/deploy-notification.service';
|
||||
import { JenkinsClient } from '../integrations/jenkins/jenkins.client';
|
||||
@@ -58,30 +59,36 @@ describe('DeployRunsService', () => {
|
||||
findById: jest.fn((id: string) =>
|
||||
Promise.resolve(runs.find((run) => run.id === id) ?? null),
|
||||
),
|
||||
create: jest.fn((input: CreateDeployRunInput) => ({
|
||||
...baseRun,
|
||||
id: input.idempotencyKey ?? 'generated_run',
|
||||
projectKey: input.projectKey,
|
||||
environment: input.environment,
|
||||
ref: input.ref,
|
||||
operator: input.operator,
|
||||
trigger: input.trigger ?? 'manual',
|
||||
})),
|
||||
create: jest.fn((input: CreateDeployRunInput) =>
|
||||
Promise.resolve({
|
||||
...baseRun,
|
||||
id: input.idempotencyKey ?? 'generated_run',
|
||||
projectKey: input.projectKey,
|
||||
environment: input.environment,
|
||||
ref: input.ref,
|
||||
operator: input.operator,
|
||||
trigger: input.trigger ?? 'manual',
|
||||
}),
|
||||
),
|
||||
updateRun: jest.fn((id: string, patch: { status?: DeployRunStatus }) =>
|
||||
runs.some((run) => run.id === id)
|
||||
? {
|
||||
...(runs.find((run) => run.id === id) ?? baseRun),
|
||||
...patch,
|
||||
}
|
||||
: null,
|
||||
Promise.resolve(
|
||||
runs.some((run) => run.id === id)
|
||||
? {
|
||||
...(runs.find((run) => run.id === id) ?? baseRun),
|
||||
...patch,
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
updateStep: jest.fn((id: string) =>
|
||||
runs.some((run) => run.id === id)
|
||||
? {
|
||||
...(runs.find((run) => run.id === id) ?? baseRun),
|
||||
status: 'canceled' as const,
|
||||
}
|
||||
: null,
|
||||
Promise.resolve(
|
||||
runs.some((run) => run.id === id)
|
||||
? {
|
||||
...(runs.find((run) => run.id === id) ?? baseRun),
|
||||
status: 'canceled' as const,
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
} satisfies Pick<
|
||||
DeployRunRepository,
|
||||
@@ -130,10 +137,22 @@ describe('DeployRunsService', () => {
|
||||
JenkinsClient,
|
||||
'healthSummary' | 'cancelQueueItem' | 'stopBuild'
|
||||
>;
|
||||
const auth = {
|
||||
listAllowedProjectKeys: jest.fn(() =>
|
||||
Promise.resolve(runs.map((run) => run.projectKey)),
|
||||
),
|
||||
requireProjectPermission: jest.fn(() => Promise.resolve()),
|
||||
assertSuperAdmin: jest.fn(),
|
||||
} satisfies Pick<
|
||||
AuthService,
|
||||
'listAllowedProjectKeys' | 'requireProjectPermission' | 'assertSuperAdmin'
|
||||
>;
|
||||
|
||||
return {
|
||||
audit,
|
||||
auth,
|
||||
execution,
|
||||
jenkins,
|
||||
notification,
|
||||
projects,
|
||||
repository,
|
||||
@@ -144,6 +163,7 @@ describe('DeployRunsService', () => {
|
||||
notification as unknown as DeployNotificationService,
|
||||
execution as unknown as DeployExecutionService,
|
||||
jenkins as unknown as JenkinsClient,
|
||||
auth as unknown as AuthService,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -222,7 +242,7 @@ describe('DeployRunsService', () => {
|
||||
expect.objectContaining({
|
||||
action: 'DEPLOY_REJECTED',
|
||||
after: expect.objectContaining({
|
||||
reason: 'Environment is not configured',
|
||||
reason: '环境未配置',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
@@ -258,7 +278,7 @@ describe('DeployRunsService', () => {
|
||||
expect.objectContaining({
|
||||
action: 'DEPLOY_REJECTED',
|
||||
after: expect.objectContaining({
|
||||
reason: 'Ref does not match release policy',
|
||||
reason: 'Ref 不符合发布策略',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { AuthenticatedUser } from '../auth/auth.types';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { redactSensitive } from '../common/security/redact-sensitive';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
@@ -30,19 +32,33 @@ export class DeployRunsService {
|
||||
private readonly deployNotificationService: DeployNotificationService,
|
||||
private readonly deployExecutionService: DeployExecutionService,
|
||||
private readonly jenkinsClient: JenkinsClient,
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
async listRuns(): Promise<DeployRunSummary[]> {
|
||||
return this.deployRunRepository.findMany();
|
||||
async listRuns(user?: AuthenticatedUser): Promise<DeployRunSummary[]> {
|
||||
const runs = await this.deployRunRepository.findMany();
|
||||
|
||||
if (!user || user.role === 'super_admin') {
|
||||
return runs;
|
||||
}
|
||||
|
||||
const allowedProjectKeys = new Set(
|
||||
await this.authService.listAllowedProjectKeys(user),
|
||||
);
|
||||
|
||||
return runs.filter((run) => allowedProjectKeys.has(run.projectKey));
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<DeployRunSummary> {
|
||||
async getRun(
|
||||
id: string,
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
const run = await this.deployRunRepository.findById(id);
|
||||
|
||||
if (!run) {
|
||||
throw new AppError(
|
||||
'RESOURCE_NOT_FOUND',
|
||||
`Deploy run ${id} not found`,
|
||||
`发布记录不存在:${id}`,
|
||||
404,
|
||||
{
|
||||
id,
|
||||
@@ -50,19 +66,38 @@ export class DeployRunsService {
|
||||
);
|
||||
}
|
||||
|
||||
if (user) {
|
||||
await this.authService.requireProjectPermission(
|
||||
user,
|
||||
run.projectKey,
|
||||
'read',
|
||||
);
|
||||
}
|
||||
|
||||
return run;
|
||||
}
|
||||
|
||||
async createRun(input: CreateDeployRunInput): Promise<DeployRunSummary> {
|
||||
async createRun(
|
||||
input: CreateDeployRunInput,
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
if (!['test', 'production'].includes(input.environment)) {
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
'environment must be test or production',
|
||||
'发布环境必须为 test 或 production',
|
||||
400,
|
||||
{ environment: input.environment },
|
||||
);
|
||||
}
|
||||
|
||||
if (user) {
|
||||
await this.authService.requireProjectPermission(
|
||||
user,
|
||||
input.projectKey,
|
||||
'build',
|
||||
);
|
||||
}
|
||||
|
||||
const project = await this.projectsService.getProject(input.projectKey);
|
||||
await this.validateReleaseRequest(input, project);
|
||||
const run = await this.deployRunRepository.create(input);
|
||||
@@ -83,13 +118,24 @@ export class DeployRunsService {
|
||||
return this.deployExecutionService.execute(run, project);
|
||||
}
|
||||
|
||||
async cancelRun(id: string): Promise<DeployRunSummary> {
|
||||
const source = await this.getRun(id);
|
||||
async cancelRun(
|
||||
id: string,
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
const source = await this.getRun(id, user);
|
||||
|
||||
if (user) {
|
||||
await this.authService.requireProjectPermission(
|
||||
user,
|
||||
source.projectKey,
|
||||
'build',
|
||||
);
|
||||
}
|
||||
|
||||
if (['success', 'failed', 'canceled'].includes(source.status)) {
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Deploy run ${id} is already ${source.status} and cannot be canceled`,
|
||||
`发布记录 ${id} 已是终态,不能取消`,
|
||||
400,
|
||||
{
|
||||
id,
|
||||
@@ -130,27 +176,52 @@ export class DeployRunsService {
|
||||
return run;
|
||||
}
|
||||
|
||||
async retryRun(id: string): Promise<DeployRunSummary> {
|
||||
const source = await this.getRun(id);
|
||||
return this.createRun({
|
||||
projectKey: source.projectKey,
|
||||
environment: source.environment,
|
||||
ref: source.ref,
|
||||
operator: source.operator,
|
||||
remark: `Retry of ${source.id}`,
|
||||
idempotencyKey: `${source.id}:retry:${new Date().toISOString()}`,
|
||||
trigger: 'retry',
|
||||
});
|
||||
async retryRun(
|
||||
id: string,
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
const source = await this.getRun(id, user);
|
||||
|
||||
return this.createRun(
|
||||
{
|
||||
projectKey: source.projectKey,
|
||||
environment: source.environment,
|
||||
ref: source.ref,
|
||||
operator: user?.account ?? source.operator,
|
||||
remark: `重试发布记录 ${source.id}`,
|
||||
idempotencyKey: `${source.id}:retry:${new Date().toISOString()}`,
|
||||
trigger: 'retry',
|
||||
},
|
||||
user,
|
||||
);
|
||||
}
|
||||
|
||||
async syncJenkinsRun(id: string): Promise<DeployRunSummary> {
|
||||
const run = await this.getRun(id);
|
||||
async syncJenkinsRun(
|
||||
id: string,
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunSummary> {
|
||||
const run = await this.getRun(id, user);
|
||||
|
||||
if (user) {
|
||||
await this.authService.requireProjectPermission(
|
||||
user,
|
||||
run.projectKey,
|
||||
'build',
|
||||
);
|
||||
}
|
||||
|
||||
const project = await this.projectsService.getProject(run.projectKey);
|
||||
|
||||
return this.deployExecutionService.syncJenkinsRun(run, project);
|
||||
}
|
||||
|
||||
async syncJenkinsRuns(): Promise<DeployRunJenkinsSyncSummary> {
|
||||
async syncJenkinsRuns(
|
||||
user?: AuthenticatedUser,
|
||||
): Promise<DeployRunJenkinsSyncSummary> {
|
||||
if (user) {
|
||||
this.authService.assertSuperAdmin(user, '无权限同步全部 Jenkins 状态');
|
||||
}
|
||||
|
||||
const runs = await this.listRuns();
|
||||
const candidates = runs.filter((run) => this.isJenkinsSyncCandidate(run));
|
||||
const syncedRuns: DeployRunSummary[] = [];
|
||||
@@ -228,7 +299,7 @@ export class DeployRunsService {
|
||||
if (jenkinsHealth.status === 'not_configured') {
|
||||
return {
|
||||
requested: false,
|
||||
reason: jenkinsHealth.message ?? 'Jenkins is not configured',
|
||||
reason: jenkinsHealth.message ?? 'Jenkins 尚未配置',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -245,7 +316,7 @@ export class DeployRunsService {
|
||||
|
||||
return {
|
||||
requested: false,
|
||||
reason: 'Deploy run has no Jenkins queue id or build number',
|
||||
reason: '发布记录缺少 Jenkins 队列编号或构建编号',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -260,7 +331,7 @@ export class DeployRunsService {
|
||||
if (!environment) {
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Project ${project.key} does not expose ${run.environment} environment`,
|
||||
`项目 ${project.key} 未配置 ${run.environment} 环境`,
|
||||
400,
|
||||
{ projectKey: project.key, environment: run.environment },
|
||||
);
|
||||
@@ -273,14 +344,14 @@ export class DeployRunsService {
|
||||
result: JenkinsCancelResult | { requested: false; reason: string },
|
||||
): string {
|
||||
if (!result.requested) {
|
||||
return `Cancellation recorded locally: ${result.reason}`;
|
||||
return `已在本地记录取消结果:${result.reason}`;
|
||||
}
|
||||
|
||||
if (result.target === 'build') {
|
||||
return `Jenkins build #${result.buildNumber ?? '-'} stop requested.`;
|
||||
return `已请求停止 Jenkins 构建 #${result.buildNumber ?? '-'}。`;
|
||||
}
|
||||
|
||||
return `Jenkins queue ${result.queueId ?? '-'} cancel requested.`;
|
||||
return `已请求取消 Jenkins 队列 ${result.queueId ?? '-'}。`;
|
||||
}
|
||||
|
||||
private async validateReleaseRequest(
|
||||
@@ -288,10 +359,10 @@ export class DeployRunsService {
|
||||
project: ProjectSummary,
|
||||
): Promise<ProjectEnvironmentSummary> {
|
||||
if (project.status !== 'active') {
|
||||
await this.recordDeployRejected(input, 'Project is archived');
|
||||
await this.recordDeployRejected(input, '项目已归档');
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Project ${project.key} is archived and cannot be deployed`,
|
||||
`项目 ${project.key} 已归档,不能发布`,
|
||||
400,
|
||||
{ projectKey: project.key },
|
||||
);
|
||||
@@ -302,10 +373,10 @@ export class DeployRunsService {
|
||||
);
|
||||
|
||||
if (!environment) {
|
||||
await this.recordDeployRejected(input, 'Environment is not configured');
|
||||
await this.recordDeployRejected(input, '环境未配置');
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Project ${project.key} does not expose ${input.environment} environment`,
|
||||
`项目 ${project.key} 未配置 ${input.environment} 环境`,
|
||||
400,
|
||||
{ projectKey: project.key, environment: input.environment },
|
||||
);
|
||||
@@ -314,11 +385,11 @@ export class DeployRunsService {
|
||||
if (!new RegExp(environment.refPattern).test(input.ref)) {
|
||||
await this.recordDeployRejected(
|
||||
input,
|
||||
'Ref does not match release policy',
|
||||
'Ref 不符合发布策略',
|
||||
);
|
||||
throw new AppError(
|
||||
'VALIDATION_FAILED',
|
||||
`Ref ${input.ref} does not match ${environment.releasePolicy} release policy`,
|
||||
`Ref ${input.ref} 不符合 ${environment.releasePolicy} 发布策略`,
|
||||
400,
|
||||
{
|
||||
projectKey: project.key,
|
||||
@@ -352,7 +423,7 @@ export class DeployRunsService {
|
||||
|
||||
private toSafeSyncError(error: unknown): string {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Jenkins sync failed';
|
||||
error instanceof Error ? error.message : 'Jenkins 同步失败';
|
||||
|
||||
return redactSensitive({ message }).message;
|
||||
}
|
||||
@@ -364,7 +435,7 @@ export class DeployRunsService {
|
||||
if (!run) {
|
||||
throw new AppError(
|
||||
'RESOURCE_NOT_FOUND',
|
||||
`Deploy run ${id} not found`,
|
||||
`发布记录不存在:${id}`,
|
||||
404,
|
||||
{
|
||||
id,
|
||||
|
||||
@@ -65,7 +65,7 @@ export class JenkinsSyncSchedulerService
|
||||
});
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Jenkins auto sync failed';
|
||||
error instanceof Error ? error.message : 'Jenkins 自动同步失败';
|
||||
|
||||
await this.auditService.record({
|
||||
action: 'JENKINS_AUTO_SYNC_TICK_FAILED',
|
||||
|
||||
Reference in New Issue
Block a user