feat(deploy): 关联历史失败与后续成功发布
- 发布记录:按项目环境和时间关联后续成功,保留原始失败状态 - 通知:追加脱敏恢复摘要并保留重试所需上下文 - 回归:覆盖并发顺序、跨环境、回滚和查询失败边界
This commit is contained in:
@@ -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 重试内容包含历史失败摘要;不能修改已经送出的旧群消息。关联查询失败不影响原发布状态推进。本地测试不会发送真实通知。
|
||||
|
||||
@@ -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<void> {
|
||||
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()}`,
|
||||
|
||||
@@ -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> = {},
|
||||
): 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<DeployRunSummary>[])(
|
||||
'不从跨边界或时间不明确的记录推断恢复 %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);
|
||||
});
|
||||
});
|
||||
@@ -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<DeployRunSummary[]>,
|
||||
) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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[];
|
||||
};
|
||||
|
||||
|
||||
@@ -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<void> {
|
||||
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()}`,
|
||||
|
||||
@@ -41,6 +41,7 @@ export type StoredNotificationConfig = {
|
||||
updatedAt?: string;
|
||||
};
|
||||
export type NotificationContext = {
|
||||
recoverySummary?: string;
|
||||
event: NotificationEvent;
|
||||
projectKey?: string;
|
||||
environment?: string;
|
||||
|
||||
@@ -117,3 +117,23 @@ describe('NotificationTemplateService', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('发布恢复摘要', () => {
|
||||
it('自定义正文也保留后续成功说明并屏蔽 HTML', () => {
|
||||
const preview = new NotificationTemplateService().render(
|
||||
{
|
||||
...structuredClone(defaultNotificationPreferences),
|
||||
bodyTemplate: '已完成',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
event: 'succeeded',
|
||||
recoverySummary:
|
||||
'后续版本成功 <script>不可执行</script>\n历史失败仍保留',
|
||||
},
|
||||
);
|
||||
expect(preview.body).toContain('后续版本成功');
|
||||
expect(preview.body).toContain('历史失败仍保留');
|
||||
expect(preview.body).not.toContain('<script>');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,6 +49,13 @@ export class NotificationTemplateService {
|
||||
.replace(/[<>]/g, '')
|
||||
.replace(/([\\`*[\]])/g, '\\$1');
|
||||
}
|
||||
if (context.recoverySummary)
|
||||
values.recoverySummary = redactSensitive({
|
||||
text: context.recoverySummary,
|
||||
})
|
||||
.text.replace(/[<>\r\n]/g, ' ')
|
||||
.replace(/([\\`*[\]])/g, '\\$1')
|
||||
.slice(0, 500);
|
||||
const rows = preferences.fields.flatMap((key) => {
|
||||
const field = fieldCatalog.find((item) => item.key === key)!;
|
||||
return values[key]
|
||||
@@ -102,7 +109,11 @@ export class NotificationTemplateService {
|
||||
const content = preferences.bodyTemplate.trim()
|
||||
? substitute(preferences.bodyTemplate)
|
||||
: [greeting, fields, links].filter(Boolean).join('\n\n');
|
||||
const body = [content.trim(), preferences.footer.trim()]
|
||||
const body = [
|
||||
content.trim(),
|
||||
values.recoverySummary,
|
||||
preferences.footer.trim(),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n\n');
|
||||
const markdown = `# ${title}\n\n${body}`;
|
||||
|
||||
@@ -457,6 +457,16 @@ export class DeployNotificationService {
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
event: `deploy.${event}`,
|
||||
recoverySummary: run.recoveredFrom?.length
|
||||
? `后续发布已成功;此前失败记录:${run.recoveredFrom
|
||||
.slice(0, 5)
|
||||
.map((item) => this.safeRefForOutbox(item.ref))
|
||||
.join(
|
||||
'、',
|
||||
)}。历史失败保留,请以本次成功版本 ${this.safeRefForOutbox(run.ref)} 为准。`
|
||||
: run.supersededBy
|
||||
? `此历史失败之后已有成功版本 ${this.safeRefForOutbox(run.supersededBy.ref)},请查看发布详情。`
|
||||
: undefined,
|
||||
title: this.titleFor(event),
|
||||
deployRunId: run.id,
|
||||
projectKey: run.projectKey,
|
||||
@@ -526,6 +536,7 @@ export class DeployNotificationService {
|
||||
const created = text('createdAt');
|
||||
return {
|
||||
event,
|
||||
recoverySummary: text('recoverySummary'),
|
||||
projectKey: text('projectKey'),
|
||||
environment: text('environment'),
|
||||
ref: text('ref'),
|
||||
|
||||
Reference in New Issue
Block a user