forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(kafka): Starts work on implementing client/server
- Loading branch information
1 parent
56071d0
commit b5ed5dd
Showing
9 changed files
with
944 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ node_modules/ | |
/.idea | ||
/.awcache | ||
/.vscode | ||
*.code-workspace | ||
|
||
# bundle | ||
packages/**/*.d.ts | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,187 @@ | ||
import { Logger } from '@nestjs/common/services/logger.service'; | ||
import { loadPackage } from '@nestjs/common/utils/load-package.util'; | ||
import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; | ||
import { EventEmitter } from 'events'; | ||
import { fromEvent, merge, Observable } from 'rxjs'; | ||
import { first, map, share, switchMap } from 'rxjs/operators'; | ||
import { ReadPacket, RmqOptions } from '../interfaces'; | ||
import { | ||
DISCONNECT_EVENT, | ||
ERROR_EVENT, | ||
RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT, | ||
RQM_DEFAULT_NOACK, | ||
RQM_DEFAULT_PREFETCH_COUNT, | ||
RQM_DEFAULT_QUEUE, | ||
RQM_DEFAULT_QUEUE_OPTIONS, | ||
RQM_DEFAULT_URL, | ||
} from './../constants'; | ||
import { WritePacket } from './../interfaces'; | ||
import { ClientProxy } from './client-proxy'; | ||
|
||
let rqmPackage: any = {}; | ||
|
||
const REPLY_QUEUE = 'amq.rabbitmq.reply-to'; | ||
|
||
export class ClientKafka extends ClientProxy { | ||
protected readonly logger = new Logger(ClientProxy.name); | ||
protected connection: Promise<any>; | ||
protected client: any = null; | ||
protected channel: any = null; | ||
protected urls: string[]; | ||
protected queue: string; | ||
protected queueOptions: any; | ||
protected responseEmitter: EventEmitter; | ||
|
||
constructor(protected readonly options: RmqOptions['options']) { | ||
super(); | ||
this. = this.getOptionsProp(this.options, 'urls') || [RQM_DEFAULT_URL]; | ||
this.groupId = | ||
this.getOptionsProp(this.options, 'queue') || RQM_DEFAULT_QUEUE; | ||
this.queueOptions = | ||
this.getOptionsProp(this.options, 'queueOptions') || | ||
RQM_DEFAULT_QUEUE_OPTIONS; | ||
|
||
loadPackage('amqplib', ClientKafka.name, () => require('amqplib')); | ||
rqmPackage = loadPackage('amqp-connection-manager', ClientKafka.name, () => | ||
require('amqp-connection-manager'), | ||
); | ||
} | ||
|
||
public close(): void { | ||
this.channel && this.channel.close(); | ||
this.client && this.client.close(); | ||
} | ||
|
||
public consumeChannel() { | ||
const noAck = | ||
this.getOptionsProp(this.options, 'noAck') || RQM_DEFAULT_NOACK; | ||
this.channel.addSetup((channel: any) => | ||
channel.consume( | ||
REPLY_QUEUE, | ||
(msg: any) => | ||
this.responseEmitter.emit(msg.properties.correlationId, msg), | ||
{ | ||
noAck, | ||
}, | ||
), | ||
); | ||
} | ||
|
||
public connect(): Promise<any> { | ||
if (this.client) { | ||
return this.connection; | ||
} | ||
this.client = this.createClient(); | ||
this.handleError(this.client); | ||
|
||
const connect$ = this.connect$(this.client); | ||
this.connection = this.mergeDisconnectEvent(this.client, connect$) | ||
.pipe( | ||
switchMap(() => this.createChannel()), | ||
share(), | ||
) | ||
.toPromise(); | ||
return this.connection; | ||
} | ||
|
||
public createChannel(): Promise<void> { | ||
return new Promise(resolve => { | ||
this.channel = this.client.createChannel({ | ||
json: false, | ||
setup: (channel: any) => this.setupChannel(channel, resolve), | ||
}); | ||
}); | ||
} | ||
|
||
public createClient<T = any>(): T { | ||
const socketOptions = this.getOptionsProp(this.options, 'socketOptions'); | ||
return rqmPackage.connect(this.urls, socketOptions) as T; | ||
} | ||
|
||
public mergeDisconnectEvent<T = any>( | ||
instance: any, | ||
source$: Observable<T>, | ||
): Observable<T> { | ||
const close$ = fromEvent(instance, DISCONNECT_EVENT).pipe( | ||
map((err: any) => { | ||
throw err; | ||
}), | ||
); | ||
return merge(source$, close$).pipe(first()); | ||
} | ||
|
||
public async setupChannel(channel: any, resolve: Function) { | ||
const prefetchCount = | ||
this.getOptionsProp(this.options, 'prefetchCount') || | ||
RQM_DEFAULT_PREFETCH_COUNT; | ||
const isGlobalPrefetchCount = | ||
this.getOptionsProp(this.options, 'isGlobalPrefetchCount') || | ||
RQM_DEFAULT_IS_GLOBAL_PREFETCH_COUNT; | ||
|
||
await channel.assertQueue(this.queue, this.queueOptions); | ||
await channel.prefetch(prefetchCount, isGlobalPrefetchCount); | ||
|
||
this.responseEmitter = new EventEmitter(); | ||
this.responseEmitter.setMaxListeners(0); | ||
this.consumeChannel(); | ||
resolve(); | ||
} | ||
|
||
public handleError(client: any): void { | ||
client.addListener(ERROR_EVENT, (err: any) => this.logger.error(err)); | ||
} | ||
|
||
public handleMessage( | ||
packet: WritePacket, | ||
callback: (packet: WritePacket) => any, | ||
) { | ||
const { err, response, isDisposed } = packet; | ||
if (isDisposed || err) { | ||
callback({ | ||
err, | ||
response: null, | ||
isDisposed: true, | ||
}); | ||
} | ||
callback({ | ||
err, | ||
response, | ||
}); | ||
} | ||
|
||
protected publish( | ||
message: ReadPacket, | ||
callback: (packet: WritePacket) => any, | ||
): Function { | ||
try { | ||
const correlationId = randomStringGenerator(); | ||
const listener = ({ content }: { content: any }) => | ||
this.handleMessage(JSON.parse(content.toString()), callback); | ||
|
||
Object.assign(message, { id: correlationId }); | ||
this.responseEmitter.on(correlationId, listener); | ||
this.channel.sendToQueue( | ||
this.queue, | ||
Buffer.from(JSON.stringify(message)), | ||
{ | ||
replyTo: REPLY_QUEUE, | ||
correlationId, | ||
}, | ||
); | ||
return () => this.responseEmitter.removeListener(correlationId, listener); | ||
} catch (err) { | ||
callback({ err }); | ||
} | ||
} | ||
|
||
protected dispatchEvent(packet: ReadPacket): Promise<any> { | ||
return new Promise((resolve, reject) => | ||
this.channel.sendToQueue( | ||
this.queue, | ||
Buffer.from(JSON.stringify(packet)), | ||
{}, | ||
err => (err ? reject(err) : resolve()), | ||
), | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,4 +5,5 @@ export enum Transport { | |
MQTT, | ||
GRPC, | ||
RMQ, | ||
KAFKA | ||
} |
Oops, something went wrong.