fix: 自动发现最新直构并修复构建来源链接

- 复用 Jenkins 同步器,每分钟顺序扫描各任务最新一次构建,跳过已完成历史。

- 限制自动扫描响应和超时,区分记录建档时间与真实构建时间。

- 支持独立 Jenkins 公开链接,内部请求地址保持不变。
This commit is contained in:
湛兮
2026-10-28 00:01:53 +08:00
parent bf9a229804
commit 289c01f0cd
10 changed files with 134 additions and 30 deletions
+32 -4
View File
@@ -7,10 +7,7 @@ import { ProjectSummary } from '../projects/project.types';
import { ProjectsService } from '../projects/projects.service';
import { DeployExecutionService } from './deploy-execution.service';
import { DeployRunRepository } from './deploy-run.repository';
import {
CreateDeployRunInput,
DeployRunSummary,
} from './deploy-run.types';
import { CreateDeployRunInput, DeployRunSummary } from './deploy-run.types';
import { DeployRunsService } from './deploy-runs.service';
/**
@@ -981,6 +978,37 @@ describe('DeployRunsService', () => {
]);
});
it('discovers only the latest external build without re-syncing completed history', async () => {
const completed = {
...baseRun,
id: 'run_existing',
status: 'success',
jenkinsBuildNumber: 41,
} as DeployRunSummary;
const { execution, jenkins, repository, service, audit } = createService({
runs: [completed],
});
jenkins.listRecentBuilds.mockResolvedValueOnce([
{
jobPath: 'my-project-dev/test-access-manage-develop',
buildNumber: 41,
building: false,
result: 'SUCCESS',
parameters: { GIT_REF: 'develop' },
},
]);
const result = await service.importJenkinsBuilds(undefined, true);
expect(jenkins.listRecentBuilds).toHaveBeenCalledWith(
'my-project-dev/test-access-manage-develop',
1,
expect.any(AbortSignal),
);
expect(repository.create).not.toHaveBeenCalled();
expect(execution.syncJenkinsRun).not.toHaveBeenCalled();
expect(result.syncedRuns).toHaveLength(0);
expect(audit.record).not.toHaveBeenCalled();
});
it('skips Jenkins builds whose platform parameters point to another environment', async () => {
const { jenkins, repository, service } = createService();
jenkins.listRecentBuilds.mockResolvedValueOnce([
+26 -17
View File
@@ -423,6 +423,7 @@ export class DeployRunsService {
async importJenkinsBuilds(
user?: AuthenticatedUser,
latestOnly = false,
): Promise<DeployRunJenkinsImportSummary> {
if (user) {
this.authService.assertSuperAdmin(user, '无权限导入 Jenkins 直构记录');
@@ -448,7 +449,8 @@ export class DeployRunsService {
try {
builds = await this.jenkinsClient.listRecentBuilds(
environment.jenkinsJobPath,
jenkinsExternalBuildScanLimit,
latestOnly ? 1 : jenkinsExternalBuildScanLimit,
latestOnly ? AbortSignal.timeout(5000) : undefined,
);
totalBuilds += builds.length;
} catch (error) {
@@ -492,6 +494,9 @@ export class DeployRunsService {
reason: existing.reason,
});
// 自动发现不反复回收已完成记录,也不重复写同步审计。
if (latestOnly && !this.isJenkinsSyncCandidate(existing.run))
continue;
const syncedRun = await this.syncLinkedJenkinsRun(
existing.run,
project,
@@ -521,19 +526,25 @@ export class DeployRunsService {
}
}
await this.auditService.record({
action: 'JENKINS_EXTERNAL_IMPORT_COMPLETED',
resourceType: 'deploy_run',
actorName: user?.account,
after: {
totalJobs,
totalBuilds,
importedCount: importedRuns.length,
syncedCount: syncedRuns.length,
skippedCount: skippedBuilds.length,
failedCount: failedBuilds.length,
},
});
if (
!latestOnly ||
importedRuns.length ||
syncedRuns.length ||
failedBuilds.length
)
await this.auditService.record({
action: 'JENKINS_EXTERNAL_IMPORT_COMPLETED',
resourceType: 'deploy_run',
actorName: user?.account,
after: {
totalJobs,
totalBuilds,
importedCount: importedRuns.length,
syncedCount: syncedRuns.length,
skippedCount: skippedBuilds.length,
failedCount: failedBuilds.length,
},
});
return {
checkedAt: new Date().toISOString(),
@@ -579,9 +590,7 @@ export class DeployRunsService {
environment: ProjectEnvironmentSummary,
build: JenkinsRecentBuild,
): string | undefined {
const parameterProject = this.trimOptional(
build.parameters.PROJECT_KEY,
);
const parameterProject = this.trimOptional(build.parameters.PROJECT_KEY);
const parameterEnvironment = this.normalizeDeployEnvironment(
build.parameters.DEPLOY_ENVIRONMENT,
);
@@ -15,8 +15,12 @@ describe('JenkinsSyncSchedulerService', () => {
it('does not start interval when auto sync is disabled', () => {
jest.useFakeTimers();
const sync = {
importJenkinsBuilds: jest.fn(),
syncJenkinsRuns: jest.fn(),
} satisfies Pick<DeployRunsService, 'syncJenkinsRuns'>;
} satisfies Pick<
DeployRunsService,
'syncJenkinsRuns' | 'importJenkinsBuilds'
>;
const service = new JenkinsSyncSchedulerService(
createConfig({
JENKINS_AUTO_SYNC_ENABLED: false,
@@ -34,6 +38,7 @@ describe('JenkinsSyncSchedulerService', () => {
it('runs one sweep and records aggregate audit data', async () => {
const sync = {
importJenkinsBuilds: jest.fn(),
syncJenkinsRuns: jest.fn(() =>
Promise.resolve({
checkedAt: '2026-06-11T00:00:00.000Z',
@@ -42,7 +47,10 @@ describe('JenkinsSyncSchedulerService', () => {
failedRuns: [{} as never],
}),
),
} satisfies Pick<DeployRunsService, 'syncJenkinsRuns'>;
} satisfies Pick<
DeployRunsService,
'syncJenkinsRuns' | 'importJenkinsBuilds'
>;
const audit = createAudit();
const service = new JenkinsSyncSchedulerService(
createConfig({
@@ -56,6 +64,9 @@ describe('JenkinsSyncSchedulerService', () => {
await service.runOnce();
expect(sync.syncJenkinsRuns).toHaveBeenCalledTimes(1);
expect(sync.importJenkinsBuilds).toHaveBeenCalledWith(undefined, true);
await service.runOnce();
expect(sync.importJenkinsBuilds).toHaveBeenCalledTimes(1);
expect(audit.recordMock).toHaveBeenCalledWith(
expect.objectContaining({
action: 'JENKINS_AUTO_SYNC_TICK_COMPLETED',
@@ -70,12 +81,16 @@ describe('JenkinsSyncSchedulerService', () => {
it('records redacted failure audit when sweep fails', async () => {
const sync = {
importJenkinsBuilds: jest.fn(),
syncJenkinsRuns: jest.fn(() =>
Promise.reject(
new Error('token=secret-value https://jenkins.internal failed'),
),
),
} satisfies Pick<DeployRunsService, 'syncJenkinsRuns'>;
} satisfies Pick<
DeployRunsService,
'syncJenkinsRuns' | 'importJenkinsBuilds'
>;
const audit = createAudit();
const service = new JenkinsSyncSchedulerService(
createConfig({}),
@@ -38,6 +38,7 @@ export class JenkinsSyncSchedulerService
private queue: Queue<JenkinsAutoSyncJobData, void, string> | undefined;
private worker: Worker<JenkinsAutoSyncJobData, void, string> | undefined;
private running = false;
private lastDiscoveryAt = 0;
private bullMqFallbackRecorded = false;
private bullMqRuntimeIssueRecorded = false;
@@ -186,6 +187,11 @@ export class JenkinsSyncSchedulerService
try {
const summary = await this.deployRunsService.syncJenkinsRuns();
// 复用同一调度器,每分钟只检查各纳管 job 的最新构建。
if (Date.now() - this.lastDiscoveryAt >= 60_000) {
this.lastDiscoveryAt = Date.now();
await this.deployRunsService.importJenkinsBuilds(undefined, true);
}
const hasObservableWork =
summary.totalCandidates > 0 ||
summary.syncedRuns.length > 0 ||