grpc.service.method.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import * as grpc from '@grpc/grpc-js';
  2. import { Observable, Subject, Subscription } from "rxjs";
  3. import { Message, ConnectionAttribute, GrpcConnectionType, ConnectionState, StreamAttribute, MessageLog } from "../interfaces/general.interface";
  4. import { Status } from '@grpc/grpc-js/build/src/constants';
  5. import { message_proto } from './protos/server.proto'
  6. import * as _ from 'lodash'
  7. export class GrpcServiceMethod {
  8. private connectionAttribute: ConnectionAttribute | undefined
  9. private connectionAttributes: ConnectionAttribute[] = []
  10. private server: grpc.Server | any
  11. private messageToBeSendOver: Message | any
  12. private clientRequest: Subject<ConnectionAttribute> = new Subject()
  13. // public interface for service client to establish connection. They will give server and client information as a pair
  14. public async create(connectionAttribute: ConnectionAttribute, connectionAttributes: ConnectionAttribute[]): Promise<any> {
  15. this.connectionAttribute = connectionAttribute
  16. this.connectionAttributes = connectionAttributes
  17. return new Promise((resolve, reject) => {
  18. this.createGrpcInstance({ instanceType: 'server' }, connectionAttribute)
  19. this.createGrpcInstance({ instanceType: 'client' }, connectionAttribute)
  20. resolve('Just putting it here for now....')
  21. })
  22. }
  23. private async createGrpcInstance(grpcType: GrpcConnectionType, connectionAttribute: ConnectionAttribute) {
  24. // Reconnection Logic
  25. while (true) {
  26. try {
  27. let recreatePromise = new Promise((resolve) => {
  28. if (grpcType.instanceType == 'server' && !this.server) {
  29. this.createServerStreamingServer().then(() => {
  30. resolve('recreate')
  31. })
  32. }
  33. if (grpcType.instanceType == 'client') {
  34. this.createServerStreamingClient(connectionAttribute).then(() => {
  35. resolve('recreate')
  36. })
  37. }
  38. })
  39. await recreatePromise
  40. } catch (error) {
  41. console.error('Connection attempt failed:', error);
  42. }
  43. await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second before the next attempt
  44. // timeout generate message to trigger this reconnection
  45. }
  46. }
  47. // Create Server Instance to stream all application Outgoing messages
  48. public async createServerStreamingServer(): Promise<any> { // '0.0.0.0:3001'
  49. return new Promise((resolve, reject) => {
  50. this.server = new grpc.Server()
  51. this.server.addService(message_proto.Message.service, {
  52. HandleMessage: (call) => {
  53. let clientRequest: ConnectionAttribute = JSON.parse(call.request.message)
  54. // client Request validation
  55. if (this.isConnectionAttribute(clientRequest)) {
  56. // Check if this connection exists
  57. let result: ConnectionAttribute | undefined = this.connectionAttributes.find((connectionAttribute: ConnectionAttribute) => connectionAttribute.ConnectionID.local === clientRequest.ConnectionID.remote)
  58. if (result) {
  59. // if exist, reassign back the buffer
  60. let subscription: Subscription = result.outGoing.MessageToBePublished!.subscribe({
  61. next: (outGoingMessage: Message) => {
  62. let message = {
  63. id: outGoingMessage.id,
  64. message: JSON.stringify(outGoingMessage.message)
  65. }
  66. console.log(`Sending ${(outGoingMessage.message as MessageLog).appData.msgId} to ${clientRequest.outGoing.PublisherID}`)
  67. call.write(message)
  68. },
  69. error: err => {
  70. console.error(err)
  71. subscription.unsubscribe()
  72. resolve(``)
  73. },
  74. complete: () => {
  75. subscription.unsubscribe()
  76. resolve(``)
  77. }
  78. })
  79. let report: ConnectionState = {
  80. status: `DIRECT_PUBLISH`
  81. }
  82. result.connectionStatus!.next(report)
  83. }
  84. if (!result) {
  85. console.log(`No matching results.... leaving the logic blank for now...`)
  86. /* Currently haven't thought of a solution for this. Even if i do , the simplest one
  87. woul be to assisgn a new buffer, which means the server client service will
  88. have to instantiate a new one for the incoming new client. Right now, there
  89. is no need since the amount of clients and their ID are predetermined.
  90. TO be discuseed further. */
  91. }
  92. }
  93. }
  94. })
  95. this.server.bindAsync(this.connectionAttribute!.outGoing.serverUrl, grpc.ServerCredentials.createInsecure(), () => {
  96. console.log(`gRPC server is running on ${this.connectionAttribute?.outGoing.serverUrl}`)
  97. this.server.start()
  98. })
  99. })
  100. }
  101. // Send a request over to the other server to open a channel for this server to emit/stream messages over
  102. public async createServerStreamingClient(connectionAttribute: ConnectionAttribute): Promise<string> {
  103. return new Promise(async (resolve, reject) => {
  104. const client = new message_proto.Message(connectionAttribute.inComing.serverUrl, grpc.credentials.createInsecure());
  105. let localInfo: ConnectionAttribute = { // need to make a new copy where it doesn't reference the subjects, otherwise circular ref error
  106. ConnectionID: connectionAttribute.ConnectionID,
  107. outGoing: {
  108. StreamID: connectionAttribute.outGoing.StreamID,
  109. PublisherID: connectionAttribute.outGoing.PublisherID,
  110. SubscriberID: connectionAttribute.outGoing.SubscriberID,
  111. serverUrl: connectionAttribute.outGoing.serverUrl,
  112. MessageToBePublished: null,
  113. MessageToBeReceived: null
  114. },
  115. inComing: {
  116. StreamID: connectionAttribute.inComing.StreamID,
  117. PublisherID: connectionAttribute.inComing.PublisherID,
  118. SubscriberID: connectionAttribute.inComing.SubscriberID,
  119. serverUrl: connectionAttribute.inComing.serverUrl,
  120. MessageToBePublished: null,
  121. MessageToBeReceived: null
  122. },
  123. connectionStatus: null
  124. }
  125. let call = client.HandleMessage({ id: connectionAttribute.inComing.serverUrl, message: JSON.stringify(localInfo) })
  126. console.log(`Sending request to ${connectionAttribute.inComing.serverUrl} to open response channel...`)
  127. call.on('status', (status: Status) => {
  128. if (status == grpc.status.OK) { // only returns a status when there's error. Otherwise it just waits
  129. console.log(`Message trasmission operation is successful`)
  130. // RPC completed successfully
  131. } if (status == grpc.status.UNAVAILABLE) {
  132. let report: ConnectionState = {
  133. status: 'BUFFER',
  134. reason: `Server doesn't seem to be alive. Error returned.`,
  135. payload: this.messageToBeSendOver ?? `There's no message at the moment...`
  136. }
  137. connectionAttribute.connectionStatus!.next(report)
  138. let clientStatusUpdateInfo: any = {
  139. connectionStatus: 'OFF',
  140. connectionID: connectionAttribute.ConnectionID.remote,
  141. message: `${connectionAttribute.outGoing.serverUrl} started.`
  142. }
  143. this.clientRequest.next(clientStatusUpdateInfo)
  144. resolve('No connection established. Server is not responding..')
  145. }
  146. });
  147. call.on('data', (data: any) => {
  148. let response: Message = {
  149. id: data.id,
  150. message: JSON.parse(data.message)
  151. }
  152. if (connectionAttribute.inComing.MessageToBeReceived) {
  153. connectionAttribute.inComing.MessageToBeReceived.next(response)
  154. }
  155. });
  156. call.on('error', (err) => {
  157. console.error(err)
  158. resolve('')
  159. });
  160. })
  161. }
  162. // TO check or validate if the client request meets the criteria
  163. private isConnectionAttribute(obj: any): obj is ConnectionAttribute {
  164. const isMatch = (
  165. typeof obj.ConnectionID === 'object' && // Further checks can be added based on the structure of ConnectionID
  166. isStreamAttribute(obj.outGoing) &&
  167. isStreamAttribute(obj.inComing) &&
  168. (obj.connectionStatus === null || obj.connectionStatus instanceof Subject)
  169. );
  170. if (isMatch) {
  171. console.log('gRPC client call matches ConnectionAttribute type');
  172. } else {
  173. console.log('gRPC client call does not match ConnectionAttribute type');
  174. }
  175. return isMatch;
  176. function isStreamAttribute(obj: any): obj is StreamAttribute {
  177. return (
  178. (typeof obj.StreamID === 'string' || obj.StreamID === undefined) &&
  179. (typeof obj.PublisherID === 'string' || obj.PublisherID === undefined) &&
  180. (typeof obj.SubscriberID === 'string' || obj.SubscriberID === undefined) &&
  181. // Check other properties like PublisherInstance and SubscriberInstance based on their expected types
  182. (typeof obj.serverUrl === 'string' || obj.serverUrl === undefined) &&
  183. // Check connectionState based on its type, assuming it's an enum or similar
  184. (obj.MessageToBePublished === null || obj.MessageToBePublished instanceof Observable) &&
  185. (obj.MessageToBeReceived === null || obj.MessageToBeReceived instanceof Subject)
  186. );
  187. }
  188. }
  189. }