Compare commits
3 Commits
3ee41ece67
...
feat-api-f
Author | SHA1 | Date | |
---|---|---|---|
0d71700f11 | |||
bd045c6abe | |||
8e3dea7099 |
0
.vscode/launch.json
vendored
0
.vscode/launch.json
vendored
7
.vscode/settings.json
vendored
7
.vscode/settings.json
vendored
@ -1,18 +1,11 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
"Repos",
|
"Repos",
|
||||||
"amqp",
|
|
||||||
"boardcat",
|
"boardcat",
|
||||||
"errout",
|
|
||||||
"fanout",
|
|
||||||
"gitea",
|
"gitea",
|
||||||
"golevelup",
|
|
||||||
"lpush",
|
"lpush",
|
||||||
"lrange",
|
"lrange",
|
||||||
"metatype",
|
"metatype",
|
||||||
"pmessage",
|
|
||||||
"psubscribe",
|
|
||||||
"rabbitmq",
|
|
||||||
"rpop",
|
"rpop",
|
||||||
"rpush"
|
"rpush"
|
||||||
]
|
]
|
||||||
|
@ -14,7 +14,5 @@ db:
|
|||||||
port: 6379
|
port: 6379
|
||||||
password:
|
password:
|
||||||
prefix: fennec
|
prefix: fennec
|
||||||
rabbitmq:
|
|
||||||
uri: 'amqp://fennec:fennec@192.168.31.194:5672'
|
|
||||||
workspaces:
|
workspaces:
|
||||||
root: '/Users/ivanli/Projects/fennec/workspaces'
|
root: '/Users/ivanli/Projects/fennec/workspaces'
|
2242
package-lock.json
generated
2242
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -21,7 +21,6 @@
|
|||||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@golevelup/nestjs-rabbitmq": "^1.16.1",
|
|
||||||
"@nestjs/bull": "^0.3.1",
|
"@nestjs/bull": "^0.3.1",
|
||||||
"@nestjs/common": "^7.5.1",
|
"@nestjs/common": "^7.5.1",
|
||||||
"@nestjs/config": "^0.6.2",
|
"@nestjs/config": "^0.6.2",
|
||||||
@ -29,6 +28,7 @@
|
|||||||
"@nestjs/graphql": "^7.9.8",
|
"@nestjs/graphql": "^7.9.8",
|
||||||
"@nestjs/platform-express": "^7.5.1",
|
"@nestjs/platform-express": "^7.5.1",
|
||||||
"@nestjs/typeorm": "^7.1.5",
|
"@nestjs/typeorm": "^7.1.5",
|
||||||
|
"@neuralegion/class-sanitizer": "^0.3.2",
|
||||||
"@types/bull": "^3.15.0",
|
"@types/bull": "^3.15.0",
|
||||||
"@types/ramda": "^0.27.38",
|
"@types/ramda": "^0.27.38",
|
||||||
"apollo-server-express": "^2.19.2",
|
"apollo-server-express": "^2.19.2",
|
||||||
@ -40,13 +40,10 @@
|
|||||||
"debug": "^4.3.1",
|
"debug": "^4.3.1",
|
||||||
"graphql": "^15.5.0",
|
"graphql": "^15.5.0",
|
||||||
"graphql-tools": "^7.0.2",
|
"graphql-tools": "^7.0.2",
|
||||||
"ioredis": "^4.25.0",
|
|
||||||
"js-yaml": "^4.0.0",
|
"js-yaml": "^4.0.0",
|
||||||
"nestjs-pino": "^1.4.0",
|
|
||||||
"nestjs-redis": "^1.2.8",
|
"nestjs-redis": "^1.2.8",
|
||||||
"observable-to-async-generator": "^1.0.1-rc",
|
"observable-to-async-generator": "^1.0.1-rc",
|
||||||
"pg": "^8.5.1",
|
"pg": "^8.5.1",
|
||||||
"pino-pretty": "^4.7.1",
|
|
||||||
"ramda": "^0.27.1",
|
"ramda": "^0.27.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
@ -61,11 +58,9 @@
|
|||||||
"@types/body-parser": "^1.19.0",
|
"@types/body-parser": "^1.19.0",
|
||||||
"@types/debug": "^4.1.5",
|
"@types/debug": "^4.1.5",
|
||||||
"@types/express": "^4.17.8",
|
"@types/express": "^4.17.8",
|
||||||
"@types/ioredis": "^4.22.2",
|
|
||||||
"@types/jest": "^26.0.15",
|
"@types/jest": "^26.0.15",
|
||||||
"@types/js-yaml": "^4.0.0",
|
"@types/js-yaml": "^4.0.0",
|
||||||
"@types/node": "^14.14.6",
|
"@types/node": "^14.14.6",
|
||||||
"@types/pino-pretty": "^4.7.0",
|
|
||||||
"@types/supertest": "^2.0.10",
|
"@types/supertest": "^2.0.10",
|
||||||
"@typescript-eslint/eslint-plugin": "^4.6.1",
|
"@typescript-eslint/eslint-plugin": "^4.6.1",
|
||||||
"@typescript-eslint/parser": "^4.6.1",
|
"@typescript-eslint/parser": "^4.6.1",
|
||||||
|
@ -15,33 +15,12 @@ import { WebhooksModule } from './webhooks/webhooks.module';
|
|||||||
import { RawBodyMiddleware } from './commons/middlewares/raw-body.middleware';
|
import { RawBodyMiddleware } from './commons/middlewares/raw-body.middleware';
|
||||||
import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller';
|
import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller';
|
||||||
import { ParseBodyMiddleware } from './commons/middlewares/parse-body.middleware';
|
import { ParseBodyMiddleware } from './commons/middlewares/parse-body.middleware';
|
||||||
import { BullModule } from '@nestjs/bull';
|
|
||||||
import { LoggerModule } from 'nestjs-pino';
|
|
||||||
|
|
||||||
import pinoPretty from 'pino-pretty';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot({
|
ConfigModule.forRoot({
|
||||||
load: [configuration],
|
load: [configuration],
|
||||||
}),
|
}),
|
||||||
LoggerModule.forRootAsync({
|
|
||||||
imports: [ConfigModule],
|
|
||||||
useFactory: (configService: ConfigService) => {
|
|
||||||
const isDev = configService.get<'dev' | 'prod'>('env') === 'dev';
|
|
||||||
return {
|
|
||||||
pinoHttp: {
|
|
||||||
prettyPrint: isDev
|
|
||||||
? {
|
|
||||||
levelFirst: true,
|
|
||||||
}
|
|
||||||
: false,
|
|
||||||
prettifier: pinoPretty,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
inject: [ConfigService],
|
|
||||||
}),
|
|
||||||
TypeOrmModule.forRootAsync({
|
TypeOrmModule.forRootAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (configService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
@ -66,17 +45,6 @@ import pinoPretty from 'pino-pretty';
|
|||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
}),
|
}),
|
||||||
BullModule.forRootAsync({
|
|
||||||
imports: [ConfigModule],
|
|
||||||
useFactory: (configService: ConfigService) => ({
|
|
||||||
redis: {
|
|
||||||
host: configService.get<string>('db.redis.host', 'localhost'),
|
|
||||||
port: configService.get<number>('db.redis.port', undefined),
|
|
||||||
password: configService.get<string>('db.redis.password', undefined),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
inject: [ConfigService],
|
|
||||||
}),
|
|
||||||
ProjectsModule,
|
ProjectsModule,
|
||||||
ReposModule,
|
ReposModule,
|
||||||
PipelinesModule,
|
PipelinesModule,
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
|
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
|
||||||
import { plainToClass } from 'class-transformer';
|
import { sanitize } from '@neuralegion/class-sanitizer/dist';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SanitizePipe implements PipeTransform {
|
export class SanitizePipe implements PipeTransform {
|
||||||
@ -12,11 +12,13 @@ export class SanitizePipe implements PipeTransform {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
const constructorFunction = metadata.metatype;
|
const constructorFunction = metadata.metatype;
|
||||||
if (!constructorFunction || value instanceof constructorFunction) {
|
if (!constructorFunction) {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
value = Object.assign(new constructorFunction(), value);
|
||||||
try {
|
try {
|
||||||
return plainToClass(constructorFunction, value);
|
sanitize(value);
|
||||||
|
return value;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
throw err;
|
throw err;
|
||||||
|
@ -1,21 +0,0 @@
|
|||||||
import { hostname } from 'os';
|
|
||||||
|
|
||||||
export function getInstanceName() {
|
|
||||||
return hostname();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getSelfInstanceRouteKey(key: string) {
|
|
||||||
return getAppInstanceRouteKey(key, getInstanceName());
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAppInstanceRouteKey(key: string, appInstance?: string) {
|
|
||||||
return appInstance ? `${key}.${appInstance}` : key;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getSelfInstanceQueueKey(key: string) {
|
|
||||||
return getAppInstanceQueueKey(key, getInstanceName());
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAppInstanceQueueKey(key: string, appInstance?: string) {
|
|
||||||
return appInstance ? `${key}.${appInstance}` : key;
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
|
||||||
import { TaskStatuses } from '../enums/task-statuses.enum';
|
|
||||||
|
|
||||||
export class PipelineTaskEvent {
|
|
||||||
taskId: string;
|
|
||||||
pipelineId: string;
|
|
||||||
projectId: string;
|
|
||||||
unit: PipelineUnits | null;
|
|
||||||
emittedAt: Date;
|
|
||||||
message: string;
|
|
||||||
messageType: 'stdout' | 'stderr' | 'stdin';
|
|
||||||
status: TaskStatuses;
|
|
||||||
}
|
|
@ -1,7 +1,6 @@
|
|||||||
import { PipelineTask } from './../pipeline-task.entity';
|
import { PipelineTask } from './../pipeline-task.entity';
|
||||||
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||||
import { Type } from 'class-transformer';
|
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class PipelineTaskLogMessage {
|
export class PipelineTaskLogMessage {
|
||||||
@ -10,7 +9,6 @@ export class PipelineTaskLogMessage {
|
|||||||
@Field(() => PipelineUnits, { nullable: true })
|
@Field(() => PipelineUnits, { nullable: true })
|
||||||
unit?: PipelineUnits;
|
unit?: PipelineUnits;
|
||||||
@Field()
|
@Field()
|
||||||
@Type(() => Date)
|
|
||||||
time: Date;
|
time: Date;
|
||||||
@Field()
|
@Field()
|
||||||
message: string;
|
message: string;
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
import { TaskStatuses } from '../enums/task-statuses.enum';
|
import { TaskStatuses } from '../enums/task-statuses.enum';
|
||||||
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
import { Field, ObjectType } from '@nestjs/graphql';
|
import { Field, ObjectType } from '@nestjs/graphql';
|
||||||
import { Type } from 'class-transformer';
|
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class PipelineTaskLogs {
|
export class PipelineTaskLogs {
|
||||||
@ -9,9 +8,7 @@ export class PipelineTaskLogs {
|
|||||||
unit: PipelineUnits;
|
unit: PipelineUnits;
|
||||||
@Field(() => TaskStatuses)
|
@Field(() => TaskStatuses)
|
||||||
status: TaskStatuses;
|
status: TaskStatuses;
|
||||||
@Type(() => Date)
|
|
||||||
startedAt?: Date;
|
startedAt?: Date;
|
||||||
@Type(() => Date)
|
|
||||||
endedAt?: Date;
|
endedAt?: Date;
|
||||||
logs = '';
|
logs = '';
|
||||||
}
|
}
|
||||||
|
25
src/pipeline-tasks/pipeline-task-logs.service.spec.ts
Normal file
25
src/pipeline-tasks/pipeline-task-logs.service.spec.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
|
||||||
|
describe('PipelineTaskLogsService', () => {
|
||||||
|
let service: PipelineTaskLogsService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
PipelineTaskLogsService,
|
||||||
|
{
|
||||||
|
provide: RedisService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<PipelineTaskLogsService>(PipelineTaskLogsService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
78
src/pipeline-tasks/pipeline-task-logs.service.ts
Normal file
78
src/pipeline-tasks/pipeline-task-logs.service.ts
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { log } from 'console';
|
||||||
|
import { PubSub } from 'graphql-subscriptions';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
import { find, omit, propEq } from 'ramda';
|
||||||
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
|
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
||||||
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
|
||||||
|
const LOG_TIMEOUT_SECONDS = 10_000;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PipelineTaskLogsService {
|
||||||
|
constructor(private readonly redisService: RedisService) {}
|
||||||
|
|
||||||
|
pubSub = new PubSub();
|
||||||
|
|
||||||
|
get redis() {
|
||||||
|
return this.redisService.getClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
getKeys(task: PipelineTask) {
|
||||||
|
return `ptl:${task.id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async recordLog(log: PipelineTaskLogMessage) {
|
||||||
|
const logDto = omit(['task'], log);
|
||||||
|
await Promise.all([
|
||||||
|
this.pubSub.publish(this.getKeys(log.task), logDto),
|
||||||
|
this.redis
|
||||||
|
.expire(this.getKeys(log.task), LOG_TIMEOUT_SECONDS)
|
||||||
|
.then(() =>
|
||||||
|
this.redis.rpush(this.getKeys(log.task), JSON.stringify(logDto)),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async readLog(task: PipelineTask): Promise<PipelineTaskLogMessage[]> {
|
||||||
|
return await this.redis.lrange(this.getKeys(task), 0, -1).then((items) =>
|
||||||
|
items.map((item) => {
|
||||||
|
const log = JSON.parse(item) as PipelineTaskLogMessage;
|
||||||
|
log.task = task;
|
||||||
|
log.time = new Date(log.time);
|
||||||
|
return log;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async readLogsAsPipelineTaskLogs(
|
||||||
|
task: PipelineTask,
|
||||||
|
): Promise<PipelineTaskLogs[]> {
|
||||||
|
const logs = await this.readLog(task);
|
||||||
|
const taskLogs: PipelineTaskLogs[] = [];
|
||||||
|
for (const log of logs) {
|
||||||
|
const taskLog = find<PipelineTaskLogs>(
|
||||||
|
propEq('unit', log.unit),
|
||||||
|
taskLogs,
|
||||||
|
);
|
||||||
|
if (!taskLog) {
|
||||||
|
taskLogs.push({
|
||||||
|
unit: (log.unit as unknown) as PipelineUnits,
|
||||||
|
status: TaskStatuses.working,
|
||||||
|
startedAt: log.time,
|
||||||
|
logs: log.message,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
taskLog.logs += log.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return taskLogs;
|
||||||
|
}
|
||||||
|
|
||||||
|
watchLogs(task: PipelineTask) {
|
||||||
|
return this.pubSub.asyncIterator(this.getKeys(task));
|
||||||
|
}
|
||||||
|
}
|
242
src/pipeline-tasks/pipeline-task.consumer.spec.ts
Normal file
242
src/pipeline-tasks/pipeline-task.consumer.spec.ts
Normal file
@ -0,0 +1,242 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { Job } from 'bull';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { ReposService } from '../repos/repos.service';
|
||||||
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
|
import { PipelineTaskConsumer } from './pipeline-task.consumer';
|
||||||
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
|
import { Project } from '../projects/project.entity';
|
||||||
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
import { ApplicationException } from '../commons/exceptions/application.exception';
|
||||||
|
|
||||||
|
describe('PipelineTaskConsumer', () => {
|
||||||
|
let consumer: PipelineTaskConsumer;
|
||||||
|
let tasksService: PipelineTasksService;
|
||||||
|
let logsService: PipelineTaskLogsService;
|
||||||
|
const getJob = () =>
|
||||||
|
({
|
||||||
|
data: {
|
||||||
|
pipelineId: 'test',
|
||||||
|
units: [PipelineUnits.checkout, PipelineUnits.test],
|
||||||
|
},
|
||||||
|
} as Job<PipelineTask>);
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: PipelineTasksService,
|
||||||
|
useValue: {
|
||||||
|
doNextTask: () => undefined,
|
||||||
|
updateTask: async (value) => value,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ReposService,
|
||||||
|
useValue: {
|
||||||
|
getWorkspaceRootByTask: () => 'workspace-root',
|
||||||
|
checkout: async () => undefined,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: PipelineTaskLogsService,
|
||||||
|
useValue: {
|
||||||
|
recordLog: async () => undefined,
|
||||||
|
readLogsAsPipelineTaskLogs: async () => [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
PipelineTaskConsumer,
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
tasksService = module.get(PipelineTasksService);
|
||||||
|
logsService = module.get(PipelineTaskLogsService);
|
||||||
|
consumer = module.get(PipelineTaskConsumer);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(consumer).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('onCompleted', () => {
|
||||||
|
it('should call doNextTask()', () => {
|
||||||
|
const job = getJob();
|
||||||
|
const doNextTask = jest.spyOn(tasksService, 'doNextTask');
|
||||||
|
consumer.onCompleted(job);
|
||||||
|
expect(doNextTask).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('runScript', () => {
|
||||||
|
let logText: string;
|
||||||
|
let errorText: string;
|
||||||
|
let recordLog: jest.SpyInstance;
|
||||||
|
beforeEach(() => {
|
||||||
|
logText = '';
|
||||||
|
errorText = '';
|
||||||
|
recordLog = jest
|
||||||
|
.spyOn(logsService, 'recordLog')
|
||||||
|
.mockImplementation(async (log: PipelineTaskLogMessage) => {
|
||||||
|
logText += log.message;
|
||||||
|
if (log.isError) {
|
||||||
|
errorText += log.message;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('should success and log right message', async () => {
|
||||||
|
await consumer.runScript(
|
||||||
|
'node one-second-work.js',
|
||||||
|
join(__dirname, '../../test/data'),
|
||||||
|
);
|
||||||
|
expect(logText).toMatch(/10.+20.+30.+40.+50.+60.+70.+80.+90/s);
|
||||||
|
expect(recordLog).toHaveBeenCalledTimes(10);
|
||||||
|
expect(
|
||||||
|
((recordLog.mock.calls[8][0] as unknown) as PipelineTaskLogMessage)
|
||||||
|
.message,
|
||||||
|
).toMatch(/^90/);
|
||||||
|
});
|
||||||
|
it('should failed and log right message', async () => {
|
||||||
|
await expect(
|
||||||
|
consumer.runScript(
|
||||||
|
'node bad-work.js',
|
||||||
|
join(__dirname, '../../test/data'),
|
||||||
|
),
|
||||||
|
).rejects.toThrowError(/exec script failed/);
|
||||||
|
expect(errorText).toMatch(/Error Message/);
|
||||||
|
const logs = recordLog.mock.calls
|
||||||
|
.map((call) => ((call[0] as unknown) as PipelineTaskLogMessage).message)
|
||||||
|
.join('');
|
||||||
|
expect(logs).toMatch(/10.+20.+30.+40.+50/s);
|
||||||
|
});
|
||||||
|
it('should log with task', async () => {
|
||||||
|
const task = new PipelineTask();
|
||||||
|
task.id = 'test';
|
||||||
|
|
||||||
|
const recordLog = jest.spyOn(logsService, 'recordLog');
|
||||||
|
await expect(
|
||||||
|
consumer.runScript(
|
||||||
|
'node bad-work.js',
|
||||||
|
join(__dirname, '../../test/data'),
|
||||||
|
task,
|
||||||
|
),
|
||||||
|
).rejects.toThrowError(/exec script failed/);
|
||||||
|
|
||||||
|
expect(errorText).toMatch(/Error Message 2/);
|
||||||
|
expect(
|
||||||
|
((recordLog.mock.calls[2][0] as unknown) as PipelineTaskLogMessage)
|
||||||
|
.task,
|
||||||
|
).toMatchObject(task);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('doTask', () => {
|
||||||
|
let task: PipelineTask;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
task = new PipelineTask();
|
||||||
|
task.id = 'test-id';
|
||||||
|
task.logs = [];
|
||||||
|
task.pipeline = new Pipeline();
|
||||||
|
task.pipeline.workUnitMetadata = {
|
||||||
|
version: 1,
|
||||||
|
units: [
|
||||||
|
{
|
||||||
|
type: PipelineUnits.checkout,
|
||||||
|
scripts: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: PipelineUnits.installDependencies,
|
||||||
|
scripts: ["echo ' Hello, Fennec!'"],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
task.units = task.pipeline.workUnitMetadata.units.map(
|
||||||
|
(unit) => unit.type,
|
||||||
|
);
|
||||||
|
task.pipeline.project = new Project();
|
||||||
|
task.pipeline.project.name = 'test-project';
|
||||||
|
});
|
||||||
|
|
||||||
|
it('success and update task on db', async () => {
|
||||||
|
const job: Job = ({
|
||||||
|
data: task,
|
||||||
|
update: jest.fn().mockImplementation(() => undefined),
|
||||||
|
} as unknown) as Job;
|
||||||
|
|
||||||
|
jest
|
||||||
|
.spyOn(consumer, 'runScript')
|
||||||
|
.mockImplementation(async () => undefined);
|
||||||
|
const updateTask = jest.spyOn(tasksService, 'updateTask');
|
||||||
|
|
||||||
|
await consumer.doTask(job);
|
||||||
|
|
||||||
|
expect(updateTask).toHaveBeenCalledTimes(2);
|
||||||
|
expect(updateTask.mock.calls[0][0].startedAt).toBeDefined();
|
||||||
|
expect(updateTask.mock.calls[1][0].endedAt).toBeDefined();
|
||||||
|
expect(updateTask.mock.calls[1][0].status).toEqual(TaskStatuses.success);
|
||||||
|
});
|
||||||
|
it('failed and update task on db', async () => {
|
||||||
|
const job: Job = ({
|
||||||
|
data: task,
|
||||||
|
update: jest.fn().mockImplementation(() => undefined),
|
||||||
|
} as unknown) as Job;
|
||||||
|
|
||||||
|
jest.spyOn(consumer, 'runScript').mockImplementation(async () => {
|
||||||
|
throw new ApplicationException('exec script failed');
|
||||||
|
});
|
||||||
|
const updateTask = jest.spyOn(tasksService, 'updateTask');
|
||||||
|
|
||||||
|
await consumer.doTask(job);
|
||||||
|
|
||||||
|
expect(updateTask).toHaveBeenCalledTimes(2);
|
||||||
|
expect(updateTask.mock.calls[0][0].startedAt).toBeDefined();
|
||||||
|
expect(updateTask.mock.calls[1][0].endedAt).toBeDefined();
|
||||||
|
expect(updateTask.mock.calls[1][0].status).toEqual(TaskStatuses.failed);
|
||||||
|
});
|
||||||
|
it('should do all task', async () => {
|
||||||
|
const job: Job = ({
|
||||||
|
data: task,
|
||||||
|
update: jest.fn().mockImplementation(() => undefined),
|
||||||
|
} as unknown) as Job;
|
||||||
|
|
||||||
|
const runScript = jest
|
||||||
|
.spyOn(consumer, 'runScript')
|
||||||
|
.mockImplementation(async () => undefined);
|
||||||
|
const updateTask = jest.spyOn(tasksService, 'updateTask');
|
||||||
|
|
||||||
|
await consumer.doTask(job);
|
||||||
|
|
||||||
|
expect(runScript).toHaveBeenCalledTimes(1);
|
||||||
|
expect(updateTask).toHaveBeenCalledTimes(2);
|
||||||
|
const taskDto: PipelineTask = updateTask.mock.calls[0][0];
|
||||||
|
expect(taskDto.logs).toHaveLength(2);
|
||||||
|
expect(taskDto.logs[0].status).toEqual(TaskStatuses.success);
|
||||||
|
expect(taskDto.logs[0].unit).toEqual(PipelineUnits.checkout);
|
||||||
|
});
|
||||||
|
it('should log error message', async () => {
|
||||||
|
const job: Job = ({
|
||||||
|
data: task,
|
||||||
|
update: jest.fn().mockImplementation(() => undefined),
|
||||||
|
} as unknown) as Job;
|
||||||
|
|
||||||
|
const runScript = jest
|
||||||
|
.spyOn(consumer, 'runScript')
|
||||||
|
.mockImplementation(async () => {
|
||||||
|
throw new Error('bad message');
|
||||||
|
});
|
||||||
|
const updateTask = jest.spyOn(tasksService, 'updateTask');
|
||||||
|
|
||||||
|
await consumer.doTask(job);
|
||||||
|
|
||||||
|
expect(updateTask).toHaveBeenCalledTimes(2);
|
||||||
|
const taskDto: PipelineTask = updateTask.mock.calls[0][0];
|
||||||
|
expect(taskDto.logs).toHaveLength(2);
|
||||||
|
expect(taskDto.logs[0].status).toEqual(TaskStatuses.success);
|
||||||
|
expect(taskDto.logs[1].status).toEqual(TaskStatuses.failed);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
147
src/pipeline-tasks/pipeline-task.consumer.ts
Normal file
147
src/pipeline-tasks/pipeline-task.consumer.ts
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
||||||
|
import { ReposService } from './../repos/repos.service';
|
||||||
|
import {
|
||||||
|
OnQueueCompleted,
|
||||||
|
OnQueueFailed,
|
||||||
|
Process,
|
||||||
|
Processor,
|
||||||
|
} from '@nestjs/bull';
|
||||||
|
import { Job } from 'bull';
|
||||||
|
import { spawn } from 'child_process';
|
||||||
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
|
||||||
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
import { ApplicationException } from '../commons/exceptions/application.exception';
|
||||||
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
import debug from 'debug';
|
||||||
|
|
||||||
|
const log = debug('fennec:pipeline-tasks:consumer');
|
||||||
|
|
||||||
|
@Processor(PIPELINE_TASK_QUEUE)
|
||||||
|
export class PipelineTaskConsumer {
|
||||||
|
constructor(
|
||||||
|
private readonly service: PipelineTasksService,
|
||||||
|
private readonly reposService: ReposService,
|
||||||
|
private readonly logsService: PipelineTaskLogsService,
|
||||||
|
) {}
|
||||||
|
@Process()
|
||||||
|
async doTask(job: Job<PipelineTask>) {
|
||||||
|
let task = job.data;
|
||||||
|
if (task.pipeline.workUnitMetadata.version !== 1) {
|
||||||
|
throw new ApplicationException(
|
||||||
|
'work unit metadata version is not match.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
task.startedAt = new Date();
|
||||||
|
task.status = TaskStatuses.working;
|
||||||
|
task = await this.service.updateTask(task);
|
||||||
|
log('start job');
|
||||||
|
await job.update(task);
|
||||||
|
|
||||||
|
const workspaceRoot = this.reposService.getWorkspaceRootByTask(task);
|
||||||
|
|
||||||
|
const units = task.units.map(
|
||||||
|
(type) =>
|
||||||
|
task.pipeline.workUnitMetadata.units.find(
|
||||||
|
(unit) => unit.type === type,
|
||||||
|
) ?? { type: type, scripts: [] },
|
||||||
|
);
|
||||||
|
|
||||||
|
log('task have [%o] units', units);
|
||||||
|
try {
|
||||||
|
for (const unit of units) {
|
||||||
|
const unitLog = new PipelineTaskLogs();
|
||||||
|
unitLog.unit = unit.type;
|
||||||
|
unitLog.startedAt = new Date();
|
||||||
|
log('curr unit is %s', unit.type);
|
||||||
|
try {
|
||||||
|
// 检出代码前执行 git checkout
|
||||||
|
if (unit.type === PipelineUnits.checkout) {
|
||||||
|
log('begin checkout');
|
||||||
|
await this.reposService.checkout(task, workspaceRoot);
|
||||||
|
unitLog.status = TaskStatuses.success;
|
||||||
|
log('end checkout');
|
||||||
|
}
|
||||||
|
for (const script of unit.scripts) {
|
||||||
|
unitLog.logs += `[RUN SCRIPT] ${script}`;
|
||||||
|
log('begin runScript %s', script);
|
||||||
|
await this.runScript(script, workspaceRoot, task, unit.type);
|
||||||
|
log('end runScript %s', script);
|
||||||
|
}
|
||||||
|
unitLog.status = TaskStatuses.success;
|
||||||
|
} catch (err) {
|
||||||
|
unitLog.status = TaskStatuses.failed;
|
||||||
|
unitLog.logs += err.message;
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
unitLog.endedAt = new Date();
|
||||||
|
unitLog.logs = await this.logsService
|
||||||
|
.readLogsAsPipelineTaskLogs(task)
|
||||||
|
.then(
|
||||||
|
(taskLogs) =>
|
||||||
|
taskLogs.find((tl) => tl.unit === unit.type)?.logs ?? '',
|
||||||
|
);
|
||||||
|
task.logs.push(unitLog);
|
||||||
|
await job.update(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
task.status = TaskStatuses.success;
|
||||||
|
} catch (err) {
|
||||||
|
task.status = TaskStatuses.failed;
|
||||||
|
log('task is failed', err);
|
||||||
|
} finally {
|
||||||
|
task.endedAt = new Date();
|
||||||
|
task = await this.service.updateTask(task);
|
||||||
|
await job.update(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async runScript(
|
||||||
|
script: string,
|
||||||
|
workspaceRoot: string,
|
||||||
|
task?: PipelineTask,
|
||||||
|
unit?: PipelineUnits,
|
||||||
|
): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const sub = spawn(script, {
|
||||||
|
shell: true,
|
||||||
|
cwd: workspaceRoot,
|
||||||
|
});
|
||||||
|
sub.stderr.on('data', (data: Buffer) => {
|
||||||
|
const str = data.toString();
|
||||||
|
this.logsService.recordLog(
|
||||||
|
PipelineTaskLogMessage.create(task, unit, str, true),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
sub.stdout.on('data', (data: Buffer) => {
|
||||||
|
const str = data.toString();
|
||||||
|
this.logsService.recordLog(
|
||||||
|
PipelineTaskLogMessage.create(task, unit, str, false),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
sub.addListener('close', (code) => {
|
||||||
|
if (code === 0) {
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
return reject(new ApplicationException('exec script failed'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@OnQueueCompleted()
|
||||||
|
onCompleted(job: Job<PipelineTask>) {
|
||||||
|
log('queue onCompleted');
|
||||||
|
this.service.doNextTask(job.data.pipeline);
|
||||||
|
}
|
||||||
|
|
||||||
|
@OnQueueFailed()
|
||||||
|
onFailed(job: Job<PipelineTask>) {
|
||||||
|
log('queue onFailed');
|
||||||
|
this.service.doNextTask(job.data.pipeline);
|
||||||
|
}
|
||||||
|
}
|
@ -1,16 +1,11 @@
|
|||||||
import { AppBaseEntity } from './../commons/entities/app-base-entity';
|
import { AppBaseEntity } from './../commons/entities/app-base-entity';
|
||||||
import { ObjectType } from '@nestjs/graphql';
|
import { Field, ObjectType } from '@nestjs/graphql';
|
||||||
import { Column, Entity, ManyToOne, ValueTransformer } from 'typeorm';
|
import { Column, Entity, ManyToOne } from 'typeorm';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
||||||
import { TaskStatuses } from './enums/task-statuses.enum';
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
import { plainToClass } from 'class-transformer';
|
|
||||||
|
|
||||||
const logsTransformer: ValueTransformer = {
|
|
||||||
from: (value) => plainToClass(PipelineTaskLogs, value),
|
|
||||||
to: (value) => value,
|
|
||||||
};
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
@Entity()
|
@Entity()
|
||||||
export class PipelineTask extends AppBaseEntity {
|
export class PipelineTask extends AppBaseEntity {
|
||||||
@ -25,7 +20,7 @@ export class PipelineTask extends AppBaseEntity {
|
|||||||
@Column({ type: 'enum', enum: PipelineUnits, array: true })
|
@Column({ type: 'enum', enum: PipelineUnits, array: true })
|
||||||
units: PipelineUnits[];
|
units: PipelineUnits[];
|
||||||
|
|
||||||
@Column({ type: 'jsonb', default: '[]', transformer: logsTransformer })
|
@Column({ type: 'jsonb', default: '[]' })
|
||||||
logs: PipelineTaskLogs[];
|
logs: PipelineTaskLogs[];
|
||||||
|
|
||||||
@Column({ type: 'enum', enum: TaskStatuses, default: TaskStatuses.pending })
|
@Column({ type: 'enum', enum: TaskStatuses, default: TaskStatuses.pending })
|
||||||
|
@ -1,321 +0,0 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
|
||||||
import { ReposService } from '../repos/repos.service';
|
|
||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
|
||||||
import { Project } from '../projects/project.entity';
|
|
||||||
import { TaskStatuses } from './enums/task-statuses.enum';
|
|
||||||
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
|
||||||
import { PipelineTaskRunner } from './pipeline-task.runner';
|
|
||||||
import { WorkUnitMetadata } from './models/work-unit-metadata.model';
|
|
||||||
describe('PipelineTaskRunner', () => {
|
|
||||||
let runner: PipelineTaskRunner;
|
|
||||||
let reposService: ReposService;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
|
||||||
providers: [
|
|
||||||
{
|
|
||||||
provide: ReposService,
|
|
||||||
useValue: {
|
|
||||||
getWorkspaceRootByTask: () => 'workspace-root',
|
|
||||||
checkout: async () => undefined,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: getLoggerToken(PipelineTaskRunner.name),
|
|
||||||
useValue: new PinoLogger({}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: 'spawn',
|
|
||||||
useValue: () => undefined,
|
|
||||||
},
|
|
||||||
PipelineTaskRunner,
|
|
||||||
],
|
|
||||||
}).compile();
|
|
||||||
|
|
||||||
reposService = module.get(ReposService);
|
|
||||||
runner = module.get(PipelineTaskRunner);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should be defined', () => {
|
|
||||||
expect(runner).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('onNewTask', async () => {
|
|
||||||
const task = new PipelineTask();
|
|
||||||
let tmpTask;
|
|
||||||
const doTask = jest
|
|
||||||
.spyOn(runner, 'doTask')
|
|
||||||
.mockImplementation(async (task) => {
|
|
||||||
tmpTask = task;
|
|
||||||
});
|
|
||||||
await runner.onNewTask(task);
|
|
||||||
expect(tmpTask).toEqual(task);
|
|
||||||
expect(doTask).toBeCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('test biz', () => {
|
|
||||||
let emitEvent: jest.SpyInstance;
|
|
||||||
beforeEach(() => {
|
|
||||||
emitEvent = jest
|
|
||||||
.spyOn(runner, 'emitEvent')
|
|
||||||
.mockImplementation((..._) => Promise.resolve());
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('doTask', () => {
|
|
||||||
let checkout: jest.SpyInstance;
|
|
||||||
let doTaskUnit: jest.SpyInstance;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
checkout = jest
|
|
||||||
.spyOn(runner, 'checkout')
|
|
||||||
.mockImplementation((..._) => Promise.resolve('/null'));
|
|
||||||
doTaskUnit = jest
|
|
||||||
.spyOn(runner, 'doTaskUnit')
|
|
||||||
.mockImplementation((..._) => Promise.resolve());
|
|
||||||
});
|
|
||||||
|
|
||||||
it('only checkout', async () => {
|
|
||||||
const task = new PipelineTask();
|
|
||||||
(task.id = 'taskId'), (task.pipeline = new Pipeline());
|
|
||||||
task.units = [PipelineUnits.checkout];
|
|
||||||
task.pipeline.id = 'pipelineId';
|
|
||||||
task.pipeline.project = new Project();
|
|
||||||
task.pipeline.project.id = 'projectId';
|
|
||||||
task.pipeline.workUnitMetadata = new WorkUnitMetadata();
|
|
||||||
task.pipeline.workUnitMetadata.version = 1;
|
|
||||||
task.pipeline.workUnitMetadata.units = [
|
|
||||||
{
|
|
||||||
type: PipelineUnits.checkout,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
await runner.doTask(task);
|
|
||||||
|
|
||||||
expect(checkout).toBeCalledTimes(1);
|
|
||||||
expect(doTaskUnit).toBeCalledTimes(0);
|
|
||||||
expect(emitEvent).toBeCalledTimes(2);
|
|
||||||
expect(emitEvent.mock.calls[0][0]).toMatchObject(task);
|
|
||||||
expect(emitEvent.mock.calls[0][1]).toBeNull();
|
|
||||||
expect(emitEvent.mock.calls[0][2]).toEqual(TaskStatuses.working);
|
|
||||||
expect(emitEvent.mock.calls[1][0]).toMatchObject(task);
|
|
||||||
expect(emitEvent.mock.calls[1][1]).toBeNull();
|
|
||||||
expect(emitEvent.mock.calls[1][2]).toEqual(TaskStatuses.success);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('many units', async () => {
|
|
||||||
const task = new PipelineTask();
|
|
||||||
(task.id = 'taskId'), (task.pipeline = new Pipeline());
|
|
||||||
task.units = [
|
|
||||||
PipelineUnits.checkout,
|
|
||||||
PipelineUnits.test,
|
|
||||||
PipelineUnits.deploy,
|
|
||||||
];
|
|
||||||
task.pipeline.id = 'pipelineId';
|
|
||||||
task.pipeline.project = new Project();
|
|
||||||
task.pipeline.project.id = 'projectId';
|
|
||||||
task.pipeline.workUnitMetadata = new WorkUnitMetadata();
|
|
||||||
task.pipeline.workUnitMetadata.version = 1;
|
|
||||||
task.pipeline.workUnitMetadata.units = [
|
|
||||||
{
|
|
||||||
type: PipelineUnits.checkout,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: PipelineUnits.installDependencies,
|
|
||||||
scripts: ['pwd'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: PipelineUnits.test,
|
|
||||||
scripts: ['pwd'],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: PipelineUnits.deploy,
|
|
||||||
scripts: ['pwd', 'uname'],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
await runner.doTask(task);
|
|
||||||
|
|
||||||
expect(checkout).toBeCalledTimes(1);
|
|
||||||
expect(doTaskUnit).toBeCalledTimes(2);
|
|
||||||
expect(emitEvent).toBeCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('unit work failed', async () => {
|
|
||||||
const task = new PipelineTask();
|
|
||||||
(task.id = 'taskId'), (task.pipeline = new Pipeline());
|
|
||||||
task.units = [PipelineUnits.checkout, PipelineUnits.test];
|
|
||||||
task.pipeline.id = 'pipelineId';
|
|
||||||
task.pipeline.project = new Project();
|
|
||||||
task.pipeline.project.id = 'projectId';
|
|
||||||
task.pipeline.workUnitMetadata = new WorkUnitMetadata();
|
|
||||||
task.pipeline.workUnitMetadata.version = 1;
|
|
||||||
task.pipeline.workUnitMetadata.units = [
|
|
||||||
{
|
|
||||||
type: PipelineUnits.checkout,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: PipelineUnits.test,
|
|
||||||
scripts: ['pwd'],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
doTaskUnit = jest
|
|
||||||
.spyOn(runner, 'doTaskUnit')
|
|
||||||
.mockImplementation((..._) =>
|
|
||||||
Promise.reject(new Error('test error')),
|
|
||||||
);
|
|
||||||
await runner.doTask(task);
|
|
||||||
|
|
||||||
expect(checkout).toBeCalledTimes(1);
|
|
||||||
expect(doTaskUnit).toBeCalledTimes(1);
|
|
||||||
expect(emitEvent).toBeCalledTimes(2);
|
|
||||||
expect(emitEvent.mock.calls[1][0]).toMatchObject(task);
|
|
||||||
expect(emitEvent.mock.calls[1][1]).toBeNull();
|
|
||||||
expect(emitEvent.mock.calls[1][2]).toEqual(TaskStatuses.failed);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('doTaskUnit', () => {
|
|
||||||
it('success', async () => {
|
|
||||||
const runScript = jest
|
|
||||||
.spyOn(runner, 'runScript')
|
|
||||||
.mockImplementation((..._) => Promise.resolve());
|
|
||||||
const task = new PipelineTask();
|
|
||||||
|
|
||||||
const unit = PipelineUnits.test;
|
|
||||||
const workspacePath = '/null';
|
|
||||||
await runner.doTaskUnit(unit, ['pwd'], task, workspacePath);
|
|
||||||
|
|
||||||
expect(emitEvent.mock.calls[0][0]).toEqual(task);
|
|
||||||
expect(emitEvent.mock.calls[0][1]).toEqual(unit);
|
|
||||||
expect(emitEvent.mock.calls[0][2]).toEqual(TaskStatuses.working);
|
|
||||||
expect(emitEvent.mock.calls[1][0]).toEqual(task);
|
|
||||||
expect(emitEvent.mock.calls[1][1]).toEqual(unit);
|
|
||||||
expect(emitEvent.mock.calls[1][2]).toEqual(TaskStatuses.success);
|
|
||||||
expect(runScript.mock.calls[0][0]).toEqual('pwd');
|
|
||||||
expect(runScript.mock.calls[0][1]).toEqual(workspacePath);
|
|
||||||
expect(runScript.mock.calls[0][2]).toEqual(task);
|
|
||||||
expect(runScript.mock.calls[0][3]).toEqual(unit);
|
|
||||||
});
|
|
||||||
it('failed', async () => {
|
|
||||||
const runScript = jest
|
|
||||||
.spyOn(runner, 'runScript')
|
|
||||||
.mockImplementation((..._) =>
|
|
||||||
Promise.reject(new Error('test error')),
|
|
||||||
);
|
|
||||||
const task = new PipelineTask();
|
|
||||||
|
|
||||||
const unit = PipelineUnits.test;
|
|
||||||
const workspacePath = '/null';
|
|
||||||
await expect(
|
|
||||||
runner.doTaskUnit(unit, ['pwd'], task, workspacePath),
|
|
||||||
).rejects.toThrow('test error');
|
|
||||||
|
|
||||||
expect(emitEvent.mock.calls[1]?.[0]).toEqual(task);
|
|
||||||
expect(emitEvent.mock.calls[1]?.[1]).toEqual(unit);
|
|
||||||
expect(emitEvent.mock.calls[1]?.[2]).toEqual(TaskStatuses.failed);
|
|
||||||
expect(runScript).toBeCalledTimes(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('runScript', () => {
|
|
||||||
it('normal', async () => {
|
|
||||||
const spawn = jest.fn((..._: any[]) => ({
|
|
||||||
stdout: {
|
|
||||||
on: () => undefined,
|
|
||||||
},
|
|
||||||
stderr: {
|
|
||||||
on: () => undefined,
|
|
||||||
},
|
|
||||||
addListener: (_: any, fn: (code: number) => void) => {
|
|
||||||
fn(0);
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
(runner as any).spawn = spawn;
|
|
||||||
|
|
||||||
const task = new PipelineTask();
|
|
||||||
task.id = 'taskId';
|
|
||||||
const unit = PipelineUnits.deploy;
|
|
||||||
|
|
||||||
await runner.runScript('script name', 'workspaceRoot', task, unit);
|
|
||||||
expect(spawn).toHaveBeenCalledTimes(1);
|
|
||||||
expect(spawn.mock.calls[0][0]).toEqual('script name');
|
|
||||||
expect(spawn.mock.calls[0][1]).toMatchObject({
|
|
||||||
shell: true,
|
|
||||||
cwd: 'workspaceRoot',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
it('failed', async () => {
|
|
||||||
const spawn = jest.fn((..._: any[]) => ({
|
|
||||||
stdout: {
|
|
||||||
on: () => undefined,
|
|
||||||
},
|
|
||||||
stderr: {
|
|
||||||
on: () => undefined,
|
|
||||||
},
|
|
||||||
addListener: (_: any, fn: (code: number) => void) => {
|
|
||||||
fn(1);
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
(runner as any).spawn = spawn;
|
|
||||||
|
|
||||||
const task = new PipelineTask();
|
|
||||||
task.id = 'taskId';
|
|
||||||
const unit = PipelineUnits.deploy;
|
|
||||||
|
|
||||||
expect(
|
|
||||||
runner.runScript('script name', 'workspaceRoot', task, unit),
|
|
||||||
).rejects.toThrowError();
|
|
||||||
});
|
|
||||||
it('wait emit message done', async () => {
|
|
||||||
let finishedFn: () => void;
|
|
||||||
const on = jest.fn((_: any, fn: (buff: Buffer) => void) => {
|
|
||||||
setTimeout(() => {
|
|
||||||
fn(Buffer.from('message 1'));
|
|
||||||
setTimeout(() => {
|
|
||||||
fn(Buffer.from('message 2'));
|
|
||||||
setTimeout(() => {
|
|
||||||
fn(Buffer.from('message 3'));
|
|
||||||
finishedFn();
|
|
||||||
}, 1000);
|
|
||||||
}, 10);
|
|
||||||
}, 10);
|
|
||||||
});
|
|
||||||
const spawn = jest.fn((..._: any[]) => ({
|
|
||||||
stdout: {
|
|
||||||
on,
|
|
||||||
},
|
|
||||||
stderr: {
|
|
||||||
on,
|
|
||||||
},
|
|
||||||
addListener: (_: any, fn: (code: number) => void) => {
|
|
||||||
finishedFn = () => fn(0);
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
let emitSuccessCount = 0;
|
|
||||||
jest.spyOn(runner, 'emitEvent').mockImplementation((..._: any[]) => {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
setTimeout(() => {
|
|
||||||
emitSuccessCount++;
|
|
||||||
resolve();
|
|
||||||
}, 1000);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
(runner as any).spawn = spawn;
|
|
||||||
|
|
||||||
const task = new PipelineTask();
|
|
||||||
task.id = 'taskId';
|
|
||||||
const unit = PipelineUnits.deploy;
|
|
||||||
|
|
||||||
await runner.runScript('script name', 'workspaceRoot', task, unit);
|
|
||||||
expect(emitSuccessCount).toEqual(1 + 6);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
@ -1,253 +0,0 @@
|
|||||||
import { ReposService } from '../repos/repos.service';
|
|
||||||
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
|
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
|
||||||
import { ApplicationException } from '../commons/exceptions/application.exception';
|
|
||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
|
||||||
import { TaskStatuses } from './enums/task-statuses.enum';
|
|
||||||
import { InjectPinoLogger, PinoLogger } from 'nestjs-pino';
|
|
||||||
import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
|
||||||
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
|
||||||
import { last } from 'ramda';
|
|
||||||
import { Inject } from '@nestjs/common';
|
|
||||||
|
|
||||||
type Spawn = typeof spawn;
|
|
||||||
|
|
||||||
export class PipelineTaskRunner {
|
|
||||||
readonly processes = new Map<string, ChildProcessWithoutNullStreams>();
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly reposService: ReposService,
|
|
||||||
@InjectPinoLogger(PipelineTaskRunner.name)
|
|
||||||
private readonly logger: PinoLogger,
|
|
||||||
@Inject('spawn')
|
|
||||||
private readonly spawn: Spawn,
|
|
||||||
) {}
|
|
||||||
@RabbitSubscribe({
|
|
||||||
exchange: 'new-pipeline-task',
|
|
||||||
routingKey: 'mac',
|
|
||||||
queue: 'mac.new-pipeline-task',
|
|
||||||
})
|
|
||||||
async onNewTask(task: PipelineTask) {
|
|
||||||
this.logger.info({ task }, 'on new task [%s].', task.id);
|
|
||||||
try {
|
|
||||||
await this.doTask(task);
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error({ task, err }, err.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@RabbitSubscribe({
|
|
||||||
exchange: 'stop-pipeline-task',
|
|
||||||
routingKey: 'mac',
|
|
||||||
queue: 'mac.stop-pipeline-task',
|
|
||||||
})
|
|
||||||
async onStopTask(task: PipelineTask) {
|
|
||||||
this.logger.info({ task }, 'on stop task [%s].', task.id);
|
|
||||||
const process = this.processes.get(task.id);
|
|
||||||
if (process) {
|
|
||||||
this.logger.info({ task }, 'send signal SIGINT to child process.');
|
|
||||||
process.kill('SIGINT');
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
if (process === this.processes.get(task.id)) {
|
|
||||||
this.logger.info({ task }, 'send signal SIGKILL to child process.');
|
|
||||||
process.kill('SIGKILL');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (this.processes.has(task.id)) {
|
|
||||||
this.logger.error(
|
|
||||||
{ task },
|
|
||||||
'this pipeline task not stop yet. there is a new process running, maybe is a bug about error capture',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, 10_000);
|
|
||||||
} else {
|
|
||||||
this.logger.info({ task }, 'child process is not running.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async doTask(task: PipelineTask) {
|
|
||||||
if (task.pipeline.workUnitMetadata.version !== 1) {
|
|
||||||
throw new ApplicationException(
|
|
||||||
'work unit metadata version is not match.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
null,
|
|
||||||
TaskStatuses.working,
|
|
||||||
`[start task]`,
|
|
||||||
'stdout',
|
|
||||||
);
|
|
||||||
|
|
||||||
this.logger.info('running task [%s].', task.id);
|
|
||||||
try {
|
|
||||||
const workspaceRoot = await this.checkout(task);
|
|
||||||
const units = task.units
|
|
||||||
.filter((unit) => unit !== PipelineUnits.checkout)
|
|
||||||
.map(
|
|
||||||
(type) =>
|
|
||||||
task.pipeline.workUnitMetadata.units.find(
|
|
||||||
(unit) => unit.type === type,
|
|
||||||
) ?? { type: type, scripts: [] },
|
|
||||||
);
|
|
||||||
this.logger.info({ units }, 'begin run units.');
|
|
||||||
for (const unit of units) {
|
|
||||||
await this.doTaskUnit(unit.type, unit.scripts, task, workspaceRoot);
|
|
||||||
}
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
null,
|
|
||||||
TaskStatuses.success,
|
|
||||||
`[finished task] success`,
|
|
||||||
'stdout',
|
|
||||||
);
|
|
||||||
this.logger.info({ task }, 'task [%s] completed.', task.id);
|
|
||||||
} catch (err) {
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
null,
|
|
||||||
TaskStatuses.failed,
|
|
||||||
`[finished unit] ${err.message}`,
|
|
||||||
'stderr',
|
|
||||||
);
|
|
||||||
this.logger.error({ task, error: err }, 'task [%s] failed.', task.id);
|
|
||||||
} finally {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async doTaskUnit(
|
|
||||||
unit: PipelineUnits,
|
|
||||||
scripts: string[],
|
|
||||||
task: PipelineTask,
|
|
||||||
workspaceRoot: string,
|
|
||||||
) {
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
unit,
|
|
||||||
TaskStatuses.working,
|
|
||||||
`[begin unit] ${unit}`,
|
|
||||||
'stdin',
|
|
||||||
);
|
|
||||||
this.logger.info({ task }, 'curr unit is %s', unit);
|
|
||||||
try {
|
|
||||||
for (const script of scripts) {
|
|
||||||
this.logger.debug('begin runScript %s', script);
|
|
||||||
await this.runScript(script, workspaceRoot, task, unit);
|
|
||||||
this.logger.debug('end runScript %s', script);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
unit,
|
|
||||||
TaskStatuses.success,
|
|
||||||
`[finished unit] ${unit}`,
|
|
||||||
'stdout',
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
unit,
|
|
||||||
TaskStatuses.failed,
|
|
||||||
`[finished unit] ${err.message}`,
|
|
||||||
'stderr',
|
|
||||||
);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async checkout(task: PipelineTask) {
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
PipelineUnits.checkout,
|
|
||||||
TaskStatuses.working,
|
|
||||||
'[begin unit] checkout',
|
|
||||||
'stdin',
|
|
||||||
);
|
|
||||||
try {
|
|
||||||
const path = await this.reposService.checkout4Task(task);
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
PipelineUnits.checkout,
|
|
||||||
TaskStatuses.success,
|
|
||||||
'checkout success.',
|
|
||||||
'stdout',
|
|
||||||
);
|
|
||||||
return path;
|
|
||||||
} catch (err) {
|
|
||||||
await this.emitEvent(
|
|
||||||
task,
|
|
||||||
PipelineUnits.checkout,
|
|
||||||
TaskStatuses.failed,
|
|
||||||
'checkout failed.',
|
|
||||||
'stderr',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async emitEvent(
|
|
||||||
task: PipelineTask,
|
|
||||||
unit: PipelineUnits | null,
|
|
||||||
status: TaskStatuses,
|
|
||||||
message: string,
|
|
||||||
messageType: 'stderr' | 'stdout' | 'stdin',
|
|
||||||
) {
|
|
||||||
const event: PipelineTaskEvent = {
|
|
||||||
taskId: task.id,
|
|
||||||
pipelineId: task.pipeline.id,
|
|
||||||
projectId: task.pipeline.project.id,
|
|
||||||
unit,
|
|
||||||
emittedAt: new Date(),
|
|
||||||
message: last(message) === '\n' ? message : message + '\n',
|
|
||||||
messageType,
|
|
||||||
status,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async runScript(
|
|
||||||
script: string,
|
|
||||||
workspaceRoot: string,
|
|
||||||
task: PipelineTask,
|
|
||||||
unit: PipelineUnits,
|
|
||||||
): Promise<void> {
|
|
||||||
await this.emitEvent(task, unit, TaskStatuses.working, script, 'stdin');
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const sub = this.spawn(script, {
|
|
||||||
shell: true,
|
|
||||||
cwd: workspaceRoot,
|
|
||||||
});
|
|
||||||
this.processes.set(task.id, sub);
|
|
||||||
let loggingCount = 0; // semaphore
|
|
||||||
|
|
||||||
sub.stderr.on('data', (data: Buffer) => {
|
|
||||||
const str = data.toString();
|
|
||||||
loggingCount++;
|
|
||||||
|
|
||||||
this.emitEvent(task, unit, TaskStatuses.working, str, 'stdout').finally(
|
|
||||||
() => loggingCount--,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
sub.stdout.on('data', (data: Buffer) => {
|
|
||||||
const str = data.toString();
|
|
||||||
loggingCount++;
|
|
||||||
|
|
||||||
this.emitEvent(task, unit, TaskStatuses.working, str, 'stderr').finally(
|
|
||||||
() => loggingCount--,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
sub.addListener('close', async (code) => {
|
|
||||||
this.processes.delete(task.id);
|
|
||||||
await new Promise<void>(async (resolve) => {
|
|
||||||
for (let i = 0; i < 10 && loggingCount > 0; i++) {
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
||||||
this.logger.debug('waiting logging... (%dx500ms)', i);
|
|
||||||
}
|
|
||||||
resolve();
|
|
||||||
});
|
|
||||||
if (code === 0) {
|
|
||||||
return resolve();
|
|
||||||
}
|
|
||||||
return reject(new ApplicationException('exec script failed'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
3
src/pipeline-tasks/pipeline-tasks.constants.ts
Normal file
3
src/pipeline-tasks/pipeline-tasks.constants.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export const PIPELINE_TASK_QUEUE = 'PIPELINE_TASK_QUEUE';
|
||||||
|
export const PIPELINE_TASK_LOG_QUEUE = 'PIPELINE_TASK_LOG_QUEUE';
|
||||||
|
export const PIPELINE_TASK_LOG_PUBSUB = 'PIPELINE_TASK_LOG_PUBSUB';
|
@ -6,55 +6,32 @@ import { PipelineTask } from './pipeline-task.entity';
|
|||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
import { ReposModule } from '../repos/repos.module';
|
import { ReposModule } from '../repos/repos.module';
|
||||||
import { RedisModule } from 'nestjs-redis';
|
import { RedisModule } from 'nestjs-redis';
|
||||||
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
import { BullModule } from '@nestjs/bull';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { PipelineTaskConsumer } from './pipeline-task.consumer';
|
||||||
import { PipelineTaskRunner } from './pipeline-task.runner';
|
import {
|
||||||
import { spawn } from 'child_process';
|
PIPELINE_TASK_QUEUE,
|
||||||
|
PIPELINE_TASK_LOG_PUBSUB,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
import { PubSub } from 'apollo-server-express';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([PipelineTask, Pipeline]),
|
TypeOrmModule.forFeature([PipelineTask, Pipeline]),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: PIPELINE_TASK_QUEUE,
|
||||||
|
}),
|
||||||
RedisModule,
|
RedisModule,
|
||||||
ReposModule,
|
ReposModule,
|
||||||
|
|
||||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
|
||||||
imports: [ConfigModule],
|
|
||||||
useFactory: (configService: ConfigService) => ({
|
|
||||||
uri: configService.get<string>('db.rabbitmq.uri'),
|
|
||||||
exchanges: [
|
|
||||||
{
|
|
||||||
name: 'new-pipeline-task',
|
|
||||||
type: 'fanout',
|
|
||||||
options: {
|
|
||||||
durable: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'stop-pipeline-task',
|
|
||||||
type: 'fanout',
|
|
||||||
options: {
|
|
||||||
durable: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'update-pipeline-task',
|
|
||||||
type: 'fanout',
|
|
||||||
options: {
|
|
||||||
durable: false,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
inject: [ConfigService],
|
|
||||||
}),
|
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
PipelineTasksService,
|
PipelineTasksService,
|
||||||
PipelineTasksResolver,
|
PipelineTasksResolver,
|
||||||
PipelineTaskRunner,
|
PipelineTaskConsumer,
|
||||||
|
PipelineTaskLogsService,
|
||||||
{
|
{
|
||||||
provide: 'spawn',
|
provide: Symbol(PIPELINE_TASK_LOG_PUBSUB),
|
||||||
useValue: spawn,
|
useValue: new PubSub(),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
exports: [PipelineTasksService],
|
exports: [PipelineTasksService],
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { PipelineTasksResolver } from './pipeline-tasks.resolver';
|
import { PipelineTasksResolver } from './pipeline-tasks.resolver';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
import { PipelineTasksService } from './pipeline-tasks.service';
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
|
||||||
describe('PipelineTasksResolver', () => {
|
describe('PipelineTasksResolver', () => {
|
||||||
@ -13,6 +14,10 @@ describe('PipelineTasksResolver', () => {
|
|||||||
provide: PipelineTasksService,
|
provide: PipelineTasksService,
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: PipelineTaskLogsService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -4,11 +4,14 @@ import { PipelineTasksService } from './pipeline-tasks.service';
|
|||||||
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
||||||
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args';
|
import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args';
|
||||||
import { plainToClass } from 'class-transformer';
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class PipelineTasksResolver {
|
export class PipelineTasksResolver {
|
||||||
constructor(private readonly service: PipelineTasksService) {}
|
constructor(
|
||||||
|
private readonly service: PipelineTasksService,
|
||||||
|
private readonly logsService: PipelineTaskLogsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Mutation(() => PipelineTask)
|
@Mutation(() => PipelineTask)
|
||||||
async createPipelineTask(@Args('task') taskDto: CreatePipelineTaskInput) {
|
async createPipelineTask(@Args('task') taskDto: CreatePipelineTaskInput) {
|
||||||
@ -17,14 +20,13 @@ export class PipelineTasksResolver {
|
|||||||
|
|
||||||
@Subscription(() => PipelineTaskLogMessage, {
|
@Subscription(() => PipelineTaskLogMessage, {
|
||||||
resolve: (value) => {
|
resolve: (value) => {
|
||||||
const data = plainToClass(PipelineTaskLogMessage, value);
|
return value;
|
||||||
return data;
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
async pipelineTaskLog(@Args() args: PipelineTaskLogArgs) {
|
async pipelineTaskLog(@Args() args: PipelineTaskLogArgs) {
|
||||||
// const task = await this.service.findTaskById(args.taskId);
|
const task = await this.service.findTaskById(args.taskId);
|
||||||
// const asyncIterator = this.logsService.watchLogs(task);
|
const asyncIterator = this.logsService.watchLogs(task);
|
||||||
// return asyncIterator;
|
return asyncIterator;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Subscription(() => PipelineTask, {
|
@Subscription(() => PipelineTask, {
|
||||||
@ -33,7 +35,7 @@ export class PipelineTasksResolver {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
async pipelineTaskChanged(@Args('id') id: string) {
|
async pipelineTaskChanged(@Args('id') id: string) {
|
||||||
// return await this.service.watchTaskUpdated(id);
|
return await this.service.watchTaskUpdated(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => [PipelineTask])
|
@Query(() => [PipelineTask])
|
||||||
@ -42,12 +44,7 @@ export class PipelineTasksResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => PipelineTask)
|
@Query(() => PipelineTask)
|
||||||
async pipelineTask(@Args('id') id: string) {
|
async findPipelineTask(@Args('id') id: string) {
|
||||||
return await this.service.findTaskById(id);
|
return await this.service.findTaskById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Mutation(() => Boolean)
|
|
||||||
async stopPipelineTask(@Args('id') id: string) {
|
|
||||||
const task = await this.service.findTaskById(id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -2,10 +2,14 @@ import { Test, TestingModule } from '@nestjs/testing';
|
|||||||
import { PipelineTasksService } from './pipeline-tasks.service';
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
|
||||||
|
import { getQueueToken } from '@nestjs/bull';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
|
import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Queue } from 'bull';
|
import { Queue } from 'bull';
|
||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
import { LockFailedException } from '../commons/exceptions/lock-failed.exception';
|
||||||
|
|
||||||
describe('PipelineTasksService', () => {
|
describe('PipelineTasksService', () => {
|
||||||
let service: PipelineTasksService;
|
let service: PipelineTasksService;
|
||||||
@ -24,8 +28,25 @@ describe('PipelineTasksService', () => {
|
|||||||
} as Pipeline);
|
} as Pipeline);
|
||||||
let redisClient;
|
let redisClient;
|
||||||
let taskQueue: Queue;
|
let taskQueue: Queue;
|
||||||
|
const getTask = () =>
|
||||||
|
({
|
||||||
|
pipelineId: 'test',
|
||||||
|
commit: 'test',
|
||||||
|
pipeline: { branch: 'master' },
|
||||||
|
units: [],
|
||||||
|
} as PipelineTask);
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
|
redisClient = (() => ({
|
||||||
|
set: jest.fn().mockImplementation(async () => 'OK'),
|
||||||
|
del: jest.fn().mockImplementation(async () => 'test'),
|
||||||
|
get: jest.fn().mockImplementation(async () => 'test'),
|
||||||
|
lpush: jest.fn().mockImplementation(async () => 1),
|
||||||
|
rpop: jest.fn().mockImplementation(async () => JSON.stringify(getTask())),
|
||||||
|
}))() as any;
|
||||||
|
taskQueue = (() => ({
|
||||||
|
add: jest.fn().mockImplementation(async () => null),
|
||||||
|
}))() as any;
|
||||||
module = await Test.createTestingModule({
|
module = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
PipelineTasksService,
|
PipelineTasksService,
|
||||||
@ -38,8 +59,14 @@ describe('PipelineTasksService', () => {
|
|||||||
useValue: new Repository(),
|
useValue: new Repository(),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: AmqpConnection,
|
provide: getQueueToken(PIPELINE_TASK_QUEUE),
|
||||||
useValue: {},
|
useValue: taskQueue,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: RedisService,
|
||||||
|
useValue: {
|
||||||
|
getClient: jest.fn(() => redisClient),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
@ -60,43 +87,119 @@ describe('PipelineTasksService', () => {
|
|||||||
expect(service).toBeDefined();
|
expect(service).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
// describe('addTask', () => {
|
describe('addTask', () => {
|
||||||
// beforeEach(() => {
|
beforeEach(() => {
|
||||||
// jest
|
jest
|
||||||
// .spyOn(pipelineRepository, 'findOneOrFail')
|
.spyOn(pipelineRepository, 'findOneOrFail')
|
||||||
// .mockImplementation(async () => getBasePipeline());
|
.mockImplementation(async () => getBasePipeline());
|
||||||
// });
|
});
|
||||||
// it('pipeline not found', async () => {
|
it('pipeline not found', async () => {
|
||||||
// jest.spyOn(taskRepository, 'findOneOrFail').mockImplementation(() => {
|
jest.spyOn(taskRepository, 'findOneOrFail').mockImplementation(() => {
|
||||||
// throw new EntityNotFoundError(Pipeline, {});
|
throw new EntityNotFoundError(Pipeline, {});
|
||||||
// });
|
});
|
||||||
// await expect(
|
await expect(
|
||||||
// service.addTask({ pipelineId: 'test', commit: 'test', units: [] }),
|
service.addTask({ pipelineId: 'test', commit: 'test', units: [] }),
|
||||||
// ).rejects;
|
).rejects;
|
||||||
// });
|
});
|
||||||
// it('create task on db', async () => {
|
it('create task on db', async () => {
|
||||||
// const save = jest
|
const save = jest
|
||||||
// .spyOn(taskRepository, 'save')
|
.spyOn(taskRepository, 'save')
|
||||||
// .mockImplementation(async (data: any) => data);
|
.mockImplementation(async (data: any) => data);
|
||||||
// const findOne = jest.spyOn(taskRepository, 'findOne');
|
const findOne = jest.spyOn(taskRepository, 'findOne');
|
||||||
// await service.addTask({ pipelineId: 'test', commit: 'test', units: [] }),
|
jest
|
||||||
// expect(save.mock.calls[0][0]).toMatchObject({
|
.spyOn(service, 'doNextTask')
|
||||||
// pipelineId: 'test',
|
.mockImplementation(async () => undefined);
|
||||||
// commit: 'test',
|
await service.addTask({ pipelineId: 'test', commit: 'test', units: [] }),
|
||||||
// units: [],
|
expect(save.mock.calls[0][0]).toMatchObject({
|
||||||
// });
|
pipelineId: 'test',
|
||||||
// expect(findOne).toBeCalled();
|
commit: 'test',
|
||||||
// });
|
units: [],
|
||||||
// it('add task', async () => {
|
});
|
||||||
// const lpush = jest.spyOn(redisClient, 'lpush');
|
expect(findOne).toBeCalled();
|
||||||
// await service.addTask({ pipelineId: 'test', commit: 'test', units: [] });
|
});
|
||||||
// expect(typeof lpush.mock.calls[0][1] === 'string').toBeTruthy();
|
it('add task', async () => {
|
||||||
// expect(JSON.parse(lpush.mock.calls[0][1] as string)).toMatchObject({
|
const lpush = jest.spyOn(redisClient, 'lpush');
|
||||||
// pipelineId: 'test',
|
const doNextTask = jest.spyOn(service, 'doNextTask');
|
||||||
// commit: 'test',
|
jest
|
||||||
// units: [],
|
.spyOn(service, 'doNextTask')
|
||||||
// pipeline: getBasePipeline(),
|
.mockImplementation(async () => undefined);
|
||||||
// });
|
await service.addTask({ pipelineId: 'test', commit: 'test', units: [] });
|
||||||
// });
|
expect(typeof lpush.mock.calls[0][1] === 'string').toBeTruthy();
|
||||||
// });
|
expect(JSON.parse(lpush.mock.calls[0][1] as string)).toMatchObject({
|
||||||
|
pipelineId: 'test',
|
||||||
|
commit: 'test',
|
||||||
|
units: [],
|
||||||
|
pipeline: getBasePipeline(),
|
||||||
|
});
|
||||||
|
expect(doNextTask).toHaveBeenCalledWith(getBasePipeline());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('doNextTask', () => {
|
||||||
|
it('add task to queue', async () => {
|
||||||
|
let lckValue: string;
|
||||||
|
const set = jest
|
||||||
|
.spyOn(redisClient, 'set')
|
||||||
|
.mockImplementation(async (...args) => (lckValue = args[3] as string));
|
||||||
|
const get = jest
|
||||||
|
.spyOn(redisClient, 'get')
|
||||||
|
.mockImplementation(async () => lckValue);
|
||||||
|
const del = jest.spyOn(redisClient, 'del');
|
||||||
|
const rpop = jest.spyOn(redisClient, 'rpop');
|
||||||
|
const add = jest.spyOn(taskQueue, 'add');
|
||||||
|
|
||||||
|
await service.doNextTask(getBasePipeline());
|
||||||
|
|
||||||
|
expect(add).toHaveBeenCalledWith(getTask());
|
||||||
|
expect(set).toHaveBeenCalledTimes(1);
|
||||||
|
expect(rpop).toHaveBeenCalledTimes(1);
|
||||||
|
expect(get).toHaveBeenCalledTimes(1);
|
||||||
|
expect(del).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
it('pipeline is busy', async () => {
|
||||||
|
let remainTimes = 3;
|
||||||
|
|
||||||
|
let lckValue: string;
|
||||||
|
const set = jest
|
||||||
|
.spyOn(redisClient, 'set')
|
||||||
|
.mockImplementation(async (...args) => {
|
||||||
|
if (remainTimes-- > 0) {
|
||||||
|
throw new Error();
|
||||||
|
} else {
|
||||||
|
lckValue = args[3] as string;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const get = jest
|
||||||
|
.spyOn(redisClient, 'get')
|
||||||
|
.mockImplementation(async () => lckValue);
|
||||||
|
const del = jest.spyOn(redisClient, 'del');
|
||||||
|
const rpop = jest.spyOn(redisClient, 'rpop');
|
||||||
|
const add = jest.spyOn(taskQueue, 'add');
|
||||||
|
|
||||||
|
await service.doNextTask(getBasePipeline());
|
||||||
|
|
||||||
|
expect(rpop).toHaveBeenCalledTimes(1);
|
||||||
|
expect(set).toHaveBeenCalledTimes(4);
|
||||||
|
expect(get).toHaveBeenCalledTimes(1);
|
||||||
|
expect(del).toHaveBeenCalledTimes(1);
|
||||||
|
expect(add).toHaveBeenCalledWith(getTask());
|
||||||
|
}, 10_000);
|
||||||
|
it('pipeline always busy and timeout', async () => {
|
||||||
|
const set = jest
|
||||||
|
.spyOn(redisClient, 'set')
|
||||||
|
.mockImplementation(async () => {
|
||||||
|
throw new Error();
|
||||||
|
});
|
||||||
|
const get = jest.spyOn(redisClient, 'get');
|
||||||
|
const del = jest.spyOn(redisClient, 'del');
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.doNextTask(getBasePipeline()),
|
||||||
|
).rejects.toBeInstanceOf(LockFailedException);
|
||||||
|
|
||||||
|
expect(set).toHaveBeenCalledTimes(5);
|
||||||
|
expect(get).toHaveBeenCalledTimes(0);
|
||||||
|
expect(del).toHaveBeenCalledTimes(0);
|
||||||
|
}, 15_000);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
@ -1,44 +1,63 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { ConflictException, Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
import { Repository } from 'typeorm';
|
import { In, Repository } from 'typeorm';
|
||||||
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
|
import { InjectQueue } from '@nestjs/bull';
|
||||||
|
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
|
||||||
|
import { Queue } from 'bull';
|
||||||
|
import { LockFailedException } from '../commons/exceptions/lock-failed.exception';
|
||||||
|
import { PubSub } from 'apollo-server-express';
|
||||||
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { isNil } from 'ramda';
|
||||||
import debug from 'debug';
|
import debug from 'debug';
|
||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
|
||||||
|
|
||||||
const log = debug('fennec:pipeline-tasks:service');
|
const log = debug('fennec:pipeline-tasks:service');
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PipelineTasksService {
|
export class PipelineTasksService {
|
||||||
|
pubSub = new PubSub();
|
||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(PipelineTask)
|
@InjectRepository(PipelineTask)
|
||||||
private readonly repository: Repository<PipelineTask>,
|
private readonly repository: Repository<PipelineTask>,
|
||||||
@InjectRepository(Pipeline)
|
@InjectRepository(Pipeline)
|
||||||
private readonly pipelineRepository: Repository<Pipeline>,
|
private readonly pipelineRepository: Repository<Pipeline>,
|
||||||
private readonly amqpConnection: AmqpConnection,
|
@InjectQueue(PIPELINE_TASK_QUEUE)
|
||||||
|
private readonly queue: Queue<PipelineTask>,
|
||||||
|
private readonly redis: RedisService,
|
||||||
) {}
|
) {}
|
||||||
async addTask(dto: CreatePipelineTaskInput) {
|
async addTask(dto: CreatePipelineTaskInput) {
|
||||||
const pipeline = await this.pipelineRepository.findOneOrFail({
|
const pipeline = await this.pipelineRepository.findOneOrFail({
|
||||||
where: { id: dto.pipelineId },
|
where: { id: dto.pipelineId },
|
||||||
relations: ['project'],
|
relations: ['project'],
|
||||||
});
|
});
|
||||||
// const hasUnfinishedTask = await this.repository
|
const hasUnfinishedTask = await this.repository
|
||||||
// .findOne({
|
.findOne({
|
||||||
// pipelineId: dto.pipelineId,
|
pipelineId: dto.pipelineId,
|
||||||
// commit: dto.commit,
|
commit: dto.commit,
|
||||||
// status: In([TaskStatuses.pending, TaskStatuses.working]),
|
status: In([TaskStatuses.pending, TaskStatuses.working]),
|
||||||
// })
|
})
|
||||||
// .then((val) => !isNil(val));
|
.then((val) => !isNil(val));
|
||||||
// if (hasUnfinishedTask) {
|
if (hasUnfinishedTask) {
|
||||||
// throw new ConflictException(
|
throw new ConflictException(
|
||||||
// 'There are the same tasks among the unfinished tasks!',
|
'There are the same tasks among the unfinished tasks!',
|
||||||
// );
|
);
|
||||||
// }
|
}
|
||||||
const task = await this.repository.save(this.repository.create(dto));
|
const task = await this.repository.save(this.repository.create(dto));
|
||||||
task.pipeline = pipeline;
|
task.pipeline = pipeline;
|
||||||
|
|
||||||
this.amqpConnection.publish('new-pipeline-task', 'mac', task);
|
const tasksKey = this.getRedisTokens(pipeline)[1];
|
||||||
|
const redis = this.redis.getClient();
|
||||||
|
await redis.lpush(tasksKey, JSON.stringify(task));
|
||||||
|
log(
|
||||||
|
'add task %s:%s-%s',
|
||||||
|
task.id,
|
||||||
|
task.pipeline.branch,
|
||||||
|
task.commit.slice(0, 6),
|
||||||
|
);
|
||||||
|
await this.doNextTask(pipeline);
|
||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,8 +69,57 @@ export class PipelineTasksService {
|
|||||||
return await this.repository.find({ pipelineId });
|
return await this.repository.find({ pipelineId });
|
||||||
}
|
}
|
||||||
|
|
||||||
async listTasksByCommitHash(hash: string) {
|
async doNextTask(pipeline: Pipeline) {
|
||||||
return await this.repository.find({ commit: hash });
|
const [lckKey, tasksKey] = this.getRedisTokens(pipeline);
|
||||||
|
const redis = this.redis.getClient();
|
||||||
|
|
||||||
|
log('doNextTask()');
|
||||||
|
const unLck = await new Promise<() => Promise<void>>(
|
||||||
|
async (resolve, reject) => {
|
||||||
|
const lckValue = Date.now().toString();
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
if (
|
||||||
|
await redis
|
||||||
|
.set(lckKey, 0, 'EX', lckValue, 'NX')
|
||||||
|
.then(() => true)
|
||||||
|
.catch(() => false)
|
||||||
|
) {
|
||||||
|
resolve(async () => {
|
||||||
|
if ((await redis.get(lckKey)) === lckValue) {
|
||||||
|
await redis.del(lckKey);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
}
|
||||||
|
reject(new LockFailedException(lckKey));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const task = JSON.parse(
|
||||||
|
(await redis.rpop(tasksKey).finally(() => unLck())) ?? 'null',
|
||||||
|
);
|
||||||
|
if (task) {
|
||||||
|
log(
|
||||||
|
'add task (%s:%s-%s) to queue',
|
||||||
|
task.id,
|
||||||
|
task.pipeline.branch,
|
||||||
|
task.commit.slice(0, 6),
|
||||||
|
);
|
||||||
|
await this.queue.add(task);
|
||||||
|
} else {
|
||||||
|
log('task is empty');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateTask(task: PipelineTask) {
|
||||||
|
this.pubSub.publish(task.id, task);
|
||||||
|
return await this.repository.save(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
async watchTaskUpdated(id: string) {
|
||||||
|
return this.pubSub.asyncIterator(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
getRedisTokens(pipeline: Pipeline): [string, string] {
|
getRedisTokens(pipeline: Pipeline): [string, string] {
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
|
||||||
import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
|
||||||
import { CommitLogsResolver } from './commit-logs.resolver';
|
|
||||||
import { PipelinesService } from './pipelines.service';
|
|
||||||
|
|
||||||
describe('CommitLogsResolver', () => {
|
|
||||||
let resolver: CommitLogsResolver;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
|
||||||
providers: [
|
|
||||||
CommitLogsResolver,
|
|
||||||
{
|
|
||||||
provide: PipelinesService,
|
|
||||||
useValue: {},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
provide: PipelineTasksService,
|
|
||||||
useValue: {},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}).compile();
|
|
||||||
|
|
||||||
resolver = module.get<CommitLogsResolver>(CommitLogsResolver);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should be defined', () => {
|
|
||||||
expect(resolver).toBeDefined();
|
|
||||||
});
|
|
||||||
});
|
|
@ -1,42 +0,0 @@
|
|||||||
import { Query } from '@nestjs/graphql';
|
|
||||||
import {
|
|
||||||
Args,
|
|
||||||
Parent,
|
|
||||||
ResolveField,
|
|
||||||
Resolver,
|
|
||||||
Subscription,
|
|
||||||
} from '@nestjs/graphql';
|
|
||||||
import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
|
||||||
import { Commit, LogFields } from '../repos/dtos/log-list.model';
|
|
||||||
import { PipelinesService } from './pipelines.service';
|
|
||||||
|
|
||||||
@Resolver(() => Commit)
|
|
||||||
export class CommitLogsResolver {
|
|
||||||
constructor(
|
|
||||||
private readonly service: PipelinesService,
|
|
||||||
private readonly taskServices: PipelineTasksService,
|
|
||||||
) {}
|
|
||||||
@Subscription(() => String, { resolve: (val) => val, nullable: true })
|
|
||||||
async syncCommits(
|
|
||||||
@Args('pipelineId', { type: () => String })
|
|
||||||
pipelineId: string,
|
|
||||||
@Args('appInstance', { type: () => String, nullable: true })
|
|
||||||
appInstance?: string,
|
|
||||||
) {
|
|
||||||
const pipeline = await this.service.findOneWithProject(pipelineId);
|
|
||||||
const syncCommitsPromise = this.service.syncCommits(pipeline, appInstance);
|
|
||||||
return (async function* () {
|
|
||||||
yield await syncCommitsPromise;
|
|
||||||
})();
|
|
||||||
}
|
|
||||||
@ResolveField()
|
|
||||||
async tasks(@Parent() commit: LogFields) {
|
|
||||||
return await this.taskServices.listTasksByCommitHash(commit.hash);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Query(() => [Commit], { nullable: true })
|
|
||||||
async commits(@Args('pipelineId', { type: () => String }) id: string) {
|
|
||||||
const pipeline = await this.service.findOneWithProject(id);
|
|
||||||
return await this.service.listCommits(pipeline);
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,6 +2,4 @@ import { InputType } from '@nestjs/graphql';
|
|||||||
import { CreatePipelineInput } from './create-pipeline.input';
|
import { CreatePipelineInput } from './create-pipeline.input';
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdatePipelineInput extends CreatePipelineInput {
|
export class UpdatePipelineInput extends CreatePipelineInput {}
|
||||||
id: string;
|
|
||||||
}
|
|
||||||
|
@ -3,25 +3,16 @@ import { PipelinesResolver } from './pipelines.resolver';
|
|||||||
import { PipelinesService } from './pipelines.service';
|
import { PipelinesService } from './pipelines.service';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { Pipeline } from './pipeline.entity';
|
import { Pipeline } from './pipeline.entity';
|
||||||
import { CommitLogsResolver } from './commit-logs.resolver';
|
import { BullModule } from '@nestjs/bull';
|
||||||
import { PipelineTasksModule } from '../pipeline-tasks/pipeline-tasks.module';
|
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||||
import { ReposModule } from '../repos/repos.module';
|
|
||||||
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Pipeline]),
|
TypeOrmModule.forFeature([Pipeline]),
|
||||||
PipelineTasksModule,
|
BullModule.registerQueue({
|
||||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
name: LIST_LOGS_TASK,
|
||||||
imports: [ConfigModule],
|
|
||||||
useFactory: (configService: ConfigService) => ({
|
|
||||||
uri: configService.get<string>('db.rabbitmq.uri'),
|
|
||||||
exchanges: [],
|
|
||||||
}),
|
|
||||||
inject: [ConfigService],
|
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
providers: [PipelinesResolver, PipelinesService, CommitLogsResolver],
|
providers: [PipelinesResolver, PipelinesService],
|
||||||
})
|
})
|
||||||
export class PipelinesModule {}
|
export class PipelinesModule {}
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
|
import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql';
|
||||||
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
||||||
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
||||||
import { Pipeline } from './pipeline.entity';
|
import { Pipeline } from './pipeline.entity';
|
||||||
import { PipelinesService } from './pipelines.service';
|
import { PipelinesService } from './pipelines.service';
|
||||||
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
||||||
|
import { LogList } from '../repos/dtos/log-list.model';
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class PipelinesResolver {
|
export class PipelinesResolver {
|
||||||
constructor(private readonly service: PipelinesService) {}
|
constructor(private readonly service: PipelinesService) {}
|
||||||
@Query(() => [Pipeline])
|
@Query(() => [Pipeline])
|
||||||
async pipelines(@Args() dto: ListPipelineArgs) {
|
async listPipelines(@Args() dto: ListPipelineArgs) {
|
||||||
return await this.service.list(dto);
|
return await this.service.list(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => Pipeline)
|
@Query(() => Pipeline)
|
||||||
async pipeline(@Args('id', { type: () => String }) id: string) {
|
async findPipeline(@Args('id', { type: () => String }) id: string) {
|
||||||
return await this.service.findOne(id);
|
return await this.service.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,11 +28,12 @@ export class PipelinesResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Mutation(() => Pipeline)
|
@Mutation(() => Pipeline)
|
||||||
async updatePipeline(
|
async modifyPipeline(
|
||||||
|
@Args('id', { type: () => String }) id: string,
|
||||||
@Args('Pipeline', { type: () => UpdatePipelineInput })
|
@Args('Pipeline', { type: () => UpdatePipelineInput })
|
||||||
dto: UpdatePipelineInput,
|
dto: UpdatePipelineInput,
|
||||||
) {
|
) {
|
||||||
const tmp = await this.service.update(dto);
|
const tmp = await this.service.update(id, dto);
|
||||||
console.log(tmp);
|
console.log(tmp);
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
@ -40,4 +42,16 @@ export class PipelinesResolver {
|
|||||||
async deletePipeline(@Args('id', { type: () => String }) id: string) {
|
async deletePipeline(@Args('id', { type: () => String }) id: string) {
|
||||||
return await this.service.remove(id);
|
return await this.service.remove(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Subscription(() => LogList, {
|
||||||
|
resolve: (value) => {
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async listLogsForPipeline(@Args('id', { type: () => String }) id: string) {
|
||||||
|
const job = await this.service.listLogsForPipeline(id);
|
||||||
|
return (async function* () {
|
||||||
|
yield await job.finished();
|
||||||
|
})();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,14 +2,18 @@ import { Test, TestingModule } from '@nestjs/testing';
|
|||||||
import { PipelinesService } from './pipelines.service';
|
import { PipelinesService } from './pipelines.service';
|
||||||
import { Pipeline } from './pipeline.entity';
|
import { Pipeline } from './pipeline.entity';
|
||||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { getQueueToken } from '@nestjs/bull';
|
||||||
|
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Project } from '../projects/project.entity';
|
import { Project } from '../projects/project.entity';
|
||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
import { Job, Queue } from 'bull';
|
||||||
|
import { ListLogsOption } from '../repos/models/list-logs.options';
|
||||||
|
|
||||||
describe('PipelinesService', () => {
|
describe('PipelinesService', () => {
|
||||||
let service: PipelinesService;
|
let service: PipelinesService;
|
||||||
let repository: Repository<Pipeline>;
|
let repository: Repository<Pipeline>;
|
||||||
let pipeline: Pipeline;
|
let pipeline: Pipeline;
|
||||||
|
let queue: Queue<ListLogsOption>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
pipeline = Object.assign(new Pipeline(), {
|
pipeline = Object.assign(new Pipeline(), {
|
||||||
@ -33,17 +37,33 @@ describe('PipelinesService', () => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: AmqpConnection,
|
provide: getQueueToken(LIST_LOGS_TASK),
|
||||||
useValue: {},
|
useValue: {
|
||||||
|
add: jest.fn().mockImplementation(() => ({ id: 1 } as Job)),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<PipelinesService>(PipelinesService);
|
service = module.get<PipelinesService>(PipelinesService);
|
||||||
repository = module.get(getRepositoryToken(Pipeline));
|
repository = module.get(getRepositoryToken(Pipeline));
|
||||||
|
queue = module.get(getQueueToken(LIST_LOGS_TASK));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(service).toBeDefined();
|
expect(service).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('listLogsForPipeline', () => {
|
||||||
|
it('should send task to queue.', async () => {
|
||||||
|
const add = jest.spyOn(queue, 'add');
|
||||||
|
await expect(
|
||||||
|
service.listLogsForPipeline('test-pipeline'),
|
||||||
|
).resolves.toEqual({ id: 1 });
|
||||||
|
expect(add).toBeCalledWith({
|
||||||
|
project: pipeline.project,
|
||||||
|
branch: pipeline.branch,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
@ -6,14 +6,10 @@ import { BaseDbService } from '../commons/services/base-db.service';
|
|||||||
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
||||||
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
||||||
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
||||||
import {
|
import { InjectQueue } from '@nestjs/bull';
|
||||||
EXCHANGE_REPO,
|
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||||
ROUTE_FETCH,
|
import { Queue } from 'bull';
|
||||||
ROUTE_LIST_COMMITS,
|
import { ListLogsOption } from '../repos/models/list-logs.options';
|
||||||
} from '../repos/repos.constants';
|
|
||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
|
||||||
import { Commit } from '../repos/dtos/log-list.model';
|
|
||||||
import { getAppInstanceRouteKey } from '../commons/utils/rabbit-mq';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PipelinesService extends BaseDbService<Pipeline> {
|
export class PipelinesService extends BaseDbService<Pipeline> {
|
||||||
@ -21,7 +17,8 @@ export class PipelinesService extends BaseDbService<Pipeline> {
|
|||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(Pipeline)
|
@InjectRepository(Pipeline)
|
||||||
readonly repository: Repository<Pipeline>,
|
readonly repository: Repository<Pipeline>,
|
||||||
private readonly amqpConnection: AmqpConnection,
|
@InjectQueue(LIST_LOGS_TASK)
|
||||||
|
private readonly listLogsQueue: Queue<ListLogsOption>,
|
||||||
) {
|
) {
|
||||||
super(repository);
|
super(repository);
|
||||||
}
|
}
|
||||||
@ -29,48 +26,30 @@ export class PipelinesService extends BaseDbService<Pipeline> {
|
|||||||
return this.repository.find(dto);
|
return this.repository.find(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOneWithProject(id: string) {
|
|
||||||
return await this.repository.findOne({
|
|
||||||
where: { id },
|
|
||||||
relations: ['project'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(dto: CreatePipelineInput) {
|
async create(dto: CreatePipelineInput) {
|
||||||
await this.isDuplicateEntity(dto);
|
await this.isDuplicateEntity(dto);
|
||||||
return await this.repository.save(this.repository.create(dto));
|
return await this.repository.save(this.repository.create(dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(dto: UpdatePipelineInput) {
|
async update(id: string, dto: UpdatePipelineInput) {
|
||||||
await this.isDuplicateEntityForUpdate(dto.id, dto);
|
await this.isDuplicateEntityForUpdate(id, dto);
|
||||||
const old = await this.findOne(dto.id);
|
const old = await this.findOne(id);
|
||||||
return await this.repository.save(this.repository.merge(old, dto));
|
return await this.repository.save(this.repository.merge(old, dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string) {
|
async remove(id: string) {
|
||||||
return (await this.repository.softDelete({ id })).affected;
|
return (await this.repository.softDelete({ id })).affected;
|
||||||
}
|
}
|
||||||
async syncCommits(pipeline: Pipeline, appInstance?: string) {
|
|
||||||
return await this.amqpConnection.request<string | null>({
|
async listLogsForPipeline(id: string) {
|
||||||
exchange: EXCHANGE_REPO,
|
const pipeline = await this.repository.findOneOrFail({
|
||||||
routingKey: getAppInstanceRouteKey(ROUTE_FETCH, appInstance),
|
where: { id },
|
||||||
payload: pipeline,
|
relations: ['project'],
|
||||||
timeout: 30_000,
|
|
||||||
});
|
});
|
||||||
}
|
const job = await this.listLogsQueue.add({
|
||||||
async listCommits(pipeline: Pipeline) {
|
project: pipeline.project,
|
||||||
return await this.amqpConnection
|
branch: pipeline.branch,
|
||||||
.request<Commit[]>({
|
});
|
||||||
exchange: EXCHANGE_REPO,
|
return job;
|
||||||
routingKey: ROUTE_LIST_COMMITS,
|
|
||||||
payload: pipeline,
|
|
||||||
timeout: 10_000,
|
|
||||||
})
|
|
||||||
.then((list) =>
|
|
||||||
list.map((item) => {
|
|
||||||
item.date = new Date(item.date);
|
|
||||||
return item;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,10 +21,7 @@ export class CreateProjectInput {
|
|||||||
comment: string;
|
comment: string;
|
||||||
|
|
||||||
@Matches(
|
@Matches(
|
||||||
/^(?:ssh:\/\/)?(?:[\w\d-_]+@)?(?:[\w\d-_]+\.)*\w{2,10}(?::\d{1,5})?(?:\/[\w\d-_.]+)*/,
|
/^(?:ssh:\/\/)?(?:[\w\d-_]+@)(?:[\w\d-_]+\.)*\w{2,10}(?::\d{1,5})?(?:\/[\w\d-_.]+)*/,
|
||||||
{
|
|
||||||
message: 'wrong ssh url',
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
@MaxLength(256)
|
@MaxLength(256)
|
||||||
sshUrl: string;
|
sshUrl: string;
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
import { InputType } from '@nestjs/graphql';
|
import { InputType } from '@nestjs/graphql';
|
||||||
import { IsUUID } from 'class-validator';
|
|
||||||
import { CreateProjectInput } from './create-project.input';
|
import { CreateProjectInput } from './create-project.input';
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdateProjectInput extends CreateProjectInput {
|
export class UpdateProjectInput extends CreateProjectInput {}
|
||||||
@IsUUID()
|
|
||||||
id: string;
|
|
||||||
}
|
|
||||||
|
@ -8,12 +8,12 @@ import { ProjectsService } from './projects.service';
|
|||||||
export class ProjectsResolver {
|
export class ProjectsResolver {
|
||||||
constructor(private readonly service: ProjectsService) {}
|
constructor(private readonly service: ProjectsService) {}
|
||||||
@Query(() => [Project])
|
@Query(() => [Project])
|
||||||
async projects() {
|
async findProjects() {
|
||||||
return await this.service.list();
|
return await this.service.list();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Query(() => Project)
|
@Query(() => Project)
|
||||||
async project(@Args('id', { type: () => String }) id: string) {
|
async findProject(@Args('id', { type: () => String }) id: string) {
|
||||||
return await this.service.findOne(id);
|
return await this.service.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -26,17 +26,18 @@ export class ProjectsResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Mutation(() => Project)
|
@Mutation(() => Project)
|
||||||
async updateProject(
|
async modifyProject(
|
||||||
|
@Args('id', { type: () => String }) id: string,
|
||||||
@Args('project', { type: () => UpdateProjectInput })
|
@Args('project', { type: () => UpdateProjectInput })
|
||||||
dto: UpdateProjectInput,
|
dto: UpdateProjectInput,
|
||||||
) {
|
) {
|
||||||
const tmp = await this.service.update(dto);
|
const tmp = await this.service.update(id, dto);
|
||||||
console.log(tmp);
|
console.log(tmp);
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Mutation(() => Number)
|
@Mutation(() => Number)
|
||||||
async removeProject(@Args('id', { type: () => String }) id: string) {
|
async deleteProject(@Args('id', { type: () => String }) id: string) {
|
||||||
return await this.service.remove(id);
|
return await this.service.remove(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,9 +25,9 @@ export class ProjectsService extends BaseDbService<Project> {
|
|||||||
return await this.repository.save(this.repository.create(dto));
|
return await this.repository.save(this.repository.create(dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(dto: UpdateProjectInput) {
|
async update(id: string, dto: UpdateProjectInput) {
|
||||||
await this.isDuplicateEntityForUpdate(dto.id, dto);
|
await this.isDuplicateEntityForUpdate(id, dto);
|
||||||
const old = await this.findOne(dto.id);
|
const old = await this.findOne(id);
|
||||||
return await this.repository.save(this.repository.merge(old, dto));
|
return await this.repository.save(this.repository.merge(old, dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,18 +1,6 @@
|
|||||||
import { ObjectType, Field } from '@nestjs/graphql';
|
import { ObjectType, Field } from '@nestjs/graphql';
|
||||||
import { LogResult, DefaultLogFields } from 'simple-git';
|
import { LogResult, DefaultLogFields } from 'simple-git';
|
||||||
import { PipelineTask } from '../../pipeline-tasks/pipeline-task.entity';
|
|
||||||
|
|
||||||
@ObjectType()
|
|
||||||
export class Commit {
|
|
||||||
hash: string;
|
|
||||||
date: Date;
|
|
||||||
message: string;
|
|
||||||
refs: string;
|
|
||||||
body: string;
|
|
||||||
author_name: string;
|
|
||||||
author_email: string;
|
|
||||||
tasks: PipelineTask[];
|
|
||||||
}
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class LogFields {
|
export class LogFields {
|
||||||
hash: string;
|
hash: string;
|
||||||
@ -22,7 +10,6 @@ export class LogFields {
|
|||||||
body: string;
|
body: string;
|
||||||
author_name: string;
|
author_name: string;
|
||||||
author_email: string;
|
author_email: string;
|
||||||
tasks: PipelineTask[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
|
14
src/repos/list-logs.consumer.ts
Normal file
14
src/repos/list-logs.consumer.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { ReposService } from './repos.service';
|
||||||
|
import { Processor, Process } from '@nestjs/bull';
|
||||||
|
import { Job } from 'bull';
|
||||||
|
import { ListLogsOption } from './models/list-logs.options';
|
||||||
|
import { LIST_LOGS_TASK } from './repos.constants';
|
||||||
|
@Processor(LIST_LOGS_TASK)
|
||||||
|
export class ListLogsConsumer {
|
||||||
|
constructor(private readonly service: ReposService) {}
|
||||||
|
@Process()
|
||||||
|
async listLogs(job: Job<ListLogsOption>) {
|
||||||
|
const logs = await this.service.listLogs(job.data);
|
||||||
|
return logs;
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +1,3 @@
|
|||||||
export const EXCHANGE_REPO = 'fennec.repo';
|
export const LIST_LOGS_TASK = 'LIST_LOGS_TASK';
|
||||||
export const ROUTE_FETCH = 'fetch';
|
export const LIST_LOGS_PUB_SUB = 'LIST_LOGS_PUB_SUB';
|
||||||
export const ROUTE_LIST_COMMITS = 'list-commits';
|
export const LIST_LOGS_DONE = 'LIST_LOGS_DONE';
|
||||||
export const QUEUE_LIST_COMMITS = 'list-commits';
|
|
||||||
export const QUEUE_FETCH = 'repo-fetch';
|
|
||||||
|
@ -3,35 +3,23 @@ import { TypeOrmModule } from '@nestjs/typeorm';
|
|||||||
import { Project } from '../projects/project.entity';
|
import { Project } from '../projects/project.entity';
|
||||||
import { ReposResolver } from './repos.resolver';
|
import { ReposResolver } from './repos.resolver';
|
||||||
import { ReposService } from './repos.service';
|
import { ReposService } from './repos.service';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
import { ProjectsModule } from '../projects/projects.module';
|
import { ProjectsModule } from '../projects/projects.module';
|
||||||
import { EXCHANGE_REPO } from './repos.constants';
|
import { BullModule } from '@nestjs/bull';
|
||||||
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
import { LIST_LOGS_TASK, LIST_LOGS_PUB_SUB } from './repos.constants';
|
||||||
|
import { PubSub } from 'graphql-subscriptions';
|
||||||
|
import { ListLogsConsumer } from './list-logs.consumer';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Project]),
|
TypeOrmModule.forFeature([Project]),
|
||||||
ConfigModule,
|
ConfigModule,
|
||||||
ProjectsModule,
|
ProjectsModule,
|
||||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
BullModule.registerQueue({
|
||||||
imports: [ConfigModule],
|
name: LIST_LOGS_TASK,
|
||||||
useFactory: (configService: ConfigService) => ({
|
|
||||||
uri: configService.get<string>('db.rabbitmq.uri'),
|
|
||||||
exchanges: [
|
|
||||||
{
|
|
||||||
name: EXCHANGE_REPO,
|
|
||||||
type: 'topic',
|
|
||||||
options: {
|
|
||||||
durable: true,
|
|
||||||
autoDelete: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
inject: [ConfigService],
|
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
providers: [ReposResolver, ReposService],
|
providers: [ReposResolver, ReposService, ListLogsConsumer],
|
||||||
exports: [ReposService],
|
exports: [ReposService],
|
||||||
})
|
})
|
||||||
export class ReposModule {}
|
export class ReposModule {}
|
||||||
|
@ -9,9 +9,6 @@ import configuration from '../commons/config/configuration';
|
|||||||
import { PipelineTask } from '../pipeline-tasks/pipeline-task.entity';
|
import { PipelineTask } from '../pipeline-tasks/pipeline-task.entity';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import { readFile } from 'fs/promises';
|
import { readFile } from 'fs/promises';
|
||||||
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
|
||||||
import { Nack } from '@golevelup/nestjs-rabbitmq';
|
|
||||||
import { getInstanceName } from '../commons/utils/rabbit-mq';
|
|
||||||
|
|
||||||
const getTest1Project = () =>
|
const getTest1Project = () =>
|
||||||
({
|
({
|
||||||
@ -48,10 +45,6 @@ describe('ReposService', () => {
|
|||||||
provide: getRepositoryToken(Project),
|
provide: getRepositoryToken(Project),
|
||||||
useFactory: repositoryMockFactory,
|
useFactory: repositoryMockFactory,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
provide: getLoggerToken(ReposService.name),
|
|
||||||
useValue: new PinoLogger({}),
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
@ -146,57 +139,4 @@ describe('ReposService', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('fetch', () => {
|
|
||||||
it('success', async () => {
|
|
||||||
const project = new Project();
|
|
||||||
const pipeline = new Pipeline();
|
|
||||||
pipeline.branch = 'test';
|
|
||||||
const fetch = jest.fn((_: any) => Promise.resolve());
|
|
||||||
pipeline.project = project;
|
|
||||||
const getGit = jest.spyOn(service, 'getGit').mockImplementation(() =>
|
|
||||||
Promise.resolve({
|
|
||||||
fetch,
|
|
||||||
} as any),
|
|
||||||
);
|
|
||||||
await expect(service.fetch(pipeline)).resolves.toEqual(getInstanceName());
|
|
||||||
expect(getGit).toBeCalledTimes(1);
|
|
||||||
expect(getGit.mock.calls[0]?.[0]).toEqual(project);
|
|
||||||
expect(fetch).toBeCalledTimes(1);
|
|
||||||
expect(fetch.mock.calls[0]?.[0]).toMatchObject([
|
|
||||||
'origin',
|
|
||||||
'test',
|
|
||||||
'--depth=100',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
it('failed a', async () => {
|
|
||||||
const project = new Project();
|
|
||||||
const pipeline = new Pipeline();
|
|
||||||
pipeline.branch = 'test';
|
|
||||||
const fetch = jest.fn((_: any) => Promise.resolve());
|
|
||||||
pipeline.project = project;
|
|
||||||
const getGit = jest
|
|
||||||
.spyOn(service, 'getGit')
|
|
||||||
.mockImplementation(() => Promise.reject('error'));
|
|
||||||
await expect(service.fetch(pipeline)).resolves.toMatchObject(new Nack());
|
|
||||||
expect(getGit).toBeCalledTimes(1);
|
|
||||||
expect(getGit.mock.calls[0]?.[0]).toEqual(project);
|
|
||||||
expect(fetch).toBeCalledTimes(0);
|
|
||||||
});
|
|
||||||
it('failed b', async () => {
|
|
||||||
const project = new Project();
|
|
||||||
const pipeline = new Pipeline();
|
|
||||||
pipeline.branch = 'test';
|
|
||||||
const fetch = jest.fn((_: any) => Promise.reject('error'));
|
|
||||||
pipeline.project = project;
|
|
||||||
const getGit = jest.spyOn(service, 'getGit').mockImplementation(() =>
|
|
||||||
Promise.resolve({
|
|
||||||
fetch,
|
|
||||||
} as any),
|
|
||||||
);
|
|
||||||
await expect(service.fetch(pipeline)).resolves.toMatchObject(new Nack());
|
|
||||||
expect(getGit).toBeCalledTimes(1);
|
|
||||||
expect(fetch).toBeCalledTimes(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import { ListLogsOption } from './models/list-logs.options';
|
import { ListLogsOption } from './models/list-logs.options';
|
||||||
|
import { Pipeline } from './../pipelines/pipeline.entity';
|
||||||
import { PipelineTask } from './../pipeline-tasks/pipeline-task.entity';
|
import { PipelineTask } from './../pipeline-tasks/pipeline-task.entity';
|
||||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
@ -9,23 +10,8 @@ import { gitP } from 'simple-git';
|
|||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Project } from '../projects/project.entity';
|
import { Project } from '../projects/project.entity';
|
||||||
import { ListBranchesArgs } from './dtos/list-branches.args';
|
import { ListBranchesArgs } from './dtos/list-branches.args';
|
||||||
|
import { ListLogsArgs } from './dtos/list-logs.args';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { Commit } from './dtos/log-list.model';
|
|
||||||
import { Nack, RabbitRPC } from '@golevelup/nestjs-rabbitmq';
|
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
|
||||||
import { InjectPinoLogger, Logger } from 'nestjs-pino';
|
|
||||||
import {
|
|
||||||
EXCHANGE_REPO,
|
|
||||||
QUEUE_FETCH,
|
|
||||||
QUEUE_LIST_COMMITS,
|
|
||||||
ROUTE_FETCH,
|
|
||||||
ROUTE_LIST_COMMITS,
|
|
||||||
} from './repos.constants';
|
|
||||||
import { getSelfInstanceQueueKey } from '../commons/utils/rabbit-mq';
|
|
||||||
import {
|
|
||||||
getInstanceName,
|
|
||||||
getSelfInstanceRouteKey,
|
|
||||||
} from '../commons/utils/rabbit-mq';
|
|
||||||
|
|
||||||
const DEFAULT_REMOTE_NAME = 'origin';
|
const DEFAULT_REMOTE_NAME = 'origin';
|
||||||
const INFO_PATH = '@info';
|
const INFO_PATH = '@info';
|
||||||
@ -35,8 +21,6 @@ export class ReposService {
|
|||||||
@InjectRepository(Project)
|
@InjectRepository(Project)
|
||||||
private readonly projectRepository: Repository<Project>,
|
private readonly projectRepository: Repository<Project>,
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
@InjectPinoLogger(ReposService.name)
|
|
||||||
private readonly logger: Logger,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
getWorkspaceRoot(project: Project): string {
|
getWorkspaceRoot(project: Project): string {
|
||||||
@ -47,11 +31,7 @@ export class ReposService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getGit(
|
async getGit(project: Project, workspaceRoot?: string) {
|
||||||
project: Project,
|
|
||||||
workspaceRoot?: string,
|
|
||||||
{ fetch = true } = {},
|
|
||||||
) {
|
|
||||||
if (!workspaceRoot) {
|
if (!workspaceRoot) {
|
||||||
workspaceRoot = this.getWorkspaceRoot(project);
|
workspaceRoot = this.getWorkspaceRoot(project);
|
||||||
}
|
}
|
||||||
@ -64,9 +44,7 @@ export class ReposService {
|
|||||||
await git.init();
|
await git.init();
|
||||||
await git.addRemote(DEFAULT_REMOTE_NAME, project.sshUrl);
|
await git.addRemote(DEFAULT_REMOTE_NAME, project.sshUrl);
|
||||||
}
|
}
|
||||||
if (fetch) {
|
await git.fetch();
|
||||||
await git.fetch();
|
|
||||||
}
|
|
||||||
return git;
|
return git;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -111,70 +89,4 @@ export class ReposService {
|
|||||||
encodeURIComponent(`${task.pipeline.name}-${task.commit}`),
|
encodeURIComponent(`${task.pipeline.name}-${task.commit}`),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async checkout4Task(task: PipelineTask): Promise<string> {
|
|
||||||
const path = this.getWorkspaceRootByTask(task);
|
|
||||||
await this.checkout(task, path);
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
|
|
||||||
@RabbitRPC({
|
|
||||||
exchange: EXCHANGE_REPO,
|
|
||||||
routingKey: [
|
|
||||||
ROUTE_LIST_COMMITS,
|
|
||||||
getSelfInstanceRouteKey(ROUTE_LIST_COMMITS),
|
|
||||||
],
|
|
||||||
queue: getSelfInstanceQueueKey(QUEUE_LIST_COMMITS),
|
|
||||||
queueOptions: {
|
|
||||||
autoDelete: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
async listCommits(pipeline: Pipeline): Promise<Commit[] | Nack> {
|
|
||||||
const git = await this.getGit(pipeline.project, undefined, {
|
|
||||||
fetch: false,
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
const data = await git.log([
|
|
||||||
'-100',
|
|
||||||
'--branches',
|
|
||||||
`remotes/origin/${pipeline.branch}`,
|
|
||||||
'--',
|
|
||||||
]);
|
|
||||||
return data.all.map(
|
|
||||||
(it) =>
|
|
||||||
({
|
|
||||||
...it,
|
|
||||||
date: new Date(it.date),
|
|
||||||
} as Commit),
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error(
|
|
||||||
{ error, pipeline },
|
|
||||||
'[listCommits] %s',
|
|
||||||
error?.message,
|
|
||||||
);
|
|
||||||
return new Nack();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@RabbitRPC({
|
|
||||||
exchange: EXCHANGE_REPO,
|
|
||||||
routingKey: [ROUTE_FETCH, getSelfInstanceRouteKey(ROUTE_FETCH)],
|
|
||||||
queue: getSelfInstanceQueueKey(QUEUE_FETCH),
|
|
||||||
queueOptions: {
|
|
||||||
autoDelete: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
async fetch(pipeline: Pipeline): Promise<string | null | Nack> {
|
|
||||||
try {
|
|
||||||
const git = await this.getGit(pipeline.project, undefined, {
|
|
||||||
fetch: false,
|
|
||||||
});
|
|
||||||
await git.fetch(['origin', pipeline.branch, '--depth=100']);
|
|
||||||
return getInstanceName();
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error({ error, pipeline }, '[fetch] %s', error?.message);
|
|
||||||
return new Nack();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -4,6 +4,7 @@ import { PipelineTasksModule } from '../pipeline-tasks/pipeline-tasks.module';
|
|||||||
import { GiteaWebhooksController } from './gitea-webhooks.controller';
|
import { GiteaWebhooksController } from './gitea-webhooks.controller';
|
||||||
import { WebhookLog } from './webhook-log.entity';
|
import { WebhookLog } from './webhook-log.entity';
|
||||||
import { WebhooksService } from './webhooks.service';
|
import { WebhooksService } from './webhooks.service';
|
||||||
|
import { raw } from 'body-parser';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([WebhookLog]), PipelineTasksModule],
|
imports: [TypeOrmModule.forFeature([WebhookLog]), PipelineTasksModule],
|
||||||
@ -11,4 +12,9 @@ import { WebhooksService } from './webhooks.service';
|
|||||||
providers: [WebhooksService],
|
providers: [WebhooksService],
|
||||||
})
|
})
|
||||||
export class WebhooksModule {
|
export class WebhooksModule {
|
||||||
|
// configure(consumer: MiddlewareConsumer) {
|
||||||
|
// consumer
|
||||||
|
// .apply(raw({ type: 'application/json' }))
|
||||||
|
// .forRoutes(GiteaWebhooksController);
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user