import path from 'path'; import { EventEmitter } from 'events'; import grpc, { ServiceError, status as ServiceErrorStatus } from 'grpc'; import { ApplicationConfiguration, getServiceConfiguration } from './configuration'; import { Transaction } from './transaction'; import { QUEUE_ENTITY_EVENTS } from './queue-entity'; import { loadSync as loadProtoSync } from '@grpc/proto-loader'; import { CreateTransactionPayload, CreateTransactionResponse } from './protos/types/transaction'; const EVENTS = { TRANSACTION_PUBLISH_SUCCESS: Symbol(), TRANSACTION_PUBLISH_ERROR: Symbol(), TRANSACTION_CANCELLED: Symbol(), CONNECTION_CREATED: Symbol(), CONNECTION_CLOSED: Symbol(), }; export const TRANSPORTER_EVENTS = EVENTS; export interface TransactionPublishedPayload { callId: string; transaction: Transaction; } export interface TransactionErrorPayload { callId?: string; reason: string; transaction?: Transaction; } export interface TransactionCancelledPayload { transaction: Transaction; } export interface TransactionErrorPayload { callId?: string; reason: string; metadata?: any; details?: any; transaction?: Transaction; } export interface TransactionTransporter extends EventEmitter { start(): void; stop(): void; push(transaction: Transaction): void; } export class DefaultTransactionTransporter extends EventEmitter implements TransactionTransporter { // Defaults for processing static readonly PROCESS_INTERVAL = 1000; static readonly PROCESS_COUNT = 50; private config: ApplicationConfiguration; private pendingTransactions: Map = new Map(); private processableTransactions: Map = new Map(); private processingTransactions: Map = new Map(); private interval: NodeJS.Timeout | null; private call: grpc.ServerDuplexStream; private client: grpc.Client; private checkCount = 0; get isRunning(): boolean { return !!this.client; } constructor(config: ApplicationConfiguration) { super(); this.config = config; this.interval = null; } public start(): void { if (this.isRunning) { // Dont create a duplicate client if one exists return; } const definition = grpc.loadPackageDefinition( loadProtoSync( `${path.join(__dirname, 'protos')}/transaction.proto`, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true } ) ); const { address, credentials } = getServiceConfiguration(); this.client = new (definition.transaction as any).Transaction(address, credentials); this.createCall(); this.interval = setInterval( this.processList.bind(this), DefaultTransactionTransporter.PROCESS_INTERVAL ); } public stop(): void { if (this.isRunning) { this.client.close(); } clearTimeout(this.interval); } public push(transaction: Transaction): void { this.pendingTransactions.set(transaction.trackingKey, transaction); // Setup transaction movements between queues transaction.once(QUEUE_ENTITY_EVENTS.ENQUEUE, () => { this.removeTransaction(transaction); this.processableTransactions.set(transaction.trackingKey, transaction); }); transaction.once(QUEUE_ENTITY_EVENTS.CANCEL, () => { this.removeTransaction(transaction); this.emit(EVENTS.TRANSACTION_CANCELLED, { transaction, } as TransactionCancelledPayload); }); transaction.on(QUEUE_ENTITY_EVENTS.PROCESS, () => { this.removeTransaction(transaction); this.processTransaction(transaction); }); transaction.on(QUEUE_ENTITY_EVENTS.RETRY, () => { this.removeTransaction(transaction); this.processableTransactions.set(transaction.trackingKey, transaction); }); transaction.once(QUEUE_ENTITY_EVENTS.FINISHED, metadata => { this.removeTransaction(transaction); this.emit(EVENTS.TRANSACTION_PUBLISH_SUCCESS, { ...metadata, transaction } as TransactionPublishedPayload); }); transaction.once(QUEUE_ENTITY_EVENTS.FAILED, metadata => { this.removeTransaction(transaction); this.emit(EVENTS.TRANSACTION_PUBLISH_ERROR, { ...metadata, transaction, } as TransactionErrorPayload); }); } public removeTransaction(transaction: Transaction | CreateTransactionResponse): void { this.pendingTransactions.delete(transaction.trackingKey); this.processableTransactions.delete(transaction.trackingKey); this.processingTransactions.delete(transaction.trackingKey); } private createCall(): void { this.call = (this.client as any).createTransaction(); this.call .on('data', (response: CreateTransactionResponse) => { const transaction = this.processingTransactions.get(response.trackingKey); if (!transaction) { // TODO: Handle case when there is no queued item to find return; } if (response.state.accepted) { // Message was accepted return transaction.published({ callId: response.callId, }); } // If message was not accepted then retry transaction.retry({ callId: response.callId, reason: 'Error occurred during publishing the transaction' // TODO: Read error from the response }); }) .on('error', (err: ServiceError) => { this.emit(EVENTS.TRANSACTION_PUBLISH_ERROR, { reason: err.message, metadata: err.metadata, details: err.details, } as TransactionErrorPayload); // Connection was interrupted, recreate const retriableErrorStatuses = [ ServiceErrorStatus.INTERNAL, ServiceErrorStatus.UNKNOWN, ServiceErrorStatus.CANCELLED, ServiceErrorStatus.DEADLINE_EXCEEDED, ServiceErrorStatus.ABORTED, ServiceErrorStatus.UNAVAILABLE ]; if (retriableErrorStatuses.includes(err.code)) { this.retryAll(); } }) .on('end', () => { // stream closed this.emit(EVENTS.CONNECTION_CLOSED); this.retryAll(); }); } private processTransaction(transaction: Transaction): void { this.processingTransactions.set(transaction.trackingKey, transaction); this.call.write(transaction.toMessage()); } private retryAll(): void { this.createCall(); this.processingTransactions.forEach(transaction => { this.call.write(transaction.toMessage()); }); } private processList(): void { if (process.env.DEBUG_INSTRUMENTATION && (++this.checkCount % 180 === 0)) { console.log(`processing list, processing: ${this.processingTransactions.size}, processable: ${this.processableTransactions.size}, pending: ${this.pendingTransactions.size}`); } let addToProcessingCount = DefaultTransactionTransporter.PROCESS_COUNT - this.processingTransactions.size; for (const transaction of this.processableTransactions.values()) { if (--addToProcessingCount < 1) { break; } transaction.process(); } } }