grpc.service.method.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import * as grpc from '@grpc/grpc-js';
  2. import { Subject, Subscription } from "rxjs";
  3. import { Message, ConnectionAttribute, ConnectionRequest, GrpcConnectionType, ConnectionState, MessageLog, State, OutGoingInfo } from "../interfaces/general.interface";
  4. import { Status } from '@grpc/grpc-js/build/src/constants';
  5. import { message_proto } from './protos/server.proto'
  6. import { ServerWritableStreamImpl } from '@grpc/grpc-js/build/src/server-call';
  7. export class GrpcServiceMethod {
  8. private server: grpc.Server | any
  9. private messageToBeSendOver: Message | any
  10. private clientInfo: any[] = []
  11. // private callRequestsFromRemote: ServerWritableStreamImpl<any, ResponseType>[] = []
  12. public async create(request: ConnectionRequest, connectionAttribute: ConnectionAttribute, outGoingInfo: OutGoingInfo): Promise<any> {
  13. // Assuming currently only one client
  14. this.createGrpcInstance(request.server.serverUrl, { instanceType: 'server' }, connectionAttribute, outGoingInfo)
  15. this.createGrpcInstance(request.client.targetServer, { instanceType: 'client' }, connectionAttribute, outGoingInfo)
  16. }
  17. private async generateAdditionalAttributes(connectionAttribute: ConnectionAttribute, clientInfo?: any, localInfo?: any) {
  18. if (clientInfo) {
  19. connectionAttribute.inComing.StreamID = clientInfo.StreamID
  20. connectionAttribute.inComing.PublisherID = clientInfo.PublisherID
  21. connectionAttribute.inComing.SubscriberID = clientInfo.SubscriberID
  22. }
  23. if (localInfo) {
  24. connectionAttribute.outGoing.StreamID = localInfo.StreamID
  25. connectionAttribute.outGoing.PublisherID = localInfo.PublisherID
  26. connectionAttribute.outGoing.SubscriberID = localInfo.SubscriberID
  27. }
  28. if (connectionAttribute.outGoing.StreamID && connectionAttribute.inComing.StreamID) {
  29. connectionAttribute.ConnectionID.local = connectionAttribute.outGoing.StreamID + connectionAttribute.inComing.StreamID
  30. connectionAttribute.ConnectionID.remote = connectionAttribute.inComing.StreamID + connectionAttribute.outGoing.StreamID
  31. }
  32. }
  33. private async createGrpcInstance(
  34. serverUrl: string,
  35. grpcType: GrpcConnectionType,
  36. connectionAttribute: ConnectionAttribute,
  37. outGoingInfo: OutGoingInfo
  38. ) {
  39. while (true) {
  40. try {
  41. let recreatePromise = new Promise((resolve) => {
  42. if (grpcType.instanceType == 'server') {
  43. this.createServerStreamingServer(serverUrl, connectionAttribute).then(() => {
  44. resolve('recreate')
  45. })
  46. }
  47. if (grpcType.instanceType == 'client') {
  48. this.createServerStreamingClient(serverUrl, connectionAttribute, outGoingInfo).then(() => {
  49. resolve('recreate')
  50. })
  51. }
  52. })
  53. await recreatePromise
  54. } catch (error) {
  55. console.error('Connection attempt failed:', error);
  56. }
  57. await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before the next attempt
  58. // timeout generate message to trigger this reconnection
  59. }
  60. }
  61. // Create Server Instance to stream all application Outgoing messages
  62. public async createServerStreamingServer(
  63. serverUrl: string,
  64. connectionAttribute: ConnectionAttribute
  65. ): Promise<any> { // '0.0.0.0:3001'
  66. return new Promise((resolve, reject) => {
  67. try {
  68. if (!this.server) {
  69. this.server = new grpc.Server()
  70. } else {
  71. console.log(`Grpc server alrady started.`) // this kept calling, that means this function is resolving on it's own, prompting the reconnection logic
  72. }
  73. this.server.addService(message_proto.Message.service, {
  74. HandleMessage: (call) => {
  75. let clientInfo = JSON.parse(call.request.message)
  76. this.clientInfo.push(clientInfo)
  77. // this.generateAdditionalAttributes(connectionAttribute, clientInfo)
  78. console.log(`Initializing stream. Opening Channel... Confirmation from ${call.request.id}`)
  79. if (connectionAttribute.outGoing.MessageToBePublished) {
  80. let subscription: Subscription = connectionAttribute.outGoing.MessageToBePublished.subscribe({
  81. next: (response: Message) => {
  82. console.log(`Sending from GRPC server: ${(response.message as MessageLog).appData.msgId} `)
  83. let message = {
  84. id: response.id,
  85. message: JSON.stringify(response.message)
  86. }
  87. call.write(message)
  88. },
  89. error: err => {
  90. console.error(err)
  91. subscription.unsubscribe()
  92. resolve('')
  93. },
  94. complete: () => {
  95. console.log(`Stream response completed for ${call.request.id}`)
  96. subscription.unsubscribe()
  97. resolve('')
  98. }
  99. })
  100. console.log(connectionAttribute)
  101. let report: ConnectionState = {
  102. status: 'DIRECT_PUBLISH'
  103. }
  104. connectionAttribute.connectionStatus.next(report)
  105. }
  106. },
  107. Check: (_, callback) => {
  108. // for now it is just sending the status message over to tell the client it is alive
  109. // For simplicity, always return "SERVING" as status
  110. callback(null, { status: 'SERVING' });
  111. },
  112. });
  113. // Bind and start the server
  114. this.server.bindAsync(serverUrl, grpc.ServerCredentials.createInsecure(), () => {
  115. console.log(`gRPC server is running on ${serverUrl}`);
  116. this.server.start();
  117. });
  118. }
  119. catch (error) {
  120. resolve(error)
  121. }
  122. })
  123. }
  124. // Send a request over to the other server to open a channel for this server to emit/stream messages over
  125. public async createServerStreamingClient(
  126. server: string,
  127. connectionAttribute: ConnectionAttribute,
  128. outGoingInfo: OutGoingInfo
  129. ): Promise<string> {
  130. return new Promise(async (resolve, reject) => {
  131. const client = new message_proto.Message(server, grpc.credentials.createInsecure());
  132. this.generateAdditionalAttributes(connectionAttribute, {}, outGoingInfo)
  133. let call = client.HandleMessage({ id: server, message: JSON.stringify(outGoingInfo) })
  134. console.log(`Sending request to ${server} to open response channel...`)
  135. call.on('status', (status: Status) => {
  136. if (status == grpc.status.OK) { // only returns a status when there's error. Otherwise it just waits
  137. console.log(`Message trasmission operation is successful`)
  138. // RPC completed successfully
  139. } if (status == grpc.status.UNAVAILABLE) {
  140. let report: ConnectionState = {
  141. status: 'BUFFER',
  142. reason: `Server doesn't seem to be alive. Error returned.`,
  143. payload: this.messageToBeSendOver ?? `There's no message at the moment...`
  144. }
  145. connectionAttribute.connectionStatus.next(report)
  146. resolve('No connection established. Server is not responding..')
  147. }
  148. });
  149. call.on('data', (data: any) => {
  150. let response: Message = {
  151. id: data.id,
  152. message: JSON.parse(data.message)
  153. }
  154. if (connectionAttribute.inComing.MessageToBeReceived) {
  155. connectionAttribute.inComing.MessageToBeReceived.next(response)
  156. }
  157. });
  158. call.on('error', (err) => {
  159. console.error(err)
  160. resolve('')
  161. });
  162. })
  163. }
  164. // THis is no longer necesarry after the introduction of connection Attribute. But it is still useful for checking for the other side's health
  165. public async checkConnectionHealth(client: any, statusControl: Subject<ConnectionState>, alreadyHealthCheck: boolean): Promise<boolean> {
  166. return new Promise((resolve, reject) => {
  167. client.Check({}, (error, response) => {
  168. if (response) {
  169. console.log(`GRPC Health check status: ${response.status} Server Connected`);
  170. // Intepret the response status and implement code logic or handler
  171. resolve(response.status)
  172. } else {
  173. if (alreadyHealthCheck == false) console.error(`Health check failed: ${error}`);
  174. reject(false)
  175. }
  176. })
  177. })
  178. }
  179. }
  180. // https://github.com/grpc/proposal/blob/master/L5-node-client-interceptors.md