nope/lib/communication/amqpLayer.ts

462 lines
16 KiB
TypeScript
Raw Normal View History

2020-11-06 08:10:30 +00:00
/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-11-06 08:52:30
* @modify date 2020-11-06 08:52:30
* @desc [description]
*/
2020-09-12 20:23:55 +00:00
import * as amqp from 'amqplib';
import { getLogger } from "../logger/getLogger";
2020-11-06 08:10:30 +00:00
import { IAvailableInstanceGeneratorsMsg, IAvailableServicesMsg, IAvailableTopicsMsg, ICommunicationInterface, IExternalEventMsg, IRequestTaskMsg, IResponseTaskMsg, ITaskCancelationMsg } from '../types/nope/communication.interface';
2020-09-12 20:23:55 +00:00
export type QueuePublishOptions = {
2020-09-15 05:58:54 +00:00
subscribeOptions?: amqp.Options.AssertQueue,
consumeOptions?: amqp.Options.Consume,
deleteOptions?: amqp.Options.DeleteQueue
prefetch?: number
}
export type QueueSubscribeOptions = {
subscribeOptions?: amqp.Options.AssertQueue,
consumeOptions?: amqp.Options.Consume,
deleteOptions?: amqp.Options.DeleteQueue
prefetch?: number
}
2020-09-15 05:58:54 +00:00
export type SubscriptionOptions = {
subscribeOptions?: amqp.Options.AssertExchange,
2020-11-04 16:39:20 +00:00
exchangeType?: 'direct' | 'topic' | 'fanout' | 'headers'
2020-09-15 05:58:54 +00:00
consumeOptions?: amqp.Options.Consume,
deleteOptions?: amqp.Options.DeleteQueue
prefetch?: number
}
2020-09-12 20:23:55 +00:00
interface IConnection {
channel: amqp.Channel,
2020-09-28 19:40:33 +00:00
delete: (event?: string, deleteOptions?: amqp.Options.DeleteQueue) => Promise<void>;
subscribe: (event?: string, consumeOptions?: amqp.Options.Consume, prefetch?: number) => Promise<void>;
unsubscribe: () => Promise<void>;
isSubscribed(): boolean;
send: (...arg) => boolean
}
2020-09-12 20:23:55 +00:00
/**
* A Communication Layer for the Dispatchers.
* In this Layer AMQP (Rabbit-MQ) is used.
* Functions are matched to Queues.
*
* @export
* @class AmqpLayer
* @implements {ICommunicationInterface}
*/
2020-09-15 05:58:54 +00:00
export class AmqpInterface {
async off(event: string, cb: (data: any, msg: amqp.Message) => void) {
2020-09-12 20:23:55 +00:00
// Store the Function
const _set = this._userDefinedCallbacks.get(event) || new Set();
2020-09-12 20:23:55 +00:00
// Delete the callback.
_set.delete(cb)
// Based on the Numbers of Elements which are included in here
// the Queue is subscribed.
2020-09-15 05:58:54 +00:00
if (_set.size > 0) {
this._userDefinedCallbacks.set(event, _set);
2020-09-12 20:23:55 +00:00
} else {
const _connection = this._connections.get(event);
if (_connection?.unsubscribe) {
2020-09-12 20:23:55 +00:00
const _this = this;
await _connection.unsubscribe().catch(e => {
2020-09-12 20:23:55 +00:00
_this._logger.error('failed unsubscribing')
_this._logger.error(e);
});
2020-09-28 19:40:33 +00:00
await _connection.delete().catch(e => {
_this._logger.error('failed deleting')
_this._logger.error(e);
});
2020-09-12 20:23:55 +00:00
}
2020-09-15 05:58:54 +00:00
}
2020-09-12 20:23:55 +00:00
}
protected _socket: amqp.Connection;
protected _connections: Map<string, IConnection>
/**
* Map holding a set of function for user defined events.
*
* @protected
* @memberof AmqpInterface
*/
protected _userDefinedCallbacks: Map<string, Set<(data: any, msg: amqp.Message) => void>>;
2020-09-12 20:23:55 +00:00
constructor(public uri: string) {
// Adapt the URI if required:
this.uri = uri.startsWith('amqp://') ? uri : 'amqp://' + uri;
const _this = this;
amqp.connect(this.uri).then(connection => {
_this._socket = connection;
_this._logger.info('Connection established with ' + _this.uri);
_this._socket.createChannel
});
this._connections = new Map();
this._userDefinedCallbacks = new Map();
2020-09-12 20:23:55 +00:00
}
protected async _createConnection(event: string, options: QueuePublishOptions = {}) {
if (this._connections.has(event)) {
2020-09-28 19:40:33 +00:00
return {
connection: this._connections.get(event),
created: false
};
}
2020-09-12 20:23:55 +00:00
const _this = this;
const _channel = await this._socket.createChannel();
2020-09-15 05:58:54 +00:00
let _sub: amqp.Replies.Consume = null;
// Define a Connection Object.
const _connection: IConnection = {
channel: _channel,
send(data) {
return _channel.sendToQueue(
event,
Buffer.from(
JSON.stringify(data)
),
{
contentEncoding: 'application/json',
}
);
},
isSubscribed() {
return _sub !== null;
},
async subscribe(_event: string = event, _opts = options.consumeOptions) {
if (_sub === null) {
_sub = await _channel.consume(_event, (msg) => {
// Transform the Data:
const data = JSON.parse(msg.content.toString('utf-8'))
for (const _func of _this._userDefinedCallbacks.get(event) || []) {
_func(data, msg)
}
}, options.consumeOptions);
}
},
2020-09-15 05:58:54 +00:00
async unsubscribe() {
2020-09-28 19:40:33 +00:00
if (_sub !== null) {
// Delte the Subscription
await _channel.cancel(_sub.consumerTag);
_sub = null;
}
},
2020-09-12 20:23:55 +00:00
2020-09-28 19:40:33 +00:00
async delete(_event: string = event, _opts = options.deleteOptions) {
try {
2020-09-28 19:40:33 +00:00
await _channel.deleteQueue(_event, _opts);
} catch (e) {
2020-09-12 20:23:55 +00:00
}
}
}
2020-09-12 20:23:55 +00:00
this._connections.set(event, _connection);
2020-09-15 05:58:54 +00:00
2020-09-28 19:40:33 +00:00
return {
connection: _connection,
created: true
};
}
2020-09-12 20:23:55 +00:00
public async createQueue(event: string, options: QueuePublishOptions = {}) {
// Get the Connection
2020-09-28 19:40:33 +00:00
const _res = await this._createConnection(event, options);
if (_res.created) {
// Extract the Connection
const _connection: IConnection = _res.connection;
// Create a Queue
const _queue = await _connection.channel.assertQueue(event, options.subscribeOptions);
// Enable Prefetch
if (options.prefetch > 0) {
await _connection.channel.prefetch(options.prefetch);
} else if (typeof options.prefetch === 'undefined') {
await _connection.channel.prefetch(1);
}
}
2020-09-28 19:40:33 +00:00
return _res.connection;
2020-09-12 20:23:55 +00:00
}
2020-09-15 05:58:54 +00:00
/**
* Function to create an Subscription in the RabbitMQ-Broker
*
* @param {string} event
* @param {SubscriptionOptions} [options={}]
* @memberof AmqpInterface
*/
public async createSubscription(event: string, options: SubscriptionOptions = {}) {
options.consumeOptions = Object.assign({
noAck: false
}, options.consumeOptions || {});
2020-09-15 05:58:54 +00:00
// Get the Connection
2020-09-28 19:40:33 +00:00
const _res = await this._createConnection(event, options);
if (_res.created) {
// Extract the Connection
const _connection: IConnection = _res.connection;
// Create a Queue
// It will contain the subscribed Messages.
const _queue = await _connection.channel.assertQueue('', {
exclusive: true
});
// Create an Exchange.
const _exchange = await _connection.channel.assertExchange('event', options.exchangeType || 'topic', options.subscribeOptions);
// Bind the Queue to the Exchange.
_connection.channel.bindQueue(_queue.queue, _exchange.exchange, event);
// Enable Prefetch
if (options.prefetch > 0) {
await _connection.channel.prefetch(options.prefetch);
}
// Update the Send Message.
_connection.send = (data) => {
return _connection.channel.publish(
'event',
event,
Buffer.from(
JSON.stringify(data)
),
{
contentEncoding: 'application/json'
}
);
}
// Store a reference to the original Method
const _delete = _connection.delete;
// Delte additionally the exchange and dynamic queue
_connection.delete = async () => {
// Delte the Queue
await _delete(_queue.queue);
// Delte the Exchange.
await _connection.channel.deleteExchange(_exchange.exchange);
}
const _subscribe = _connection.subscribe;
_connection.subscribe = async () => {
await _subscribe(_queue.queue)
}
}
2020-09-28 19:40:33 +00:00
return _res.connection;
2020-09-12 20:23:55 +00:00
}
2020-09-15 05:58:54 +00:00
protected _logger = getLogger('info', 'AMQP-Interface');
async on(mode: 'queue' | 'subscribe', event: string, cb: (data: any, msg: amqp.Message) => void, options: QueuePublishOptions | SubscriptionOptions = {}) {
2020-09-12 20:23:55 +00:00
// Store the Function
const _set = this._userDefinedCallbacks.get(event) || new Set();
2020-09-12 20:23:55 +00:00
// Add the callback.
_set.add(cb)
// Store the Set.
this._userDefinedCallbacks.set(event, _set);
2020-09-12 20:23:55 +00:00
// Based on the Numbers of Elements which are included in here
// the Queue is subscribed.
if (_set.size === 1) {
let _connection: IConnection;
2020-09-15 05:58:54 +00:00
switch (mode) {
case 'queue':
_connection = await this.createQueue(event, options as QueueSubscribeOptions);
await _connection.subscribe();
2020-09-15 05:58:54 +00:00
break;
case 'subscribe':
_connection = await this.createSubscription(event, options as SubscriptionOptions);
await _connection.subscribe();
2020-09-15 05:58:54 +00:00
break;
}
}
2020-09-12 20:23:55 +00:00
}
public async emit(mode: 'queue' | 'publish', event: string, data: any, options: QueuePublishOptions | SubscriptionOptions = {}): Promise<void> {
const _connection: IConnection = this._connections.get(event);
if (_connection) {
_connection.send(data);
2020-09-12 20:23:55 +00:00
} else {
2020-09-15 05:58:54 +00:00
// No Queue or Subscription is available =>
// Create the corresponding queue / subscription
switch (mode) {
case 'queue':
await this.createQueue(event, options as QueueSubscribeOptions);
2020-09-15 05:58:54 +00:00
break;
case 'publish':
await this.createSubscription(event, options as SubscriptionOptions)
break;
}
// Recall the Method.
await this.emit(mode, event, data, options);
2020-09-12 20:23:55 +00:00
}
}
2020-09-15 05:58:54 +00:00
close(){
this._socket.close();
}
}
/**
* A Communication Layer for the Dispatchers.
* In this Layer AMQP (Rabbit-MQ) is used.
* Functions are matched to Queues.
*
* @export
* @class AmqpLayer
* @implements {ICommunicationInterface}
*/
export class AmqpLayer extends AmqpInterface implements ICommunicationInterface {
2020-11-04 16:39:20 +00:00
async onAurevoir(cb: (dispatcher: string) => void): Promise<void> {
await this.on('subscribe','aurevoir',cb);
}
async emitAurevoir(dispatcher: string): Promise<void> {
await this.emit('publish','aurevoir', dispatcher);
}
async onTaskCancelation(cb: (msg: ITaskCancelationMsg) => void): Promise<void> {
await this.on('subscribe','taskCancelation',cb);
}
async emitTaskCancelation(msg: ITaskCancelationMsg): Promise<void> {
await this.emit('publish','taskCancelation',msg);
}
2020-09-15 05:58:54 +00:00
2020-09-30 06:25:03 +00:00
async emitNewTopicsAvailable(topics: IAvailableTopicsMsg): Promise<void> {
await this.emit('publish','newTopicsAvailable',topics);
}
2020-09-30 06:25:03 +00:00
async onNewTopicsAvailable(cb: (topics: IAvailableTopicsMsg) => void) {
await this.on('subscribe','newTopicsAvailable',cb);
}
2020-09-30 06:25:03 +00:00
async onEvent(event: string, cb: (data: IExternalEventMsg) => void): Promise<void> {
await this.on('subscribe','event.' + event, cb);
}
2020-09-30 06:25:03 +00:00
async offEvent(event: string, cb: (data: IExternalEventMsg) => void): Promise<void> {
await this.off('event.' + event, cb);
}
2020-09-30 06:25:03 +00:00
async emitEvent(event: string, data: IExternalEventMsg): Promise<void> {
await this.emit('publish','event.' + event, data);
}
2020-11-04 16:39:20 +00:00
async emitNewInstanceGeneratorsAvailable(generators: IAvailableInstanceGeneratorsMsg): Promise<void> {
2020-09-30 06:25:03 +00:00
await this.emit('publish', 'newInstanceGeneratorsAvailable', generators)
}
2020-11-04 16:39:20 +00:00
async onNewInstanceGeneratorsAvailable(cb: (generators: IAvailableInstanceGeneratorsMsg) => void) {
2020-09-30 06:25:03 +00:00
await this.on('subscribe', 'newInstanceGeneratorsAvailable', cb);
}
2020-09-30 06:25:03 +00:00
async onBonjour(cb: (dispatcher: string) => void): Promise<void> {
await this.on('subscribe','bonjour', cb);
}
2020-09-30 06:25:03 +00:00
async emitBonjour(dispatcher: string): Promise<void> {
await this.emit('publish', 'bonjour' , dispatcher);
}
subscriptionMode?: "individual" | "generic" = 'individual';
2020-09-15 05:58:54 +00:00
resultSharing?: "individual" | "generic" = 'individual';
protected _tasks = new Map<string, () => void>();
2020-09-30 06:25:03 +00:00
async emitRpcRequest(name: string, request: IRequestTaskMsg): Promise<void> {
await this.emit('queue', name, request, this.generateQueueOptions(name));
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
async emitRpcResult(name: string, result: IResponseTaskMsg): Promise<void> {
2020-09-15 05:58:54 +00:00
// Ackknowlegde, that the Task was sucessfull
if (this._tasks.has(result.taskId)){
// Send the Acknoledgement
this._tasks.get(result.taskId)();
this._tasks.delete(result.taskId);
}
2020-09-30 06:25:03 +00:00
await this.emit('publish', name, result);
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
async onRpcResult(name: string, cb: (result: IResponseTaskMsg) => void): Promise<void> {
await this.on('subscribe', name, cb);
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
async offRpcResponse(name: string, cb: (result: IResponseTaskMsg) => void): Promise<void> {
await this.off(name, cb);
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
async onRpcRequest(name: string, cb: (req: IRequestTaskMsg) => void): Promise<void> {
2020-09-15 05:58:54 +00:00
const _this = this;
2020-09-30 06:25:03 +00:00
await this.on('queue', name, (req: IRequestTaskMsg, msg) => {
2020-09-15 05:58:54 +00:00
_this._logger.debug('Getting new Request ' + req.taskId);
// Define a callback for finished Tasks.
_this._tasks.set(req.taskId, () => {
// Select the corresponding channel
const _channel = _this._connections.get(name).channel;
2020-09-15 05:58:54 +00:00
// Test if the Channel exists
if (_channel) {
_this._logger.debug('Sending Acknowledgement of Request ' + req.taskId);
// Ackknowlegde the Message.
_channel.ack(msg)
}
});
// Perform the Original Callback.
cb(req);
}, this.generateQueueOptions(name));
}
2020-09-30 06:25:03 +00:00
async offRpcRequest(name: string, cb: (data: IRequestTaskMsg) => void): Promise<void> {
await this.off(name, cb);
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
async emitNewServicesAvailable(services: IAvailableServicesMsg): Promise<void> {
await this.emit('publish', 'newServicesAvailable', services)
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
async onNewServicesAvailable(cb: (services: IAvailableServicesMsg) => void) {
await this.on('subscribe', 'newServicesAvailable', cb);
2020-09-15 05:58:54 +00:00
}
protected _logger = getLogger('info', 'AMQP-Event-Layer');
public generateQueueOptions: (name: string) => QueuePublishOptions = (name) => {
2020-09-15 05:58:54 +00:00
return {
consumeOptions: {
2020-09-30 06:25:03 +00:00
noAck: false,
},
subscribeOptions: {
durable: false,
2020-09-15 05:58:54 +00:00
}
2020-09-30 06:25:03 +00:00
} as QueuePublishOptions
2020-09-15 05:58:54 +00:00
}
2020-09-15 05:58:54 +00:00
public generateSubscriptionOptions: (name: string) => SubscriptionOptions = (name) => { return {} }
2020-09-12 20:23:55 +00:00
}