diff --git a/README.md b/README.md index bbc0314..4b989d5 100644 --- a/README.md +++ b/README.md @@ -175,3 +175,7 @@ Jenkins 自动同步器每分钟顺序检查各纳管 job 的最新 1 次构建 支持通知开关、六种发布时机、十一种显示字段及顺序、三种 Markdown 样式、emoji、标题/正文变量、信尾和链接开关。预览、真实事件和 outbox 重试共用 `NotificationTemplateService`。模板可使用 `{{emoji}}`、`{{eventTitle}}`、`{{greeting}}`、`{{fields}}`、`{{links}}` 和已勾选字段名;空正文使用预设排版。未勾选或缺失字段为空,HTTP(S) 之外的链接不会输出。内容按企微 Markdown 字节上限提前校验;企微响应必须同时满足 HTTP 成功和 `errcode=0`。 通知偏好经 Prisma 存入 `notification_configs`,上线需执行 `20261028030000_notification_config` 迁移并生成 Prisma Client;未启用数据库的本地模式仅在当前进程保留偏好。保存与测试均记录脱敏审计。关闭的通知时机不创建新的 outbox;已有相应失败消息停止自动重试,不会重新开启历史补发。 + +### 发布历史的后续成功关联 + +`src/deploy-runs/deploy-run-recovery.ts` 根据同项目、同环境和完成时间关联历史失败与后续成功。读取接口返回 `supersededBy` / `recoveredFrom`,保留原状态;回滚、跨环境和时间不明确的记录不推断恢复。成功通知及 outbox 重试内容包含历史失败摘要;不能修改已经送出的旧群消息。关联查询失败不影响原发布状态推进。本地测试不会发送真实通知。 diff --git a/src/deploy-runs/deploy-execution.service.ts b/src/deploy-runs/deploy-execution.service.ts index 2dfe405..810a2ea 100644 --- a/src/deploy-runs/deploy-execution.service.ts +++ b/src/deploy-runs/deploy-execution.service.ts @@ -2,6 +2,7 @@ * 编排发布单从 Gitea 校验、Jenkins 构建、健康检查到通知归档的状态推进。 * Jenkins 触发与轮询可能跨进程完成,终态写入时必须清理运行态提示。 */ +import { notificationRunWithRecovery } from './deploy-run-recovery'; import { Injectable } from '@nestjs/common'; import { AuditService } from '../audit/audit.service'; import { AppError } from '../common/errors/app-error'; @@ -648,7 +649,19 @@ export class DeployExecutionService { let currentRun = await this.markStep(run, 'notify-wecom', 'running'); const notification = await this.deployNotificationService.sendDeployRunEvent( - currentRun, + await notificationRunWithRecovery( + { + ...currentRun, + status: + event === 'succeeded' + ? 'success' + : event === 'failed' + ? 'failed' + : currentRun.status, + finishedAt: currentRun.finishedAt ?? new Date().toISOString(), + }, + () => this.deployRunRepository.findMany(), + ), event, ); const stepStatus = @@ -976,7 +989,12 @@ export class DeployExecutionService { event: DeployNotificationEvent, ): Promise { const notification = - await this.deployNotificationService.sendDeployRunEvent(run, event); + await this.deployNotificationService.sendDeployRunEvent( + await notificationRunWithRecovery(run, () => + this.deployRunRepository.findMany(), + ), + event, + ); await this.auditService.record({ action: `DEPLOY_NOTIFICATION_${notification.status.toUpperCase()}`, diff --git a/src/deploy-runs/deploy-run-recovery.spec.ts b/src/deploy-runs/deploy-run-recovery.spec.ts new file mode 100644 index 0000000..c4e223d --- /dev/null +++ b/src/deploy-runs/deploy-run-recovery.spec.ts @@ -0,0 +1,69 @@ +/** 发布关联的时间顺序与项目环境边界,历史状态始终保留。 */ +import { + relateDeployRuns, + notificationRunWithRecovery, +} from './deploy-run-recovery'; +import type { DeployRunSummary } from './deploy-run.types'; +const run = ( + id: string, + status: DeployRunSummary['status'], + minute: number, + extra: Partial = {}, +): DeployRunSummary => ({ + id, + status, + projectKey: 'role-user', + environment: 'production', + ref: id, + version: 1, + trigger: 'jenkins_external', + operator: 'jenkins-direct', + createdAt: `2026-10-28T09:0${minute}:00Z`, + finishedAt: `2026-10-28T09:0${minute}:30Z`, + steps: [], + ...extra, +}); +describe('发布恢复关联', () => { + it('关联后续成功但不改写原失败', () => { + const failed = run('v3', 'failed', 1), + success = run('v4', 'success', 2); + const related = relateDeployRuns([failed, success]); + expect(related[0].status).toBe('failed'); + expect(related[0].supersededBy).toEqual({ id: 'v4', ref: 'v4' }); + expect(related[1].recoveredFrom).toEqual([{ id: 'v3', ref: 'v3' }]); + expect(failed.supersededBy).toBeUndefined(); + }); + it('只让最早的后续成功携带恢复摘要,避免重复宣告同一历史失败', () => { + const related = relateDeployRuns([ + run('old', 'failed', 1), + run('first', 'success', 2), + run('later', 'success', 3), + ]); + expect(related[2].recoveredFrom).toBeUndefined(); + }); + it.each([ + { environment: 'test' }, + { projectKey: 'other' }, + { operationKind: 'rollback' }, + { finishedAt: undefined }, + { createdAt: '2026-10-28T09:00:00Z' }, + ] as Partial[])( + '不从跨边界或时间不明确的记录推断恢复 %p', + (extra) => { + expect( + relateDeployRuns([ + run('old', 'failed', 1), + run('new', 'success', 2, extra), + ])[0].supersededBy, + ).toBeUndefined(); + }, + ); + it('历史查询失败不能阻止通知和发布终态推进', async () => { + const current = run('current', 'success', 2); + expect( + await notificationRunWithRecovery(current, () => + Promise.reject(new Error('db')), + ), + ).toBe(current); + }); +}); diff --git a/src/deploy-runs/deploy-run-recovery.ts b/src/deploy-runs/deploy-run-recovery.ts new file mode 100644 index 0000000..1a28d2d --- /dev/null +++ b/src/deploy-runs/deploy-run-recovery.ts @@ -0,0 +1,64 @@ +/** 发布历史关联只描述同项目同环境的后续成功,不改写原失败状态,也不把回滚视作修复。 */ +import type { DeployRunSummary } from './deploy-run.types'; + +/** 时间缺失或并行发布结束顺序不明确时不推断恢复。 */ +export function relateDeployRuns(runs: DeployRunSummary[]): DeployRunSummary[] { + const time = (value?: string) => (value ? Date.parse(value) : NaN); + const succeeds = (old: DeployRunSummary, next: DeployRunSummary) => + next.status === 'success' && + next.operationKind !== 'rollback' && + old.projectKey === next.projectKey && + old.environment === next.environment && + time(next.createdAt) > time(old.createdAt) && + time(next.finishedAt) >= time(old.finishedAt); + return runs.map((run) => { + const base = { ...run }; + delete base.supersededBy; + delete base.recoveredFrom; + const later = + run.status === 'failed' + ? runs + .filter((next) => succeeds(run, next)) + .sort((a, b) => time(a.finishedAt) - time(b.finishedAt))[0] + : undefined; + const recoveredFrom = + run.status === 'success' && run.operationKind !== 'rollback' + ? runs + .filter( + (old) => + old.status === 'failed' && + succeeds(old, run) && + !runs.some( + (middle) => + middle.id !== run.id && + succeeds(old, middle) && + time(middle.finishedAt) < time(run.finishedAt), + ), + ) + .map((old) => ({ id: old.id, ref: old.ref })) + : []; + return { + ...base, + ...(later ? { supersededBy: { id: later.id, ref: later.ref } } : {}), + ...(recoveredFrom.length ? { recoveredFrom } : {}), + }; + }); +} + +/** 通知链路读取关联失败时保持原发布结果,不让历史查询影响部署状态。 */ +export async function notificationRunWithRecovery( + run: DeployRunSummary, + load: () => Promise, +) { + if (run.status !== 'success' && run.status !== 'failed') return run; + try { + return ( + relateDeployRuns([ + ...(await load()).filter((item) => item.id !== run.id), + run, + ]).find((item) => item.id === run.id) ?? run + ); + } catch { + return run; + } +} diff --git a/src/deploy-runs/deploy-run.types.ts b/src/deploy-runs/deploy-run.types.ts index b482872..35c828f 100644 --- a/src/deploy-runs/deploy-run.types.ts +++ b/src/deploy-runs/deploy-run.types.ts @@ -40,6 +40,8 @@ export type DeployRunSummary = { resolvedCommit?: string; operationKind?: 'deploy' | 'rollback' | 'retry'; sourceRunId?: string; + supersededBy?: { id: string; ref: string }; + recoveredFrom?: Array<{ id: string; ref: string }>; steps: DeployRunStepSummary[]; }; diff --git a/src/deploy-runs/deploy-runs.service.ts b/src/deploy-runs/deploy-runs.service.ts index 2dde594..c41fbb4 100644 --- a/src/deploy-runs/deploy-runs.service.ts +++ b/src/deploy-runs/deploy-runs.service.ts @@ -1,6 +1,10 @@ /** * 发布记录应用服务负责创建、取消、同步发布单,并归档审计与通知结果。 */ +import { + relateDeployRuns, + notificationRunWithRecovery, +} from './deploy-run-recovery'; import { Injectable } from '@nestjs/common'; import { AuthService } from '../auth/auth.service'; import { AuthenticatedUser } from '../auth/auth.types'; @@ -85,7 +89,11 @@ export class DeployRunsService { const shouldSyncJenkins = options.syncJenkins ?? true; if (!user || user.role === 'super_admin') { - return shouldSyncJenkins ? this.syncJenkinsCandidatesForRead(runs) : runs; + return relateDeployRuns( + shouldSyncJenkins + ? await this.syncJenkinsCandidatesForRead(runs) + : runs, + ); } const allowedProjectKeys = new Set( @@ -96,9 +104,11 @@ export class DeployRunsService { allowedProjectKeys.has(run.projectKey), ); - return shouldSyncJenkins - ? this.syncJenkinsCandidatesForRead(visibleRuns) - : visibleRuns; + return relateDeployRuns( + shouldSyncJenkins + ? await this.syncJenkinsCandidatesForRead(visibleRuns) + : visibleRuns, + ); } async getRun( @@ -122,9 +132,13 @@ export class DeployRunsService { ); } - return (options.syncJenkins ?? true) - ? this.syncJenkinsCandidateForRead(run) - : run; + const current = + (options.syncJenkins ?? true) + ? await this.syncJenkinsCandidateForRead(run) + : run; + return notificationRunWithRecovery(current, () => + this.deployRunRepository.findMany(), + ); } async createRun( @@ -562,7 +576,12 @@ export class DeployRunsService { event: DeployNotificationEvent, ): Promise { const notification = - await this.deployNotificationService.sendDeployRunEvent(run, event); + await this.deployNotificationService.sendDeployRunEvent( + await notificationRunWithRecovery(run, () => + this.deployRunRepository.findMany(), + ), + event, + ); await this.auditService.record({ action: `DEPLOY_NOTIFICATION_${notification.status.toUpperCase()}`, diff --git a/src/notifications/config/notification-config.types.ts b/src/notifications/config/notification-config.types.ts index f230092..ddc7313 100644 --- a/src/notifications/config/notification-config.types.ts +++ b/src/notifications/config/notification-config.types.ts @@ -41,6 +41,7 @@ export type StoredNotificationConfig = { updatedAt?: string; }; export type NotificationContext = { + recoverySummary?: string; event: NotificationEvent; projectKey?: string; environment?: string; diff --git a/src/notifications/config/notification-template.service.spec.ts b/src/notifications/config/notification-template.service.spec.ts index eb261e6..9d16bdd 100644 --- a/src/notifications/config/notification-template.service.spec.ts +++ b/src/notifications/config/notification-template.service.spec.ts @@ -117,3 +117,23 @@ describe('NotificationTemplateService', () => { ).toBe(false); }); }); + +describe('发布恢复摘要', () => { + it('自定义正文也保留后续成功说明并屏蔽 HTML', () => { + const preview = new NotificationTemplateService().render( + { + ...structuredClone(defaultNotificationPreferences), + bodyTemplate: '已完成', + footer: '', + }, + { + event: 'succeeded', + recoverySummary: + '后续版本成功 \n历史失败仍保留', + }, + ); + expect(preview.body).toContain('后续版本成功'); + expect(preview.body).toContain('历史失败仍保留'); + expect(preview.body).not.toContain('