Compare commits
48 Commits
dfaee1fb56
...
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 | |||
e908d2981d | |||
0dadc09ec5 | |||
38d3cb0db8 | |||
8901c49bb3 | |||
7913184174 | |||
f39c801fc2 | |||
33b09594f5 | |||
64ec1433a6 | |||
31a200206f | |||
22d9bf47d3 | |||
e3e698b8cb | |||
ea4ca724e3 | |||
32102ffefd | |||
11cf2a6c12 | |||
2d5763ac02 | |||
3b7c50438f | |||
1d8b99fe8e | |||
5b2a017858 | |||
90d851d85c | |||
042f8876f0 | |||
625ed18ae9 | |||
1e7c594e72 | |||
42c389b913 | |||
9470aa8f8a | |||
ab6c56e55a |
3
.gitignore
vendored
3
.gitignore
vendored
@ -33,5 +33,4 @@ lerna-debug.log*
|
|||||||
!.vscode/launch.json
|
!.vscode/launch.json
|
||||||
!.vscode/extensions.json
|
!.vscode/extensions.json
|
||||||
|
|
||||||
workspaces/*
|
/config.yml
|
||||||
!workspaces/.gitkeep
|
|
9
.vscode/settings.json
vendored
9
.vscode/settings.json
vendored
@ -1,5 +1,12 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
"Repos"
|
"Repos",
|
||||||
|
"boardcat",
|
||||||
|
"gitea",
|
||||||
|
"lpush",
|
||||||
|
"lrange",
|
||||||
|
"metatype",
|
||||||
|
"rpop",
|
||||||
|
"rpush"
|
||||||
]
|
]
|
||||||
}
|
}
|
11
config.yml
11
config.yml
@ -1,11 +0,0 @@
|
|||||||
env: dev
|
|
||||||
http:
|
|
||||||
port: 7122
|
|
||||||
|
|
||||||
db:
|
|
||||||
postgres:
|
|
||||||
host: 192.168.31.194
|
|
||||||
port: 5432
|
|
||||||
database: fennec
|
|
||||||
username: fennec
|
|
||||||
password:
|
|
18
config.yml.example
Normal file
18
config.yml.example
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
env: dev
|
||||||
|
http:
|
||||||
|
port: 7122
|
||||||
|
|
||||||
|
db:
|
||||||
|
postgres:
|
||||||
|
host: 192.168.31.194
|
||||||
|
port: 5432
|
||||||
|
database: fennec
|
||||||
|
username: fennec
|
||||||
|
password:
|
||||||
|
redis:
|
||||||
|
host: 192.168.31.194
|
||||||
|
port: 6379
|
||||||
|
password:
|
||||||
|
prefix: fennec
|
||||||
|
workspaces:
|
||||||
|
root: '/Users/ivanli/Projects/fennec/workspaces'
|
33
docs/ci-cd.md
Normal file
33
docs/ci-cd.md
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
# CI/CD 流程
|
||||||
|
0. 准备
|
||||||
|
- project information
|
||||||
|
- commit hash
|
||||||
|
1. checkout
|
||||||
|
2. install dependencies
|
||||||
|
3. run test script
|
||||||
|
5. run deploy script
|
||||||
|
6. clear workspace
|
||||||
|
|
||||||
|
## 流水线任务单元描述
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"unit": {
|
||||||
|
"install-dependencies": {
|
||||||
|
"script": "npm ci"
|
||||||
|
},
|
||||||
|
"test": {
|
||||||
|
"script": "npm test"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"script": "npm build"
|
||||||
|
},
|
||||||
|
"deploy": {
|
||||||
|
"script": [
|
||||||
|
"npm build"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
10
docs/development-notes.md
Normal file
10
docs/development-notes.md
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
# Fennec CI/CD 工具开发手记
|
||||||
|
## 前言
|
||||||
|
这是 Fennec 后端项目开发手记,用于记录开发过程中遇到的知识点、难点、思路和解决方案。
|
||||||
|
|
||||||
|
## Git Repository 操作
|
||||||
|
### 获取 git 远程仓库信息流程
|
||||||
|
1. `git init` // 初始化一个本地 git 仓库。
|
||||||
|
2. `git remote add <name> <address>` // 添加远程仓库
|
||||||
|
3. `git fetch` // 获取远程仓库信息
|
||||||
|
|
22651
package-lock.json
generated
22651
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
17
package.json
17
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": "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",
|
||||||
@ -21,6 +21,7 @@
|
|||||||
"test:e2e": "jest --config ./test/jest-e2e.json"
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@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",
|
||||||
"@nestjs/core": "^7.5.1",
|
"@nestjs/core": "^7.5.1",
|
||||||
@ -28,14 +29,22 @@
|
|||||||
"@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",
|
"@neuralegion/class-sanitizer": "^0.3.2",
|
||||||
|
"@types/bull": "^3.15.0",
|
||||||
|
"@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",
|
||||||
"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",
|
||||||
|
"observable-to-async-generator": "^1.0.1-rc",
|
||||||
"pg": "^8.5.1",
|
"pg": "^8.5.1",
|
||||||
|
"ramda": "^0.27.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"rxjs": "^6.6.3",
|
"rxjs": "^6.6.3",
|
||||||
@ -43,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';
|
||||||
@ -7,7 +7,14 @@ import { AppResolver } from './app.resolver';
|
|||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
import { ProjectsModule } from './projects/projects.module';
|
import { ProjectsModule } from './projects/projects.module';
|
||||||
import { ReposModule } from './repos/repos.module';
|
import { ReposModule } from './repos/repos.module';
|
||||||
|
import { PipelinesModule } from './pipelines/pipelines.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 { 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: [
|
||||||
@ -16,13 +23,13 @@ import configuration from './commons/config/configuration';
|
|||||||
}),
|
}),
|
||||||
TypeOrmModule.forRootAsync({
|
TypeOrmModule.forRootAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (cnfigService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
type: 'postgres',
|
type: 'postgres',
|
||||||
host: cnfigService.get<string>('db.postgres.host'),
|
host: configService.get<string>('db.postgres.host'),
|
||||||
port: cnfigService.get<number>('db.postgres.port'),
|
port: configService.get<number>('db.postgres.port'),
|
||||||
username: cnfigService.get<string>('db.postgres.username'),
|
username: configService.get<string>('db.postgres.username'),
|
||||||
password: cnfigService.get<string>('db.postgres.password'),
|
password: configService.get<string>('db.postgres.password'),
|
||||||
database: cnfigService.get<string>('db.postgres.database'),
|
database: configService.get<string>('db.postgres.database'),
|
||||||
synchronize: true,
|
synchronize: true,
|
||||||
autoLoadEntities: true,
|
autoLoadEntities: true,
|
||||||
}),
|
}),
|
||||||
@ -30,17 +37,39 @@ import configuration from './commons/config/configuration';
|
|||||||
}),
|
}),
|
||||||
GraphQLModule.forRootAsync({
|
GraphQLModule.forRootAsync({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (cnfigService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
debug: cnfigService.get<string>('env') !== 'prod',
|
debug: configService.get<string>('env') !== 'prod',
|
||||||
playground: true,
|
playground: true,
|
||||||
autoSchemaFile: true,
|
autoSchemaFile: true,
|
||||||
|
installSubscriptionHandlers: true,
|
||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
}),
|
}),
|
||||||
ProjectsModule,
|
ProjectsModule,
|
||||||
ReposModule,
|
ReposModule,
|
||||||
|
PipelinesModule,
|
||||||
|
PipelineTasksModule,
|
||||||
|
RedisModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
host: configService.get<string>('db.redis.host', 'localhost'),
|
||||||
|
port: configService.get<number>('db.redis.port', 6379),
|
||||||
|
password: configService.get<string>('db.redis.password', ''),
|
||||||
|
keyPrefix: configService.get<string>('db.redis.prefix', 'fennec') + ':',
|
||||||
|
}),
|
||||||
|
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,
|
timestamp: new Date().toISOString(),
|
||||||
});
|
|
||||||
} else {
|
|
||||||
response.status(status).json({
|
|
||||||
message: ex,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
path: request.url,
|
path: request.url,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else if (exception instanceof EntityNotFoundError) {
|
default:
|
||||||
response.status(HttpStatus.NOT_FOUND).json({
|
throw exception;
|
||||||
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(),
|
|
||||||
message: '服务器内部错误',
|
|
||||||
error: exception,
|
|
||||||
path: request.url,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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();
|
||||||
|
11
src/pipeline-tasks/dtos/create-pipeline-task.input.ts
Normal file
11
src/pipeline-tasks/dtos/create-pipeline-task.input.ts
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import { Field, InputType } from '@nestjs/graphql';
|
||||||
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class CreatePipelineTaskInput {
|
||||||
|
pipelineId: string;
|
||||||
|
|
||||||
|
commit: string;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
14
src/pipeline-tasks/enums/pipeline-units.enum.ts
Normal file
14
src/pipeline-tasks/enums/pipeline-units.enum.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { registerEnumType } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
export enum PipelineUnits {
|
||||||
|
checkout = 'checkout',
|
||||||
|
installDependencies = 'installDependencies',
|
||||||
|
test = 'test',
|
||||||
|
deploy = 'deploy',
|
||||||
|
cleanUp = 'cleanUp',
|
||||||
|
}
|
||||||
|
|
||||||
|
registerEnumType(PipelineUnits, {
|
||||||
|
name: 'PipelineUnits',
|
||||||
|
description: '流水线单元',
|
||||||
|
});
|
13
src/pipeline-tasks/enums/task-statuses.enum.ts
Normal file
13
src/pipeline-tasks/enums/task-statuses.enum.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { registerEnumType } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
export enum TaskStatuses {
|
||||||
|
success = 'success',
|
||||||
|
failed = 'failed',
|
||||||
|
working = 'working',
|
||||||
|
pending = 'pending',
|
||||||
|
}
|
||||||
|
|
||||||
|
registerEnumType(TaskStatuses, {
|
||||||
|
name: 'TaskStatuses',
|
||||||
|
description: '任务状态',
|
||||||
|
});
|
@ -0,0 +1,32 @@
|
|||||||
|
import { PipelineTask } from './../pipeline-task.entity';
|
||||||
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
|
import { Field, HideField, ObjectType } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class PipelineTaskLogMessage {
|
||||||
|
@HideField()
|
||||||
|
task: PipelineTask;
|
||||||
|
@Field(() => PipelineUnits, { nullable: true })
|
||||||
|
unit?: PipelineUnits;
|
||||||
|
@Field()
|
||||||
|
time: Date;
|
||||||
|
@Field()
|
||||||
|
message: string;
|
||||||
|
@Field()
|
||||||
|
isError: boolean;
|
||||||
|
|
||||||
|
static create(
|
||||||
|
task: PipelineTask,
|
||||||
|
unit: PipelineUnits,
|
||||||
|
message: string,
|
||||||
|
isError: boolean,
|
||||||
|
) {
|
||||||
|
return Object.assign(new PipelineTaskLogMessage(), {
|
||||||
|
task,
|
||||||
|
message,
|
||||||
|
time: new Date(),
|
||||||
|
unit,
|
||||||
|
isError,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
14
src/pipeline-tasks/models/pipeline-task-logs.model.ts
Normal file
14
src/pipeline-tasks/models/pipeline-task-logs.model.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { TaskStatuses } from '../enums/task-statuses.enum';
|
||||||
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
|
import { Field, ObjectType } from '@nestjs/graphql';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
export class PipelineTaskLogs {
|
||||||
|
@Field(() => PipelineUnits)
|
||||||
|
unit: PipelineUnits;
|
||||||
|
@Field(() => TaskStatuses)
|
||||||
|
status: TaskStatuses;
|
||||||
|
startedAt?: Date;
|
||||||
|
endedAt?: Date;
|
||||||
|
logs = '';
|
||||||
|
}
|
9
src/pipeline-tasks/models/work-unit-metadata.model.ts
Normal file
9
src/pipeline-tasks/models/work-unit-metadata.model.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import { InputType, ObjectType } from '@nestjs/graphql';
|
||||||
|
import { WorkUnit } from './work-unit.model';
|
||||||
|
|
||||||
|
@InputType('WorkUnitMetadataInput')
|
||||||
|
@ObjectType()
|
||||||
|
export class WorkUnitMetadata {
|
||||||
|
version = 1;
|
||||||
|
units: WorkUnit[];
|
||||||
|
}
|
13
src/pipeline-tasks/models/work-unit.model.ts
Normal file
13
src/pipeline-tasks/models/work-unit.model.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { Field, InputType, ObjectType } from '@nestjs/graphql';
|
||||||
|
import {
|
||||||
|
PipelineUnits,
|
||||||
|
PipelineUnits as PipelineUnitTypes,
|
||||||
|
} from '../enums/pipeline-units.enum';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
@InputType('WorkUnitInput')
|
||||||
|
export class WorkUnit {
|
||||||
|
@Field(() => PipelineUnits)
|
||||||
|
type: PipelineUnitTypes;
|
||||||
|
scripts: string[];
|
||||||
|
}
|
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);
|
||||||
|
}
|
||||||
|
}
|
34
src/pipeline-tasks/pipeline-task.entity.ts
Normal file
34
src/pipeline-tasks/pipeline-task.entity.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import { AppBaseEntity } from './../commons/entities/app-base-entity';
|
||||||
|
import { Field, ObjectType } from '@nestjs/graphql';
|
||||||
|
import { Column, Entity, ManyToOne } from 'typeorm';
|
||||||
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
|
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
||||||
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
@Entity()
|
||||||
|
export class PipelineTask extends AppBaseEntity {
|
||||||
|
@ManyToOne(() => Pipeline)
|
||||||
|
pipeline: Pipeline;
|
||||||
|
@Column()
|
||||||
|
pipelineId: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
commit: string;
|
||||||
|
|
||||||
|
@Column({ type: 'enum', enum: PipelineUnits, array: true })
|
||||||
|
units: PipelineUnits[];
|
||||||
|
|
||||||
|
@Column({ type: 'jsonb', default: '[]' })
|
||||||
|
logs: PipelineTaskLogs[];
|
||||||
|
|
||||||
|
@Column({ type: 'enum', enum: TaskStatuses, default: TaskStatuses.pending })
|
||||||
|
status: TaskStatuses;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
startedAt?: Date;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
endedAt?: Date;
|
||||||
|
}
|
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';
|
39
src/pipeline-tasks/pipeline-tasks.module.ts
Normal file
39
src/pipeline-tasks/pipeline-tasks.module.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
import { PipelineTasksResolver } from './pipeline-tasks.resolver';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
|
import { ReposModule } from '../repos/repos.module';
|
||||||
|
import { RedisModule } from 'nestjs-redis';
|
||||||
|
import { BullModule } from '@nestjs/bull';
|
||||||
|
import { PipelineTaskConsumer } from './pipeline-task.consumer';
|
||||||
|
import {
|
||||||
|
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({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([PipelineTask, Pipeline]),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: PIPELINE_TASK_QUEUE,
|
||||||
|
}),
|
||||||
|
RedisModule,
|
||||||
|
ReposModule,
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
PipelineTasksService,
|
||||||
|
PipelineTasksResolver,
|
||||||
|
PipelineTaskConsumer,
|
||||||
|
PipelineTaskLogsService,
|
||||||
|
{
|
||||||
|
provide: Symbol(PIPELINE_TASK_LOG_PUBSUB),
|
||||||
|
useValue: new PubSub(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
exports: [PipelineTasksService],
|
||||||
|
})
|
||||||
|
export class PipelineTasksModule {}
|
30
src/pipeline-tasks/pipeline-tasks.resolver.spec.ts
Normal file
30
src/pipeline-tasks/pipeline-tasks.resolver.spec.ts
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelineTasksResolver } from './pipeline-tasks.resolver';
|
||||||
|
import { PipelineTaskLogsService } from './pipeline-task-logs.service';
|
||||||
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
|
||||||
|
describe('PipelineTasksResolver', () => {
|
||||||
|
let resolver: PipelineTasksResolver;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
PipelineTasksResolver,
|
||||||
|
{
|
||||||
|
provide: PipelineTasksService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: PipelineTaskLogsService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
resolver = module.get<PipelineTasksResolver>(PipelineTasksResolver);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(resolver).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
50
src/pipeline-tasks/pipeline-tasks.resolver.ts
Normal file
50
src/pipeline-tasks/pipeline-tasks.resolver.ts
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
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()
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
205
src/pipeline-tasks/pipeline-tasks.service.spec.ts
Normal file
205
src/pipeline-tasks/pipeline-tasks.service.spec.ts
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
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 { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { Queue } from 'bull';
|
||||||
|
import { LockFailedException } from '../commons/exceptions/lock-failed.exception';
|
||||||
|
|
||||||
|
describe('PipelineTasksService', () => {
|
||||||
|
let service: PipelineTasksService;
|
||||||
|
let module: TestingModule;
|
||||||
|
let taskRepository: Repository<PipelineTask>;
|
||||||
|
let pipelineRepository: Repository<Pipeline>;
|
||||||
|
const getBasePipeline = () =>
|
||||||
|
({
|
||||||
|
id: 'test',
|
||||||
|
name: '测试流水线',
|
||||||
|
branch: 'master',
|
||||||
|
workUnitMetadata: {},
|
||||||
|
project: {
|
||||||
|
id: 'test-project',
|
||||||
|
},
|
||||||
|
} as Pipeline);
|
||||||
|
let redisClient;
|
||||||
|
let taskQueue: Queue;
|
||||||
|
const getTask = () =>
|
||||||
|
({
|
||||||
|
pipelineId: 'test',
|
||||||
|
commit: 'test',
|
||||||
|
pipeline: { branch: 'master' },
|
||||||
|
units: [],
|
||||||
|
} as PipelineTask);
|
||||||
|
|
||||||
|
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({
|
||||||
|
providers: [
|
||||||
|
PipelineTasksService,
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(PipelineTask),
|
||||||
|
useValue: new Repository(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(Pipeline),
|
||||||
|
useValue: new Repository(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: getQueueToken(PIPELINE_TASK_QUEUE),
|
||||||
|
useValue: taskQueue,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: RedisService,
|
||||||
|
useValue: {
|
||||||
|
getClient: jest.fn(() => redisClient),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<PipelineTasksService>(PipelineTasksService);
|
||||||
|
taskRepository = module.get(getRepositoryToken(PipelineTask));
|
||||||
|
pipelineRepository = module.get(getRepositoryToken(Pipeline));
|
||||||
|
jest
|
||||||
|
.spyOn(taskRepository, 'save')
|
||||||
|
.mockImplementation(async (data: any) => data);
|
||||||
|
jest
|
||||||
|
.spyOn(taskRepository, 'create')
|
||||||
|
.mockImplementation((data: any) => data);
|
||||||
|
jest.spyOn(taskRepository, 'findOne').mockImplementation(async () => null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('addTask', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest
|
||||||
|
.spyOn(pipelineRepository, 'findOneOrFail')
|
||||||
|
.mockImplementation(async () => getBasePipeline());
|
||||||
|
});
|
||||||
|
it('pipeline not found', async () => {
|
||||||
|
jest.spyOn(taskRepository, 'findOneOrFail').mockImplementation(() => {
|
||||||
|
throw new EntityNotFoundError(Pipeline, {});
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.addTask({ pipelineId: 'test', commit: 'test', units: [] }),
|
||||||
|
).rejects;
|
||||||
|
});
|
||||||
|
it('create task on db', async () => {
|
||||||
|
const save = jest
|
||||||
|
.spyOn(taskRepository, 'save')
|
||||||
|
.mockImplementation(async (data: any) => data);
|
||||||
|
const findOne = jest.spyOn(taskRepository, 'findOne');
|
||||||
|
jest
|
||||||
|
.spyOn(service, 'doNextTask')
|
||||||
|
.mockImplementation(async () => undefined);
|
||||||
|
await service.addTask({ pipelineId: 'test', commit: 'test', units: [] }),
|
||||||
|
expect(save.mock.calls[0][0]).toMatchObject({
|
||||||
|
pipelineId: 'test',
|
||||||
|
commit: 'test',
|
||||||
|
units: [],
|
||||||
|
});
|
||||||
|
expect(findOne).toBeCalled();
|
||||||
|
});
|
||||||
|
it('add task', async () => {
|
||||||
|
const lpush = jest.spyOn(redisClient, 'lpush');
|
||||||
|
const doNextTask = jest.spyOn(service, 'doNextTask');
|
||||||
|
jest
|
||||||
|
.spyOn(service, 'doNextTask')
|
||||||
|
.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);
|
||||||
|
});
|
||||||
|
});
|
128
src/pipeline-tasks/pipeline-tasks.service.ts
Normal file
128
src/pipeline-tasks/pipeline-tasks.service.ts
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
import { ConflictException, Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
|
import { In, Repository } from 'typeorm';
|
||||||
|
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
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';
|
||||||
|
|
||||||
|
const log = debug('fennec:pipeline-tasks:service');
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PipelineTasksService {
|
||||||
|
pubSub = new PubSub();
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(PipelineTask)
|
||||||
|
private readonly repository: Repository<PipelineTask>,
|
||||||
|
@InjectRepository(Pipeline)
|
||||||
|
private readonly pipelineRepository: Repository<Pipeline>,
|
||||||
|
@InjectQueue(PIPELINE_TASK_QUEUE)
|
||||||
|
private readonly queue: Queue<PipelineTask>,
|
||||||
|
private readonly redis: RedisService,
|
||||||
|
) {}
|
||||||
|
async addTask(dto: CreatePipelineTaskInput) {
|
||||||
|
const pipeline = await this.pipelineRepository.findOneOrFail({
|
||||||
|
where: { id: dto.pipelineId },
|
||||||
|
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));
|
||||||
|
task.pipeline = pipeline;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findTaskById(id: string) {
|
||||||
|
return await this.repository.findOneOrFail({ id });
|
||||||
|
}
|
||||||
|
|
||||||
|
async listTasksByPipelineId(pipelineId: string) {
|
||||||
|
return await this.repository.find({ pipelineId });
|
||||||
|
}
|
||||||
|
|
||||||
|
async doNextTask(pipeline: Pipeline) {
|
||||||
|
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] {
|
||||||
|
return [`pipeline-${pipeline.id}:lck`, `pipeline-${pipeline.id}:tasks`];
|
||||||
|
}
|
||||||
|
}
|
27
src/pipelines/dtos/create-pipeline.input.ts
Normal file
27
src/pipelines/dtos/create-pipeline.input.ts
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import { InputType } from '@nestjs/graphql';
|
||||||
|
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
|
||||||
|
import {
|
||||||
|
IsObject,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUUID,
|
||||||
|
MaxLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
@InputType({ isAbstract: true })
|
||||||
|
export class CreatePipelineInput {
|
||||||
|
@IsUUID()
|
||||||
|
projectId: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(100)
|
||||||
|
branch: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(32)
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
workUnitMetadata: WorkUnitMetadata;
|
||||||
|
}
|
8
src/pipelines/dtos/list-pipelines.args.ts
Normal file
8
src/pipelines/dtos/list-pipelines.args.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import { ArgsType } from '@nestjs/graphql';
|
||||||
|
import { IsUUID } from 'class-validator';
|
||||||
|
|
||||||
|
@ArgsType()
|
||||||
|
export class ListPipelineArgs {
|
||||||
|
@IsUUID()
|
||||||
|
projectId?: string;
|
||||||
|
}
|
5
src/pipelines/dtos/update-pipeline.input.ts
Normal file
5
src/pipelines/dtos/update-pipeline.input.ts
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { InputType } from '@nestjs/graphql';
|
||||||
|
import { CreatePipelineInput } from './create-pipeline.input';
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class UpdatePipelineInput extends CreatePipelineInput {}
|
23
src/pipelines/pipeline.entity.ts
Normal file
23
src/pipelines/pipeline.entity.ts
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import { Column, Entity, ManyToOne } from 'typeorm';
|
||||||
|
import { AppBaseEntity } from '../commons/entities/app-base-entity';
|
||||||
|
import { Project } from '../projects/project.entity';
|
||||||
|
import { ObjectType } from '@nestjs/graphql';
|
||||||
|
import { WorkUnitMetadata } from '../pipeline-tasks/models/work-unit-metadata.model';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
|
@Entity()
|
||||||
|
export class Pipeline extends AppBaseEntity {
|
||||||
|
@ManyToOne(() => Project)
|
||||||
|
project: Project;
|
||||||
|
@Column()
|
||||||
|
projectId: string;
|
||||||
|
|
||||||
|
@Column({ comment: 'eg: remotes/origin/master' })
|
||||||
|
branch: string;
|
||||||
|
|
||||||
|
@Column()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@Column({ type: 'jsonb' })
|
||||||
|
workUnitMetadata: WorkUnitMetadata;
|
||||||
|
}
|
18
src/pipelines/pipelines.module.ts
Normal file
18
src/pipelines/pipelines.module.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { PipelinesResolver } from './pipelines.resolver';
|
||||||
|
import { PipelinesService } from './pipelines.service';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { Pipeline } from './pipeline.entity';
|
||||||
|
import { BullModule } from '@nestjs/bull';
|
||||||
|
import { LIST_LOGS_TASK } from '../repos/repos.constants';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([Pipeline]),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: LIST_LOGS_TASK,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
providers: [PipelinesResolver, PipelinesService],
|
||||||
|
})
|
||||||
|
export class PipelinesModule {}
|
25
src/pipelines/pipelines.resolver.spec.ts
Normal file
25
src/pipelines/pipelines.resolver.spec.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelinesResolver } from './pipelines.resolver';
|
||||||
|
import { PipelinesService } from './pipelines.service';
|
||||||
|
|
||||||
|
describe('PipelinesResolver', () => {
|
||||||
|
let resolver: PipelinesResolver;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
PipelinesResolver,
|
||||||
|
{
|
||||||
|
provide: PipelinesService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
resolver = module.get<PipelinesResolver>(PipelinesResolver);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(resolver).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
57
src/pipelines/pipelines.resolver.ts
Normal file
57
src/pipelines/pipelines.resolver.ts
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql';
|
||||||
|
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
||||||
|
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
||||||
|
import { Pipeline } from './pipeline.entity';
|
||||||
|
import { PipelinesService } from './pipelines.service';
|
||||||
|
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
||||||
|
import { LogList } from '../repos/dtos/log-list.model';
|
||||||
|
|
||||||
|
@Resolver()
|
||||||
|
export class PipelinesResolver {
|
||||||
|
constructor(private readonly service: PipelinesService) {}
|
||||||
|
@Query(() => [Pipeline])
|
||||||
|
async listPipelines(@Args() dto: ListPipelineArgs) {
|
||||||
|
return await this.service.list(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Query(() => Pipeline)
|
||||||
|
async findPipeline(@Args('id', { type: () => String }) id: string) {
|
||||||
|
return await this.service.findOne(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mutation(() => Pipeline)
|
||||||
|
async createPipeline(
|
||||||
|
@Args('pipeline', { type: () => CreatePipelineInput })
|
||||||
|
dto: UpdatePipelineInput,
|
||||||
|
) {
|
||||||
|
return await this.service.create(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mutation(() => Pipeline)
|
||||||
|
async modifyPipeline(
|
||||||
|
@Args('id', { type: () => String }) id: string,
|
||||||
|
@Args('Pipeline', { type: () => UpdatePipelineInput })
|
||||||
|
dto: UpdatePipelineInput,
|
||||||
|
) {
|
||||||
|
const tmp = await this.service.update(id, dto);
|
||||||
|
console.log(tmp);
|
||||||
|
return tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Mutation(() => Number)
|
||||||
|
async deletePipeline(@Args('id', { type: () => String }) id: string) {
|
||||||
|
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();
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
69
src/pipelines/pipelines.service.spec.ts
Normal file
69
src/pipelines/pipelines.service.spec.ts
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelinesService } from './pipelines.service';
|
||||||
|
import { Pipeline } from './pipeline.entity';
|
||||||
|
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', () => {
|
||||||
|
let service: PipelinesService;
|
||||||
|
let repository: Repository<Pipeline>;
|
||||||
|
let pipeline: Pipeline;
|
||||||
|
let queue: Queue<ListLogsOption>;
|
||||||
|
|
||||||
|
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({
|
||||||
|
providers: [
|
||||||
|
PipelinesService,
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(Pipeline),
|
||||||
|
useValue: {
|
||||||
|
findOneOrFail: jest.fn().mockImplementation(() => pipeline),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: getQueueToken(LIST_LOGS_TASK),
|
||||||
|
useValue: {
|
||||||
|
add: jest.fn().mockImplementation(() => ({ id: 1 } as Job)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<PipelinesService>(PipelinesService);
|
||||||
|
repository = module.get(getRepositoryToken(Pipeline));
|
||||||
|
queue = module.get(getQueueToken(LIST_LOGS_TASK));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
55
src/pipelines/pipelines.service.ts
Normal file
55
src/pipelines/pipelines.service.ts
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Pipeline } from './pipeline.entity';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { BaseDbService } from '../commons/services/base-db.service';
|
||||||
|
import { CreatePipelineInput } from './dtos/create-pipeline.input';
|
||||||
|
import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
||||||
|
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()
|
||||||
|
export class PipelinesService extends BaseDbService<Pipeline> {
|
||||||
|
readonly uniqueFields: Array<Array<keyof Pipeline>> = [['projectId', 'name']];
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(Pipeline)
|
||||||
|
readonly repository: Repository<Pipeline>,
|
||||||
|
@InjectQueue(LIST_LOGS_TASK)
|
||||||
|
private readonly listLogsQueue: Queue<ListLogsOption>,
|
||||||
|
) {
|
||||||
|
super(repository);
|
||||||
|
}
|
||||||
|
async list(dto: ListPipelineArgs) {
|
||||||
|
return this.repository.find(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(dto: CreatePipelineInput) {
|
||||||
|
await this.isDuplicateEntity(dto);
|
||||||
|
return await this.repository.save(this.repository.create(dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, dto: UpdatePipelineInput) {
|
||||||
|
await this.isDuplicateEntityForUpdate(id, dto);
|
||||||
|
const old = await this.findOne(id);
|
||||||
|
return await this.repository.save(this.repository.merge(old, dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: string) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,7 @@ import {
|
|||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
IsUrl,
|
IsUrl,
|
||||||
|
Matches,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
MinLength,
|
MinLength,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
@ -19,7 +20,9 @@ export class CreateProjectInput {
|
|||||||
@MinLength(2)
|
@MinLength(2)
|
||||||
comment: string;
|
comment: string;
|
||||||
|
|
||||||
@IsUrl({ protocols: ['ssh'] })
|
@Matches(
|
||||||
|
/^(?:ssh:\/\/)?(?:[\w\d-_]+@)(?:[\w\d-_]+\.)*\w{2,10}(?::\d{1,5})?(?:\/[\w\d-_.]+)*/,
|
||||||
|
)
|
||||||
@MaxLength(256)
|
@MaxLength(256)
|
||||||
sshUrl: string;
|
sshUrl: string;
|
||||||
|
|
||||||
|
@ -22,7 +22,4 @@ export class Project extends AppBaseEntity {
|
|||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
webHookSecret?: string;
|
webHookSecret?: string;
|
||||||
|
|
||||||
@DeleteDateColumn()
|
|
||||||
deletedAt?: Date;
|
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,19 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { ProjectsResolver } from './projects.resolver';
|
import { ProjectsResolver } from './projects.resolver';
|
||||||
|
import { ProjectsService } from './projects.service';
|
||||||
|
|
||||||
describe('ProjectsResolver', () => {
|
describe('ProjectsResolver', () => {
|
||||||
let resolver: ProjectsResolver;
|
let resolver: ProjectsResolver;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [ProjectsResolver],
|
providers: [
|
||||||
|
ProjectsResolver,
|
||||||
|
{
|
||||||
|
provide: ProjectsService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
resolver = module.get<ProjectsResolver>(ProjectsResolver);
|
resolver = module.get<ProjectsResolver>(ProjectsResolver);
|
||||||
|
@ -1,12 +1,20 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { ProjectsService } from './projects.service';
|
import { ProjectsService } from './projects.service';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { Project } from './project.entity';
|
||||||
|
|
||||||
describe('ProjectsService', () => {
|
describe('ProjectsService', () => {
|
||||||
let service: ProjectsService;
|
let service: ProjectsService;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [ProjectsService],
|
providers: [
|
||||||
|
ProjectsService,
|
||||||
|
{
|
||||||
|
provide: getRepositoryToken(Project),
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<ProjectsService>(ProjectsService);
|
service = module.get<ProjectsService>(ProjectsService);
|
||||||
|
@ -4,6 +4,7 @@ import { BaseDbService } from '../commons/services/base-db.service';
|
|||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { CreateProjectInput } from './dtos/create-project.input';
|
import { CreateProjectInput } from './dtos/create-project.input';
|
||||||
import { Project } from './project.entity';
|
import { Project } from './project.entity';
|
||||||
|
import { UpdateProjectInput } from './dtos/update-project.input';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ProjectsService extends BaseDbService<Project> {
|
export class ProjectsService extends BaseDbService<Project> {
|
||||||
@ -24,7 +25,7 @@ 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(id: string, dto: CreateProjectInput) {
|
async update(id: string, dto: UpdateProjectInput) {
|
||||||
await this.isDuplicateEntityForUpdate(id, dto);
|
await this.isDuplicateEntityForUpdate(id, dto);
|
||||||
const old = await this.findOne(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));
|
||||||
|
@ -15,7 +15,7 @@ export class Branch implements BranchSummaryBranch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class BranchesList {
|
export class BranchList {
|
||||||
detached: boolean;
|
detached: boolean;
|
||||||
current: string;
|
current: string;
|
||||||
all: string[];
|
all: string[];
|
16
src/repos/dtos/checkout.input.ts
Normal file
16
src/repos/dtos/checkout.input.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { InputType } from '@nestjs/graphql';
|
||||||
|
import { IsOptional, IsString, IsUUID } from 'class-validator';
|
||||||
|
|
||||||
|
@InputType()
|
||||||
|
export class CheckoutInput {
|
||||||
|
@IsUUID()
|
||||||
|
pipelineId: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
branch?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
commitNumber?: string;
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
import { InputType, ObjectType } from '@nestjs/graphql';
|
import { InputType } from '@nestjs/graphql';
|
||||||
import { IsOptional, IsString, IsUUID } from 'class-validator';
|
import { IsOptional, IsString, IsUUID } from 'class-validator';
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
|
@ -13,7 +13,7 @@ export class LogFields {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class LogsList implements LogResult<DefaultLogFields> {
|
export class LogList implements LogResult<DefaultLogFields> {
|
||||||
@Field(() => [LogFields])
|
@Field(() => [LogFields])
|
||||||
all: LogFields[];
|
all: LogFields[];
|
||||||
total: number;
|
total: number;
|
@ -0,0 +1,2 @@
|
|||||||
|
import { ApplicationException } from '../../commons/exceptions/application.exception';
|
||||||
|
export class GetWorkspaceLockFailedException extends ApplicationException {}
|
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';
|
@ -3,9 +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 } from '@nestjs/config';
|
||||||
|
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])],
|
imports: [
|
||||||
providers: [ReposResolver, ReposService],
|
TypeOrmModule.forFeature([Project]),
|
||||||
|
ConfigModule,
|
||||||
|
ProjectsModule,
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: LIST_LOGS_TASK,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
providers: [ReposResolver, ReposService, ListLogsConsumer],
|
||||||
|
exports: [ReposService],
|
||||||
})
|
})
|
||||||
export class ReposModule {}
|
export class ReposModule {}
|
||||||
|
@ -1,18 +1,30 @@
|
|||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { ReposResolver } from './repos.resolver';
|
import { ReposResolver } from './repos.resolver';
|
||||||
|
import { ReposService } from './repos.service';
|
||||||
|
import { ProjectsService } from '../projects/projects.service';
|
||||||
|
|
||||||
describe('ReposResolver', () => {
|
describe('ReposResolver', () => {
|
||||||
let resolver: ReposResolver;
|
let resolver: ReposResolver;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
providers: [ReposResolver],
|
providers: [
|
||||||
|
ReposResolver,
|
||||||
|
{
|
||||||
|
provide: ReposService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: ProjectsService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
resolver = module.get<ReposResolver>(ReposResolver);
|
resolver = module.get<ReposResolver>(ReposResolver);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(resolver).toBeDefined();
|
expect(resolver).toBeDefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -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 { LogsList } from './dtos/logs-list.model';
|
|
||||||
import { ListBranchesArgs } from './dtos/list-branches.args';
|
|
||||||
import { BranchesList } from './dtos/branches-list.model';
|
|
||||||
|
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class ReposResolver {
|
export class ReposResolver {}
|
||||||
con
|
|
||||||
@Query(() => LogsList)
|
|
||||||
async listLogs(@Args('listLogsArgs') dto: ListLogsArgs) {
|
|
||||||
return await this.service.listLogs(dto);
|
|
||||||
}
|
|
||||||
@Query(() => BranchesList)
|
|
||||||
async ListBranchesArgs(
|
|
||||||
@Args('listBranchesArgs') dto: ListBranchesArgs,
|
|
||||||
): Promise<BranchesList> {
|
|
||||||
return await this.service.listBranches(dto).then((data) => {
|
|
||||||
return {
|
|
||||||
...data,
|
|
||||||
branches: Object.values(data.branches),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,23 +1,44 @@
|
|||||||
|
import { Pipeline } from './../pipelines/pipeline.entity';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
import { Project } from '../projects/project.entity';
|
import { Project } from '../projects/project.entity';
|
||||||
import { ReposService } from './repos.service';
|
import { ReposService } from './repos.service';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { rm } from 'fs/promises';
|
||||||
|
import configuration from '../commons/config/configuration';
|
||||||
|
import { PipelineTask } from '../pipeline-tasks/pipeline-task.entity';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { readFile } from 'fs/promises';
|
||||||
|
|
||||||
|
const getTest1Project = () =>
|
||||||
|
({
|
||||||
|
id: '1',
|
||||||
|
sshUrl: 'ssh://gitea@git.ivanli.cc:7018/Fennec/test-1.git',
|
||||||
|
name: 'test-1',
|
||||||
|
} as Project);
|
||||||
|
|
||||||
describe('ReposService', () => {
|
describe('ReposService', () => {
|
||||||
let service: ReposService;
|
let service: ReposService;
|
||||||
const repositoryMockFactory = jest.fn(() => ({
|
const repositoryMockFactory = jest.fn(() => ({
|
||||||
findOneOrFail: jest.fn(
|
findOneOrFail: jest.fn(
|
||||||
(entity): Project => ({
|
(entity): Project => ({
|
||||||
id: '1',
|
...getTest1Project(),
|
||||||
// sshUrl: 'ssh://gitea@git.ivanli.cc:7018/ivan/test1.git',
|
|
||||||
sshUrl: 'ssh://gitea@git.ivanli.cc:7018/Fennec/fennec-fe.git',
|
|
||||||
name: 'test1',
|
|
||||||
...entity,
|
...entity,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
|
afterEach(async () => {
|
||||||
|
await rm(service.getWorkspaceRoot(getTest1Project()), {
|
||||||
|
recursive: true,
|
||||||
|
}).catch(() => undefined);
|
||||||
|
});
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
load: [configuration],
|
||||||
|
}),
|
||||||
|
],
|
||||||
providers: [
|
providers: [
|
||||||
ReposService,
|
ReposService,
|
||||||
{
|
{
|
||||||
@ -28,21 +49,94 @@ describe('ReposService', () => {
|
|||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
service = module.get<ReposService>(ReposService);
|
service = module.get<ReposService>(ReposService);
|
||||||
|
|
||||||
|
await rm(service.getWorkspaceRoot(getTest1Project()), {
|
||||||
|
recursive: true,
|
||||||
|
}).catch(() => undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
expect(service).toBeDefined();
|
expect(service).toBeDefined();
|
||||||
});
|
});
|
||||||
|
it('getWorkspaceRoot', () => {
|
||||||
|
expect(service.getWorkspaceRoot(getTest1Project())).toBeDefined();
|
||||||
|
});
|
||||||
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();
|
||||||
}, 10_000);
|
}, 20_000);
|
||||||
});
|
});
|
||||||
describe('listBranch', () => {
|
describe('listBranch', () => {
|
||||||
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', () => {
|
||||||
|
let task: PipelineTask;
|
||||||
|
let workspaceRoot: string;
|
||||||
|
beforeEach(() => {
|
||||||
|
const project = new Project();
|
||||||
|
const pipeline = new Pipeline();
|
||||||
|
task = new PipelineTask();
|
||||||
|
pipeline.project = project;
|
||||||
|
task.pipeline = pipeline;
|
||||||
|
project.id = 'pid';
|
||||||
|
project.name = 'pname';
|
||||||
|
pipeline.id = 'lid';
|
||||||
|
pipeline.name = 'pipeline';
|
||||||
|
task.id = 'tid';
|
||||||
|
task.commit = '123123hash';
|
||||||
|
workspaceRoot = service.getWorkspaceRootByTask(task);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be checkout', async () => {
|
||||||
|
task.commit = '498c782685';
|
||||||
|
await service.checkout(task, workspaceRoot);
|
||||||
|
const filePath = join(workspaceRoot, 'README.md');
|
||||||
|
const text = await readFile(filePath, { encoding: 'utf-8' });
|
||||||
|
expect(text).toMatch(/Commit 1/gi);
|
||||||
|
}, 20_000);
|
||||||
|
it('should be checkout right commit', async () => {
|
||||||
|
task.commit = '7f7123fe5b';
|
||||||
|
await service.checkout(task, workspaceRoot);
|
||||||
|
const filePath = join(workspaceRoot, 'README.md');
|
||||||
|
const text = await readFile(filePath, { encoding: 'utf-8' });
|
||||||
|
expect(text).toMatch(/(?!Commit 1)/gi);
|
||||||
|
}, 20_000);
|
||||||
|
it('should be checkout right commit (复用)', async () => {
|
||||||
|
task.commit = '498c782685';
|
||||||
|
await service.checkout(task, workspaceRoot);
|
||||||
|
task.commit = '7f7123fe5b';
|
||||||
|
await service.checkout(task, workspaceRoot);
|
||||||
|
const filePath = join(workspaceRoot, 'README.md');
|
||||||
|
const text = await readFile(filePath, { encoding: 'utf-8' });
|
||||||
|
expect(text).toMatch(/(?!Commit 1)/gi);
|
||||||
|
}, 30_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getWorkspaceRootByTask', () => {
|
||||||
|
it('should be return right path', () => {
|
||||||
|
const project = new Project();
|
||||||
|
const pipeline = new Pipeline();
|
||||||
|
const task = new PipelineTask();
|
||||||
|
pipeline.project = project;
|
||||||
|
task.pipeline = pipeline;
|
||||||
|
project.id = 'pid';
|
||||||
|
project.name = 'pname';
|
||||||
|
pipeline.id = 'lid';
|
||||||
|
pipeline.name = 'pipeline/\\-名称';
|
||||||
|
task.id = 'tid';
|
||||||
|
task.commit = '123123hash';
|
||||||
|
|
||||||
|
expect(service.getWorkspaceRootByTask(task)).toMatch(
|
||||||
|
/\/pname\/pipeline%2F%5C-%E5%90%8D%E7%A7%B0-123123hash$/,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { ListLogsOption } from './models/list-logs.options';
|
||||||
|
import { Pipeline } from './../pipelines/pipeline.entity';
|
||||||
|
import { PipelineTask } from './../pipeline-tasks/pipeline-task.entity';
|
||||||
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { F_OK } from 'constants';
|
import { F_OK } from 'constants';
|
||||||
import { access, mkdir } from 'fs/promises';
|
import { access, mkdir } from 'fs/promises';
|
||||||
@ -8,27 +11,48 @@ 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 { ListLogsArgs } from './dtos/list-logs.args';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
const DEFAULT_REMOTE_NAME = 'origin';
|
||||||
|
const INFO_PATH = '@info';
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ReposService {
|
export class ReposService {
|
||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(Project)
|
@InjectRepository(Project)
|
||||||
private readonly projectRepository: Repository<Project>,
|
private readonly projectRepository: Repository<Project>,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getGit(project: Project) {
|
getWorkspaceRoot(project: Project): string {
|
||||||
const workspacePath = join(__dirname, '../../workspaces', project.name);
|
return join(
|
||||||
await access(workspacePath, F_OK).catch(() => mkdir(workspacePath));
|
this.configService.get<string>('workspaces.root'),
|
||||||
return gitP(workspacePath);
|
encodeURIComponent(project.name),
|
||||||
|
INFO_PATH,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async listLogs(dto: ListLogsArgs) {
|
async getGit(project: Project, workspaceRoot?: string) {
|
||||||
const project = await this.projectRepository.findOneOrFail({
|
if (!workspaceRoot) {
|
||||||
id: dto.projectId,
|
workspaceRoot = this.getWorkspaceRoot(project);
|
||||||
|
}
|
||||||
|
|
||||||
|
await access(workspaceRoot, F_OK).catch(async () => {
|
||||||
|
await mkdir(workspaceRoot, { recursive: true });
|
||||||
});
|
});
|
||||||
const git = await this.getGit(project);
|
const git = gitP(workspaceRoot);
|
||||||
|
if (!(await git.checkIsRepo().catch(() => false))) {
|
||||||
|
await git.init();
|
||||||
|
await git.addRemote(DEFAULT_REMOTE_NAME, project.sshUrl);
|
||||||
|
}
|
||||||
await git.fetch();
|
await git.fetch();
|
||||||
return git.log();
|
return git;
|
||||||
|
}
|
||||||
|
|
||||||
|
async listLogs({ project, branch }: ListLogsOption) {
|
||||||
|
const git = await this.getGit(project);
|
||||||
|
return await git.log(
|
||||||
|
branch ? ['--branches', `remotes/origin/${branch}`, '--'] : ['--all'],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async listBranches(dto: ListBranchesArgs) {
|
async listBranches(dto: ListBranchesArgs) {
|
||||||
@ -38,4 +62,31 @@ export class ReposService {
|
|||||||
const git = await this.getGit(project);
|
const git = await this.getGit(project);
|
||||||
return git.branch();
|
return git.branch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async checkout(task: PipelineTask, workspaceRoot: string) {
|
||||||
|
const git = await this.getGit(task.pipeline.project, workspaceRoot);
|
||||||
|
try {
|
||||||
|
await git.fetch(DEFAULT_REMOTE_NAME);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.message.includes("couldn't find remote ref nonexistent")) {
|
||||||
|
throw new NotFoundException(err.message);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
await git.checkout([task.commit]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get workspace root absolute path
|
||||||
|
*
|
||||||
|
* ! example: `/var/tmp/fennec-workspaces-root/project/pipeline_name-commit_hash`
|
||||||
|
* @param task {PipelineTask} task (with pipeline and project info)
|
||||||
|
*/
|
||||||
|
getWorkspaceRootByTask(task: PipelineTask) {
|
||||||
|
return join(
|
||||||
|
this.configService.get<string>('workspaces.root'),
|
||||||
|
encodeURIComponent(task.pipeline.project.name),
|
||||||
|
encodeURIComponent(`${task.pipeline.name}-${task.commit}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
8
test/data/bad-work.js
Normal file
8
test/data/bad-work.js
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
for (let i = 1; i <= 5; i++) {
|
||||||
|
console.log(i * 10);
|
||||||
|
}
|
||||||
|
console.error('Error Message');
|
||||||
|
console.error('Error Message 2');
|
||||||
|
console.log('Bye-bye');
|
||||||
|
|
||||||
|
process.exit(1);
|
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"
|
||||||
|
}
|
||||||
|
}
|
7
test/data/one-second-work.js
Normal file
7
test/data/one-second-work.js
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
let timer;
|
||||||
|
let count = 0;
|
||||||
|
setTimeout(() => clearInterval(timer), 1_000);
|
||||||
|
|
||||||
|
timer = setInterval(() => {
|
||||||
|
console.log(++count * 10);
|
||||||
|
}, 95);
|
Reference in New Issue
Block a user