Compare commits
37 Commits
3ee41ece67
...
master
Author | SHA1 | Date | |
---|---|---|---|
a299958fcb | |||
f07e18f71d | |||
eb7adc0ef2 | |||
122dca689d | |||
fcca1508eb | |||
34cfc71a18 | |||
de2e9fa8c4 | |||
0f1466bf91 | |||
ed71d83581 | |||
574e7ecae7 | |||
1b469e34f9 | |||
c86772a5dd | |||
aec7f65434 | |||
ab4ef36bf8 | |||
0a03bcd36e | |||
ec351d12f2 | |||
c3c73fbe65 | |||
02059ee54f | |||
5ed17cc04b | |||
256878890b | |||
9908bd229e | |||
07f19101a5 | |||
7d84017f9e | |||
a231a02c28 | |||
7e17de0f15 | |||
9d735c582c | |||
b626eed859 | |||
5b5a657651 | |||
a510f411a7 | |||
246623b5db | |||
37f8ae19be | |||
133439bb49 | |||
646f68d298 | |||
0c3310d3a5 | |||
ead32a1204 | |||
20612d4301 | |||
7091f9df6a |
1
.gitignore
vendored
1
.gitignore
vendored
@ -34,3 +34,4 @@ lerna-debug.log*
|
|||||||
!.vscode/extensions.json
|
!.vscode/extensions.json
|
||||||
|
|
||||||
/config.yml
|
/config.yml
|
||||||
|
tsconfig.build.tsbuildinfo
|
3
.vscode/extensions.json
vendored
Normal file
3
.vscode/extensions.json
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"recommendations": []
|
||||||
|
}
|
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
|
"Mutex",
|
||||||
"Repos",
|
"Repos",
|
||||||
"amqp",
|
"amqp",
|
||||||
"boardcat",
|
"boardcat",
|
||||||
|
@ -16,5 +16,9 @@ db:
|
|||||||
prefix: fennec
|
prefix: fennec
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
uri: 'amqp://fennec:fennec@192.168.31.194:5672'
|
uri: 'amqp://fennec:fennec@192.168.31.194:5672'
|
||||||
|
etcd:
|
||||||
|
hosts:
|
||||||
|
- 'http://192.168.31.194:2379'
|
||||||
|
|
||||||
workspaces:
|
workspaces:
|
||||||
root: '/Users/ivanli/Projects/fennec/workspaces'
|
root: '/Users/ivanli/Projects/fennec/workspaces'
|
14
ecosystem.config.js
Normal file
14
ecosystem.config.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'fennec-be',
|
||||||
|
script: 'npm',
|
||||||
|
args: 'run start:prod',
|
||||||
|
watch: false,
|
||||||
|
ignore_watch: ['node_modules'],
|
||||||
|
log_date_format: 'MM-DD HH:mm:ss.SSS Z',
|
||||||
|
env: {},
|
||||||
|
max_restarts: 5,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
19300
package-lock.json
generated
19300
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
21
package.json
21
package.json
@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "fennec-be",
|
"name": "fennec-be",
|
||||||
"version": "0.0.1",
|
"version": "0.1.1",
|
||||||
"description": "",
|
"description": "a ci/cd project.",
|
||||||
"author": "",
|
"author": "Ivan Li\b<ivanli2048@gmail.com>",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@ -22,31 +22,33 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@golevelup/nestjs-rabbitmq": "^1.16.1",
|
"@golevelup/nestjs-rabbitmq": "^1.16.1",
|
||||||
"@nestjs/bull": "^0.3.1",
|
"@nestjs-lib/auth": "^0.2.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",
|
||||||
"@nestjs/graphql": "^7.9.8",
|
"@nestjs/graphql": "^7.9.8",
|
||||||
"@nestjs/platform-express": "^7.5.1",
|
"@nestjs/platform-express": "^7.5.1",
|
||||||
"@nestjs/typeorm": "^7.1.5",
|
"@nestjs/typeorm": "^7.1.5",
|
||||||
"@types/bull": "^3.15.0",
|
"@types/amqplib": "^0.8.0",
|
||||||
"@types/ramda": "^0.27.38",
|
"@types/ramda": "^0.27.38",
|
||||||
"apollo-server-express": "^2.19.2",
|
"apollo-server-express": "^2.19.2",
|
||||||
"bcrypt": "^5.0.0",
|
"bcrypt": "^5.0.0",
|
||||||
"body-parser": "^1.19.0",
|
"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",
|
"debug": "^4.3.1",
|
||||||
"graphql": "^15.5.0",
|
"graphql": "^15.5.0",
|
||||||
"graphql-tools": "^7.0.2",
|
"graphql-tools": "^8.1.0",
|
||||||
"ioredis": "^4.25.0",
|
"ioredis": "^4.25.0",
|
||||||
|
"jose": "^3.14.0",
|
||||||
"js-yaml": "^4.0.0",
|
"js-yaml": "^4.0.0",
|
||||||
|
"nestjs-etcd": "^0.2.0",
|
||||||
"nestjs-pino": "^1.4.0",
|
"nestjs-pino": "^1.4.0",
|
||||||
"nestjs-redis": "^1.2.8",
|
"nestjs-redis": "^1.2.8",
|
||||||
"observable-to-async-generator": "^1.0.1-rc",
|
"observable-to-async-generator": "^1.0.1-rc",
|
||||||
"pg": "^8.5.1",
|
"pg": "^8.5.1",
|
||||||
"pino-pretty": "^4.7.1",
|
"pino-pretty": "^4.7.1",
|
||||||
|
"pm2": "^5.1.0",
|
||||||
"ramda": "^0.27.1",
|
"ramda": "^0.27.1",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
@ -55,7 +57,7 @@
|
|||||||
"typeorm": "^0.2.30"
|
"typeorm": "^0.2.30"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^7.5.7",
|
"@nestjs/cli": "^7.6.0",
|
||||||
"@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/body-parser": "^1.19.0",
|
||||||
@ -95,6 +97,9 @@
|
|||||||
"collectCoverageFrom": [
|
"collectCoverageFrom": [
|
||||||
"**/*.(t|j)s"
|
"**/*.(t|j)s"
|
||||||
],
|
],
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^jose/(.*)$": "<rootDir>/../node_modules/jose/dist/node/cjs/$1"
|
||||||
|
},
|
||||||
"coverageDirectory": "../coverage",
|
"coverageDirectory": "../coverage",
|
||||||
"testEnvironment": "node"
|
"testEnvironment": "node"
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { CommonsModule } from './commons/commons.module';
|
||||||
import { MiddlewareConsumer, Module, NestModule } 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';
|
||||||
@ -12,13 +13,13 @@ import { PipelineTasksModule } from './pipeline-tasks/pipeline-tasks.module';
|
|||||||
import configuration from './commons/config/configuration';
|
import configuration from './commons/config/configuration';
|
||||||
import { RedisModule } from 'nestjs-redis';
|
import { RedisModule } from 'nestjs-redis';
|
||||||
import { WebhooksModule } from './webhooks/webhooks.module';
|
import { WebhooksModule } from './webhooks/webhooks.module';
|
||||||
import { RawBodyMiddleware } from './commons/middlewares/raw-body.middleware';
|
import { RawBodyMiddleware } from './commons/middleware/raw-body.middleware';
|
||||||
import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller';
|
import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller';
|
||||||
import { ParseBodyMiddleware } from './commons/middlewares/parse-body.middleware';
|
import { ParseBodyMiddleware } from './commons/middleware/parse-body.middleware';
|
||||||
import { BullModule } from '@nestjs/bull';
|
|
||||||
import { LoggerModule } from 'nestjs-pino';
|
import { LoggerModule } from 'nestjs-pino';
|
||||||
|
import { EtcdModule } from 'nestjs-etcd';
|
||||||
import pinoPretty from 'pino-pretty';
|
import pinoPretty from 'pino-pretty';
|
||||||
|
import { fromPairs, map, pipe, toPairs } from 'ramda';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@ -63,16 +64,21 @@ import pinoPretty from 'pino-pretty';
|
|||||||
playground: true,
|
playground: true,
|
||||||
autoSchemaFile: true,
|
autoSchemaFile: true,
|
||||||
installSubscriptionHandlers: true,
|
installSubscriptionHandlers: true,
|
||||||
}),
|
context: ({ req, connection, ...args }) => {
|
||||||
inject: [ConfigService],
|
return connection ? { req: connection.context } : { req };
|
||||||
}),
|
},
|
||||||
BullModule.forRootAsync({
|
subscriptions: {
|
||||||
imports: [ConfigModule],
|
onConnect: (connectionParams: Record<string, string>) => {
|
||||||
useFactory: (configService: ConfigService) => ({
|
const connectionParamsWithLowerKeys = pipe(
|
||||||
redis: {
|
toPairs,
|
||||||
host: configService.get<string>('db.redis.host', 'localhost'),
|
map(([key, value]) => [key.toLowerCase(), value]),
|
||||||
port: configService.get<number>('db.redis.port', undefined),
|
fromPairs,
|
||||||
password: configService.get<string>('db.redis.password', undefined),
|
)(connectionParams);
|
||||||
|
|
||||||
|
return {
|
||||||
|
headers: connectionParamsWithLowerKeys,
|
||||||
|
};
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
@ -91,7 +97,15 @@ import pinoPretty from 'pino-pretty';
|
|||||||
}),
|
}),
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
}),
|
}),
|
||||||
|
EtcdModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
hosts: configService.get<string>('db.etcd.hosts', 'localhost:2379'),
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
WebhooksModule,
|
WebhooksModule,
|
||||||
|
CommonsModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService, AppResolver],
|
providers: [AppService, AppResolver],
|
||||||
|
@ -1,8 +1,11 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { PasswordConverter } from './services/password-converter';
|
import { PasswordConverter } from './services/password-converter';
|
||||||
|
import { RedisMutexModule } from './redis-mutex/redis-mutex.module';
|
||||||
|
import { AuthModule } from '@nestjs-lib/auth';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
imports: [RedisMutexModule, AuthModule],
|
||||||
providers: [PasswordConverter],
|
providers: [PasswordConverter],
|
||||||
exports: [PasswordConverter],
|
exports: [PasswordConverter, RedisMutexModule, AuthModule],
|
||||||
})
|
})
|
||||||
export class CommonsModule {}
|
export class CommonsModule {}
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
|
import { pick } from 'ramda';
|
||||||
|
|
||||||
export class ApplicationException extends Error {
|
export class ApplicationException extends Error {
|
||||||
code: number;
|
code: number;
|
||||||
error: Error;
|
error: Error;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
message:
|
message: string | { error?: Error; message?: string | any; code?: number },
|
||||||
| string
|
|
||||||
| { error?: Error; message?: string | object; code?: number },
|
|
||||||
) {
|
) {
|
||||||
if (message instanceof Object) {
|
if (message instanceof Object) {
|
||||||
super();
|
super();
|
||||||
@ -18,4 +18,8 @@ export class ApplicationException extends Error {
|
|||||||
super((message as unknown) as any);
|
super((message as unknown) as any);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
toJSON() {
|
||||||
|
return pick(['code', 'message'], this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,13 +6,18 @@ import {
|
|||||||
HttpStatus,
|
HttpStatus,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApolloError } from 'apollo-server-errors';
|
import { ApolloError } from 'apollo-server-errors';
|
||||||
|
import { PinoLogger, InjectPinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
@Catch(HttpException)
|
@Catch(HttpException)
|
||||||
export class HttpExceptionFilter implements ExceptionFilter {
|
export class HttpExceptionFilter implements ExceptionFilter {
|
||||||
|
constructor(
|
||||||
|
@InjectPinoLogger(HttpExceptionFilter.name)
|
||||||
|
private readonly logger: PinoLogger,
|
||||||
|
) {}
|
||||||
catch(exception: HttpException, host: ArgumentsHost) {
|
catch(exception: HttpException, host: ArgumentsHost) {
|
||||||
switch (host.getType<'http' | 'graphql' | string>()) {
|
switch (host.getType<'http' | 'graphql' | string>()) {
|
||||||
case 'graphql': {
|
case 'graphql': {
|
||||||
const message = exception.message;
|
const errorName = exception.message;
|
||||||
const extensions: Record<string, any> = {};
|
const extensions: Record<string, any> = {};
|
||||||
const err = exception.getResponse();
|
const err = exception.getResponse();
|
||||||
if (typeof err === 'string') {
|
if (typeof err === 'string') {
|
||||||
@ -21,8 +26,10 @@ export class HttpExceptionFilter implements ExceptionFilter {
|
|||||||
Object.assign(extensions, (err as any).extension);
|
Object.assign(extensions, (err as any).extension);
|
||||||
extensions.message = (err as any).message;
|
extensions.message = (err as any).message;
|
||||||
}
|
}
|
||||||
|
extensions.error = errorName;
|
||||||
|
this.logger.error(extensions);
|
||||||
return new ApolloError(
|
return new ApolloError(
|
||||||
message,
|
extensions.message,
|
||||||
exception.getStatus().toString(),
|
exception.getStatus().toString(),
|
||||||
extensions,
|
extensions,
|
||||||
);
|
);
|
||||||
|
10
src/commons/redis-mutex/redis-mutex.module.ts
Normal file
10
src/commons/redis-mutex/redis-mutex.module.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { RedisMutexService } from './redis-mutex.service';
|
||||||
|
import { RedisModule } from 'nestjs-redis';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [RedisModule],
|
||||||
|
providers: [RedisMutexService],
|
||||||
|
exports: [RedisMutexService],
|
||||||
|
})
|
||||||
|
export class RedisMutexModule {}
|
25
src/commons/redis-mutex/redis-mutex.service.spec.ts
Normal file
25
src/commons/redis-mutex/redis-mutex.service.spec.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
import { RedisMutexService } from './redis-mutex.service';
|
||||||
|
|
||||||
|
describe('RedisMutexService', () => {
|
||||||
|
let service: RedisMutexService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
RedisMutexService,
|
||||||
|
{
|
||||||
|
provide: RedisService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<RedisMutexService>(RedisMutexService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
71
src/commons/redis-mutex/redis-mutex.service.ts
Normal file
71
src/commons/redis-mutex/redis-mutex.service.ts
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
import * as uuid from 'uuid';
|
||||||
|
import { ApplicationException } from '../exceptions/application.exception';
|
||||||
|
|
||||||
|
export interface RedisMutexOption {
|
||||||
|
/**
|
||||||
|
* seconds
|
||||||
|
*/
|
||||||
|
expires?: number;
|
||||||
|
/**
|
||||||
|
* seconds
|
||||||
|
*/
|
||||||
|
timeout?: number | null;
|
||||||
|
/**
|
||||||
|
* milliseconds
|
||||||
|
*/
|
||||||
|
retryDelay?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RedisMutexService {
|
||||||
|
constructor(private readonly redisClient: RedisService) {}
|
||||||
|
|
||||||
|
public async lock(
|
||||||
|
key: string,
|
||||||
|
{ expires = 100, timeout = 10, retryDelay = 100 }: RedisMutexOption = {
|
||||||
|
expires: 100,
|
||||||
|
timeout: 10,
|
||||||
|
retryDelay: 100,
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const redisKey = `${'mutex-lock'}:${key}`;
|
||||||
|
const redis = this.redisClient.getClient();
|
||||||
|
const value = uuid.v4();
|
||||||
|
const timeoutAt = timeout ? Date.now() + timeout * 1000 : null;
|
||||||
|
|
||||||
|
while (
|
||||||
|
!(await redis
|
||||||
|
.set(redisKey, value, 'EX', expires, 'NX')
|
||||||
|
.then(() => true)
|
||||||
|
.catch(() => false))
|
||||||
|
) {
|
||||||
|
if (timeoutAt && timeoutAt > Date.now()) {
|
||||||
|
throw new ApplicationException('lock timeout');
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, retryDelay));
|
||||||
|
}
|
||||||
|
|
||||||
|
const renewTimer = setInterval(() => {
|
||||||
|
redis.expire(redisKey, expires);
|
||||||
|
}, (expires * 1000) / 2);
|
||||||
|
|
||||||
|
return async () => {
|
||||||
|
clearInterval(renewTimer);
|
||||||
|
await redis.eval(
|
||||||
|
`
|
||||||
|
if redis.call("get", KEYS[1]) == ARGV[1]
|
||||||
|
then
|
||||||
|
return redis.call("del", KEYS[1])
|
||||||
|
else
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
`,
|
||||||
|
1,
|
||||||
|
redisKey,
|
||||||
|
value,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
@ -53,8 +53,22 @@ export class BaseDbService<Entity extends AppBaseEntity> extends TypeormHelper {
|
|||||||
async isDuplicateEntityForUpdate<Dto extends Entity>(
|
async isDuplicateEntityForUpdate<Dto extends Entity>(
|
||||||
id: string,
|
id: string,
|
||||||
dto: Partial<Dto>,
|
dto: Partial<Dto>,
|
||||||
|
extendsFields?: Array<keyof Dto & string>,
|
||||||
|
): Promise<false | never>;
|
||||||
|
async isDuplicateEntityForUpdate<Dto extends Entity>(
|
||||||
|
old: Entity,
|
||||||
|
dto: Partial<Dto>,
|
||||||
|
extendsFields?: Array<keyof Dto & string>,
|
||||||
|
): Promise<false | never>;
|
||||||
|
async isDuplicateEntityForUpdate<Dto extends Entity>(
|
||||||
|
id: string | Entity,
|
||||||
|
dto: Partial<Dto>,
|
||||||
extendsFields: Array<keyof Dto & string> = [],
|
extendsFields: Array<keyof Dto & string> = [],
|
||||||
): Promise<false | never> {
|
): Promise<false | never> {
|
||||||
|
if (typeof id !== 'string') {
|
||||||
|
dto = Object.assign({}, id, dto);
|
||||||
|
id = id.id;
|
||||||
|
}
|
||||||
const qb = this.repository.createQueryBuilder('entity');
|
const qb = this.repository.createQueryBuilder('entity');
|
||||||
const compareFields = this.getCompareFields(dto, [
|
const compareFields = this.getCompareFields(dto, [
|
||||||
...this.uniqueFields,
|
...this.uniqueFields,
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
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';
|
||||||
@ -14,7 +15,8 @@ async function bootstrap() {
|
|||||||
transform: true,
|
transform: true,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
app.useGlobalFilters(new HttpExceptionFilter());
|
const httpExceptionFilterLogger = await app.resolve(PinoLogger);
|
||||||
|
app.useGlobalFilters(new HttpExceptionFilter(httpExceptionFilterLogger));
|
||||||
await app.listen(configService.get<number>('http.port'));
|
await app.listen(configService.get<number>('http.port'));
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
@ -11,3 +11,5 @@ registerEnumType(TaskStatuses, {
|
|||||||
name: 'TaskStatuses',
|
name: 'TaskStatuses',
|
||||||
description: '任务状态',
|
description: '任务状态',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const terminalTaskStatuses = [TaskStatuses.success, TaskStatuses.failed];
|
||||||
|
@ -1,13 +1,25 @@
|
|||||||
|
import { Field, ObjectType } from '@nestjs/graphql';
|
||||||
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
import { PipelineUnits } from '../enums/pipeline-units.enum';
|
||||||
import { TaskStatuses } from '../enums/task-statuses.enum';
|
import { TaskStatuses } from '../enums/task-statuses.enum';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
|
||||||
|
@ObjectType()
|
||||||
export class PipelineTaskEvent {
|
export class PipelineTaskEvent {
|
||||||
|
@Field()
|
||||||
taskId: string;
|
taskId: string;
|
||||||
|
@Field()
|
||||||
pipelineId: string;
|
pipelineId: string;
|
||||||
|
@Field()
|
||||||
projectId: string;
|
projectId: string;
|
||||||
|
@Field(() => PipelineUnits, { nullable: true })
|
||||||
unit: PipelineUnits | null;
|
unit: PipelineUnits | null;
|
||||||
|
@Field()
|
||||||
|
@Type(() => Date)
|
||||||
emittedAt: Date;
|
emittedAt: Date;
|
||||||
|
@Field()
|
||||||
message: string;
|
message: string;
|
||||||
|
@Field()
|
||||||
messageType: 'stdout' | 'stderr' | 'stdin';
|
messageType: 'stdout' | 'stderr' | 'stdin';
|
||||||
|
@Field(() => TaskStatuses)
|
||||||
status: TaskStatuses;
|
status: TaskStatuses;
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,16 @@
|
|||||||
import { InputType, ObjectType } from '@nestjs/graphql';
|
import { Field, InputType, Int, ObjectType } from '@nestjs/graphql';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import { IsInstance, isInstance, ValidateNested } from 'class-validator';
|
||||||
import { WorkUnit } from './work-unit.model';
|
import { WorkUnit } from './work-unit.model';
|
||||||
|
|
||||||
@InputType('WorkUnitMetadataInput')
|
@InputType('WorkUnitMetadataInput')
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class WorkUnitMetadata {
|
export class WorkUnitMetadata {
|
||||||
|
@Field(() => Int)
|
||||||
version = 1;
|
version = 1;
|
||||||
|
|
||||||
|
@Type(() => WorkUnit)
|
||||||
|
@IsInstance(WorkUnit, { each: true })
|
||||||
|
@ValidateNested({ each: true })
|
||||||
units: WorkUnit[];
|
units: WorkUnit[];
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import { Field, InputType, ObjectType } from '@nestjs/graphql';
|
import { Field, InputType, ObjectType } from '@nestjs/graphql';
|
||||||
|
import { IsNotEmpty } from 'class-validator';
|
||||||
import {
|
import {
|
||||||
PipelineUnits,
|
PipelineUnits,
|
||||||
PipelineUnits as PipelineUnitTypes,
|
PipelineUnits as PipelineUnitTypes,
|
||||||
@ -9,5 +10,7 @@ import {
|
|||||||
export class WorkUnit {
|
export class WorkUnit {
|
||||||
@Field(() => PipelineUnits)
|
@Field(() => PipelineUnits)
|
||||||
type: PipelineUnitTypes;
|
type: PipelineUnitTypes;
|
||||||
|
|
||||||
|
@IsNotEmpty({ each: true })
|
||||||
scripts: string[];
|
scripts: string[];
|
||||||
}
|
}
|
||||||
|
88
src/pipeline-tasks/pipeline-task-flush.service.spec.ts
Normal file
88
src/pipeline-tasks/pipeline-task-flush.service.spec.ts
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
import { PipelineTaskFlushService } from './pipeline-task-flush.service';
|
||||||
|
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
||||||
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
ROUTE_PIPELINE_TASK_DONE,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
|
||||||
|
describe('PipelineTaskFlushService', () => {
|
||||||
|
let service: PipelineTaskFlushService;
|
||||||
|
let redisService: RedisService;
|
||||||
|
let amqpConnection: AmqpConnection;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const redisClient = {
|
||||||
|
rpush: jest.fn(() => Promise.resolve()),
|
||||||
|
lrange: jest.fn(() => Promise.resolve()),
|
||||||
|
expire: jest.fn(() => Promise.resolve()),
|
||||||
|
};
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
PipelineTaskFlushService,
|
||||||
|
{
|
||||||
|
provide: RedisService,
|
||||||
|
useValue: {
|
||||||
|
getClient() {
|
||||||
|
return redisClient;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: AmqpConnection,
|
||||||
|
useValue: {
|
||||||
|
request: jest.fn(() => Promise.resolve()),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<PipelineTaskFlushService>(PipelineTaskFlushService);
|
||||||
|
redisService = module.get<RedisService>(RedisService);
|
||||||
|
amqpConnection = module.get<AmqpConnection>(AmqpConnection);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('write', () => {
|
||||||
|
const amqpMsg = {
|
||||||
|
properties: { headers: { sender: 'test' } },
|
||||||
|
} as any;
|
||||||
|
it('normal', async () => {
|
||||||
|
const testEvent = new PipelineTaskEvent();
|
||||||
|
testEvent.taskId = 'test';
|
||||||
|
testEvent.status = TaskStatuses.working;
|
||||||
|
const rpush = jest.spyOn(redisService.getClient(), 'rpush');
|
||||||
|
const request = jest.spyOn(amqpConnection, 'request');
|
||||||
|
await service.write(testEvent, amqpMsg);
|
||||||
|
expect(rpush).toBeCalledTimes(1);
|
||||||
|
expect(rpush.mock.calls[0][0]).toEqual('p-task:log:test');
|
||||||
|
expect(rpush.mock.calls[0][1]).toEqual(JSON.stringify(testEvent));
|
||||||
|
expect(request).toBeCalledTimes(1);
|
||||||
|
});
|
||||||
|
it('event for which task done', async () => {
|
||||||
|
const testEvent = new PipelineTaskEvent();
|
||||||
|
testEvent.taskId = 'test';
|
||||||
|
testEvent.status = TaskStatuses.success;
|
||||||
|
const rpush = jest.spyOn(redisService.getClient(), 'rpush');
|
||||||
|
const request = jest.spyOn(amqpConnection, 'request');
|
||||||
|
await service.write(testEvent, amqpMsg);
|
||||||
|
expect(rpush).toBeCalledTimes(1);
|
||||||
|
expect(request).toBeCalledTimes(1);
|
||||||
|
expect(request.mock.calls[0][0]).toMatchObject({
|
||||||
|
exchange: EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
routingKey: ROUTE_PIPELINE_TASK_DONE,
|
||||||
|
payload: {
|
||||||
|
taskId: 'test',
|
||||||
|
status: TaskStatuses.success,
|
||||||
|
runOn: 'test',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
66
src/pipeline-tasks/pipeline-task-flush.service.ts
Normal file
66
src/pipeline-tasks/pipeline-task-flush.service.ts
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import { AmqpConnection, RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { ConsumeMessage } from 'amqplib';
|
||||||
|
import { deserialize } from 'class-transformer';
|
||||||
|
import { RedisService } from 'nestjs-redis';
|
||||||
|
import { isNil } from 'ramda';
|
||||||
|
import { getSelfInstanceQueueKey } from '../commons/utils/rabbit-mq';
|
||||||
|
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
ROUTE_PIPELINE_TASK_DONE,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
|
ROUTE_PIPELINE_TASK_LOG,
|
||||||
|
QUEUE_WRITE_PIPELINE_TASK_LOG,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PipelineTaskFlushService {
|
||||||
|
constructor(
|
||||||
|
private readonly redisService: RedisService,
|
||||||
|
private readonly amqpConnection: AmqpConnection,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@RabbitSubscribe({
|
||||||
|
exchange: EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
|
routingKey: ROUTE_PIPELINE_TASK_LOG,
|
||||||
|
queue: getSelfInstanceQueueKey(QUEUE_WRITE_PIPELINE_TASK_LOG),
|
||||||
|
queueOptions: {
|
||||||
|
autoDelete: true,
|
||||||
|
durable: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async write(message: PipelineTaskEvent, amqpMsg: ConsumeMessage) {
|
||||||
|
const client = this.redisService.getClient();
|
||||||
|
await client.rpush(this.getKey(message.taskId), JSON.stringify(message));
|
||||||
|
await client.expire(this.getKey(message.taskId), 600); // ten minutes
|
||||||
|
if (isNil(message.unit)) {
|
||||||
|
try {
|
||||||
|
await this.amqpConnection.request({
|
||||||
|
exchange: EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
routingKey: ROUTE_PIPELINE_TASK_DONE,
|
||||||
|
payload: {
|
||||||
|
taskId: message.taskId,
|
||||||
|
status: message.status,
|
||||||
|
runOn: amqpMsg.properties.headers.sender,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async read(taskId: string) {
|
||||||
|
const raw = await this.redisService
|
||||||
|
.getClient()
|
||||||
|
.lrange(this.getKey(taskId), 0, -1);
|
||||||
|
return raw.map((it) => deserialize(PipelineTaskEvent, it));
|
||||||
|
}
|
||||||
|
|
||||||
|
private getKey(taskId: string) {
|
||||||
|
return `p-task:log:${taskId}`;
|
||||||
|
}
|
||||||
|
}
|
@ -36,4 +36,7 @@ export class PipelineTask extends AppBaseEntity {
|
|||||||
|
|
||||||
@Column({ nullable: true })
|
@Column({ nullable: true })
|
||||||
endedAt?: Date;
|
endedAt?: Date;
|
||||||
|
|
||||||
|
@Column({ nullable: true })
|
||||||
|
runOn: string;
|
||||||
}
|
}
|
||||||
|
77
src/pipeline-tasks/pipeline-task.logger.spec.ts
Normal file
77
src/pipeline-tasks/pipeline-task.logger.spec.ts
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelineTaskLogger } from './pipeline-task.logger';
|
||||||
|
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
||||||
|
import { take, timeout } from 'rxjs/operators';
|
||||||
|
|
||||||
|
describe('PipelineTaskRunner', () => {
|
||||||
|
let logger: PipelineTaskLogger;
|
||||||
|
let module: TestingModule;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
module = await Test.createTestingModule({
|
||||||
|
providers: [PipelineTaskLogger],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
logger = module.get(PipelineTaskLogger);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(logger).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getMessage$', () => {
|
||||||
|
it('normal', async () => {
|
||||||
|
const event = new PipelineTaskEvent();
|
||||||
|
event.taskId = 'test';
|
||||||
|
const emittedAt = new Date();
|
||||||
|
event.emittedAt = emittedAt.toISOString() as any;
|
||||||
|
const message$ = logger.getMessage$('test');
|
||||||
|
|
||||||
|
let receiveEvent;
|
||||||
|
message$.pipe(take(1)).subscribe((value) => (receiveEvent = value));
|
||||||
|
await logger.handleEvent(event);
|
||||||
|
expect(receiveEvent).toMatchObject({
|
||||||
|
...event,
|
||||||
|
emittedAt,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('no match', async () => {
|
||||||
|
const event = new PipelineTaskEvent();
|
||||||
|
event.taskId = 'test';
|
||||||
|
const message$ = logger.getMessage$('other');
|
||||||
|
setTimeout(() => {
|
||||||
|
logger.handleEvent(event);
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
message$.pipe(take(1), timeout(100)).toPromise(),
|
||||||
|
).rejects.toThrow(/timeout/i);
|
||||||
|
});
|
||||||
|
it('multiple subscribers', async () => {
|
||||||
|
const event = new PipelineTaskEvent();
|
||||||
|
event.taskId = 'test';
|
||||||
|
const message$ = logger.getMessage$('test');
|
||||||
|
const message2$ = logger.getMessage$('test');
|
||||||
|
setTimeout(() => {
|
||||||
|
logger.handleEvent(event);
|
||||||
|
logger.handleEvent(event);
|
||||||
|
});
|
||||||
|
await Promise.all([
|
||||||
|
expect(
|
||||||
|
message$.pipe(take(1), timeout(100)).toPromise(),
|
||||||
|
).resolves.toEqual(event),
|
||||||
|
expect(
|
||||||
|
message2$.pipe(take(1), timeout(100)).toPromise(),
|
||||||
|
).resolves.toEqual(event),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('onModuleDestroy', () => {
|
||||||
|
it('complete observable when destroying module', async () => {
|
||||||
|
logger.onModuleDestroy();
|
||||||
|
await expect(
|
||||||
|
(logger as any).message$.toPromise(),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
38
src/pipeline-tasks/pipeline-task.logger.ts
Normal file
38
src/pipeline-tasks/pipeline-task.logger.ts
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import { Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||||
|
import { plainToClass } from 'class-transformer';
|
||||||
|
import { Observable, Subject } from 'rxjs';
|
||||||
|
import { filter } from 'rxjs/operators';
|
||||||
|
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
|
QUEUE_HANDLE_PIPELINE_TASK_LOG_EVENT,
|
||||||
|
ROUTE_PIPELINE_TASK_LOG,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PipelineTaskLogger implements OnModuleDestroy {
|
||||||
|
private readonly messageSubject = new Subject<PipelineTaskEvent>();
|
||||||
|
private readonly message$: Observable<PipelineTaskEvent> =
|
||||||
|
this.messageSubject.pipe();
|
||||||
|
|
||||||
|
@RabbitSubscribe({
|
||||||
|
exchange: EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
|
routingKey: ROUTE_PIPELINE_TASK_LOG,
|
||||||
|
queue: QUEUE_HANDLE_PIPELINE_TASK_LOG_EVENT,
|
||||||
|
queueOptions: {
|
||||||
|
autoDelete: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async handleEvent(message: PipelineTaskEvent) {
|
||||||
|
this.messageSubject.next(plainToClass(PipelineTaskEvent, message));
|
||||||
|
}
|
||||||
|
|
||||||
|
getMessage$(taskId: string) {
|
||||||
|
return this.message$.pipe(filter((event) => event.taskId === taskId));
|
||||||
|
}
|
||||||
|
|
||||||
|
onModuleDestroy() {
|
||||||
|
this.messageSubject.complete();
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
import { DeployByPm2Service } from './runners/deploy-by-pm2/deploy-by-pm2.service';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { ReposService } from '../repos/repos.service';
|
import { ReposService } from '../repos/repos.service';
|
||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
@ -8,9 +9,10 @@ import { TaskStatuses } from './enums/task-statuses.enum';
|
|||||||
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
||||||
import { PipelineTaskRunner } from './pipeline-task.runner';
|
import { PipelineTaskRunner } from './pipeline-task.runner';
|
||||||
import { WorkUnitMetadata } from './models/work-unit-metadata.model';
|
import { WorkUnitMetadata } from './models/work-unit-metadata.model';
|
||||||
|
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||||
describe('PipelineTaskRunner', () => {
|
describe('PipelineTaskRunner', () => {
|
||||||
let runner: PipelineTaskRunner;
|
let runner: PipelineTaskRunner;
|
||||||
let reposService: ReposService;
|
let deployByPM2Service: DeployByPm2Service;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const module: TestingModule = await Test.createTestingModule({
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
@ -31,11 +33,22 @@ describe('PipelineTaskRunner', () => {
|
|||||||
useValue: () => undefined,
|
useValue: () => undefined,
|
||||||
},
|
},
|
||||||
PipelineTaskRunner,
|
PipelineTaskRunner,
|
||||||
|
{
|
||||||
|
provide: AmqpConnection,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: DeployByPm2Service,
|
||||||
|
useValue: {
|
||||||
|
deploy: () => Promise.resolve(),
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
reposService = module.get(ReposService);
|
module.get(ReposService);
|
||||||
runner = module.get(PipelineTaskRunner);
|
runner = module.get(PipelineTaskRunner);
|
||||||
|
deployByPM2Service = module.get(DeployByPm2Service);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should be defined', () => {
|
it('should be defined', () => {
|
||||||
@ -60,7 +73,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
emitEvent = jest
|
emitEvent = jest
|
||||||
.spyOn(runner, 'emitEvent')
|
.spyOn(runner, 'emitEvent')
|
||||||
.mockImplementation((..._) => Promise.resolve());
|
.mockImplementation(() => Promise.resolve());
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('doTask', () => {
|
describe('doTask', () => {
|
||||||
@ -70,10 +83,10 @@ describe('PipelineTaskRunner', () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
checkout = jest
|
checkout = jest
|
||||||
.spyOn(runner, 'checkout')
|
.spyOn(runner, 'checkout')
|
||||||
.mockImplementation((..._) => Promise.resolve('/null'));
|
.mockImplementation(() => Promise.resolve('/null'));
|
||||||
doTaskUnit = jest
|
doTaskUnit = jest
|
||||||
.spyOn(runner, 'doTaskUnit')
|
.spyOn(runner, 'doTaskUnit')
|
||||||
.mockImplementation((..._) => Promise.resolve());
|
.mockImplementation(() => Promise.resolve());
|
||||||
});
|
});
|
||||||
|
|
||||||
it('only checkout', async () => {
|
it('only checkout', async () => {
|
||||||
@ -140,7 +153,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
await runner.doTask(task);
|
await runner.doTask(task);
|
||||||
|
|
||||||
expect(checkout).toBeCalledTimes(1);
|
expect(checkout).toBeCalledTimes(1);
|
||||||
expect(doTaskUnit).toBeCalledTimes(2);
|
expect(doTaskUnit).toBeCalledTimes(1);
|
||||||
expect(emitEvent).toBeCalledTimes(2);
|
expect(emitEvent).toBeCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -166,9 +179,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
|
|
||||||
doTaskUnit = jest
|
doTaskUnit = jest
|
||||||
.spyOn(runner, 'doTaskUnit')
|
.spyOn(runner, 'doTaskUnit')
|
||||||
.mockImplementation((..._) =>
|
.mockImplementation(() => Promise.reject(new Error('test error')));
|
||||||
Promise.reject(new Error('test error')),
|
|
||||||
);
|
|
||||||
await runner.doTask(task);
|
await runner.doTask(task);
|
||||||
|
|
||||||
expect(checkout).toBeCalledTimes(1);
|
expect(checkout).toBeCalledTimes(1);
|
||||||
@ -184,7 +195,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
it('success', async () => {
|
it('success', async () => {
|
||||||
const runScript = jest
|
const runScript = jest
|
||||||
.spyOn(runner, 'runScript')
|
.spyOn(runner, 'runScript')
|
||||||
.mockImplementation((..._) => Promise.resolve());
|
.mockImplementation(() => Promise.resolve());
|
||||||
const task = new PipelineTask();
|
const task = new PipelineTask();
|
||||||
|
|
||||||
const unit = PipelineUnits.test;
|
const unit = PipelineUnits.test;
|
||||||
@ -205,9 +216,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
it('failed', async () => {
|
it('failed', async () => {
|
||||||
const runScript = jest
|
const runScript = jest
|
||||||
.spyOn(runner, 'runScript')
|
.spyOn(runner, 'runScript')
|
||||||
.mockImplementation((..._) =>
|
.mockImplementation(() => Promise.reject(new Error('test error')));
|
||||||
Promise.reject(new Error('test error')),
|
|
||||||
);
|
|
||||||
const task = new PipelineTask();
|
const task = new PipelineTask();
|
||||||
|
|
||||||
const unit = PipelineUnits.test;
|
const unit = PipelineUnits.test;
|
||||||
@ -225,7 +234,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
|
|
||||||
describe('runScript', () => {
|
describe('runScript', () => {
|
||||||
it('normal', async () => {
|
it('normal', async () => {
|
||||||
const spawn = jest.fn((..._: any[]) => ({
|
const spawn = jest.fn<any, any>(() => ({
|
||||||
stdout: {
|
stdout: {
|
||||||
on: () => undefined,
|
on: () => undefined,
|
||||||
},
|
},
|
||||||
@ -251,7 +260,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('failed', async () => {
|
it('failed', async () => {
|
||||||
const spawn = jest.fn((..._: any[]) => ({
|
const spawn = jest.fn(() => ({
|
||||||
stdout: {
|
stdout: {
|
||||||
on: () => undefined,
|
on: () => undefined,
|
||||||
},
|
},
|
||||||
@ -286,7 +295,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
}, 10);
|
}, 10);
|
||||||
}, 10);
|
}, 10);
|
||||||
});
|
});
|
||||||
const spawn = jest.fn((..._: any[]) => ({
|
const spawn = jest.fn(() => ({
|
||||||
stdout: {
|
stdout: {
|
||||||
on,
|
on,
|
||||||
},
|
},
|
||||||
@ -299,7 +308,7 @@ describe('PipelineTaskRunner', () => {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
let emitSuccessCount = 0;
|
let emitSuccessCount = 0;
|
||||||
jest.spyOn(runner, 'emitEvent').mockImplementation((..._: any[]) => {
|
jest.spyOn(runner, 'emitEvent').mockImplementation(() => {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
emitSuccessCount++;
|
emitSuccessCount++;
|
||||||
@ -318,4 +327,25 @@ describe('PipelineTaskRunner', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('tryRunDeployScript', () => {
|
||||||
|
it('should be call deploy with right args', async () => {
|
||||||
|
const deploy = jest.spyOn(deployByPM2Service, 'deploy');
|
||||||
|
await expect(
|
||||||
|
runner['tryRunDeployScript'](
|
||||||
|
'/test/dir',
|
||||||
|
'@@DEPLOY ecosystem.config.js',
|
||||||
|
),
|
||||||
|
).resolves.toBe(true);
|
||||||
|
expect(deploy.mock.calls[0][0]).toEqual('/test/dir/ecosystem.config.js');
|
||||||
|
});
|
||||||
|
it('should return false', async () => {
|
||||||
|
await expect(
|
||||||
|
runner['tryRunDeployScript'](
|
||||||
|
'/test/dir',
|
||||||
|
'pm2 start ecosystem.config.js',
|
||||||
|
),
|
||||||
|
).resolves.toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { DeployByPm2Service } from './runners/deploy-by-pm2/deploy-by-pm2.service';
|
||||||
import { ReposService } from '../repos/repos.service';
|
import { ReposService } from '../repos/repos.service';
|
||||||
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
|
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
@ -5,15 +6,37 @@ import { ApplicationException } from '../commons/exceptions/application.exceptio
|
|||||||
import { PipelineUnits } from './enums/pipeline-units.enum';
|
import { PipelineUnits } from './enums/pipeline-units.enum';
|
||||||
import { TaskStatuses } from './enums/task-statuses.enum';
|
import { TaskStatuses } from './enums/task-statuses.enum';
|
||||||
import { InjectPinoLogger, PinoLogger } from 'nestjs-pino';
|
import { InjectPinoLogger, PinoLogger } from 'nestjs-pino';
|
||||||
import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
import {
|
||||||
|
AmqpConnection,
|
||||||
|
RabbitRPC,
|
||||||
|
RabbitSubscribe,
|
||||||
|
} from '@golevelup/nestjs-rabbitmq';
|
||||||
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
||||||
import { last } from 'ramda';
|
import { last } from 'ramda';
|
||||||
import { Inject } from '@nestjs/common';
|
import { Inject } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
QUEUE_PIPELINE_TASK_KILL,
|
||||||
|
ROUTE_PIPELINE_TASK_KILL,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
|
ROUTE_PIPELINE_TASK_LOG,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
import {
|
||||||
|
getInstanceName,
|
||||||
|
getSelfInstanceQueueKey,
|
||||||
|
getSelfInstanceRouteKey,
|
||||||
|
} from '../commons/utils/rabbit-mq';
|
||||||
|
import { rm } from 'fs/promises';
|
||||||
|
import { rename } from 'fs/promises';
|
||||||
|
import { join } from 'path';
|
||||||
|
|
||||||
type Spawn = typeof spawn;
|
type Spawn = typeof spawn;
|
||||||
|
|
||||||
export class PipelineTaskRunner {
|
export class PipelineTaskRunner {
|
||||||
readonly processes = new Map<string, ChildProcessWithoutNullStreams>();
|
readonly processes = new Map<string, ChildProcessWithoutNullStreams>();
|
||||||
|
readonly stopTaskIds = new Set<string>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly reposService: ReposService,
|
private readonly reposService: ReposService,
|
||||||
@ -21,6 +44,8 @@ export class PipelineTaskRunner {
|
|||||||
private readonly logger: PinoLogger,
|
private readonly logger: PinoLogger,
|
||||||
@Inject('spawn')
|
@Inject('spawn')
|
||||||
private readonly spawn: Spawn,
|
private readonly spawn: Spawn,
|
||||||
|
private readonly amqpConnection: AmqpConnection,
|
||||||
|
private readonly deployByPM2Service: DeployByPm2Service,
|
||||||
) {}
|
) {}
|
||||||
@RabbitSubscribe({
|
@RabbitSubscribe({
|
||||||
exchange: 'new-pipeline-task',
|
exchange: 'new-pipeline-task',
|
||||||
@ -35,19 +60,27 @@ export class PipelineTaskRunner {
|
|||||||
this.logger.error({ task, err }, err.message);
|
this.logger.error({ task, err }, err.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@RabbitSubscribe({
|
@RabbitRPC({
|
||||||
exchange: 'stop-pipeline-task',
|
exchange: EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
routingKey: 'mac',
|
routingKey: getSelfInstanceRouteKey(ROUTE_PIPELINE_TASK_KILL),
|
||||||
queue: 'mac.stop-pipeline-task',
|
queue: getSelfInstanceQueueKey(QUEUE_PIPELINE_TASK_KILL),
|
||||||
|
queueOptions: {
|
||||||
|
autoDelete: true,
|
||||||
|
durable: true,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
async onStopTask(task: PipelineTask) {
|
async onStopTask(task: PipelineTask) {
|
||||||
this.logger.info({ task }, 'on stop task [%s].', task.id);
|
this.logger.info({ task }, 'on stop task [%s].', task.id);
|
||||||
|
this.stopTaskIds.add(task.id);
|
||||||
const process = this.processes.get(task.id);
|
const process = this.processes.get(task.id);
|
||||||
if (process) {
|
if (process) {
|
||||||
this.logger.info({ task }, 'send signal SIGINT to child process.');
|
this.logger.info({ task }, 'send signal SIGINT to child process.');
|
||||||
process.kill('SIGINT');
|
process.kill('SIGINT');
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
setTimeout(() => {
|
||||||
|
this.stopTaskIds.delete(task.id);
|
||||||
|
}, 10_000);
|
||||||
if (process === this.processes.get(task.id)) {
|
if (process === this.processes.get(task.id)) {
|
||||||
this.logger.info({ task }, 'send signal SIGKILL to child process.');
|
this.logger.info({ task }, 'send signal SIGKILL to child process.');
|
||||||
process.kill('SIGKILL');
|
process.kill('SIGKILL');
|
||||||
@ -63,6 +96,7 @@ export class PipelineTaskRunner {
|
|||||||
} else {
|
} else {
|
||||||
this.logger.info({ task }, 'child process is not running.');
|
this.logger.info({ task }, 'child process is not running.');
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async doTask(task: PipelineTask) {
|
async doTask(task: PipelineTask) {
|
||||||
@ -81,7 +115,7 @@ export class PipelineTaskRunner {
|
|||||||
|
|
||||||
this.logger.info('running task [%s].', task.id);
|
this.logger.info('running task [%s].', task.id);
|
||||||
try {
|
try {
|
||||||
const workspaceRoot = await this.checkout(task);
|
let workspaceRoot = await this.checkout(task);
|
||||||
const units = task.units
|
const units = task.units
|
||||||
.filter((unit) => unit !== PipelineUnits.checkout)
|
.filter((unit) => unit !== PipelineUnits.checkout)
|
||||||
.map(
|
.map(
|
||||||
@ -92,6 +126,22 @@ export class PipelineTaskRunner {
|
|||||||
);
|
);
|
||||||
this.logger.info({ units }, 'begin run units.');
|
this.logger.info({ units }, 'begin run units.');
|
||||||
for (const unit of units) {
|
for (const unit of units) {
|
||||||
|
if (unit.type === PipelineUnits.deploy) {
|
||||||
|
const oldRoot = workspaceRoot;
|
||||||
|
workspaceRoot = this.reposService.getDeployRoot(task);
|
||||||
|
if (oldRoot !== workspaceRoot) {
|
||||||
|
await rm(workspaceRoot, { force: true, recursive: true });
|
||||||
|
await rename(oldRoot, workspaceRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.emitEvent(
|
||||||
|
task,
|
||||||
|
unit.type,
|
||||||
|
TaskStatuses.success,
|
||||||
|
`[deploy] change deploy folder content success`,
|
||||||
|
'stdout',
|
||||||
|
);
|
||||||
|
}
|
||||||
await this.doTaskUnit(unit.type, unit.scripts, task, workspaceRoot);
|
await this.doTaskUnit(unit.type, unit.scripts, task, workspaceRoot);
|
||||||
}
|
}
|
||||||
await this.emitEvent(
|
await this.emitEvent(
|
||||||
@ -132,6 +182,9 @@ export class PipelineTaskRunner {
|
|||||||
try {
|
try {
|
||||||
for (const script of scripts) {
|
for (const script of scripts) {
|
||||||
this.logger.debug('begin runScript %s', script);
|
this.logger.debug('begin runScript %s', script);
|
||||||
|
if (this.stopTaskIds.has(task.id)) {
|
||||||
|
throw new ApplicationException('Task is be KILLED');
|
||||||
|
}
|
||||||
await this.runScript(script, workspaceRoot, task, unit);
|
await this.runScript(script, workspaceRoot, task, unit);
|
||||||
this.logger.debug('end runScript %s', script);
|
this.logger.debug('end runScript %s', script);
|
||||||
}
|
}
|
||||||
@ -181,6 +234,7 @@ export class PipelineTaskRunner {
|
|||||||
'checkout failed.',
|
'checkout failed.',
|
||||||
'stderr',
|
'stderr',
|
||||||
);
|
);
|
||||||
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -201,6 +255,19 @@ export class PipelineTaskRunner {
|
|||||||
messageType,
|
messageType,
|
||||||
status,
|
status,
|
||||||
};
|
};
|
||||||
|
this.amqpConnection
|
||||||
|
.publish(EXCHANGE_PIPELINE_TASK_FANOUT, ROUTE_PIPELINE_TASK_LOG, event, {
|
||||||
|
headers: {
|
||||||
|
sender: getInstanceName(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
this.logger.error(
|
||||||
|
{ error, event },
|
||||||
|
'send event message to queue failed. %s',
|
||||||
|
error.message,
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async runScript(
|
async runScript(
|
||||||
@ -210,6 +277,9 @@ export class PipelineTaskRunner {
|
|||||||
unit: PipelineUnits,
|
unit: PipelineUnits,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await this.emitEvent(task, unit, TaskStatuses.working, script, 'stdin');
|
await this.emitEvent(task, unit, TaskStatuses.working, script, 'stdin');
|
||||||
|
if (await this.tryRunDeployScript(workspaceRoot, script)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const sub = this.spawn(script, {
|
const sub = this.spawn(script, {
|
||||||
shell: true,
|
shell: true,
|
||||||
@ -246,8 +316,24 @@ export class PipelineTaskRunner {
|
|||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
return resolve();
|
return resolve();
|
||||||
}
|
}
|
||||||
|
if (this.stopTaskIds.has(task.id)) {
|
||||||
|
throw reject(new ApplicationException('Task is be KILLED'));
|
||||||
|
}
|
||||||
return reject(new ApplicationException('exec script failed'));
|
return reject(new ApplicationException('exec script failed'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async tryRunDeployScript(workspaceRoot: string, script: string) {
|
||||||
|
const match = /^@@DEPLOY\s+(\S*)/.exec(script);
|
||||||
|
if (match) {
|
||||||
|
await this.deployByPM2Service.deploy(
|
||||||
|
join(workspaceRoot, match[1]),
|
||||||
|
workspaceRoot,
|
||||||
|
);
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
11
src/pipeline-tasks/pipeline-tasks.constants.ts
Normal file
11
src/pipeline-tasks/pipeline-tasks.constants.ts
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
export const EXCHANGE_PIPELINE_TASK_TOPIC = 'pipeline-task.topic';
|
||||||
|
export const EXCHANGE_PIPELINE_TASK_FANOUT = 'pipeline-task.fanout';
|
||||||
|
export const ROUTE_PIPELINE_TASK_LOG = 'pipeline-task-log';
|
||||||
|
export const QUEUE_HANDLE_PIPELINE_TASK_LOG_EVENT = 'pipeline-task-log';
|
||||||
|
export const QUEUE_WRITE_PIPELINE_TASK_LOG = 'write-pipeline-task-log';
|
||||||
|
export const ROUTE_PIPELINE_TASK_DONE = 'pipeline-task-done';
|
||||||
|
export const QUEUE_PIPELINE_TASK_DONE = 'pipeline-task-done';
|
||||||
|
export const ROUTE_PIPELINE_TASK_KILL = 'pipeline-task-kill';
|
||||||
|
export const QUEUE_PIPELINE_TASK_KILL = 'pipeline-task-kill';
|
||||||
|
|
||||||
|
export const PM2_TOKEN = Symbol('pm2-token');
|
@ -10,13 +10,21 @@ import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
|||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { PipelineTaskRunner } from './pipeline-task.runner';
|
import { PipelineTaskRunner } from './pipeline-task.runner';
|
||||||
import { spawn } from 'child_process';
|
import { spawn } from 'child_process';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
|
EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
import { PipelineTaskLogger } from './pipeline-task.logger';
|
||||||
|
import { PipelineTaskFlushService } from './pipeline-task-flush.service';
|
||||||
|
import { CommonsModule } from '../commons/commons.module';
|
||||||
|
import { DeployByPm2Service } from './runners/deploy-by-pm2/deploy-by-pm2.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
CommonsModule,
|
||||||
TypeOrmModule.forFeature([PipelineTask, Pipeline]),
|
TypeOrmModule.forFeature([PipelineTask, Pipeline]),
|
||||||
RedisModule,
|
RedisModule,
|
||||||
ReposModule,
|
ReposModule,
|
||||||
|
|
||||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (configService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
@ -27,20 +35,23 @@ import { spawn } from 'child_process';
|
|||||||
type: 'fanout',
|
type: 'fanout',
|
||||||
options: {
|
options: {
|
||||||
durable: true,
|
durable: true,
|
||||||
|
autoDelete: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'stop-pipeline-task',
|
name: EXCHANGE_PIPELINE_TASK_FANOUT,
|
||||||
type: 'fanout',
|
|
||||||
options: {
|
|
||||||
durable: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'update-pipeline-task',
|
|
||||||
type: 'fanout',
|
type: 'fanout',
|
||||||
options: {
|
options: {
|
||||||
durable: false,
|
durable: false,
|
||||||
|
autoDelete: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
type: 'topic',
|
||||||
|
options: {
|
||||||
|
durable: false,
|
||||||
|
autoDelete: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@ -52,10 +63,13 @@ import { spawn } from 'child_process';
|
|||||||
PipelineTasksService,
|
PipelineTasksService,
|
||||||
PipelineTasksResolver,
|
PipelineTasksResolver,
|
||||||
PipelineTaskRunner,
|
PipelineTaskRunner,
|
||||||
|
PipelineTaskLogger,
|
||||||
{
|
{
|
||||||
provide: 'spawn',
|
provide: 'spawn',
|
||||||
useValue: spawn,
|
useValue: spawn,
|
||||||
},
|
},
|
||||||
|
PipelineTaskFlushService,
|
||||||
|
DeployByPm2Service,
|
||||||
],
|
],
|
||||||
exports: [PipelineTasksService],
|
exports: [PipelineTasksService],
|
||||||
})
|
})
|
||||||
|
@ -1,4 +1,6 @@
|
|||||||
|
import { JwtService } from '@nestjs-lib/auth';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PipelineTaskLogger } from './pipeline-task.logger';
|
||||||
import { PipelineTasksResolver } from './pipeline-tasks.resolver';
|
import { PipelineTasksResolver } from './pipeline-tasks.resolver';
|
||||||
import { PipelineTasksService } from './pipeline-tasks.service';
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
|
|
||||||
@ -13,6 +15,14 @@ describe('PipelineTasksResolver', () => {
|
|||||||
provide: PipelineTasksService,
|
provide: PipelineTasksService,
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: PipelineTaskLogger,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: JwtService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -2,29 +2,37 @@ import { Resolver, Args, Mutation, Subscription, Query } from '@nestjs/graphql';
|
|||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
import { PipelineTasksService } from './pipeline-tasks.service';
|
import { PipelineTasksService } from './pipeline-tasks.service';
|
||||||
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
||||||
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
|
|
||||||
import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args';
|
import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args';
|
||||||
import { plainToClass } from 'class-transformer';
|
import { plainToClass } from 'class-transformer';
|
||||||
|
import { PipelineTaskLogger } from './pipeline-task.logger';
|
||||||
|
import { observableToAsyncIterable } from '@graphql-tools/utils';
|
||||||
|
import { PipelineTaskEvent } from './models/pipeline-task-event';
|
||||||
|
import { Roles, AccountRole } from '@nestjs-lib/auth';
|
||||||
|
|
||||||
|
@Roles(AccountRole.admin, AccountRole.super)
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class PipelineTasksResolver {
|
export class PipelineTasksResolver {
|
||||||
constructor(private readonly service: PipelineTasksService) {}
|
constructor(
|
||||||
|
private readonly service: PipelineTasksService,
|
||||||
|
private readonly taskLogger: PipelineTaskLogger,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Mutation(() => PipelineTask)
|
@Mutation(() => PipelineTask)
|
||||||
async createPipelineTask(@Args('task') taskDto: CreatePipelineTaskInput) {
|
async createPipelineTask(@Args('task') taskDto: CreatePipelineTaskInput) {
|
||||||
return await this.service.addTask(taskDto);
|
return await this.service.addTask(taskDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Subscription(() => PipelineTaskLogMessage, {
|
@Subscription(() => PipelineTaskEvent, {
|
||||||
resolve: (value) => {
|
resolve: (value) => {
|
||||||
const data = plainToClass(PipelineTaskLogMessage, value);
|
const data = plainToClass(PipelineTaskEvent, value);
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
async pipelineTaskLog(@Args() args: PipelineTaskLogArgs) {
|
async pipelineTaskEvent(@Args() args: PipelineTaskLogArgs) {
|
||||||
// const task = await this.service.findTaskById(args.taskId);
|
const task = await this.service.findTaskById(args.taskId);
|
||||||
// const asyncIterator = this.logsService.watchLogs(task);
|
return observableToAsyncIterable<PipelineTaskEvent>(
|
||||||
// return asyncIterator;
|
this.taskLogger.getMessage$(task.id),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Subscription(() => PipelineTask, {
|
@Subscription(() => PipelineTask, {
|
||||||
@ -49,5 +57,7 @@ export class PipelineTasksResolver {
|
|||||||
@Mutation(() => Boolean)
|
@Mutation(() => Boolean)
|
||||||
async stopPipelineTask(@Args('id') id: string) {
|
async stopPipelineTask(@Args('id') id: string) {
|
||||||
const task = await this.service.findTaskById(id);
|
const task = await this.service.findTaskById(id);
|
||||||
|
await this.service.stopTask(task);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,26 +4,15 @@ import { getRepositoryToken } from '@nestjs/typeorm';
|
|||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { Queue } from 'bull';
|
|
||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import { PipelineTaskFlushService } from './pipeline-task-flush.service';
|
||||||
|
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
describe('PipelineTasksService', () => {
|
describe('PipelineTasksService', () => {
|
||||||
let service: PipelineTasksService;
|
let service: PipelineTasksService;
|
||||||
let module: TestingModule;
|
let module: TestingModule;
|
||||||
let taskRepository: Repository<PipelineTask>;
|
let taskRepository: Repository<PipelineTask>;
|
||||||
let pipelineRepository: Repository<Pipeline>;
|
let pipelineRepository: Repository<Pipeline>;
|
||||||
const getBasePipeline = () =>
|
|
||||||
({
|
|
||||||
id: 'test',
|
|
||||||
name: '测试流水线',
|
|
||||||
branch: 'master',
|
|
||||||
workUnitMetadata: {},
|
|
||||||
project: {
|
|
||||||
id: 'test-project',
|
|
||||||
},
|
|
||||||
} as Pipeline);
|
|
||||||
let redisClient;
|
|
||||||
let taskQueue: Queue;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
module = await Test.createTestingModule({
|
module = await Test.createTestingModule({
|
||||||
@ -41,6 +30,14 @@ describe('PipelineTasksService', () => {
|
|||||||
provide: AmqpConnection,
|
provide: AmqpConnection,
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: PipelineTaskFlushService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: getLoggerToken(PipelineTasksService.name),
|
||||||
|
useValue: new PinoLogger({}),
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -1,11 +1,23 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { PipelineTask } from './pipeline-task.entity';
|
import { PipelineTask } from './pipeline-task.entity';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
import debug from 'debug';
|
import debug from 'debug';
|
||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
import { AmqpConnection, RabbitRPC } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
QUEUE_PIPELINE_TASK_DONE,
|
||||||
|
ROUTE_PIPELINE_TASK_DONE,
|
||||||
|
} from './pipeline-tasks.constants';
|
||||||
|
import { PipelineTaskFlushService } from './pipeline-task-flush.service';
|
||||||
|
import { find, isNil, propEq } from 'ramda';
|
||||||
|
import { PipelineTaskLogs } from './models/pipeline-task-logs.model';
|
||||||
|
import { TaskStatuses, terminalTaskStatuses } from './enums/task-statuses.enum';
|
||||||
|
import { InjectPinoLogger, PinoLogger } from 'nestjs-pino';
|
||||||
|
import { getAppInstanceRouteKey } from '../commons/utils/rabbit-mq';
|
||||||
|
import { ROUTE_PIPELINE_TASK_KILL } from './pipeline-tasks.constants';
|
||||||
|
|
||||||
const log = debug('fennec:pipeline-tasks:service');
|
const log = debug('fennec:pipeline-tasks:service');
|
||||||
|
|
||||||
@ -17,6 +29,9 @@ export class PipelineTasksService {
|
|||||||
@InjectRepository(Pipeline)
|
@InjectRepository(Pipeline)
|
||||||
private readonly pipelineRepository: Repository<Pipeline>,
|
private readonly pipelineRepository: Repository<Pipeline>,
|
||||||
private readonly amqpConnection: AmqpConnection,
|
private readonly amqpConnection: AmqpConnection,
|
||||||
|
private readonly eventFlushService: PipelineTaskFlushService,
|
||||||
|
@InjectPinoLogger(PipelineTasksService.name)
|
||||||
|
private readonly logger: PinoLogger,
|
||||||
) {}
|
) {}
|
||||||
async addTask(dto: CreatePipelineTaskInput) {
|
async addTask(dto: CreatePipelineTaskInput) {
|
||||||
const pipeline = await this.pipelineRepository.findOneOrFail({
|
const pipeline = await this.pipelineRepository.findOneOrFail({
|
||||||
@ -51,10 +66,93 @@ export class PipelineTasksService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async listTasksByCommitHash(hash: string) {
|
async listTasksByCommitHash(hash: string) {
|
||||||
return await this.repository.find({ commit: hash });
|
return await this.repository.find({
|
||||||
|
where: { commit: hash },
|
||||||
|
order: { createdAt: 'DESC' },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getRedisTokens(pipeline: Pipeline): [string, string] {
|
getRedisTokens(pipeline: Pipeline): [string, string] {
|
||||||
return [`pipeline-${pipeline.id}:lck`, `pipeline-${pipeline.id}:tasks`];
|
return [`pipeline-${pipeline.id}:lck`, `pipeline-${pipeline.id}:tasks`];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@RabbitRPC({
|
||||||
|
exchange: EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
routingKey: ROUTE_PIPELINE_TASK_DONE,
|
||||||
|
queue: QUEUE_PIPELINE_TASK_DONE,
|
||||||
|
queueOptions: {
|
||||||
|
autoDelete: true,
|
||||||
|
durable: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async updateByEvent({ taskId, runOn }: { taskId: string; runOn: string }) {
|
||||||
|
try {
|
||||||
|
const [events, task] = await Promise.all([
|
||||||
|
this.eventFlushService.read(taskId),
|
||||||
|
this.findTaskById(taskId),
|
||||||
|
]);
|
||||||
|
this.logger.info('[updateByEvent] start. taskId: %s', taskId);
|
||||||
|
|
||||||
|
for (const event of events) {
|
||||||
|
if (isNil(event.unit)) {
|
||||||
|
if (
|
||||||
|
event.status !== TaskStatuses.pending &&
|
||||||
|
task.status === TaskStatuses.pending
|
||||||
|
) {
|
||||||
|
task.startedAt = event.emittedAt;
|
||||||
|
} else if (terminalTaskStatuses.includes(event.status)) {
|
||||||
|
task.endedAt = event.emittedAt;
|
||||||
|
}
|
||||||
|
task.status = event.status;
|
||||||
|
} else {
|
||||||
|
let l: PipelineTaskLogs = find<PipelineTaskLogs>(
|
||||||
|
propEq('unit', event.unit),
|
||||||
|
task.logs,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isNil(l)) {
|
||||||
|
l = {
|
||||||
|
unit: event.unit,
|
||||||
|
startedAt: event.emittedAt,
|
||||||
|
endedAt: null,
|
||||||
|
logs: event.message,
|
||||||
|
status: event.status,
|
||||||
|
};
|
||||||
|
|
||||||
|
task.logs.push(l);
|
||||||
|
} else {
|
||||||
|
l.logs += event.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (terminalTaskStatuses.includes(event.status)) {
|
||||||
|
l.endedAt = event.emittedAt;
|
||||||
|
}
|
||||||
|
l.status = event.status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task.runOn = runOn;
|
||||||
|
await this.repository.update({ id: taskId }, task);
|
||||||
|
this.logger.info('[updateByEvent] success. taskId: %s', taskId);
|
||||||
|
return task;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
{ error },
|
||||||
|
'[updateByEvent] failed. taskId: %s',
|
||||||
|
taskId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async stopTask(task: PipelineTask) {
|
||||||
|
if (isNil(task.runOn)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"the task have not running instance on database. field 'runOn' is nil",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.amqpConnection.request({
|
||||||
|
exchange: EXCHANGE_PIPELINE_TASK_TOPIC,
|
||||||
|
routingKey: getAppInstanceRouteKey(ROUTE_PIPELINE_TASK_KILL, task.runOn),
|
||||||
|
payload: task,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,117 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { DeployByPm2Service } from './deploy-by-pm2.service';
|
||||||
|
|
||||||
|
describe('DeployByPm2Service', () => {
|
||||||
|
let service: DeployByPm2Service;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
DeployByPm2Service,
|
||||||
|
{
|
||||||
|
provide: getLoggerToken(DeployByPm2Service.name),
|
||||||
|
useValue: new PinoLogger({
|
||||||
|
pinoHttp: {
|
||||||
|
level: 'silent',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<DeployByPm2Service>(DeployByPm2Service);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be defined', () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getAppsSn', () => {
|
||||||
|
it('should return right value', () => {
|
||||||
|
expect(
|
||||||
|
service['getAppsSn']([
|
||||||
|
{ name: 'app' },
|
||||||
|
{ name: 'app#4' },
|
||||||
|
{ name: 'app#1' },
|
||||||
|
]),
|
||||||
|
).toEqual(4 + 1);
|
||||||
|
});
|
||||||
|
it('should return 1 when no match', () => {
|
||||||
|
expect(
|
||||||
|
service['getAppsSn']([
|
||||||
|
{ name: 'bar' },
|
||||||
|
{ name: 'foo#4' },
|
||||||
|
{ name: 'foo#1' },
|
||||||
|
]),
|
||||||
|
).toEqual(4 + 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('filterOldApps', () => {
|
||||||
|
it('should return right value', () => {
|
||||||
|
expect(
|
||||||
|
service['filterOldApps'](
|
||||||
|
[{ name: 'app' }],
|
||||||
|
[
|
||||||
|
{ name: 'app' },
|
||||||
|
{ name: 'app#4' },
|
||||||
|
{ name: 'foo#2' },
|
||||||
|
{ name: 'bar' },
|
||||||
|
],
|
||||||
|
),
|
||||||
|
).toEqual([{ name: 'app' }, { name: 'app#4' }]);
|
||||||
|
});
|
||||||
|
it('should return [] when no match', () => {
|
||||||
|
expect(
|
||||||
|
service['filterOldApps'](
|
||||||
|
[{ name: 'app' }],
|
||||||
|
[{ name: 'foo#2' }, { name: 'bar' }],
|
||||||
|
),
|
||||||
|
).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('replaceAppName', () => {
|
||||||
|
it('should be replaced with right value', () => {
|
||||||
|
const getAppsSn = jest
|
||||||
|
.spyOn(service, 'getAppsSn' as any)
|
||||||
|
.mockImplementation(() => 1);
|
||||||
|
const options = [{ name: 'app' }, { name: 'foo' }];
|
||||||
|
service['replaceAppName'](options, []);
|
||||||
|
expect(options).toEqual([{ name: 'app#1' }, { name: 'foo#1' }]);
|
||||||
|
expect(getAppsSn).toBeCalledTimes(1);
|
||||||
|
expect(getAppsSn.mock.calls[0][0]).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('deploy', () => {
|
||||||
|
it('should be success', async () => {
|
||||||
|
const filterOldApps = jest
|
||||||
|
.spyOn(service, 'filterOldApps' as any)
|
||||||
|
.mockImplementation(() => [{ name: 'app#1' }, { name: 'app#2' }]);
|
||||||
|
const replaceAppName = jest
|
||||||
|
.spyOn(service, 'replaceAppName' as any)
|
||||||
|
.mockImplementation((options) => (options[0].name = 'app#2'));
|
||||||
|
const stopApps = jest
|
||||||
|
.spyOn(service, 'stopApps' as any)
|
||||||
|
.mockImplementation(() => Promise.resolve());
|
||||||
|
await expect(
|
||||||
|
service['deploy'](
|
||||||
|
join(
|
||||||
|
__dirname,
|
||||||
|
'../../../../test/__mocks__/deploy-service/ecosystem.config.js',
|
||||||
|
),
|
||||||
|
join(__dirname, '../../../../test/__mocks__/deploy-service'),
|
||||||
|
),
|
||||||
|
).resolves.toBeFalsy();
|
||||||
|
expect(filterOldApps).toBeCalledTimes(1);
|
||||||
|
expect(replaceAppName).toBeCalledTimes(1);
|
||||||
|
expect(stopApps).toBeCalledTimes(1);
|
||||||
|
stopApps.mockReset();
|
||||||
|
|
||||||
|
await service['stopApps']([{ name: 'app#2' }]);
|
||||||
|
}, 10_000);
|
||||||
|
});
|
||||||
|
});
|
@ -0,0 +1,98 @@
|
|||||||
|
import { InjectPinoLogger, PinoLogger } from 'nestjs-pino';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { promisify } from 'util';
|
||||||
|
import * as pm2 from 'pm2';
|
||||||
|
import { Proc, ProcessDescription, StartOptions } from 'pm2';
|
||||||
|
import { clone, last } from 'ramda';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DeployByPm2Service {
|
||||||
|
constructor(
|
||||||
|
@InjectPinoLogger(DeployByPm2Service.name)
|
||||||
|
private readonly logger: PinoLogger,
|
||||||
|
) {}
|
||||||
|
async deploy(filePath: string, workspace: string) {
|
||||||
|
const baseConfig: { apps: StartOptions[] } = await import(filePath);
|
||||||
|
const appOptionsList: StartOptions[] = clone(baseConfig.apps);
|
||||||
|
|
||||||
|
await promisify<void>(pm2.connect.bind(pm2))();
|
||||||
|
const allApps = await promisify(pm2.list.bind(pm2))();
|
||||||
|
try {
|
||||||
|
if (!Array.isArray(baseConfig.apps)) {
|
||||||
|
this.logger.error(
|
||||||
|
'the "apps" in the PM2 ecosystem configuration is not array',
|
||||||
|
);
|
||||||
|
throw new Error('apps is not array');
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldApps = this.filterOldApps(appOptionsList, allApps);
|
||||||
|
|
||||||
|
this.replaceAppName(appOptionsList, oldApps);
|
||||||
|
for (const appOptions of appOptionsList) {
|
||||||
|
const proc = await promisify<StartOptions, Proc>(pm2.start.bind(pm2))({
|
||||||
|
...appOptions,
|
||||||
|
cwd: workspace,
|
||||||
|
});
|
||||||
|
this.logger.info({ proc }, `start ${appOptions.name}`);
|
||||||
|
}
|
||||||
|
await this.stopApps(oldApps);
|
||||||
|
} catch (err) {
|
||||||
|
await this.stopApps(appOptionsList);
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
pm2.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async stopApps(apps: ProcessDescription[] | StartOptions[]) {
|
||||||
|
await Promise.all(
|
||||||
|
apps.map(async (app: ProcessDescription | StartOptions) => {
|
||||||
|
let procAtStop: ProcessDescription;
|
||||||
|
let procAtDelete: ProcessDescription;
|
||||||
|
try {
|
||||||
|
const idOrName = 'pm_id' in app ? app.pm_id : app.name;
|
||||||
|
procAtStop = await promisify(pm2.stop.bind(pm2))(idOrName);
|
||||||
|
procAtDelete = await promisify(pm2.delete.bind(pm2))(idOrName);
|
||||||
|
this.logger.info('stop & delete %s success', app.name);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
{ error, procAtStop, procAtDelete },
|
||||||
|
'stop & delete %s error',
|
||||||
|
app.name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private replaceAppName(
|
||||||
|
optionsList: StartOptions[],
|
||||||
|
oldApps: ProcessDescription[],
|
||||||
|
) {
|
||||||
|
const appSn = this.getAppsSn(oldApps);
|
||||||
|
|
||||||
|
optionsList.forEach((options) => {
|
||||||
|
if (!options.name) {
|
||||||
|
this.logger.error('please give a name for application');
|
||||||
|
throw new Error('app name is not given');
|
||||||
|
}
|
||||||
|
options.name = `${options.name}#${appSn}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private filterOldApps(
|
||||||
|
optionsList: StartOptions[],
|
||||||
|
apps: ProcessDescription[],
|
||||||
|
) {
|
||||||
|
return apps.filter((app) =>
|
||||||
|
optionsList.some((options) => app.name.split('#')[0] === options.name),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAppsSn(oldApps: ProcessDescription[]) {
|
||||||
|
const appsSn: number[] = oldApps.map(
|
||||||
|
(app) => +(app.name.split('#')?.[1] ?? 0),
|
||||||
|
);
|
||||||
|
return (last(appsSn.sort()) ?? 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +1,4 @@
|
|||||||
|
import { JwtService } from '@nestjs-lib/auth';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
||||||
import { CommitLogsResolver } from './commit-logs.resolver';
|
import { CommitLogsResolver } from './commit-logs.resolver';
|
||||||
@ -18,6 +19,10 @@ describe('CommitLogsResolver', () => {
|
|||||||
provide: PipelineTasksService,
|
provide: PipelineTasksService,
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: JwtService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { Roles, AccountRole } from '@nestjs-lib/auth';
|
||||||
import { Query } from '@nestjs/graphql';
|
import { Query } from '@nestjs/graphql';
|
||||||
import {
|
import {
|
||||||
Args,
|
Args,
|
||||||
@ -10,6 +11,7 @@ import { PipelineTasksService } from '../pipeline-tasks/pipeline-tasks.service';
|
|||||||
import { Commit, LogFields } from '../repos/dtos/log-list.model';
|
import { Commit, LogFields } from '../repos/dtos/log-list.model';
|
||||||
import { PipelinesService } from './pipelines.service';
|
import { PipelinesService } from './pipelines.service';
|
||||||
|
|
||||||
|
@Roles(AccountRole.admin, AccountRole.super)
|
||||||
@Resolver(() => Commit)
|
@Resolver(() => Commit)
|
||||||
export class CommitLogsResolver {
|
export class CommitLogsResolver {
|
||||||
constructor(
|
constructor(
|
||||||
|
@ -1,11 +1,13 @@
|
|||||||
|
import { Type } from 'class-transformer';
|
||||||
import { InputType } from '@nestjs/graphql';
|
import { InputType } from '@nestjs/graphql';
|
||||||
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
|
import { WorkUnitMetadata } from '../../pipeline-tasks/models/work-unit-metadata.model';
|
||||||
import {
|
import {
|
||||||
IsObject,
|
IsInstance,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
IsUUID,
|
IsUUID,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
|
ValidateNested,
|
||||||
} from 'class-validator';
|
} from 'class-validator';
|
||||||
|
|
||||||
@InputType({ isAbstract: true })
|
@InputType({ isAbstract: true })
|
||||||
@ -21,7 +23,9 @@ export class CreatePipelineInput {
|
|||||||
@MaxLength(32)
|
@MaxLength(32)
|
||||||
name: string;
|
name: string;
|
||||||
|
|
||||||
|
@Type(() => WorkUnitMetadata)
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsObject()
|
@ValidateNested()
|
||||||
|
@IsInstance(WorkUnitMetadata)
|
||||||
workUnitMetadata: WorkUnitMetadata;
|
workUnitMetadata: WorkUnitMetadata;
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
import { InputType } from '@nestjs/graphql';
|
import { InputType, OmitType } from '@nestjs/graphql';
|
||||||
import { CreatePipelineInput } from './create-pipeline.input';
|
import { CreatePipelineInput } from './create-pipeline.input';
|
||||||
|
|
||||||
@InputType()
|
@InputType()
|
||||||
export class UpdatePipelineInput extends CreatePipelineInput {
|
export class UpdatePipelineInput extends OmitType(CreatePipelineInput, [
|
||||||
|
'projectId',
|
||||||
|
]) {
|
||||||
id: string;
|
id: string;
|
||||||
}
|
}
|
||||||
|
@ -8,9 +8,11 @@ import { PipelineTasksModule } from '../pipeline-tasks/pipeline-tasks.module';
|
|||||||
import { ReposModule } from '../repos/repos.module';
|
import { ReposModule } from '../repos/repos.module';
|
||||||
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
||||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { CommonsModule } from '../commons/commons.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
CommonsModule,
|
||||||
TypeOrmModule.forFeature([Pipeline]),
|
TypeOrmModule.forFeature([Pipeline]),
|
||||||
PipelineTasksModule,
|
PipelineTasksModule,
|
||||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { JwtService } from '@nestjs-lib/auth';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { PipelinesResolver } from './pipelines.resolver';
|
import { PipelinesResolver } from './pipelines.resolver';
|
||||||
import { PipelinesService } from './pipelines.service';
|
import { PipelinesService } from './pipelines.service';
|
||||||
@ -13,6 +14,10 @@ describe('PipelinesResolver', () => {
|
|||||||
provide: PipelinesService,
|
provide: PipelinesService,
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: JwtService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -4,7 +4,9 @@ import { UpdatePipelineInput } from './dtos/update-pipeline.input';
|
|||||||
import { Pipeline } from './pipeline.entity';
|
import { Pipeline } from './pipeline.entity';
|
||||||
import { PipelinesService } from './pipelines.service';
|
import { PipelinesService } from './pipelines.service';
|
||||||
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
import { ListPipelineArgs } from './dtos/list-pipelines.args';
|
||||||
|
import { Roles, AccountRole } from '@nestjs-lib/auth';
|
||||||
|
|
||||||
|
@Roles(AccountRole.admin, AccountRole.super)
|
||||||
@Resolver()
|
@Resolver()
|
||||||
export class PipelinesResolver {
|
export class PipelinesResolver {
|
||||||
constructor(private readonly service: PipelinesService) {}
|
constructor(private readonly service: PipelinesService) {}
|
||||||
@ -21,14 +23,14 @@ export class PipelinesResolver {
|
|||||||
@Mutation(() => Pipeline)
|
@Mutation(() => Pipeline)
|
||||||
async createPipeline(
|
async createPipeline(
|
||||||
@Args('pipeline', { type: () => CreatePipelineInput })
|
@Args('pipeline', { type: () => CreatePipelineInput })
|
||||||
dto: UpdatePipelineInput,
|
dto: CreatePipelineInput,
|
||||||
) {
|
) {
|
||||||
return await this.service.create(dto);
|
return await this.service.create(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Mutation(() => Pipeline)
|
@Mutation(() => Pipeline)
|
||||||
async updatePipeline(
|
async updatePipeline(
|
||||||
@Args('Pipeline', { type: () => UpdatePipelineInput })
|
@Args('pipeline', { type: () => UpdatePipelineInput })
|
||||||
dto: UpdatePipelineInput,
|
dto: UpdatePipelineInput,
|
||||||
) {
|
) {
|
||||||
const tmp = await this.service.update(dto);
|
const tmp = await this.service.update(dto);
|
||||||
|
@ -14,6 +14,8 @@ import {
|
|||||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||||
import { Commit } from '../repos/dtos/log-list.model';
|
import { Commit } from '../repos/dtos/log-list.model';
|
||||||
import { getAppInstanceRouteKey } from '../commons/utils/rabbit-mq';
|
import { getAppInstanceRouteKey } from '../commons/utils/rabbit-mq';
|
||||||
|
import { ApplicationException } from '../commons/exceptions/application.exception';
|
||||||
|
import { plainToClass } from 'class-transformer';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PipelinesService extends BaseDbService<Pipeline> {
|
export class PipelinesService extends BaseDbService<Pipeline> {
|
||||||
@ -42,8 +44,8 @@ export class PipelinesService extends BaseDbService<Pipeline> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async update(dto: UpdatePipelineInput) {
|
async update(dto: UpdatePipelineInput) {
|
||||||
await this.isDuplicateEntityForUpdate(dto.id, dto);
|
|
||||||
const old = await this.findOne(dto.id);
|
const old = await this.findOne(dto.id);
|
||||||
|
await this.isDuplicateEntityForUpdate(old, dto);
|
||||||
return await this.repository.save(this.repository.merge(old, dto));
|
return await this.repository.save(this.repository.merge(old, dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,22 +57,22 @@ export class PipelinesService extends BaseDbService<Pipeline> {
|
|||||||
exchange: EXCHANGE_REPO,
|
exchange: EXCHANGE_REPO,
|
||||||
routingKey: getAppInstanceRouteKey(ROUTE_FETCH, appInstance),
|
routingKey: getAppInstanceRouteKey(ROUTE_FETCH, appInstance),
|
||||||
payload: pipeline,
|
payload: pipeline,
|
||||||
timeout: 30_000,
|
timeout: 120_000,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
async listCommits(pipeline: Pipeline) {
|
async listCommits(pipeline: Pipeline) {
|
||||||
return await this.amqpConnection
|
return await this.amqpConnection
|
||||||
.request<Commit[]>({
|
.request<[Error, Commit[]]>({
|
||||||
exchange: EXCHANGE_REPO,
|
exchange: EXCHANGE_REPO,
|
||||||
routingKey: ROUTE_LIST_COMMITS,
|
routingKey: ROUTE_LIST_COMMITS,
|
||||||
payload: pipeline,
|
payload: pipeline,
|
||||||
timeout: 10_000,
|
timeout: 30_000,
|
||||||
})
|
})
|
||||||
.then((list) =>
|
.then(([error, list]) => {
|
||||||
list.map((item) => {
|
if (error) {
|
||||||
item.date = new Date(item.date);
|
throw new ApplicationException(error);
|
||||||
return item;
|
}
|
||||||
}),
|
return plainToClass(Commit, list);
|
||||||
);
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
3
src/projects/projects.constants.ts
Normal file
3
src/projects/projects.constants.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export const EXCHANGE_PROJECT_TOPIC = 'project.topic';
|
||||||
|
export const EXCHANGE_PROJECT_FANOUT = 'project.fanout';
|
||||||
|
export const ROUTE_PROJECT_CHANGE = 'project-change';
|
@ -3,9 +3,33 @@ import { ProjectsService } from './projects.service';
|
|||||||
import { ProjectsResolver } from './projects.resolver';
|
import { ProjectsResolver } from './projects.resolver';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { Project } from './project.entity';
|
import { Project } from './project.entity';
|
||||||
|
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { EXCHANGE_PROJECT_FANOUT } from './projects.constants';
|
||||||
|
import { CommonsModule } from '../commons/commons.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TypeOrmModule.forFeature([Project])],
|
imports: [
|
||||||
|
CommonsModule,
|
||||||
|
TypeOrmModule.forFeature([Project]),
|
||||||
|
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
uri: configService.get<string>('db.rabbitmq.uri'),
|
||||||
|
exchanges: [
|
||||||
|
{
|
||||||
|
name: EXCHANGE_PROJECT_FANOUT,
|
||||||
|
type: 'fanout',
|
||||||
|
options: {
|
||||||
|
durable: false,
|
||||||
|
autoDelete: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
],
|
||||||
providers: [ProjectsService, ProjectsResolver],
|
providers: [ProjectsService, ProjectsResolver],
|
||||||
exports: [ProjectsService],
|
exports: [ProjectsService],
|
||||||
})
|
})
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { JwtService } from '@nestjs-lib/auth';
|
||||||
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';
|
import { ProjectsService } from './projects.service';
|
||||||
@ -13,6 +14,10 @@ describe('ProjectsResolver', () => {
|
|||||||
provide: ProjectsService,
|
provide: ProjectsService,
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: JwtService,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
|
import { AccountRole, Roles } from '@nestjs-lib/auth';
|
||||||
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
|
||||||
import { CreateProjectInput } from './dtos/create-project.input';
|
import { CreateProjectInput } from './dtos/create-project.input';
|
||||||
import { UpdateProjectInput } from './dtos/update-project.input';
|
import { UpdateProjectInput } from './dtos/update-project.input';
|
||||||
import { Project } from './project.entity';
|
import { Project } from './project.entity';
|
||||||
import { ProjectsService } from './projects.service';
|
import { ProjectsService } from './projects.service';
|
||||||
|
|
||||||
|
@Roles(AccountRole.admin, AccountRole.super)
|
||||||
@Resolver(() => Project)
|
@Resolver(() => Project)
|
||||||
export class ProjectsResolver {
|
export class ProjectsResolver {
|
||||||
constructor(private readonly service: ProjectsService) {}
|
constructor(private readonly service: ProjectsService) {}
|
||||||
@ -20,7 +22,7 @@ export class ProjectsResolver {
|
|||||||
@Mutation(() => Project)
|
@Mutation(() => Project)
|
||||||
async createProject(
|
async createProject(
|
||||||
@Args('project', { type: () => CreateProjectInput })
|
@Args('project', { type: () => CreateProjectInput })
|
||||||
dto: UpdateProjectInput,
|
dto: CreateProjectInput,
|
||||||
) {
|
) {
|
||||||
return await this.service.create(dto);
|
return await this.service.create(dto);
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
|
|||||||
import { ProjectsService } from './projects.service';
|
import { ProjectsService } from './projects.service';
|
||||||
import { getRepositoryToken } from '@nestjs/typeorm';
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
import { Project } from './project.entity';
|
import { Project } from './project.entity';
|
||||||
|
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
|
||||||
describe('ProjectsService', () => {
|
describe('ProjectsService', () => {
|
||||||
let service: ProjectsService;
|
let service: ProjectsService;
|
||||||
@ -14,6 +15,10 @@ describe('ProjectsService', () => {
|
|||||||
provide: getRepositoryToken(Project),
|
provide: getRepositoryToken(Project),
|
||||||
useValue: {},
|
useValue: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: AmqpConnection,
|
||||||
|
useValue: {},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -5,6 +5,11 @@ 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';
|
import { UpdateProjectInput } from './dtos/update-project.input';
|
||||||
|
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PROJECT_FANOUT,
|
||||||
|
ROUTE_PROJECT_CHANGE,
|
||||||
|
} from './projects.constants';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ProjectsService extends BaseDbService<Project> {
|
export class ProjectsService extends BaseDbService<Project> {
|
||||||
@ -12,6 +17,7 @@ export class ProjectsService extends BaseDbService<Project> {
|
|||||||
constructor(
|
constructor(
|
||||||
@InjectRepository(Project)
|
@InjectRepository(Project)
|
||||||
readonly repository: Repository<Project>,
|
readonly repository: Repository<Project>,
|
||||||
|
private readonly amqpConnection: AmqpConnection,
|
||||||
) {
|
) {
|
||||||
super(repository);
|
super(repository);
|
||||||
}
|
}
|
||||||
@ -28,7 +34,12 @@ export class ProjectsService extends BaseDbService<Project> {
|
|||||||
async update(dto: UpdateProjectInput) {
|
async update(dto: UpdateProjectInput) {
|
||||||
await this.isDuplicateEntityForUpdate(dto.id, dto);
|
await this.isDuplicateEntityForUpdate(dto.id, dto);
|
||||||
const old = await this.findOne(dto.id);
|
const old = await this.findOne(dto.id);
|
||||||
return await this.repository.save(this.repository.merge(old, dto));
|
const project = await this.repository.save(this.repository.merge(old, dto));
|
||||||
|
this.amqpConnection.publish(EXCHANGE_PROJECT_FANOUT, ROUTE_PROJECT_CHANGE, [
|
||||||
|
project,
|
||||||
|
old,
|
||||||
|
]);
|
||||||
|
return project;
|
||||||
}
|
}
|
||||||
|
|
||||||
async remove(id: string) {
|
async remove(id: string) {
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
import { ObjectType, Field } from '@nestjs/graphql';
|
import { ObjectType, Field } from '@nestjs/graphql';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
import { LogResult, DefaultLogFields } from 'simple-git';
|
import { LogResult, DefaultLogFields } from 'simple-git';
|
||||||
import { PipelineTask } from '../../pipeline-tasks/pipeline-task.entity';
|
import { PipelineTask } from '../../pipeline-tasks/pipeline-task.entity';
|
||||||
|
|
||||||
@ObjectType()
|
@ObjectType()
|
||||||
export class Commit {
|
export class Commit {
|
||||||
hash: string;
|
hash: string;
|
||||||
|
@Type(() => Date)
|
||||||
date: Date;
|
date: Date;
|
||||||
message: string;
|
message: string;
|
||||||
refs: string;
|
refs: string;
|
||||||
|
@ -3,3 +3,4 @@ export const ROUTE_FETCH = 'fetch';
|
|||||||
export const ROUTE_LIST_COMMITS = 'list-commits';
|
export const ROUTE_LIST_COMMITS = 'list-commits';
|
||||||
export const QUEUE_LIST_COMMITS = 'list-commits';
|
export const QUEUE_LIST_COMMITS = 'list-commits';
|
||||||
export const QUEUE_FETCH = 'repo-fetch';
|
export const QUEUE_FETCH = 'repo-fetch';
|
||||||
|
export const QUEUE_REFRESH_REPO = 'refresh-repo';
|
||||||
|
@ -7,12 +7,14 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
|
|||||||
import { ProjectsModule } from '../projects/projects.module';
|
import { ProjectsModule } from '../projects/projects.module';
|
||||||
import { EXCHANGE_REPO } from './repos.constants';
|
import { EXCHANGE_REPO } from './repos.constants';
|
||||||
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
||||||
|
import { CommonsModule } from '../commons/commons.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([Project]),
|
TypeOrmModule.forFeature([Project]),
|
||||||
ConfigModule,
|
ConfigModule,
|
||||||
ProjectsModule,
|
ProjectsModule,
|
||||||
|
CommonsModule,
|
||||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
useFactory: (configService: ConfigService) => ({
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
@ -12,6 +12,7 @@ import { readFile } from 'fs/promises';
|
|||||||
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
import { getLoggerToken, PinoLogger } from 'nestjs-pino';
|
||||||
import { Nack } from '@golevelup/nestjs-rabbitmq';
|
import { Nack } from '@golevelup/nestjs-rabbitmq';
|
||||||
import { getInstanceName } from '../commons/utils/rabbit-mq';
|
import { getInstanceName } from '../commons/utils/rabbit-mq';
|
||||||
|
import { RedisMutexService } from '../commons/redis-mutex/redis-mutex.service';
|
||||||
|
|
||||||
const getTest1Project = () =>
|
const getTest1Project = () =>
|
||||||
({
|
({
|
||||||
@ -52,6 +53,14 @@ describe('ReposService', () => {
|
|||||||
provide: getLoggerToken(ReposService.name),
|
provide: getLoggerToken(ReposService.name),
|
||||||
useValue: new PinoLogger({}),
|
useValue: new PinoLogger({}),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
provide: RedisMutexService,
|
||||||
|
useValue: {
|
||||||
|
lock: jest.fn(() =>
|
||||||
|
Promise.resolve(() => Promise.resolve(undefined)),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
@ -11,13 +11,14 @@ import { Project } from '../projects/project.entity';
|
|||||||
import { ListBranchesArgs } from './dtos/list-branches.args';
|
import { ListBranchesArgs } from './dtos/list-branches.args';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { Commit } from './dtos/log-list.model';
|
import { Commit } from './dtos/log-list.model';
|
||||||
import { Nack, RabbitRPC } from '@golevelup/nestjs-rabbitmq';
|
import { Nack, RabbitRPC, RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
||||||
import { Pipeline } from '../pipelines/pipeline.entity';
|
import { Pipeline } from '../pipelines/pipeline.entity';
|
||||||
import { InjectPinoLogger, Logger } from 'nestjs-pino';
|
import { InjectPinoLogger, PinoLogger } from 'nestjs-pino';
|
||||||
import {
|
import {
|
||||||
EXCHANGE_REPO,
|
EXCHANGE_REPO,
|
||||||
QUEUE_FETCH,
|
QUEUE_FETCH,
|
||||||
QUEUE_LIST_COMMITS,
|
QUEUE_LIST_COMMITS,
|
||||||
|
QUEUE_REFRESH_REPO,
|
||||||
ROUTE_FETCH,
|
ROUTE_FETCH,
|
||||||
ROUTE_LIST_COMMITS,
|
ROUTE_LIST_COMMITS,
|
||||||
} from './repos.constants';
|
} from './repos.constants';
|
||||||
@ -26,6 +27,13 @@ import {
|
|||||||
getInstanceName,
|
getInstanceName,
|
||||||
getSelfInstanceRouteKey,
|
getSelfInstanceRouteKey,
|
||||||
} from '../commons/utils/rabbit-mq';
|
} from '../commons/utils/rabbit-mq';
|
||||||
|
import { ApplicationException } from '../commons/exceptions/application.exception';
|
||||||
|
import {
|
||||||
|
EXCHANGE_PROJECT_FANOUT,
|
||||||
|
ROUTE_PROJECT_CHANGE,
|
||||||
|
} from '../projects/projects.constants';
|
||||||
|
import { RedisMutexService } from '../commons/redis-mutex/redis-mutex.service';
|
||||||
|
import { rm } from 'fs/promises';
|
||||||
|
|
||||||
const DEFAULT_REMOTE_NAME = 'origin';
|
const DEFAULT_REMOTE_NAME = 'origin';
|
||||||
const INFO_PATH = '@info';
|
const INFO_PATH = '@info';
|
||||||
@ -36,7 +44,8 @@ export class ReposService {
|
|||||||
private readonly projectRepository: Repository<Project>,
|
private readonly projectRepository: Repository<Project>,
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
@InjectPinoLogger(ReposService.name)
|
@InjectPinoLogger(ReposService.name)
|
||||||
private readonly logger: Logger,
|
private readonly logger: PinoLogger,
|
||||||
|
private readonly redisMutexService: RedisMutexService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
getWorkspaceRoot(project: Project): string {
|
getWorkspaceRoot(project: Project): string {
|
||||||
@ -47,6 +56,14 @@ export class ReposService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getDeployRoot(task: PipelineTask) {
|
||||||
|
return join(
|
||||||
|
this.configService.get<string>('workspaces.root'),
|
||||||
|
encodeURIComponent(task.pipeline.project.name),
|
||||||
|
encodeURIComponent(`deploy-${task.pipeline.name}`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
async getGit(
|
async getGit(
|
||||||
project: Project,
|
project: Project,
|
||||||
workspaceRoot?: string,
|
workspaceRoot?: string,
|
||||||
@ -129,7 +146,7 @@ export class ReposService {
|
|||||||
autoDelete: true,
|
autoDelete: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
async listCommits(pipeline: Pipeline): Promise<Commit[] | Nack> {
|
async listCommits(pipeline: Pipeline): Promise<[Error, Commit[]?]> {
|
||||||
const git = await this.getGit(pipeline.project, undefined, {
|
const git = await this.getGit(pipeline.project, undefined, {
|
||||||
fetch: false,
|
fetch: false,
|
||||||
});
|
});
|
||||||
@ -140,20 +157,23 @@ export class ReposService {
|
|||||||
`remotes/origin/${pipeline.branch}`,
|
`remotes/origin/${pipeline.branch}`,
|
||||||
'--',
|
'--',
|
||||||
]);
|
]);
|
||||||
return data.all.map(
|
return [
|
||||||
|
null,
|
||||||
|
data.all.map(
|
||||||
(it) =>
|
(it) =>
|
||||||
({
|
({
|
||||||
...it,
|
...it,
|
||||||
date: new Date(it.date),
|
date: new Date(it.date),
|
||||||
} as Commit),
|
} as Commit),
|
||||||
);
|
),
|
||||||
|
];
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
{ error, pipeline },
|
{ error, pipeline },
|
||||||
'[listCommits] %s',
|
'[listCommits] %s',
|
||||||
error?.message,
|
error?.message,
|
||||||
);
|
);
|
||||||
return new Nack();
|
return [new ApplicationException(error)];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -166,6 +186,9 @@ export class ReposService {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
async fetch(pipeline: Pipeline): Promise<string | null | Nack> {
|
async fetch(pipeline: Pipeline): Promise<string | null | Nack> {
|
||||||
|
const unlock = await this.redisMutexService.lock(
|
||||||
|
`repo-project-${pipeline.projectId}`,
|
||||||
|
);
|
||||||
try {
|
try {
|
||||||
const git = await this.getGit(pipeline.project, undefined, {
|
const git = await this.getGit(pipeline.project, undefined, {
|
||||||
fetch: false,
|
fetch: false,
|
||||||
@ -175,6 +198,43 @@ export class ReposService {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error({ error, pipeline }, '[fetch] %s', error?.message);
|
this.logger.error({ error, pipeline }, '[fetch] %s', error?.message);
|
||||||
return new Nack();
|
return new Nack();
|
||||||
|
} finally {
|
||||||
|
await unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@RabbitSubscribe({
|
||||||
|
exchange: EXCHANGE_PROJECT_FANOUT,
|
||||||
|
routingKey: ROUTE_PROJECT_CHANGE,
|
||||||
|
queue: QUEUE_REFRESH_REPO,
|
||||||
|
queueOptions: {
|
||||||
|
autoDelete: true,
|
||||||
|
durable: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async refreshRepo([project]: [Project]) {
|
||||||
|
this.logger.info({ project }, '[refreshRepo] start');
|
||||||
|
const unlock = await this.redisMutexService.lock(
|
||||||
|
`repo-project-${project.id}`,
|
||||||
|
{
|
||||||
|
timeout: null,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const path = join(
|
||||||
|
this.configService.get<string>('workspaces.root'),
|
||||||
|
encodeURIComponent(project.name),
|
||||||
|
);
|
||||||
|
await rm(path, { recursive: true });
|
||||||
|
this.logger.info({ project }, '[refreshRepo] success');
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
{ project, error },
|
||||||
|
'[refreshRepo] failed. $s',
|
||||||
|
error.message,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
15
test/__mocks__/deploy-service/ecosystem.config.js
Normal file
15
test/__mocks__/deploy-service/ecosystem.config.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'app',
|
||||||
|
script: __dirname + '/index.js',
|
||||||
|
watch: false,
|
||||||
|
ignore_watch: ['node_modules'],
|
||||||
|
log_date_format: 'MM-DD HH:mm:ss.SSS Z',
|
||||||
|
env: {},
|
||||||
|
max_restarts: 5,
|
||||||
|
kill_timeout: 10_000,
|
||||||
|
wait_ready: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
23
test/__mocks__/deploy-service/index.js
Normal file
23
test/__mocks__/deploy-service/index.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import { createServer } from 'http';
|
||||||
|
|
||||||
|
var app = createServer(function (req, res) {
|
||||||
|
res.writeHead(200);
|
||||||
|
setTimeout(() => {
|
||||||
|
res.end('hey');
|
||||||
|
}, 2000);
|
||||||
|
});
|
||||||
|
|
||||||
|
var listener = app.listen(0, function () {
|
||||||
|
console.log('Listening on port ' + listener.address().port);
|
||||||
|
setTimeout(() => {
|
||||||
|
// Here we send the ready signal to PM2
|
||||||
|
process.send('ready');
|
||||||
|
}, 5000);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGINT', function () {
|
||||||
|
listener.close();
|
||||||
|
setTimeout(() => {
|
||||||
|
process.exit(0);
|
||||||
|
}, 2000);
|
||||||
|
});
|
10
test/__mocks__/deploy-service/package.json
Normal file
10
test/__mocks__/deploy-service/package.json
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"name": "deploy-service",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "For Test",
|
||||||
|
"main": "index.js",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {},
|
||||||
|
"author": "Ivan Li",
|
||||||
|
"license": "ISC"
|
||||||
|
}
|
16
test/__mocks__/deploy-service/test.js
Normal file
16
test/__mocks__/deploy-service/test.js
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { createServer } from 'http';
|
||||||
|
|
||||||
|
var app = createServer(function (req, res) {
|
||||||
|
res.writeHead(200);
|
||||||
|
setTimeout(() => {
|
||||||
|
res.end('pm2');
|
||||||
|
}, 2000);
|
||||||
|
});
|
||||||
|
|
||||||
|
var listener = app.listen(33333, function () {
|
||||||
|
console.log('Listening on port ' + listener.address().port);
|
||||||
|
setTimeout(() => {
|
||||||
|
// Here we send the ready signal to PM2
|
||||||
|
process.send('ready');
|
||||||
|
}, 5000);
|
||||||
|
});
|
@ -7,9 +7,10 @@
|
|||||||
"experimentalDecorators": true,
|
"experimentalDecorators": true,
|
||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"target": "es2017",
|
"target": "es2017",
|
||||||
|
"lib": ["ES2021"],
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
"baseUrl": "./",
|
"baseUrl": "./",
|
||||||
"incremental": true
|
},
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user