import * as grpc from '@grpc/grpc-js'; import { Subject, Subscription } from "rxjs"; import { Message, ConnectionAttribute, ConnectionRequest, GrpcConnectionType, ConnectionState, MessageLog, State, OutGoingInfo } from "../interfaces/general.interface"; import { Status } from '@grpc/grpc-js/build/src/constants'; import { message_proto } from './protos/server.proto' import { ServerWritableStreamImpl } from '@grpc/grpc-js/build/src/server-call'; export class GrpcServiceMethod { private server: grpc.Server | any private messageToBeSendOver: Message | any private clientInfo: any[] = [] // private callRequestsFromRemote: ServerWritableStreamImpl[] = [] public async create(request: ConnectionRequest, connectionAttribute: ConnectionAttribute, outGoingInfo: OutGoingInfo): Promise { // Assuming currently only one client this.createGrpcInstance(request.server.serverUrl, { instanceType: 'server' }, connectionAttribute, outGoingInfo) this.createGrpcInstance(request.client.targetServer, { instanceType: 'client' }, connectionAttribute, outGoingInfo) } private async generateAdditionalAttributes(connectionAttribute: ConnectionAttribute, clientInfo?: any, localInfo?: any) { if (clientInfo) { connectionAttribute.inComing.StreamID = clientInfo.StreamID connectionAttribute.inComing.PublisherID = clientInfo.PublisherID connectionAttribute.inComing.SubscriberID = clientInfo.SubscriberID } if (localInfo) { connectionAttribute.outGoing.StreamID = localInfo.StreamID connectionAttribute.outGoing.PublisherID = localInfo.PublisherID connectionAttribute.outGoing.SubscriberID = localInfo.SubscriberID } if (connectionAttribute.outGoing.StreamID && connectionAttribute.inComing.StreamID) { connectionAttribute.ConnectionID.local = connectionAttribute.outGoing.StreamID + connectionAttribute.inComing.StreamID connectionAttribute.ConnectionID.remote = connectionAttribute.inComing.StreamID + connectionAttribute.outGoing.StreamID } } private async createGrpcInstance( serverUrl: string, grpcType: GrpcConnectionType, connectionAttribute: ConnectionAttribute, outGoingInfo: OutGoingInfo ) { while (true) { try { let recreatePromise = new Promise((resolve) => { if (grpcType.instanceType == 'server') { this.createServerStreamingServer(serverUrl, connectionAttribute).then(() => { resolve('recreate') }) } if (grpcType.instanceType == 'client') { this.createServerStreamingClient(serverUrl, connectionAttribute, outGoingInfo).then(() => { resolve('recreate') }) } }) await recreatePromise } catch (error) { console.error('Connection attempt failed:', error); } await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before the next attempt // timeout generate message to trigger this reconnection } } // Create Server Instance to stream all application Outgoing messages public async createServerStreamingServer( serverUrl: string, connectionAttribute: ConnectionAttribute ): Promise { // '0.0.0.0:3001' return new Promise((resolve, reject) => { try { if (!this.server) { this.server = new grpc.Server() } else { console.log(`Grpc server alrady started.`) // this kept calling, that means this function is resolving on it's own, prompting the reconnection logic } this.server.addService(message_proto.Message.service, { HandleMessage: (call) => { let clientInfo = JSON.parse(call.request.message) this.clientInfo.push(clientInfo) // this.generateAdditionalAttributes(connectionAttribute, clientInfo) console.log(`Initializing stream. Opening Channel... Confirmation from ${call.request.id}`) if (connectionAttribute.outGoing.MessageToBePublished) { let subscription: Subscription = connectionAttribute.outGoing.MessageToBePublished.subscribe({ next: (response: Message) => { console.log(`Sending from GRPC server: ${(response.message as MessageLog).appData.msgId} `) let message = { id: response.id, message: JSON.stringify(response.message) } call.write(message) }, error: err => { console.error(err) subscription.unsubscribe() resolve('') }, complete: () => { console.log(`Stream response completed for ${call.request.id}`) subscription.unsubscribe() resolve('') } }) console.log(connectionAttribute) let report: ConnectionState = { status: 'DIRECT_PUBLISH' } connectionAttribute.connectionStatus.next(report) } }, Check: (_, callback) => { // for now it is just sending the status message over to tell the client it is alive // For simplicity, always return "SERVING" as status callback(null, { status: 'SERVING' }); }, }); // Bind and start the server this.server.bindAsync(serverUrl, grpc.ServerCredentials.createInsecure(), () => { console.log(`gRPC server is running on ${serverUrl}`); this.server.start(); }); } catch (error) { resolve(error) } }) } // Send a request over to the other server to open a channel for this server to emit/stream messages over public async createServerStreamingClient( server: string, connectionAttribute: ConnectionAttribute, outGoingInfo: OutGoingInfo ): Promise { return new Promise(async (resolve, reject) => { const client = new message_proto.Message(server, grpc.credentials.createInsecure()); this.generateAdditionalAttributes(connectionAttribute, {}, outGoingInfo) let call = client.HandleMessage({ id: server, message: JSON.stringify(outGoingInfo) }) console.log(`Sending request to ${server} to open response channel...`) call.on('status', (status: Status) => { if (status == grpc.status.OK) { // only returns a status when there's error. Otherwise it just waits console.log(`Message trasmission operation is successful`) // RPC completed successfully } if (status == grpc.status.UNAVAILABLE) { let report: ConnectionState = { status: 'BUFFER', reason: `Server doesn't seem to be alive. Error returned.`, payload: this.messageToBeSendOver ?? `There's no message at the moment...` } connectionAttribute.connectionStatus.next(report) resolve('No connection established. Server is not responding..') } }); call.on('data', (data: any) => { let response: Message = { id: data.id, message: JSON.parse(data.message) } if (connectionAttribute.inComing.MessageToBeReceived) { connectionAttribute.inComing.MessageToBeReceived.next(response) } }); call.on('error', (err) => { console.error(err) resolve('') }); }) } // THis is no longer necesarry after the introduction of connection Attribute. But it is still useful for checking for the other side's health public async checkConnectionHealth(client: any, statusControl: Subject, alreadyHealthCheck: boolean): Promise { return new Promise((resolve, reject) => { client.Check({}, (error, response) => { if (response) { console.log(`GRPC Health check status: ${response.status} Server Connected`); // Intepret the response status and implement code logic or handler resolve(response.status) } else { if (alreadyHealthCheck == false) console.error(`Health check failed: ${error}`); reject(false) } }) }) } } // https://github.com/grpc/proposal/blob/master/L5-node-client-interceptors.md