Compare commits
23 Commits
e908d2981d
...
feat-api-f
Author | SHA1 | Date | |
---|---|---|---|
|
0d71700f11 | ||
|
bd045c6abe | ||
|
8e3dea7099 | ||
|
429de1eaed | ||
|
08e5c7e7d3 | ||
|
713f5b2426 | ||
|
607a4f57de | ||
|
211a90590f | ||
|
07fc98bc86 | ||
|
9bdd991cfb | ||
|
9078835c28 | ||
|
42c5e4d608 | ||
|
cdc28cb102 | ||
|
7923ae6d41 | ||
|
4e7c825170 | ||
|
aa92c518f0 | ||
|
cba4c0464c | ||
|
d02cea2115 | ||
|
22d3dc299c | ||
|
ba0ba46a35 | ||
|
f00f75673b | ||
|
bba7963949 | ||
|
bf4590bd4c |
7
.vscode/settings.json
vendored
7
.vscode/settings.json
vendored
@@ -1,7 +1,12 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
"Repos",
|
"Repos",
|
||||||
|
"boardcat",
|
||||||
|
"gitea",
|
||||||
"lpush",
|
"lpush",
|
||||||
"rpop"
|
"lrange",
|
||||||
|
"metatype",
|
||||||
|
"rpop",
|
||||||
|
"rpush"
|
||||||
]
|
]
|
||||||
}
|
}
|
22861
package-lock.json
generated
22861
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
@@ -10,8 +10,8 @@
|
|||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
"start:dev": "nest start --watch",
|
"start:dev": "DEBUG=fennec:* nest start --watch",
|
||||||
"start:debug": "DEBUG=simple-git,simple-git:* nest start --debug --watch",
|
"start:debug": "DEBUG=fennec:* nest start --debug --watch",
|
||||||
"start:prod": "node dist/main",
|
"start:prod": "node dist/main",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
@@ -33,13 +33,16 @@
|
|||||||
"@types/ramda": "^0.27.38",
|
"@types/ramda": "^0.27.38",
|
||||||
"apollo-server-express": "^2.19.2",
|
"apollo-server-express": "^2.19.2",
|
||||||
"bcrypt": "^5.0.0",
|
"bcrypt": "^5.0.0",
|
||||||
|
"body-parser": "^1.19.0",
|
||||||
"bull": "^3.20.1",
|
"bull": "^3.20.1",
|
||||||
"class-transformer": "^0.3.2",
|
"class-transformer": "^0.3.2",
|
||||||
"class-validator": "^0.13.1",
|
"class-validator": "^0.13.1",
|
||||||
|
"debug": "^4.3.1",
|
||||||
"graphql": "^15.5.0",
|
"graphql": "^15.5.0",
|
||||||
"graphql-tools": "^7.0.2",
|
"graphql-tools": "^7.0.2",
|
||||||
"js-yaml": "^4.0.0",
|
"js-yaml": "^4.0.0",
|
||||||
"nestjs-redis": "^1.2.8",
|
"nestjs-redis": "^1.2.8",
|
||||||
|
"observable-to-async-generator": "^1.0.1-rc",
|
||||||
"pg": "^8.5.1",
|
"pg": "^8.5.1",
|
||||||
"ramda": "^0.27.1",
|
"ramda": "^0.27.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
@@ -49,9 +52,11 @@
|
|||||||
"typeorm": "^0.2.30"
|
"typeorm": "^0.2.30"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^7.5.1",
|
"@nestjs/cli": "^7.5.7",
|
||||||
"@nestjs/schematics": "^7.1.3",
|
"@nestjs/schematics": "^7.1.3",
|
||||||
"@nestjs/testing": "^7.5.1",
|
"@nestjs/testing": "^7.5.1",
|
||||||
|
"@types/body-parser": "^1.19.0",
|
||||||
|
"@types/debug": "^4.1.5",
|
||||||
"@types/express": "^4.17.8",
|
"@types/express": "^4.17.8",
|
||||||
"@types/jest": "^26.0.15",
|
"@types/jest": "^26.0.15",
|
||||||
"@types/js-yaml": "^4.0.0",
|
"@types/js-yaml": "^4.0.0",
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { GraphQLModule } from '@nestjs/graphql';
|
import { GraphQLModule } from '@nestjs/graphql';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
@@ -11,6 +11,10 @@ import { PipelinesModule } from './pipelines/pipelines.module';
|
|||||||
import { PipelineTasksModule } from './pipeline-tasks/pipeline-tasks.module';
|
import { PipelineTasksModule } from './pipeline-tasks/pipeline-tasks.module';
|
||||||
import configuration from './commons/config/configuration';
|
import configuration from './commons/config/configuration';
|
||||||
import { RedisModule } from 'nestjs-redis';
|
import { RedisModule } from 'nestjs-redis';
|
||||||
|
import { WebhooksModule } from './webhooks/webhooks.module';
|
||||||
|
import { RawBodyMiddleware } from './commons/middlewares/raw-body.middleware';
|
||||||
|
import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller';
|
||||||
|
import { ParseBodyMiddleware } from './commons/middlewares/parse-body.middleware';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -37,6 +41,7 @@ import { RedisModule } from 'nestjs-redis';
|
|||||||
debug: configService.get<string>('env') !== 'prod',
|
debug: configService.get<string>('env') !== 'prod',
|
||||||
playground: true,
|
playground: true,
|
||||||
autoSchemaFile: true,
|
autoSchemaFile: true,
|
||||||
|
installSubscriptionHandlers: true,
|
||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
}),
|
}),
|
||||||
@@ -50,12 +55,21 @@ import { RedisModule } from 'nestjs-redis';
|
|||||||
host: configService.get<string>('db.redis.host', 'localhost'),
|
host: configService.get<string>('db.redis.host', 'localhost'),
|
||||||
port: configService.get<number>('db.redis.port', 6379),
|
port: configService.get<number>('db.redis.port', 6379),
|
||||||
password: configService.get<string>('db.redis.password', ''),
|
password: configService.get<string>('db.redis.password', ''),
|
||||||
keyPrefix: configService.get<string>('db.redis.prefix', 'fennec'),
|
keyPrefix: configService.get<string>('db.redis.prefix', 'fennec') + ':',
|
||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
}),
|
}),
|
||||||
|
WebhooksModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService, AppResolver],
|
providers: [AppService, AppResolver],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule implements NestModule {
|
||||||
|
public configure(consumer: MiddlewareConsumer): void {
|
||||||
|
consumer
|
||||||
|
.apply(RawBodyMiddleware)
|
||||||
|
.forRoutes(GiteaWebhooksController)
|
||||||
|
.apply(ParseBodyMiddleware)
|
||||||
|
.forRoutes('*');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||||
import {
|
import {
|
||||||
CreateDateColumn,
|
CreateDateColumn,
|
||||||
|
DeleteDateColumn,
|
||||||
PrimaryGeneratedColumn,
|
PrimaryGeneratedColumn,
|
||||||
UpdateDateColumn,
|
UpdateDateColumn,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
@@ -16,4 +17,7 @@ export class AppBaseEntity {
|
|||||||
|
|
||||||
@UpdateDateColumn({ select: false })
|
@UpdateDateColumn({ select: false })
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
|
|
||||||
|
@DeleteDateColumn({ select: false })
|
||||||
|
deletedAt?: Date;
|
||||||
}
|
}
|
||||||
|
@@ -1,15 +1,33 @@
|
|||||||
import {
|
import {
|
||||||
ArgumentsHost,
|
|
||||||
Catch,
|
|
||||||
ExceptionFilter,
|
ExceptionFilter,
|
||||||
|
Catch,
|
||||||
|
ArgumentsHost,
|
||||||
HttpException,
|
HttpException,
|
||||||
HttpStatus,
|
HttpStatus,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';
|
import { ApolloError } from 'apollo-server-errors';
|
||||||
|
|
||||||
@Catch()
|
@Catch(HttpException)
|
||||||
export class AllExceptionsFilter implements ExceptionFilter {
|
export class HttpExceptionFilter implements ExceptionFilter {
|
||||||
catch(exception: any, host: ArgumentsHost) {
|
catch(exception: HttpException, host: ArgumentsHost) {
|
||||||
|
switch (host.getType<'http' | 'graphql' | string>()) {
|
||||||
|
case 'graphql': {
|
||||||
|
const message = exception.message;
|
||||||
|
const extensions: Record<string, any> = {};
|
||||||
|
const err = exception.getResponse();
|
||||||
|
if (typeof err === 'string') {
|
||||||
|
extensions.message = err;
|
||||||
|
} else {
|
||||||
|
Object.assign(extensions, (err as any).extension);
|
||||||
|
extensions.message = (err as any).message;
|
||||||
|
}
|
||||||
|
return new ApolloError(
|
||||||
|
message,
|
||||||
|
exception.getStatus().toString(),
|
||||||
|
extensions,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
case 'http': {
|
||||||
const ctx = host.switchToHttp();
|
const ctx = host.switchToHttp();
|
||||||
const response = ctx.getResponse();
|
const response = ctx.getResponse();
|
||||||
const request = ctx.getRequest();
|
const request = ctx.getRequest();
|
||||||
@@ -19,37 +37,15 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
|||||||
? exception.getStatus()
|
? exception.getStatus()
|
||||||
: HttpStatus.INTERNAL_SERVER_ERROR;
|
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
|
||||||
if (exception instanceof HttpException) {
|
|
||||||
const ex = exception.getResponse();
|
|
||||||
if (ex instanceof Object) {
|
|
||||||
response.status(status).json({
|
response.status(status).json({
|
||||||
...ex,
|
statusCode: status,
|
||||||
timestamp: Date.now(),
|
message: exception.message,
|
||||||
path: request.url,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
response.status(status).json({
|
|
||||||
message: ex,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
path: request.url,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if (exception instanceof EntityNotFoundError) {
|
|
||||||
response.status(HttpStatus.NOT_FOUND).json({
|
|
||||||
message: '资源未找到!',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
path: request.url,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
console.error('服务器内部错误');
|
|
||||||
console.error(exception);
|
|
||||||
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
|
|
||||||
code: status,
|
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
message: '服务器内部错误',
|
|
||||||
error: exception,
|
|
||||||
path: request.url,
|
path: request.url,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
7
src/commons/middlewares/parse-body.middleware.spec.ts
Normal file
7
src/commons/middlewares/parse-body.middleware.spec.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { ParseBodyMiddleware } from './parse-body.middleware';
|
||||||
|
|
||||||
|
describe('ParseBodyMiddleware', () => {
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(new ParseBodyMiddleware()).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
13
src/commons/middlewares/parse-body.middleware.ts
Normal file
13
src/commons/middlewares/parse-body.middleware.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
|
import { json, urlencoded, text } from 'body-parser';
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ParseBodyMiddleware implements NestMiddleware {
|
||||||
|
use(req: Request, res: Response, next: NextFunction) {
|
||||||
|
json()(req, res, () =>
|
||||||
|
urlencoded()(req, res, () => text()(req, res, next)),
|
||||||
|
);
|
||||||
|
// next();
|
||||||
|
}
|
||||||
|
}
|
7
src/commons/middlewares/raw-body.middleware.spec.ts
Normal file
7
src/commons/middlewares/raw-body.middleware.spec.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { RawBodyMiddleware } from './raw-body.middleware';
|
||||||
|
|
||||||
|
describe('RawBodyMiddleware', () => {
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(new RawBodyMiddleware()).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
10
src/commons/middlewares/raw-body.middleware.ts
Normal file
10
src/commons/middlewares/raw-body.middleware.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
|
import { raw } from 'body-parser';
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RawBodyMiddleware implements NestMiddleware {
|
||||||
|
use(req: Request, res: Response, next: NextFunction) {
|
||||||
|
raw({ type: '*/*' })(req, res, next);
|
||||||
|
}
|
||||||
|
}
|
27
src/commons/pipes/sanitize.pipe.ts
Normal file
27
src/commons/pipes/sanitize.pipe.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
|
||||||
|
import { sanitize } from '@neuralegion/class-sanitizer/dist';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SanitizePipe implements PipeTransform {
|
||||||
|
transform(value: any, metadata: ArgumentMetadata) {
|
||||||
|
if (
|
||||||
|
!(value instanceof Object) ||
|
||||||
|
value instanceof Buffer ||
|
||||||
|
value instanceof Array
|
||||||
|
) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
const constructorFunction = metadata.metatype;
|
||||||
|
if (!constructorFunction) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
value = Object.assign(new constructorFunction(), value);
|
||||||
|
try {
|
||||||
|
sanitize(value);
|
||||||
|
return value;
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
12
src/main.ts
12
src/main.ts
@@ -2,11 +2,19 @@ import { ValidationPipe } from '@nestjs/common';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
import { HttpExceptionFilter } from './commons/filters/all.exception-filter';
|
||||||
|
import { SanitizePipe } from './commons/pipes/sanitize.pipe';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule, { bodyParser: false });
|
||||||
const configService = app.get(ConfigService);
|
const configService = app.get(ConfigService);
|
||||||
app.useGlobalPipes(new ValidationPipe());
|
app.useGlobalPipes(new SanitizePipe());
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
app.useGlobalFilters(new HttpExceptionFilter());
|
||||||
await app.listen(configService.get<number>('http.port'));
|
await app.listen(configService.get<number>('http.port'));
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
@@ -7,6 +7,5 @@ export class CreatePipelineTaskInput {
|
|||||||
|
|
||||||
commit: string;
|
commit: string;
|
||||||
|
|
||||||
@Field(() => PipelineUnits)
|
|
||||||
units: PipelineUnits[];
|
units: PipelineUnits[];
|
||||||
}
|
}
|
||||||
|
8
src/pipeline-tasks/dtos/pipeline-task-log.args.ts
Normal file
8
src/pipeline-tasks/dtos/pipeline-task-log.args.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { ArgsType } from '@nestjs/graphql';
|
||||||
|
import { IsUUID } from 'class-validator';
|
||||||
|
|
||||||
|
@ArgsType()
|
||||||
|
export class PipelineTaskLogArgs {
|
||||||
|
@IsUUID()
|
||||||
|
taskId: string;
|
||||||
|
}
|
@@ -1,6 +1,13 @@
|
|||||||
|
import { registerEnumType } from '@nestjs/graphql';
|
||||||
|
|
||||||
export enum TaskStatuses {
|
export enum TaskStatuses {
|
||||||
success = 'success',
|
success = 'success',
|
||||||
failed = 'failed',
|
failed = 'failed',
|
||||||
working = 'working',
|
working = 'working',
|
||||||
pending = 'pending',
|
pending = 'pending',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
registerEnumType(TaskStatuses, {
|
||||||
|
name: 'TaskStatuses',
|
||||||
|
description: '任务状态',
|
||||||
|
});
|
||||||
|
@@ -1,15 +1,32 @@
|
|||||||
import { PipelineTask } from './../pipeline-task.entity';
|
import { PipelineTask } from './../pipeline-task.entity';
|
||||||
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
|
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
export class PipelineTaskLogMessage {
|
export class PipelineTaskLogMessage {
|
||||||
|
@HideField()
|
||||||
task: PipelineTask;
|
task: PipelineTask;
|
||||||
|
@Field(() => PipelineUnits, { nullable: true })
|
||||||
|
unit?: PipelineUnits;
|
||||||
|
@Field()
|
||||||
time: Date;
|
time: Date;
|
||||||
|
@Field()
|
||||||
message: string;
|
message: string;
|
||||||
|
@Field()
|
||||||
|
isError: boolean;
|
||||||
|
|
||||||
static create(task: PipelineTask, message: string) {
|
static create(
|
||||||
|
task: PipelineTask,
|
||||||
|
unit: PipelineUnits,
|
||||||
|
message: string,
|
||||||
|
isError: boolean,
|
||||||
|
) {
|
||||||
return Object.assign(new PipelineTaskLogMessage(), {
|
return Object.assign(new PipelineTaskLogMessage(), {
|
||||||
task,
|
task,
|
||||||
message,
|
message,
|
||||||
time: new Date(),
|
time: new Date(),
|
||||||
|
unit,
|
||||||
|
isError,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,12 @@
|
|||||||
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';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
export class PipelineTaskLogs {
|
export class PipelineTaskLogs {
|
||||||
|
@Field(() => PipelineUnits)
|
||||||
unit: PipelineUnits;
|
unit: PipelineUnits;
|
||||||
|
@Field(() => TaskStatuses)
|
||||||
status: TaskStatuses;
|
status: TaskStatuses;
|
||||||
startedAt?: Date;
|
startedAt?: Date;
|
||||||
endedAt?: Date;
|
endedAt?: Date;
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
@@ -1,22 +1,22 @@
|
|||||||
import { PIPELINE_TASK_LOG_QUEUE } from './pipeline-tasks.constants';
|
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { Job, Queue } from 'bull';
|
import { Job } from 'bull';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
import { ReposService } from '../repos/repos.service';
|
import { ReposService } from '../repos/repos.service';
|
||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
import { PipelineTaskConsumer } from './pipeline-task.consumer';
|
import { PipelineTaskConsumer } from './pipeline-task.consumer';
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
import { PipelineTasksService } from './pipeline-tasks.service';
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
import { getQueueToken } from '@nestjs/bull';
|
|
||||||
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
import { Project } from '../projects/project.entity';
|
import { Project } from '../projects/project.entity';
|
||||||
import { TaskStatuses } from './enums/task-statuses.enum';
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
import { ApplicationException } from '../commons/exceptions/application.exception';
|
||||||
|
|
||||||
describe('PipelineTaskConsumer', () => {
|
describe('PipelineTaskConsumer', () => {
|
||||||
let consumer: PipelineTaskConsumer;
|
let consumer: PipelineTaskConsumer;
|
||||||
let tasksService: PipelineTasksService;
|
let tasksService: PipelineTasksService;
|
||||||
let logQueue: Queue<PipelineTaskLogMessage>;
|
let logsService: PipelineTaskLogsService;
|
||||||
const getJob = () =>
|
const getJob = () =>
|
||||||
({
|
({
|
||||||
data: {
|
data: {
|
||||||
@@ -42,19 +42,20 @@ describe('PipelineTaskConsumer', () => {
|
|||||||
checkout: async () => undefined,
|
checkout: async () => undefined,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
PipelineTaskConsumer,
|
|
||||||
{
|
{
|
||||||
provide: getQueueToken(PIPELINE_TASK_LOG_QUEUE),
|
provide: PipelineTaskLogsService,
|
||||||
useValue: {
|
useValue: {
|
||||||
add: () => undefined,
|
recordLog: async () => undefined,
|
||||||
|
readLogsAsPipelineTaskLogs: async () => [],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
PipelineTaskConsumer,
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
tasksService = module.get(PipelineTasksService);
|
tasksService = module.get(PipelineTasksService);
|
||||||
|
logsService = module.get(PipelineTaskLogsService);
|
||||||
consumer = module.get(PipelineTaskConsumer);
|
consumer = module.get(PipelineTaskConsumer);
|
||||||
logQueue = module.get(getQueueToken(PIPELINE_TASK_LOG_QUEUE));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
@@ -71,31 +72,42 @@ describe('PipelineTaskConsumer', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('runScript', () => {
|
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 () => {
|
it('should success and log right message', async () => {
|
||||||
const add = jest.spyOn(logQueue, 'add');
|
await consumer.runScript(
|
||||||
await expect(
|
|
||||||
consumer
|
|
||||||
.runScript(
|
|
||||||
'node one-second-work.js',
|
'node one-second-work.js',
|
||||||
join(__dirname, '../../test/data'),
|
join(__dirname, '../../test/data'),
|
||||||
)
|
);
|
||||||
.then((arr) => arr.join('')),
|
expect(logText).toMatch(/10.+20.+30.+40.+50.+60.+70.+80.+90/s);
|
||||||
).resolves.toMatch(/10.+20.+30.+40.+50.+60.+70.+80.+90/s);
|
expect(recordLog).toHaveBeenCalledTimes(10);
|
||||||
// expect(add).toHaveBeenCalledTimes(10);
|
|
||||||
expect(
|
expect(
|
||||||
((add.mock.calls[8][0] as unknown) as PipelineTaskLogMessage).message,
|
((recordLog.mock.calls[8][0] as unknown) as PipelineTaskLogMessage)
|
||||||
|
.message,
|
||||||
).toMatch(/^90/);
|
).toMatch(/^90/);
|
||||||
});
|
});
|
||||||
it('should failed and log right message', async () => {
|
it('should failed and log right message', async () => {
|
||||||
const add = jest.spyOn(logQueue, 'add');
|
|
||||||
await expect(
|
await expect(
|
||||||
consumer.runScript(
|
consumer.runScript(
|
||||||
'node bad-work.js',
|
'node bad-work.js',
|
||||||
join(__dirname, '../../test/data'),
|
join(__dirname, '../../test/data'),
|
||||||
),
|
),
|
||||||
).rejects.toThrowError(/Error Message/);
|
).rejects.toThrowError(/exec script failed/);
|
||||||
// expect(add).toHaveBeenCalledTimes(8);
|
expect(errorText).toMatch(/Error Message/);
|
||||||
const logs = add.mock.calls
|
const logs = recordLog.mock.calls
|
||||||
.map((call) => ((call[0] as unknown) as PipelineTaskLogMessage).message)
|
.map((call) => ((call[0] as unknown) as PipelineTaskLogMessage).message)
|
||||||
.join('');
|
.join('');
|
||||||
expect(logs).toMatch(/10.+20.+30.+40.+50/s);
|
expect(logs).toMatch(/10.+20.+30.+40.+50/s);
|
||||||
@@ -104,16 +116,19 @@ describe('PipelineTaskConsumer', () => {
|
|||||||
const task = new PipelineTask();
|
const task = new PipelineTask();
|
||||||
task.id = 'test';
|
task.id = 'test';
|
||||||
|
|
||||||
const add = jest.spyOn(logQueue, 'add');
|
const recordLog = jest.spyOn(logsService, 'recordLog');
|
||||||
await expect(
|
await expect(
|
||||||
consumer.runScript(
|
consumer.runScript(
|
||||||
'node bad-work.js',
|
'node bad-work.js',
|
||||||
join(__dirname, '../../test/data'),
|
join(__dirname, '../../test/data'),
|
||||||
task,
|
task,
|
||||||
),
|
),
|
||||||
).rejects.toThrowError(/Error Message 2/);
|
).rejects.toThrowError(/exec script failed/);
|
||||||
|
|
||||||
|
expect(errorText).toMatch(/Error Message 2/);
|
||||||
expect(
|
expect(
|
||||||
((add.mock.calls[2][0] as unknown) as PipelineTaskLogMessage).task,
|
((recordLog.mock.calls[2][0] as unknown) as PipelineTaskLogMessage)
|
||||||
|
.task,
|
||||||
).toMatchObject(task);
|
).toMatchObject(task);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -145,6 +160,43 @@ describe('PipelineTaskConsumer', () => {
|
|||||||
task.pipeline.project = new Project();
|
task.pipeline.project = new Project();
|
||||||
task.pipeline.project.name = 'test-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 () => {
|
it('should do all task', async () => {
|
||||||
const job: Job = ({
|
const job: Job = ({
|
||||||
data: task,
|
data: task,
|
||||||
@@ -153,18 +205,17 @@ describe('PipelineTaskConsumer', () => {
|
|||||||
|
|
||||||
const runScript = jest
|
const runScript = jest
|
||||||
.spyOn(consumer, 'runScript')
|
.spyOn(consumer, 'runScript')
|
||||||
.mockImplementation(async () => []);
|
.mockImplementation(async () => undefined);
|
||||||
const updateTask = jest.spyOn(tasksService, 'updateTask');
|
const updateTask = jest.spyOn(tasksService, 'updateTask');
|
||||||
|
|
||||||
await consumer.doTask(job);
|
await consumer.doTask(job);
|
||||||
|
|
||||||
expect(runScript).toHaveBeenCalledTimes(1);
|
expect(runScript).toHaveBeenCalledTimes(1);
|
||||||
expect(updateTask).toHaveBeenCalledTimes(1);
|
expect(updateTask).toHaveBeenCalledTimes(2);
|
||||||
const taskDto: PipelineTask = updateTask.mock.calls[0][0];
|
const taskDto: PipelineTask = updateTask.mock.calls[0][0];
|
||||||
expect(taskDto.logs).toHaveLength(2);
|
expect(taskDto.logs).toHaveLength(2);
|
||||||
expect(taskDto.logs[0].status).toEqual(TaskStatuses.success);
|
expect(taskDto.logs[0].status).toEqual(TaskStatuses.success);
|
||||||
expect(taskDto.logs[0].unit).toEqual(PipelineUnits.checkout);
|
expect(taskDto.logs[0].unit).toEqual(PipelineUnits.checkout);
|
||||||
expect(taskDto.logs[1].logs).toMatch(/Hello, Fennec!/);
|
|
||||||
});
|
});
|
||||||
it('should log error message', async () => {
|
it('should log error message', async () => {
|
||||||
const job: Job = ({
|
const job: Job = ({
|
||||||
@@ -181,12 +232,11 @@ describe('PipelineTaskConsumer', () => {
|
|||||||
|
|
||||||
await consumer.doTask(job);
|
await consumer.doTask(job);
|
||||||
|
|
||||||
expect(updateTask).toHaveBeenCalledTimes(1);
|
expect(updateTask).toHaveBeenCalledTimes(2);
|
||||||
const taskDto: PipelineTask = updateTask.mock.calls[0][0];
|
const taskDto: PipelineTask = updateTask.mock.calls[0][0];
|
||||||
expect(taskDto.logs).toHaveLength(2);
|
expect(taskDto.logs).toHaveLength(2);
|
||||||
expect(taskDto.logs[0].status).toEqual(TaskStatuses.success);
|
expect(taskDto.logs[0].status).toEqual(TaskStatuses.success);
|
||||||
expect(taskDto.logs[1].status).toEqual(TaskStatuses.failed);
|
expect(taskDto.logs[1].status).toEqual(TaskStatuses.failed);
|
||||||
expect(taskDto.logs[1].logs).toMatch(/bad message/);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@@ -1,39 +1,47 @@
|
|||||||
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
||||||
import { ReposService } from './../repos/repos.service';
|
import { ReposService } from './../repos/repos.service';
|
||||||
import {
|
import {
|
||||||
InjectQueue,
|
|
||||||
OnQueueCompleted,
|
OnQueueCompleted,
|
||||||
|
OnQueueFailed,
|
||||||
Process,
|
Process,
|
||||||
Processor,
|
Processor,
|
||||||
} from '@nestjs/bull';
|
} from '@nestjs/bull';
|
||||||
import { Job, Queue } from 'bull';
|
import { Job } from 'bull';
|
||||||
import { spawn } from 'child_process';
|
import { spawn } from 'child_process';
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
import {
|
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
|
||||||
PIPELINE_TASK_LOG_QUEUE,
|
|
||||||
PIPELINE_TASK_QUEUE,
|
|
||||||
} from './pipeline-tasks.constants';
|
|
||||||
import { PipelineTasksService } from './pipeline-tasks.service';
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
import { ApplicationException } from '../commons/exceptions/application.exception';
|
import { ApplicationException } from '../commons/exceptions/application.exception';
|
||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
import { TaskStatuses } from './enums/task-statuses.enum';
|
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)
|
@Processor(PIPELINE_TASK_QUEUE)
|
||||||
export class PipelineTaskConsumer {
|
export class PipelineTaskConsumer {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly service: PipelineTasksService,
|
private readonly service: PipelineTasksService,
|
||||||
private readonly reposService: ReposService,
|
private readonly reposService: ReposService,
|
||||||
@InjectQueue(PIPELINE_TASK_LOG_QUEUE)
|
private readonly logsService: PipelineTaskLogsService,
|
||||||
private readonly logQueue: Queue<PipelineTaskLogMessage>,
|
|
||||||
) {}
|
) {}
|
||||||
@Process()
|
@Process()
|
||||||
async doTask({ data: task, update }: Job<PipelineTask>) {
|
async doTask(job: Job<PipelineTask>) {
|
||||||
|
let task = job.data;
|
||||||
if (task.pipeline.workUnitMetadata.version !== 1) {
|
if (task.pipeline.workUnitMetadata.version !== 1) {
|
||||||
throw new ApplicationException(
|
throw new ApplicationException(
|
||||||
'work unit metadata version is not match.',
|
'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 workspaceRoot = this.reposService.getWorkspaceRootByTask(task);
|
||||||
|
|
||||||
const units = task.units.map(
|
const units = task.units.map(
|
||||||
@@ -43,22 +51,26 @@ export class PipelineTaskConsumer {
|
|||||||
) ?? { type: type, scripts: [] },
|
) ?? { type: type, scripts: [] },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
log('task have [%o] units', units);
|
||||||
try {
|
try {
|
||||||
for (const unit of units) {
|
for (const unit of units) {
|
||||||
const unitLog = new PipelineTaskLogs();
|
const unitLog = new PipelineTaskLogs();
|
||||||
unitLog.unit = unit.type;
|
unitLog.unit = unit.type;
|
||||||
unitLog.startedAt = new Date();
|
unitLog.startedAt = new Date();
|
||||||
|
log('curr unit is %s', unit.type);
|
||||||
try {
|
try {
|
||||||
// 检出代码时,不执行其他脚本。
|
// 检出代码前执行 git checkout
|
||||||
if (unit.type === PipelineUnits.checkout) {
|
if (unit.type === PipelineUnits.checkout) {
|
||||||
|
log('begin checkout');
|
||||||
await this.reposService.checkout(task, workspaceRoot);
|
await this.reposService.checkout(task, workspaceRoot);
|
||||||
unitLog.status = TaskStatuses.success;
|
unitLog.status = TaskStatuses.success;
|
||||||
continue;
|
log('end checkout');
|
||||||
}
|
}
|
||||||
for (const script of unit.scripts) {
|
for (const script of unit.scripts) {
|
||||||
unitLog.logs += `[RUN SCRIPT] ${script}`;
|
unitLog.logs += `[RUN SCRIPT] ${script}`;
|
||||||
const messages = await this.runScript(script, workspaceRoot, task);
|
log('begin runScript %s', script);
|
||||||
unitLog.logs += messages.join('');
|
await this.runScript(script, workspaceRoot, task, unit.type);
|
||||||
|
log('end runScript %s', script);
|
||||||
}
|
}
|
||||||
unitLog.status = TaskStatuses.success;
|
unitLog.status = TaskStatuses.success;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -67,14 +79,25 @@ export class PipelineTaskConsumer {
|
|||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
unitLog.endedAt = new Date();
|
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);
|
task.logs.push(unitLog);
|
||||||
|
await job.update(task);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
task.status = TaskStatuses.success;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
task.status = TaskStatuses.failed;
|
||||||
|
log('task is failed', err);
|
||||||
} finally {
|
} finally {
|
||||||
|
task.endedAt = new Date();
|
||||||
task = await this.service.updateTask(task);
|
task = await this.service.updateTask(task);
|
||||||
update(task);
|
await job.update(task);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,37 +105,43 @@ export class PipelineTaskConsumer {
|
|||||||
script: string,
|
script: string,
|
||||||
workspaceRoot: string,
|
workspaceRoot: string,
|
||||||
task?: PipelineTask,
|
task?: PipelineTask,
|
||||||
): Promise<string[]> {
|
unit?: PipelineUnits,
|
||||||
|
): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const errorMessages: string[] = [];
|
|
||||||
const logs: string[] = [];
|
|
||||||
const sub = spawn(script, {
|
const sub = spawn(script, {
|
||||||
shell: true,
|
shell: true,
|
||||||
cwd: workspaceRoot,
|
cwd: workspaceRoot,
|
||||||
});
|
});
|
||||||
sub.stderr.on('data', (data: Buffer) => {
|
sub.stderr.on('data', (data: Buffer) => {
|
||||||
const str = data.toString();
|
const str = data.toString();
|
||||||
errorMessages.push(str);
|
this.logsService.recordLog(
|
||||||
logs.push(str);
|
PipelineTaskLogMessage.create(task, unit, str, true),
|
||||||
this.logQueue.add(PipelineTaskLogMessage.create(task, str));
|
);
|
||||||
});
|
});
|
||||||
sub.stdout.on('data', (data: Buffer) => {
|
sub.stdout.on('data', (data: Buffer) => {
|
||||||
const str = data.toString();
|
const str = data.toString();
|
||||||
logs.push(str);
|
this.logsService.recordLog(
|
||||||
this.logQueue.add(PipelineTaskLogMessage.create(task, str));
|
PipelineTaskLogMessage.create(task, unit, str, false),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
sub.addListener('close', (code) => {
|
sub.addListener('close', (code) => {
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
sub.stdout;
|
return resolve();
|
||||||
return resolve(logs);
|
|
||||||
}
|
}
|
||||||
return reject(new ApplicationException(errorMessages.join('')));
|
return reject(new ApplicationException('exec script failed'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@OnQueueCompleted()
|
@OnQueueCompleted()
|
||||||
onCompleted(job: Job<PipelineTask>) {
|
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);
|
this.service.doNextTask(job.data.pipeline);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
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 } 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';
|
||||||
@@ -26,9 +26,9 @@ export class PipelineTask extends AppBaseEntity {
|
|||||||
@Column({ type: 'enum', enum: TaskStatuses, default: TaskStatuses.pending })
|
@Column({ type: 'enum', enum: TaskStatuses, default: TaskStatuses.pending })
|
||||||
status: TaskStatuses;
|
status: TaskStatuses;
|
||||||
|
|
||||||
@Column()
|
@Column({ nullable: true })
|
||||||
startedAt: Date;
|
startedAt?: Date;
|
||||||
|
|
||||||
@Column()
|
@Column({ nullable: true })
|
||||||
endedAt: Date;
|
endedAt?: Date;
|
||||||
}
|
}
|
||||||
|
@@ -1,2 +1,3 @@
|
|||||||
export const PIPELINE_TASK_QUEUE = 'PIPELINE_TASK_QUEUE';
|
export const PIPELINE_TASK_QUEUE = 'PIPELINE_TASK_QUEUE';
|
||||||
export const PIPELINE_TASK_LOG_QUEUE = 'PIPELINE_TASK_LOG_QUEUE';
|
export const PIPELINE_TASK_LOG_QUEUE = 'PIPELINE_TASK_LOG_QUEUE';
|
||||||
|
export const PIPELINE_TASK_LOG_PUBSUB = 'PIPELINE_TASK_LOG_PUBSUB';
|
||||||
|
@@ -7,23 +7,33 @@ 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 { BullModule } from '@nestjs/bull';
|
import { BullModule } from '@nestjs/bull';
|
||||||
|
import { PipelineTaskConsumer } from './pipeline-task.consumer';
|
||||||
import {
|
import {
|
||||||
PIPELINE_TASK_QUEUE,
|
PIPELINE_TASK_QUEUE,
|
||||||
PIPELINE_TASK_LOG_QUEUE,
|
PIPELINE_TASK_LOG_PUBSUB,
|
||||||
} from './pipeline-tasks.constants';
|
} 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(
|
BullModule.registerQueue({
|
||||||
{
|
|
||||||
name: PIPELINE_TASK_QUEUE,
|
name: PIPELINE_TASK_QUEUE,
|
||||||
},
|
}),
|
||||||
{ name: PIPELINE_TASK_LOG_QUEUE },
|
|
||||||
),
|
|
||||||
RedisModule,
|
RedisModule,
|
||||||
ReposModule,
|
ReposModule,
|
||||||
],
|
],
|
||||||
providers: [PipelineTasksService, PipelineTasksResolver],
|
providers: [
|
||||||
|
PipelineTasksService,
|
||||||
|
PipelineTasksResolver,
|
||||||
|
PipelineTaskConsumer,
|
||||||
|
PipelineTaskLogsService,
|
||||||
|
{
|
||||||
|
provide: Symbol(PIPELINE_TASK_LOG_PUBSUB),
|
||||||
|
useValue: new PubSub(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
exports: [PipelineTasksService],
|
||||||
})
|
})
|
||||||
export class PipelineTasksModule {}
|
export class PipelineTasksModule {}
|
||||||
|
@@ -1,12 +1,24 @@
|
|||||||
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';
|
||||||
|
|
||||||
describe('PipelineTasksResolver', () => {
|
describe('PipelineTasksResolver', () => {
|
||||||
let resolver: PipelineTasksResolver;
|
let resolver: PipelineTasksResolver;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [PipelineTasksResolver],
|
providers: [
|
||||||
|
PipelineTasksResolver,
|
||||||
|
{
|
||||||
|
provide: PipelineTasksService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: PipelineTaskLogsService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
resolver = module.get<PipelineTasksResolver>(PipelineTasksResolver);
|
resolver = module.get<PipelineTasksResolver>(PipelineTasksResolver);
|
||||||
|
@@ -1,4 +1,50 @@
|
|||||||
import { Resolver } from '@nestjs/graphql';
|
import { Resolver, Args, Mutation, Subscription, Query } from '@nestjs/graphql';
|
||||||
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
||||||
|
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
||||||
|
import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class PipelineTasksResolver {}
|
export class PipelineTasksResolver {
|
||||||
|
constructor(
|
||||||
|
private readonly service: PipelineTasksService,
|
||||||
|
private readonly logsService: PipelineTaskLogsService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Mutation(() => PipelineTask)
|
||||||
|
async createPipelineTask(@Args('task') taskDto: CreatePipelineTaskInput) {
|
||||||
|
return await this.service.addTask(taskDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Subscription(() => PipelineTaskLogMessage, {
|
||||||
|
resolve: (value) => {
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async pipelineTaskLog(@Args() args: PipelineTaskLogArgs) {
|
||||||
|
const task = await this.service.findTaskById(args.taskId);
|
||||||
|
const asyncIterator = this.logsService.watchLogs(task);
|
||||||
|
return asyncIterator;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Subscription(() => PipelineTask, {
|
||||||
|
resolve: (value) => {
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async pipelineTaskChanged(@Args('id') id: string) {
|
||||||
|
return await this.service.watchTaskUpdated(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => [PipelineTask])
|
||||||
|
async listPipelineTaskByPipelineId(@Args('pipelineId') pipelineId: string) {
|
||||||
|
return await this.service.listTasksByPipelineId(pipelineId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => PipelineTask)
|
||||||
|
async findPipelineTask(@Args('id') id: string) {
|
||||||
|
return await this.service.findTaskById(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -32,6 +32,7 @@ describe('PipelineTasksService', () => {
|
|||||||
({
|
({
|
||||||
pipelineId: 'test',
|
pipelineId: 'test',
|
||||||
commit: 'test',
|
commit: 'test',
|
||||||
|
pipeline: { branch: 'master' },
|
||||||
units: [],
|
units: [],
|
||||||
} as PipelineTask);
|
} as PipelineTask);
|
||||||
|
|
||||||
@@ -79,6 +80,7 @@ describe('PipelineTasksService', () => {
|
|||||||
jest
|
jest
|
||||||
.spyOn(taskRepository, 'create')
|
.spyOn(taskRepository, 'create')
|
||||||
.mockImplementation((data: any) => data);
|
.mockImplementation((data: any) => data);
|
||||||
|
jest.spyOn(taskRepository, 'findOne').mockImplementation(async () => null);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
@@ -103,6 +105,7 @@ describe('PipelineTasksService', () => {
|
|||||||
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');
|
||||||
jest
|
jest
|
||||||
.spyOn(service, 'doNextTask')
|
.spyOn(service, 'doNextTask')
|
||||||
.mockImplementation(async () => undefined);
|
.mockImplementation(async () => undefined);
|
||||||
@@ -112,6 +115,7 @@ describe('PipelineTasksService', () => {
|
|||||||
commit: 'test',
|
commit: 'test',
|
||||||
units: [],
|
units: [],
|
||||||
});
|
});
|
||||||
|
expect(findOne).toBeCalled();
|
||||||
});
|
});
|
||||||
it('add task', async () => {
|
it('add task', async () => {
|
||||||
const lpush = jest.spyOn(redisClient, 'lpush');
|
const lpush = jest.spyOn(redisClient, 'lpush');
|
||||||
@@ -155,20 +159,31 @@ describe('PipelineTasksService', () => {
|
|||||||
it('pipeline is busy', async () => {
|
it('pipeline is busy', async () => {
|
||||||
let remainTimes = 3;
|
let remainTimes = 3;
|
||||||
|
|
||||||
const incr = jest
|
let lckValue: string;
|
||||||
.spyOn(redisClient, 'incr')
|
const set = jest
|
||||||
.mockImplementation(() => remainTimes--);
|
.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 rpop = jest.spyOn(redisClient, 'rpop');
|
||||||
const decr = jest.spyOn(redisClient, 'decr');
|
|
||||||
const add = jest.spyOn(taskQueue, 'add');
|
const add = jest.spyOn(taskQueue, 'add');
|
||||||
|
|
||||||
await service.doNextTask(getBasePipeline());
|
await service.doNextTask(getBasePipeline());
|
||||||
|
|
||||||
expect(rpop).toHaveBeenCalledTimes(1);
|
expect(rpop).toHaveBeenCalledTimes(1);
|
||||||
expect(incr).toHaveBeenCalledTimes(3);
|
expect(set).toHaveBeenCalledTimes(4);
|
||||||
expect(decr).toHaveBeenCalledTimes(3);
|
expect(get).toHaveBeenCalledTimes(1);
|
||||||
|
expect(del).toHaveBeenCalledTimes(1);
|
||||||
expect(add).toHaveBeenCalledWith(getTask());
|
expect(add).toHaveBeenCalledWith(getTask());
|
||||||
});
|
}, 10_000);
|
||||||
it('pipeline always busy and timeout', async () => {
|
it('pipeline always busy and timeout', async () => {
|
||||||
const set = jest
|
const set = jest
|
||||||
.spyOn(redisClient, 'set')
|
.spyOn(redisClient, 'set')
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
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 { RedisService } from 'nestjs-redis';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
@@ -9,9 +9,16 @@ import { InjectQueue } from '@nestjs/bull';
|
|||||||
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
|
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
|
||||||
import { Queue } from 'bull';
|
import { Queue } from 'bull';
|
||||||
import { LockFailedException } from '../commons/exceptions/lock-failed.exception';
|
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';
|
||||||
|
|
||||||
|
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>,
|
||||||
@@ -26,19 +33,47 @@ export class PipelineTasksService {
|
|||||||
where: { id: dto.pipelineId },
|
where: { id: dto.pipelineId },
|
||||||
relations: ['project'],
|
relations: ['project'],
|
||||||
});
|
});
|
||||||
|
const hasUnfinishedTask = await this.repository
|
||||||
|
.findOne({
|
||||||
|
pipelineId: dto.pipelineId,
|
||||||
|
commit: dto.commit,
|
||||||
|
status: In([TaskStatuses.pending, TaskStatuses.working]),
|
||||||
|
})
|
||||||
|
.then((val) => !isNil(val));
|
||||||
|
if (hasUnfinishedTask) {
|
||||||
|
throw new ConflictException(
|
||||||
|
'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;
|
||||||
|
|
||||||
const tasksKey = this.getRedisTokens(pipeline)[1];
|
const tasksKey = this.getRedisTokens(pipeline)[1];
|
||||||
const redis = this.redis.getClient();
|
const redis = this.redis.getClient();
|
||||||
await redis.lpush(tasksKey, JSON.stringify(task));
|
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);
|
await this.doNextTask(pipeline);
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findTaskById(id: string) {
|
||||||
|
return await this.repository.findOneOrFail({ id });
|
||||||
|
}
|
||||||
|
|
||||||
|
async listTasksByPipelineId(pipelineId: string) {
|
||||||
|
return await this.repository.find({ pipelineId });
|
||||||
}
|
}
|
||||||
|
|
||||||
async doNextTask(pipeline: Pipeline) {
|
async doNextTask(pipeline: Pipeline) {
|
||||||
const [lckKey, tasksKey] = this.getRedisTokens(pipeline);
|
const [lckKey, tasksKey] = this.getRedisTokens(pipeline);
|
||||||
const redis = this.redis.getClient();
|
const redis = this.redis.getClient();
|
||||||
|
|
||||||
|
log('doNextTask()');
|
||||||
const unLck = await new Promise<() => Promise<void>>(
|
const unLck = await new Promise<() => Promise<void>>(
|
||||||
async (resolve, reject) => {
|
async (resolve, reject) => {
|
||||||
const lckValue = Date.now().toString();
|
const lckValue = Date.now().toString();
|
||||||
@@ -66,14 +101,27 @@ export class PipelineTasksService {
|
|||||||
(await redis.rpop(tasksKey).finally(() => unLck())) ?? 'null',
|
(await redis.rpop(tasksKey).finally(() => unLck())) ?? 'null',
|
||||||
);
|
);
|
||||||
if (task) {
|
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);
|
await this.queue.add(task);
|
||||||
|
} else {
|
||||||
|
log('task is empty');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateTask(task: PipelineTask) {
|
async updateTask(task: PipelineTask) {
|
||||||
|
this.pubSub.publish(task.id, task);
|
||||||
return await this.repository.save(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] {
|
||||||
return [`pipeline-${pipeline.id}:lck`, `pipeline-${pipeline.id}:tasks`];
|
return [`pipeline-${pipeline.id}:lck`, `pipeline-${pipeline.id}:tasks`];
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import { InputType } from '@nestjs/graphql';
|
import { InputType } from '@nestjs/graphql';
|
||||||
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
|
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
|
||||||
import {
|
import {
|
||||||
IsInstance,
|
IsObject,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
IsUUID,
|
IsUUID,
|
||||||
@@ -22,6 +22,6 @@ export class CreatePipelineInput {
|
|||||||
name: string;
|
name: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsInstance(WorkUnitMetadata)
|
@IsObject()
|
||||||
workUnitMetadata: WorkUnitMetadata;
|
workUnitMetadata: WorkUnitMetadata;
|
||||||
}
|
}
|
||||||
|
@@ -3,9 +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 { BullModule } from '@nestjs/bull';
|
||||||
|
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Pipeline])],
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([Pipeline]),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: LIST_LOGS_TASK,
|
||||||
|
}),
|
||||||
|
],
|
||||||
providers: [PipelinesResolver, PipelinesService],
|
providers: [PipelinesResolver, PipelinesService],
|
||||||
})
|
})
|
||||||
export class PipelinesModule {}
|
export class PipelinesModule {}
|
||||||
|
@@ -1,9 +1,10 @@
|
|||||||
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 {
|
||||||
@@ -41,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,25 +2,68 @@ 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 { Project } from '../projects/project.entity';
|
||||||
|
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 pipeline: Pipeline;
|
||||||
|
let queue: Queue<ListLogsOption>;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
|
pipeline = Object.assign(new Pipeline(), {
|
||||||
|
id: 'test-pipeline',
|
||||||
|
name: 'pipeline',
|
||||||
|
branch: 'master',
|
||||||
|
projectId: 'test-project',
|
||||||
|
project: Object.assign(new Project(), {
|
||||||
|
id: 'test-project',
|
||||||
|
name: 'project',
|
||||||
|
} as Project),
|
||||||
|
} as Pipeline);
|
||||||
|
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
PipelinesService,
|
PipelinesService,
|
||||||
{
|
{
|
||||||
provide: getRepositoryToken(Pipeline),
|
provide: getRepositoryToken(Pipeline),
|
||||||
useValue: {},
|
useValue: {
|
||||||
|
findOneOrFail: jest.fn().mockImplementation(() => pipeline),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: getQueueToken(LIST_LOGS_TASK),
|
||||||
|
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));
|
||||||
|
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,13 +6,19 @@ 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 { InjectQueue } from '@nestjs/bull';
|
||||||
|
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||||
|
import { Queue } from 'bull';
|
||||||
|
import { ListLogsOption } from '../repos/models/list-logs.options';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PipelinesService extends BaseDbService<Pipeline> {
|
export class PipelinesService extends BaseDbService<Pipeline> {
|
||||||
readonly uniqueFields: Array<keyof Pipeline> = ['branch', 'projectId'];
|
readonly uniqueFields: Array<Array<keyof Pipeline>> = [['projectId', 'name']];
|
||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(Pipeline)
|
@InjectRepository(Pipeline)
|
||||||
readonly repository: Repository<Pipeline>,
|
readonly repository: Repository<Pipeline>,
|
||||||
|
@InjectQueue(LIST_LOGS_TASK)
|
||||||
|
private readonly listLogsQueue: Queue<ListLogsOption>,
|
||||||
) {
|
) {
|
||||||
super(repository);
|
super(repository);
|
||||||
}
|
}
|
||||||
@@ -34,4 +40,16 @@ export class PipelinesService extends BaseDbService<Pipeline> {
|
|||||||
async remove(id: string) {
|
async remove(id: string) {
|
||||||
return (await this.repository.softDelete({ id })).affected;
|
return (await this.repository.softDelete({ id })).affected;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async listLogsForPipeline(id: string) {
|
||||||
|
const pipeline = await this.repository.findOneOrFail({
|
||||||
|
where: { id },
|
||||||
|
relations: ['project'],
|
||||||
|
});
|
||||||
|
const job = await this.listLogsQueue.add({
|
||||||
|
project: pipeline.project,
|
||||||
|
branch: pipeline.branch,
|
||||||
|
});
|
||||||
|
return job;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -22,7 +22,4 @@ export class Project extends AppBaseEntity {
|
|||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
webHookSecret?: string;
|
webHookSecret?: string;
|
||||||
|
|
||||||
@DeleteDateColumn()
|
|
||||||
deletedAt?: Date;
|
|
||||||
}
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
5
src/repos/models/list-logs.options.ts
Normal file
5
src/repos/models/list-logs.options.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { Project } from '../../projects/project.entity';
|
||||||
|
export interface ListLogsOption {
|
||||||
|
project: Project;
|
||||||
|
branch: string;
|
||||||
|
}
|
3
src/repos/repos.constants.ts
Normal file
3
src/repos/repos.constants.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export const LIST_LOGS_TASK = 'LIST_LOGS_TASK';
|
||||||
|
export const LIST_LOGS_PUB_SUB = 'LIST_LOGS_PUB_SUB';
|
||||||
|
export const LIST_LOGS_DONE = 'LIST_LOGS_DONE';
|
@@ -5,10 +5,21 @@ import { ReposResolver } from './repos.resolver';
|
|||||||
import { ReposService } from './repos.service';
|
import { ReposService } from './repos.service';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
import { ProjectsModule } from '../projects/projects.module';
|
import { ProjectsModule } from '../projects/projects.module';
|
||||||
|
import { BullModule } from '@nestjs/bull';
|
||||||
|
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: [TypeOrmModule.forFeature([Project]), ConfigModule, ProjectsModule],
|
imports: [
|
||||||
providers: [ReposResolver, ReposService],
|
TypeOrmModule.forFeature([Project]),
|
||||||
|
ConfigModule,
|
||||||
|
ProjectsModule,
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: LIST_LOGS_TASK,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
providers: [ReposResolver, ReposService, ListLogsConsumer],
|
||||||
exports: [ReposService],
|
exports: [ReposService],
|
||||||
})
|
})
|
||||||
export class ReposModule {}
|
export class ReposModule {}
|
||||||
|
@@ -1,26 +1,4 @@
|
|||||||
import { Args, Query, Resolver } from '@nestjs/graphql';
|
import { Resolver } from '@nestjs/graphql';
|
||||||
import { ListLogsArgs } from './dtos/list-logs.args';
|
|
||||||
import { ReposService } from './repos.service';
|
|
||||||
import { LogList } from './dtos/log-list.model';
|
|
||||||
import { ListBranchesArgs } from './dtos/list-branches.args';
|
|
||||||
import { BranchList } from './dtos/branch-list.model';
|
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class ReposResolver {
|
export class ReposResolver {}
|
||||||
constructor(private readonly service: ReposService) {}
|
|
||||||
@Query(() => LogList)
|
|
||||||
async listLogs(@Args('listLogsArgs') dto: ListLogsArgs) {
|
|
||||||
return await this.service.listLogs(dto);
|
|
||||||
}
|
|
||||||
@Query(() => BranchList)
|
|
||||||
async listBranches(
|
|
||||||
@Args('listBranchesArgs') dto: ListBranchesArgs,
|
|
||||||
): Promise<BranchList> {
|
|
||||||
return await this.service.listBranches(dto).then((data) => {
|
|
||||||
return {
|
|
||||||
...data,
|
|
||||||
branches: Object.values(data.branches),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@@ -63,7 +63,10 @@ describe('ReposService', () => {
|
|||||||
});
|
});
|
||||||
describe('listLogs', () => {
|
describe('listLogs', () => {
|
||||||
it('should be return logs', async () => {
|
it('should be return logs', async () => {
|
||||||
const result = await service.listLogs({ projectId: '1' });
|
const result = await service.listLogs({
|
||||||
|
project: getTest1Project(),
|
||||||
|
branch: 'master',
|
||||||
|
});
|
||||||
expect(result).toBeDefined();
|
expect(result).toBeDefined();
|
||||||
}, 20_000);
|
}, 20_000);
|
||||||
});
|
});
|
||||||
@@ -71,7 +74,7 @@ describe('ReposService', () => {
|
|||||||
it('should be return branches', async () => {
|
it('should be return branches', async () => {
|
||||||
const result = await service.listBranches({ projectId: '1' });
|
const result = await service.listBranches({ projectId: '1' });
|
||||||
expect(result).toBeDefined();
|
expect(result).toBeDefined();
|
||||||
}, 10_000);
|
}, 20_000);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe.skip('checkout', () => {
|
describe.skip('checkout', () => {
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
import { ListLogsOption } from './models/list-logs.options';
|
||||||
import { Pipeline } from './../pipelines/pipeline.entity';
|
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';
|
||||||
@@ -39,7 +40,7 @@ export class ReposService {
|
|||||||
await mkdir(workspaceRoot, { recursive: true });
|
await mkdir(workspaceRoot, { recursive: true });
|
||||||
});
|
});
|
||||||
const git = gitP(workspaceRoot);
|
const git = gitP(workspaceRoot);
|
||||||
if (!(await git.checkIsRepo())) {
|
if (!(await git.checkIsRepo().catch(() => false))) {
|
||||||
await git.init();
|
await git.init();
|
||||||
await git.addRemote(DEFAULT_REMOTE_NAME, project.sshUrl);
|
await git.addRemote(DEFAULT_REMOTE_NAME, project.sshUrl);
|
||||||
}
|
}
|
||||||
@@ -47,13 +48,10 @@ export class ReposService {
|
|||||||
return git;
|
return git;
|
||||||
}
|
}
|
||||||
|
|
||||||
async listLogs(dto: ListLogsArgs) {
|
async listLogs({ project, branch }: ListLogsOption) {
|
||||||
const project = await this.projectRepository.findOneOrFail({
|
|
||||||
id: dto.projectId,
|
|
||||||
});
|
|
||||||
const git = await this.getGit(project);
|
const git = await this.getGit(project);
|
||||||
return await git.log(
|
return await git.log(
|
||||||
dto.branch ? ['--branches', dto.branch, '--'] : ['--all'],
|
branch ? ['--branches', `remotes/origin/${branch}`, '--'] : ['--all'],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
8
src/webhooks/dtos/gitea-hook-payload.dto.ts
Normal file
8
src/webhooks/dtos/gitea-hook-payload.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class GiteaHookPayloadDto {
|
||||||
|
@IsString()
|
||||||
|
ref: string;
|
||||||
|
@IsString()
|
||||||
|
after: string;
|
||||||
|
}
|
3
src/webhooks/enums/source-service.enum.ts
Normal file
3
src/webhooks/enums/source-service.enum.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export enum SourceService {
|
||||||
|
gitea = 'gitea',
|
||||||
|
}
|
25
src/webhooks/gitea-webhooks.controller.spec.ts
Normal file
25
src/webhooks/gitea-webhooks.controller.spec.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { GiteaWebhooksController } from './gitea-webhooks.controller';
|
||||||
|
import { WebhooksService } from './webhooks.service';
|
||||||
|
|
||||||
|
describe('GiteaWebhooksController', () => {
|
||||||
|
let controller: GiteaWebhooksController;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [GiteaWebhooksController],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: WebhooksService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
controller = module.get<GiteaWebhooksController>(GiteaWebhooksController);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(controller).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
37
src/webhooks/gitea-webhooks.controller.ts
Normal file
37
src/webhooks/gitea-webhooks.controller.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { Body, Controller, Headers, Param, Post } from '@nestjs/common';
|
||||||
|
import { validateOrReject } from 'class-validator';
|
||||||
|
import { pick } from 'ramda';
|
||||||
|
import { GiteaHookPayloadDto } from './dtos/gitea-hook-payload.dto';
|
||||||
|
import { SourceService } from './enums/source-service.enum';
|
||||||
|
import { WebhookLog } from './webhook-log.entity';
|
||||||
|
import { WebhooksService } from './webhooks.service';
|
||||||
|
|
||||||
|
@Controller('gitea-webhooks')
|
||||||
|
export class GiteaWebhooksController {
|
||||||
|
constructor(private readonly service: WebhooksService) {}
|
||||||
|
@Post(':pipelineId')
|
||||||
|
async onCall(
|
||||||
|
@Headers('X-Gitea-Delivery') delivery: string,
|
||||||
|
@Headers('X-Gitea-Event') event: string,
|
||||||
|
@Headers('X-Gitea-Signature') signature: string,
|
||||||
|
@Body() body: Buffer,
|
||||||
|
@Param('pipelineId') pipelineId: string,
|
||||||
|
) {
|
||||||
|
const payload = Object.assign(
|
||||||
|
new GiteaHookPayloadDto(),
|
||||||
|
JSON.parse(body.toString('utf-8')),
|
||||||
|
);
|
||||||
|
await validateOrReject(payload);
|
||||||
|
await this.service.verifySignature(body, signature, 'boardcat');
|
||||||
|
return await this.service
|
||||||
|
.onCall(pipelineId, {
|
||||||
|
payload,
|
||||||
|
sourceDelivery: delivery,
|
||||||
|
sourceEvent: event,
|
||||||
|
sourceService: SourceService.gitea,
|
||||||
|
})
|
||||||
|
.then((data) =>
|
||||||
|
pick<keyof WebhookLog>(['id', 'createdAt', 'localEvent'])(data),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
9
src/webhooks/models/create-webhook-log.model.ts
Normal file
9
src/webhooks/models/create-webhook-log.model.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { SourceService } from '../enums/source-service.enum';
|
||||||
|
import { WebhookLog } from '../webhook-log.entity';
|
||||||
|
|
||||||
|
export class CreateWebhookLogModel<T> implements Partial<WebhookLog> {
|
||||||
|
sourceDelivery: string;
|
||||||
|
sourceEvent: string;
|
||||||
|
sourceService: SourceService;
|
||||||
|
payload: T;
|
||||||
|
}
|
19
src/webhooks/webhook-log.entity.ts
Normal file
19
src/webhooks/webhook-log.entity.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Column, Entity } from 'typeorm';
|
||||||
|
import { AppBaseEntity } from './../commons/entities/app-base-entity';
|
||||||
|
import { SourceService } from './enums/source-service.enum';
|
||||||
|
|
||||||
|
@Entity()
|
||||||
|
export class WebhookLog extends AppBaseEntity {
|
||||||
|
@Column()
|
||||||
|
sourceDelivery: string;
|
||||||
|
@Column({ type: 'enum', enum: SourceService })
|
||||||
|
sourceService: SourceService;
|
||||||
|
@Column()
|
||||||
|
sourceEvent: string;
|
||||||
|
@Column({ type: 'jsonb' })
|
||||||
|
payload: any;
|
||||||
|
@Column()
|
||||||
|
localEvent: string;
|
||||||
|
@Column({ type: 'jsonb' })
|
||||||
|
localPayload: any;
|
||||||
|
}
|
20
src/webhooks/webhooks.module.ts
Normal file
20
src/webhooks/webhooks.module.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { MiddlewareConsumer, Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { PipelineTasksModule } from '../pipeline-tasks/pipeline-tasks.module';
|
||||||
|
import { GiteaWebhooksController } from './gitea-webhooks.controller';
|
||||||
|
import { WebhookLog } from './webhook-log.entity';
|
||||||
|
import { WebhooksService } from './webhooks.service';
|
||||||
|
import { raw } from 'body-parser';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([WebhookLog]), PipelineTasksModule],
|
||||||
|
controllers: [GiteaWebhooksController],
|
||||||
|
providers: [WebhooksService],
|
||||||
|
})
|
||||||
|
export class WebhooksModule {
|
||||||
|
// configure(consumer: MiddlewareConsumer) {
|
||||||
|
// consumer
|
||||||
|
// .apply(raw({ type: 'application/json' }))
|
||||||
|
// .forRoutes(GiteaWebhooksController);
|
||||||
|
// }
|
||||||
|
}
|
57
src/webhooks/webhooks.service.spec.ts
Normal file
57
src/webhooks/webhooks.service.spec.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { readFile } from 'fs/promises';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
||||||
|
import { WebhookLog } from './webhook-log.entity';
|
||||||
|
import { WebhooksService } from './webhooks.service';
|
||||||
|
|
||||||
|
describe('WebhooksService', () => {
|
||||||
|
let service: WebhooksService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
WebhooksService,
|
||||||
|
{
|
||||||
|
provide: PipelineTasksService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(WebhookLog),
|
||||||
|
useValue: new Repository(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<WebhooksService>(WebhooksService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('verifySignature', () => {
|
||||||
|
const signature =
|
||||||
|
'b175e07189a6106f386b62253b18b5879c4b1f3af2f11fe13a294602671e361a';
|
||||||
|
const secret = 'boardcat';
|
||||||
|
let payload: Buffer;
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await readFile(
|
||||||
|
join(__dirname, '../../test/data/gitea-hook-payload.json.bin'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
it('must be valid', async () => {
|
||||||
|
await expect(
|
||||||
|
service.verifySignature(payload, signature, secret),
|
||||||
|
).resolves.toEqual(undefined);
|
||||||
|
});
|
||||||
|
it('must be invalid', async () => {
|
||||||
|
await expect(
|
||||||
|
service.verifySignature(payload, 'test', secret),
|
||||||
|
).rejects.toThrowError(UnauthorizedException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
65
src/webhooks/webhooks.service.ts
Normal file
65
src/webhooks/webhooks.service.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { createHmac } from 'crypto';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { PipelineUnits } from '../pipeline-tasks/enums/pipeline-units.enum';
|
||||||
|
import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
||||||
|
import { GiteaHookPayloadDto } from './dtos/gitea-hook-payload.dto';
|
||||||
|
import { CreateWebhookLogModel } from './models/create-webhook-log.model';
|
||||||
|
import { WebhookLog } from './webhook-log.entity';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class WebhooksService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(WebhookLog)
|
||||||
|
private readonly repository: Repository<WebhookLog>,
|
||||||
|
private readonly taskService: PipelineTasksService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async onCall(
|
||||||
|
pipelineId: string,
|
||||||
|
model: CreateWebhookLogModel<GiteaHookPayloadDto>,
|
||||||
|
) {
|
||||||
|
if (model.sourceEvent.toLowerCase() === 'push') {
|
||||||
|
const taskDto = {
|
||||||
|
pipelineId,
|
||||||
|
commit: model.payload.after,
|
||||||
|
units: Object.values(PipelineUnits),
|
||||||
|
};
|
||||||
|
await this.taskService.addTask(taskDto);
|
||||||
|
return await this.repository.save(
|
||||||
|
this.repository.create({
|
||||||
|
...model,
|
||||||
|
localEvent: 'create-pipeline-task',
|
||||||
|
localPayload: taskDto,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
throw new BadRequestException('无法处理的请求');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifySignature(payload: any, signature: string, secret: string) {
|
||||||
|
const local = await new Promise<string>((resolve, reject) => {
|
||||||
|
const hmac = createHmac('sha256', secret);
|
||||||
|
hmac.on('readable', () => {
|
||||||
|
const data = hmac.read();
|
||||||
|
if (data) {
|
||||||
|
resolve(data.toString('hex'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
hmac.on('error', (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
hmac.write(payload);
|
||||||
|
hmac.end();
|
||||||
|
});
|
||||||
|
if (local !== signature) {
|
||||||
|
throw new UnauthorizedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
115
test/data/gitea-hook-payload.json.bin
Normal file
115
test/data/gitea-hook-payload.json.bin
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
{
|
||||||
|
"secret": "boardcat",
|
||||||
|
"ref": "refs/heads/master",
|
||||||
|
"before": "429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"after": "429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"compare_url": "",
|
||||||
|
"commits": [
|
||||||
|
{
|
||||||
|
"id": "429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"message": "test(pipeline-tasks): pass test cases.\n",
|
||||||
|
"url": "https://git.ivanli.cc/Fennec/fennec-be/commit/429de1eaedf1da83f1e0e3ac3d8b20e771b7051c",
|
||||||
|
"author": {
|
||||||
|
"name": "Ivan",
|
||||||
|
"email": "ivanli@live.cn",
|
||||||
|
"username": ""
|
||||||
|
},
|
||||||
|
"committer": {
|
||||||
|
"name": "Ivan",
|
||||||
|
"email": "ivanli@live.cn",
|
||||||
|
"username": ""
|
||||||
|
},
|
||||||
|
"verification": null,
|
||||||
|
"timestamp": "0001-01-01T00:00:00Z",
|
||||||
|
"added": null,
|
||||||
|
"removed": null,
|
||||||
|
"modified": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"head_commit": null,
|
||||||
|
"repository": {
|
||||||
|
"id": 3,
|
||||||
|
"owner": {
|
||||||
|
"id": 3,
|
||||||
|
"login": "Fennec",
|
||||||
|
"full_name": "",
|
||||||
|
"email": "",
|
||||||
|
"avatar_url": "https://git.ivanli.cc/user/avatar/Fennec/-1",
|
||||||
|
"language": "",
|
||||||
|
"is_admin": false,
|
||||||
|
"last_login": "1970-01-01T08:00:00+08:00",
|
||||||
|
"created": "2021-01-30T16:46:11+08:00",
|
||||||
|
"username": "Fennec"
|
||||||
|
},
|
||||||
|
"name": "fennec-be",
|
||||||
|
"full_name": "Fennec/fennec-be",
|
||||||
|
"description": "Fennec CI/CD Back-End",
|
||||||
|
"empty": false,
|
||||||
|
"private": false,
|
||||||
|
"fork": false,
|
||||||
|
"template": false,
|
||||||
|
"parent": null,
|
||||||
|
"mirror": false,
|
||||||
|
"size": 1897,
|
||||||
|
"html_url": "https://git.ivanli.cc/Fennec/fennec-be",
|
||||||
|
"ssh_url": "ssh://gitea@git.ivanli.cc:7018/Fennec/fennec-be.git",
|
||||||
|
"clone_url": "https://git.ivanli.cc/Fennec/fennec-be.git",
|
||||||
|
"original_url": "",
|
||||||
|
"website": "",
|
||||||
|
"stars_count": 1,
|
||||||
|
"forks_count": 0,
|
||||||
|
"watchers_count": 1,
|
||||||
|
"open_issues_count": 0,
|
||||||
|
"open_pr_counter": 0,
|
||||||
|
"release_counter": 0,
|
||||||
|
"default_branch": "master",
|
||||||
|
"archived": false,
|
||||||
|
"created_at": "2021-01-31T09:58:38+08:00",
|
||||||
|
"updated_at": "2021-03-27T15:57:00+08:00",
|
||||||
|
"permissions": {
|
||||||
|
"admin": false,
|
||||||
|
"push": false,
|
||||||
|
"pull": false
|
||||||
|
},
|
||||||
|
"has_issues": true,
|
||||||
|
"internal_tracker": {
|
||||||
|
"enable_time_tracker": true,
|
||||||
|
"allow_only_contributors_to_track_time": true,
|
||||||
|
"enable_issue_dependencies": true
|
||||||
|
},
|
||||||
|
"has_wiki": true,
|
||||||
|
"has_pull_requests": true,
|
||||||
|
"has_projects": true,
|
||||||
|
"ignore_whitespace_conflicts": false,
|
||||||
|
"allow_merge_commits": true,
|
||||||
|
"allow_rebase": true,
|
||||||
|
"allow_rebase_explicit": true,
|
||||||
|
"allow_squash_merge": true,
|
||||||
|
"avatar_url": "",
|
||||||
|
"internal": false
|
||||||
|
},
|
||||||
|
"pusher": {
|
||||||
|
"id": 1,
|
||||||
|
"login": "Ivan",
|
||||||
|
"full_name": "Ivan Li",
|
||||||
|
"email": "ivan@noreply.%(DOMAIN)s",
|
||||||
|
"avatar_url": "https://git.ivanli.cc/user/avatar/Ivan/-1",
|
||||||
|
"language": "zh-CN",
|
||||||
|
"is_admin": true,
|
||||||
|
"last_login": "2021-03-26T22:28:05+08:00",
|
||||||
|
"created": "2021-01-23T18:15:30+08:00",
|
||||||
|
"username": "Ivan"
|
||||||
|
},
|
||||||
|
"sender": {
|
||||||
|
"id": 1,
|
||||||
|
"login": "Ivan",
|
||||||
|
"full_name": "Ivan Li",
|
||||||
|
"email": "ivan@noreply.%(DOMAIN)s",
|
||||||
|
"avatar_url": "https://git.ivanli.cc/user/avatar/Ivan/-1",
|
||||||
|
"language": "zh-CN",
|
||||||
|
"is_admin": true,
|
||||||
|
"last_login": "2021-03-26T22:28:05+08:00",
|
||||||
|
"created": "2021-01-23T18:15:30+08:00",
|
||||||
|
"username": "Ivan"
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user