feat: 初始化DevOps平台后端

This commit is contained in:
湛兮
2026-06-11 20:49:59 +08:00
commit caec5a618d
88 changed files with 11893 additions and 0 deletions
@@ -0,0 +1,251 @@
import { AuditService } from '../audit/audit.service';
import { JenkinsClient } from '../integrations/jenkins/jenkins.client';
import { DeployNotificationService } from '../notifications/wecom/deploy-notification.service';
import { ProjectSummary } from '../projects/project.types';
import { DeployExecutionService } from './deploy-execution.service';
import { DeployRunRepository } from './deploy-run.repository';
import { CreateDeployRunInput, DeployRunSummary } from './deploy-run.types';
describe('DeployExecutionService', () => {
const project: ProjectSummary = {
id: 'project_001',
key: 'access-manage',
name: 'access-manage',
repositoryUrl: 'https://gitea.ops.mrzhan.top/my-project/access-manage.git',
defaultBranch: 'develop',
status: 'active',
environments: [
{
name: 'test',
displayName: '测试环境',
jenkinsJobPath: 'my-project-dev/test-access-manage-develop',
},
],
};
const input: CreateDeployRunInput = {
projectKey: 'access-manage',
environment: 'test',
ref: 'develop',
operator: 'ops-admin',
};
function createRepository(): DeployRunRepository {
return new DeployRunRepository(
{
get: jest.fn(() => false),
} as never,
{} as never,
);
}
function createService(options: {
jenkinsHealth: ReturnType<JenkinsClient['healthSummary']>;
notificationStatus: 'sent' | 'skipped';
queueId?: string;
queueBuildNumber?: number;
buildResult?: 'SUCCESS' | 'FAILURE' | 'ABORTED' | 'UNSTABLE';
buildRunning?: boolean;
logText?: string;
}) {
const repository = createRepository();
const audit = {
record: jest.fn(),
} satisfies Pick<AuditService, 'record'>;
const notification = {
sendDeployRunEvent: jest.fn(() =>
Promise.resolve({
status: options.notificationStatus,
channel: 'wecom' as const,
reason:
options.notificationStatus === 'skipped'
? 'Missing WECOM_WEBHOOK_URL'
: undefined,
}),
),
} satisfies Pick<DeployNotificationService, 'sendDeployRunEvent'>;
const jenkins = {
healthSummary: jest.fn(() => options.jenkinsHealth),
buildWithParameters: jest.fn(() =>
Promise.resolve({
queueId: options.queueId ?? 'queue_001',
}),
),
getQueueItem: jest.fn((queueId: string) =>
Promise.resolve({
queueId,
buildNumber: options.queueBuildNumber,
executableUrl: options.queueBuildNumber
? `https://jenkins.example/job/${options.queueBuildNumber}/`
: undefined,
}),
),
getBuildStatus: jest.fn((_jobPath: string, buildNumber: number) =>
Promise.resolve({
jobPath: 'my-project-dev/test-access-manage-develop',
buildNumber,
building: options.buildRunning ?? false,
result: options.buildResult,
url: `https://jenkins.example/job/${buildNumber}/`,
}),
),
getProgressiveText: jest.fn(() =>
Promise.resolve({
text: options.logText ?? '',
nextStart: options.logText?.length ?? 0,
hasMore: false,
}),
),
} satisfies Pick<
JenkinsClient,
| 'healthSummary'
| 'buildWithParameters'
| 'getQueueItem'
| 'getBuildStatus'
| 'getProgressiveText'
>;
const service = new DeployExecutionService(
repository,
audit as unknown as AuditService,
notification as unknown as DeployNotificationService,
jenkins as unknown as JenkinsClient,
);
return {
audit,
jenkins,
notification,
repository,
service,
};
}
function createRun(
repository: DeployRunRepository,
idempotencyKey: string,
): DeployRunSummary {
return repository.create({
...input,
idempotencyKey,
});
}
function step(run: DeployRunSummary, bpmnNodeId: string) {
return run.steps.find((item) => item.bpmnNodeId === bpmnNodeId);
}
it('completes a dry-run release when Jenkins is not configured', async () => {
const { audit, jenkins, repository, service } = createService({
jenkinsHealth: {
status: 'not_configured',
message: 'Missing JENKINS_API_TOKEN',
},
notificationStatus: 'skipped',
});
const run = createRun(repository, 'run_dry_001');
const result = await service.execute(run, project);
expect(result.status).toBe('success');
expect(result.jenkinsQueueId).toBeUndefined();
expect(step(result, 'gitea-check')?.status).toBe('success');
expect(step(result, 'jenkins-build')?.status).toBe('success');
expect(step(result, 'health-check')?.status).toBe('success');
expect(step(result, 'notify-wecom')?.status).toBe('skipped');
expect(step(result, 'finish-release')?.status).toBe('success');
expect(jenkins.buildWithParameters).not.toHaveBeenCalled();
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({ action: 'JENKINS_DRY_RUN_COMPLETED' }),
);
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({ action: 'DEPLOY_SUCCEEDED' }),
);
});
it('triggers Jenkins and keeps the run queued until status polling completes', async () => {
const { audit, jenkins, repository, service } = createService({
jenkinsHealth: { status: 'ok' },
notificationStatus: 'sent',
queueId: 'jenkins_queue_42',
});
const run = createRun(repository, 'run_queue_001');
const result = await service.execute(run, project);
expect(result.status).toBe('queued');
expect(result.jenkinsQueueId).toBe('jenkins_queue_42');
expect(step(result, 'jenkins-build')?.status).toBe('queued');
expect(step(result, 'health-check')?.status).toBe('pending');
expect(step(result, 'notify-wecom')?.status).toBe('pending');
expect(jenkins.buildWithParameters).toHaveBeenCalledWith(
'my-project-dev/test-access-manage-develop',
expect.objectContaining({
DEPLOY_RUN_ID: 'run_queue_001',
DEPLOY_ENVIRONMENT: 'test',
GIT_REF: 'develop',
}),
);
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({
action: 'JENKINS_BUILD_TRIGGERED',
after: expect.objectContaining({
queueId: 'jenkins_queue_42',
}),
}),
);
expect(audit.record).not.toHaveBeenCalledWith(
expect.objectContaining({ action: 'DEPLOY_SUCCEEDED' }),
);
});
it('syncs a queued Jenkins run to success', async () => {
const { audit, repository, service } = createService({
jenkinsHealth: { status: 'ok' },
notificationStatus: 'sent',
queueId: 'queue_success',
queueBuildNumber: 18,
buildResult: 'SUCCESS',
});
const run = await service.execute(createRun(repository, 'run_success_001'), project);
const result = await service.syncJenkinsRun(run, project);
expect(result.status).toBe('success');
expect(result.jenkinsBuildNumber).toBe(18);
expect(step(result, 'jenkins-build')?.status).toBe('success');
expect(step(result, 'health-check')?.status).toBe('success');
expect(step(result, 'notify-wecom')?.status).toBe('success');
expect(step(result, 'finish-release')?.status).toBe('success');
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({ action: 'JENKINS_BUILD_STARTED' }),
);
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({ action: 'DEPLOY_SUCCEEDED' }),
);
});
it('syncs a queued Jenkins run to failure with a log excerpt', async () => {
const { audit, repository, service } = createService({
jenkinsHealth: { status: 'ok' },
notificationStatus: 'skipped',
queueId: 'queue_failure',
queueBuildNumber: 19,
buildResult: 'FAILURE',
logText: ['install ok', 'build failed', 'token=secret-value'].join('\n'),
});
const run = await service.execute(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(step(result, 'jenkins-build')?.status).toBe('failed');
expect(step(result, 'jenkins-build')?.errorSummary).toBe(
'Jenkins build #19 FAILURE',
);
expect(step(result, 'jenkins-build')?.logExcerpt).toContain('build failed');
expect(step(result, 'notify-wecom')?.status).toBe('skipped');
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({ action: 'DEPLOY_FAILED' }),
);
});
});