feat: 使用 PubSub 进行消息广播。

This commit is contained in:
Ivan 2021-04-04 00:36:58 +08:00
parent bb3efd3714
commit b4307f05d6
17 changed files with 94 additions and 68 deletions

View File

@ -16,6 +16,7 @@ import { RawBodyMiddleware } from './commons/middlewares/raw-body.middleware';
import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller'; import { GiteaWebhooksController } from './webhooks/gitea-webhooks.controller';
import { ParseBodyMiddleware } from './commons/middlewares/parse-body.middleware'; import { ParseBodyMiddleware } from './commons/middlewares/parse-body.middleware';
import { BullModule } from '@nestjs/bull'; import { BullModule } from '@nestjs/bull';
import { PubSubModule } from './commons/pub-sub/pub-sub.module';
@Module({ @Module({
imports: [ imports: [
@ -51,8 +52,19 @@ import { BullModule } from '@nestjs/bull';
useFactory: (configService: ConfigService) => ({ useFactory: (configService: ConfigService) => ({
redis: { redis: {
host: configService.get<string>('db.redis.host', 'localhost'), host: configService.get<string>('db.redis.host', 'localhost'),
port: configService.get<number>('db.redis.port', 6379), port: configService.get<number>('db.redis.port', undefined),
password: configService.get<string>('db.redis.password', ''), password: configService.get<string>('db.redis.password', undefined),
},
}),
inject: [ConfigService],
}),
PubSubModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
redis: {
host: configService.get<string>('db.redis.host', 'localhost'),
port: configService.get<number>('db.redis.port', undefined),
password: configService.get<string>('db.redis.password', undefined),
}, },
}), }),
inject: [ConfigService], inject: [ConfigService],

View File

@ -1,5 +1,5 @@
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common'; import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
import { sanitize } from '@neuralegion/class-sanitizer/dist'; import { plainToClass } from 'class-transformer';
@Injectable() @Injectable()
export class SanitizePipe implements PipeTransform { export class SanitizePipe implements PipeTransform {
@ -12,13 +12,11 @@ export class SanitizePipe implements PipeTransform {
return value; return value;
} }
const constructorFunction = metadata.metatype; const constructorFunction = metadata.metatype;
if (!constructorFunction) { if (!constructorFunction || value instanceof constructorFunction) {
return value; return value;
} }
value = Object.assign(new constructorFunction(), value);
try { try {
sanitize(value); return plainToClass(constructorFunction, value);
return value;
} catch (err) { } catch (err) {
console.error(err); console.error(err);
throw err; throw err;

View File

@ -0,0 +1,5 @@
import { Inject } from '@nestjs/common';
import { getPubSubToken } from '../utils/token';
export const InjectPubSub = (name?: string): ParameterDecorator =>
Inject(getPubSubToken(name));

View File

@ -1,5 +1,5 @@
import { ModuleMetadata } from '@nestjs/common'; import { ModuleMetadata } from '@nestjs/common';
import { PubSubOptions } from 'graphql-subscriptions'; import { PubSubOptions } from './pub-sub-options.interface';
export interface PubSubAsyncConfig extends Pick<ModuleMetadata, 'imports'> { export interface PubSubAsyncConfig extends Pick<ModuleMetadata, 'imports'> {
name?: string; name?: string;

View File

@ -1,6 +1,6 @@
import { RedisOptions } from 'ioredis'; import { RedisOptions } from 'ioredis';
export interface PubSubOptions { export interface PubSubOptions {
name: string; name?: string;
redis: RedisOptions; redis: RedisOptions;
} }

View File

@ -1,2 +1 @@
export const DEFAULT_PUB_SUB_NAME = 'default'; export const DEFAULT_PUB_SUB_NAME = 'default';
export const PUB_SUB_CONFIG_TOKEN = 'pub_sub_config_token';

View File

@ -1,47 +1,48 @@
import { DynamicModule, Module, Provider } from '@nestjs/common'; import { DynamicModule, Module } from '@nestjs/common';
import { PubSubService } from './pub-sub.service'; import { PubSubService } from './pub-sub.service';
import { import {
createOptionsProvider, createAsyncPubSubProviders,
createPubSubProvider, createPubSubProvider,
} from './pub-sub.providers'; } from './pub-sub.providers';
import { PubSubOptions } from './interfaces/pub-sub-options.interface'; import { PubSubOptions } from './interfaces/pub-sub-options.interface';
import { PubSubAsyncConfig } from './interfaces/pub-sub-async-config.interface'; import { PubSubAsyncConfig } from './interfaces/pub-sub-async-config.interface';
import { getPubSubToken } from './utils/token'; import { getPubSubConfigToken } from './utils/token';
import { PUB_SUB_CONFIG_TOKEN } from './pub-sub.constants';
@Module({ @Module({
providers: [PubSubService], providers: [PubSubService],
}) })
export class PubSubModule { export class PubSubModule {
public static forRoot(options: PubSubOptions): DynamicModule { public static forRoot(options: PubSubOptions): DynamicModule {
const providers = [createPubSubProvider(options)]; const providers = [
return {
global: true,
module: PubSubModule,
providers,
exports: providers,
};
}
public static forRootAsync(config: PubSubAsyncConfig) {
const providers: Provider[] = [
createOptionsProvider(config),
{ {
provide: getPubSubToken(config.name), provide: getPubSubConfigToken(options.name),
inject: [PUB_SUB_CONFIG_TOKEN], useValue: options,
useFactory: (options: PubSubOptions) => {
return createPubSubProvider({
name: config.name,
...options,
});
},
}, },
createPubSubProvider(options.name),
]; ];
return { return {
global: true, global: true,
module: PubSubModule, module: PubSubModule,
imports: config.imports,
providers, providers,
exports: providers, exports: providers,
}; };
} }
public static forRootAsync(...configs: PubSubAsyncConfig[]): DynamicModule {
const providers = createAsyncPubSubProviders(configs);
return {
global: true,
module: PubSubModule,
imports: configs
.map((config) => config.imports)
.flat()
.filter((o, i, a) => a.indexOf(o) === i),
providers,
exports: providers,
};
}
public static forFeature(): DynamicModule {
return {
module: PubSubModule,
};
}
} }

View File

@ -2,22 +2,30 @@ import { Provider } from '@nestjs/common';
import { PubSubAsyncConfig } from './interfaces/pub-sub-async-config.interface'; import { PubSubAsyncConfig } from './interfaces/pub-sub-async-config.interface';
import { PubSubOptions } from './interfaces/pub-sub-options.interface'; import { PubSubOptions } from './interfaces/pub-sub-options.interface';
import { PubSub } from './pub-sub'; import { PubSub } from './pub-sub';
import { PUB_SUB_CONFIG_TOKEN } from './pub-sub.constants'; import { getPubSubConfigToken, getPubSubToken } from './utils/token';
import { getPubSubToken } from './utils/token';
export function createPubSubProvider(options: PubSubOptions): Provider { export function createPubSubProvider(name: string): Provider {
return { return {
provide: getPubSubToken(options.name), provide: getPubSubToken(name),
useFactory: () => { useFactory: (option: PubSubOptions) => new PubSub(option),
return new PubSub(options); inject: [getPubSubConfigToken(name)],
},
}; };
} }
export function createOptionsProvider(config: PubSubAsyncConfig): Provider { export function createOptionsProvider(config: PubSubAsyncConfig): Provider {
return { return {
provide: PUB_SUB_CONFIG_TOKEN, provide: getPubSubConfigToken(config.name),
useFactory: config.useFactory, useFactory: config.useFactory,
inject: config.inject || [], inject: config.inject || [],
}; };
} }
export function createAsyncPubSubProviders(
configs: PubSubAsyncConfig[],
): Provider[] {
return configs
.map((config) => [
createOptionsProvider(config),
createPubSubProvider(config.name),
])
.flat();
}

View File

@ -10,7 +10,7 @@ import {
PubSubRawNextMessage, PubSubRawNextMessage,
} from './interfaces/pub-sub-raw-message.interface'; } from './interfaces/pub-sub-raw-message.interface';
const log = debug('app:pubsub:instance'); const log = debug('fennec:pubsub:instance');
export class PubSub extends EventEmitter { export class PubSub extends EventEmitter {
pubRedis: Redis; pubRedis: Redis;
pSubRedis: Redis; pSubRedis: Redis;

View File

@ -3,3 +3,6 @@ import { DEFAULT_PUB_SUB_NAME } from '../pub-sub.constants';
export function getPubSubToken(name) { export function getPubSubToken(name) {
return `app:pub-usb:${name || DEFAULT_PUB_SUB_NAME}`; return `app:pub-usb:${name || DEFAULT_PUB_SUB_NAME}`;
} }
export function getPubSubConfigToken(name) {
return `app:pub-usb:config:${name || DEFAULT_PUB_SUB_NAME}`;
}

View File

@ -1,6 +1,7 @@
import { PipelineTask } from './../pipeline-task.entity'; import { PipelineTask } from './../pipeline-task.entity';
import { PipelineUnits } from '../enums/pipeline-units.enum'; import { PipelineUnits } from '../enums/pipeline-units.enum';
import { Field, HideField, ObjectType } from '@nestjs/graphql'; import { Field, HideField, ObjectType } from '@nestjs/graphql';
import { Type } from 'class-transformer';
@ObjectType() @ObjectType()
export class PipelineTaskLogMessage { export class PipelineTaskLogMessage {
@ -9,6 +10,7 @@ export class PipelineTaskLogMessage {
@Field(() => PipelineUnits, { nullable: true }) @Field(() => PipelineUnits, { nullable: true })
unit?: PipelineUnits; unit?: PipelineUnits;
@Field() @Field()
@Type(() => Date)
time: Date; time: Date;
@Field() @Field()
message: string; message: string;

View File

@ -1,8 +1,9 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { log } from 'console'; import { observableToAsyncIterable } from 'graphql-tools';
import { PubSub } from 'graphql-subscriptions';
import { RedisService } from 'nestjs-redis'; import { RedisService } from 'nestjs-redis';
import { find, omit, propEq } from 'ramda'; import { find, omit, propEq } from 'ramda';
import { InjectPubSub } from '../commons/pub-sub/decorators/inject-pub-sub.decorator';
import { PubSub } from '../commons/pub-sub/pub-sub';
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 { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module'; import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
@ -13,9 +14,11 @@ const LOG_TIMEOUT_SECONDS = 10_000;
@Injectable() @Injectable()
export class PipelineTaskLogsService { export class PipelineTaskLogsService {
constructor(private readonly redisService: RedisService) {} constructor(
private readonly redisService: RedisService,
pubSub = new PubSub(); @InjectPubSub()
private readonly pubSub: PubSub,
) {}
get redis() { get redis() {
return this.redisService.getClient(); return this.redisService.getClient();
@ -73,6 +76,6 @@ export class PipelineTaskLogsService {
} }
watchLogs(task: PipelineTask) { watchLogs(task: PipelineTask) {
return this.pubSub.asyncIterator(this.getKeys(task)); return observableToAsyncIterable(this.pubSub.message$(this.getKeys(task)));
} }
} }

View File

@ -1,3 +1,2 @@
export const PIPELINE_TASK_QUEUE = 'PIPELINE_TASK_QUEUE'; export const PIPELINE_TASK_QUEUE = 'PIPELINE_TASK_QUEUE';
export const PIPELINE_TASK_LOG_QUEUE = 'PIPELINE_TASK_LOG_QUEUE'; export const PIPELINE_TASK_LOG_QUEUE = 'PIPELINE_TASK_LOG_QUEUE';
export const PIPELINE_TASK_LOG_PUBSUB = 'PIPELINE_TASK_LOG_PUBSUB';

View File

@ -8,12 +8,10 @@ import { ReposModule } from '../repos/repos.module';
import { RedisModule } from 'nestjs-redis'; import { RedisModule } from 'nestjs-redis';
import { BullModule } from '@nestjs/bull'; import { BullModule } from '@nestjs/bull';
import { PipelineTaskConsumer } from './pipeline-task.consumer'; import { PipelineTaskConsumer } from './pipeline-task.consumer';
import { import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
PIPELINE_TASK_QUEUE,
PIPELINE_TASK_LOG_PUBSUB,
} from './pipeline-tasks.constants';
import { PipelineTaskLogsService } from './pipeline-task-logs.service'; import { PipelineTaskLogsService } from './pipeline-task-logs.service';
import { PubSub } from 'apollo-server-express'; import { PubSub } from 'apollo-server-express';
import { PubSubModule } from '../commons/pub-sub/pub-sub.module';
@Module({ @Module({
imports: [ imports: [
@ -21,6 +19,7 @@ import { PubSub } from 'apollo-server-express';
BullModule.registerQueue({ BullModule.registerQueue({
name: PIPELINE_TASK_QUEUE, name: PIPELINE_TASK_QUEUE,
}), }),
PubSubModule.forFeature(),
RedisModule, RedisModule,
ReposModule, ReposModule,
], ],
@ -29,10 +28,6 @@ import { PubSub } from 'apollo-server-express';
PipelineTasksResolver, PipelineTasksResolver,
PipelineTaskConsumer, PipelineTaskConsumer,
PipelineTaskLogsService, PipelineTaskLogsService,
{
provide: Symbol(PIPELINE_TASK_LOG_PUBSUB),
useValue: new PubSub(),
},
], ],
exports: [PipelineTasksService], exports: [PipelineTasksService],
}) })

View File

@ -5,6 +5,7 @@ import { CreatePipelineTaskInput } from './dtos/create-pipeline-task.input';
import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module'; import { PipelineTaskLogMessage } from './models/pipeline-task-log-message.module';
import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args'; import { PipelineTaskLogArgs } from './dtos/pipeline-task-log.args';
import { PipelineTaskLogsService } from './pipeline-task-logs.service'; import { PipelineTaskLogsService } from './pipeline-task-logs.service';
import { plainToClass } from 'class-transformer';
@Resolver() @Resolver()
export class PipelineTasksResolver { export class PipelineTasksResolver {
@ -20,7 +21,8 @@ export class PipelineTasksResolver {
@Subscription(() => PipelineTaskLogMessage, { @Subscription(() => PipelineTaskLogMessage, {
resolve: (value) => { resolve: (value) => {
return value; const data = plainToClass(PipelineTaskLogMessage, value);
return data;
}, },
}) })
async pipelineTaskLog(@Args() args: PipelineTaskLogArgs) { async pipelineTaskLog(@Args() args: PipelineTaskLogArgs) {

View File

@ -9,16 +9,17 @@ import { InjectQueue } from '@nestjs/bull';
import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants'; import { PIPELINE_TASK_QUEUE } from './pipeline-tasks.constants';
import { Queue } from 'bull'; import { Queue } from 'bull';
import { LockFailedException } from '../commons/exceptions/lock-failed.exception'; import { LockFailedException } from '../commons/exceptions/lock-failed.exception';
import { PubSub } from 'apollo-server-express';
import { TaskStatuses } from './enums/task-statuses.enum'; import { TaskStatuses } from './enums/task-statuses.enum';
import { isNil } from 'ramda'; import { isNil } from 'ramda';
import debug from 'debug'; import debug from 'debug';
import { InjectPubSub } from '../commons/pub-sub/decorators/inject-pub-sub.decorator';
import { PubSub } from '../commons/pub-sub/pub-sub';
import { observableToAsyncIterable } from '@graphql-tools/utils';
const log = debug('fennec:pipeline-tasks:service'); const log = debug('fennec:pipeline-tasks:service');
@Injectable() @Injectable()
export class PipelineTasksService { export class PipelineTasksService {
pubSub = new PubSub();
constructor( constructor(
@InjectRepository(PipelineTask) @InjectRepository(PipelineTask)
private readonly repository: Repository<PipelineTask>, private readonly repository: Repository<PipelineTask>,
@ -27,6 +28,8 @@ export class PipelineTasksService {
@InjectQueue(PIPELINE_TASK_QUEUE) @InjectQueue(PIPELINE_TASK_QUEUE)
private readonly queue: Queue<PipelineTask>, private readonly queue: Queue<PipelineTask>,
private readonly redis: RedisService, private readonly redis: RedisService,
@InjectPubSub()
private readonly pubSub: PubSub,
) {} ) {}
async addTask(dto: CreatePipelineTaskInput) { async addTask(dto: CreatePipelineTaskInput) {
const pipeline = await this.pipelineRepository.findOneOrFail({ const pipeline = await this.pipelineRepository.findOneOrFail({
@ -118,12 +121,12 @@ export class PipelineTasksService {
} }
async updateTask(task: PipelineTask) { async updateTask(task: PipelineTask) {
this.pubSub.publish(task.id, task); this.pubSub.publish(`task:${task.id}`, task);
return await this.repository.save(task); return await this.repository.save(task);
} }
async watchTaskUpdated(id: string) { async watchTaskUpdated(id: string) {
return this.pubSub.asyncIterator(id); return observableToAsyncIterable(this.pubSub.message$(`task:${id}`));
} }
getRedisTokens(pipeline: Pipeline): [string, string] { getRedisTokens(pipeline: Pipeline): [string, string] {

View File

@ -22,11 +22,7 @@ export class CommitLogsResolver {
return value; return value;
}, },
}) })
async listLogsForPipeline( async listLogsForPipeline(@Args('id', { type: () => String }) id: string) {
@Args('id', { type: () => String }) id: string,
@Info() info: GraphQLResolveInfo,
) {
info.returnType.toString();
const job = await this.service.listLogsForPipeline(id); const job = await this.service.listLogsForPipeline(id);
return (async function* () { return (async function* () {
yield await job.finished(); yield await job.finished();