server-client.service.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import { BehaviorSubject, Subject } from 'rxjs';
  2. import { ClientRequest, ConnectionAttribute, ConnectionRequest, ConnectionState, Message, ServerRequest, State } from '../interfaces/general.interface';
  3. import { GrpcServiceMethod } from './grpc.service.method';
  4. import { BufferService } from './buffer.service';
  5. import * as dotenv from 'dotenv'
  6. import * as _ from 'lodash'
  7. dotenv.config()
  8. export class ServerClientManager {
  9. private connectionAttributes: ConnectionAttribute[] = []
  10. private grpcService: GrpcServiceMethod = new GrpcServiceMethod()
  11. private defaultServerAttribute: ServerRequest = {
  12. name: 'Default - Server',
  13. serverUrl: "localhost:3000",
  14. connectionType: 'GRPC',
  15. messageToBePublishedFromApplication: new Subject<Message>()
  16. }
  17. private defaultClientAttribute: ClientRequest = {
  18. name: 'Default - Client',
  19. targetServer: "localhost:3001",
  20. connectionType: 'GRPC',
  21. messageToBeReceivedFromRemote: new Subject<Message>()
  22. }
  23. constructor() {
  24. }
  25. public async generateConnection(request: ConnectionRequest): Promise<any> {
  26. return new Promise(async (resolve, reject) => {
  27. let initialReport: ConnectionState
  28. let reportSubject: BehaviorSubject<ConnectionState>
  29. let retransmission: BufferService
  30. let errorString: string
  31. let originalRequest = _.cloneDeep(request)
  32. let database: string
  33. let response: any = { message: `Fail to complete connection generation` }
  34. let statusChain: State = 1
  35. let connectionAttribute: ConnectionAttribute
  36. if (statusChain == 1) {
  37. if (!request.server) {
  38. request.server = this.defaultServerAttribute
  39. }
  40. if (!request.client) {
  41. request.client = this.defaultClientAttribute
  42. }
  43. if (request.database) {
  44. database = request.database
  45. } else {
  46. database = request.server.name + request.client.name
  47. }
  48. /* Inject retransmission here */
  49. initialReport = { status: 'BUFFER' }
  50. reportSubject = new BehaviorSubject(initialReport)
  51. retransmission = new BufferService(request.server.messageToBePublishedFromApplication, reportSubject, database)
  52. }
  53. if (statusChain == 1) {
  54. // Connection Type checking
  55. if (request.server!.connectionType != request.client!.connectionType) {
  56. statusChain = -1
  57. errorString = "Connection Type DOES NOT MATCH!"
  58. } else {
  59. statusChain = 1
  60. }
  61. }
  62. if (statusChain == 1) {
  63. connectionAttribute = {
  64. ConnectionID: {
  65. local: request.server!.name + request.client!.name,
  66. remote: request.client!.name + request.server!.name
  67. },
  68. outGoing: {
  69. StreamID: request.server!.name,
  70. PublisherID: request.server!.name,
  71. SubscriberID: request.server!.name,
  72. serverUrl: request.server?.serverUrl,
  73. connectionState: `OFF`,
  74. MessageToBePublished: retransmission!.getMessages(),
  75. MessageToBeReceived: null
  76. },
  77. inComing: {
  78. StreamID: request.client!.name,
  79. PublisherID: request.client!.name,
  80. SubscriberID: request.client!.name,
  81. serverUrl: request.client?.targetServer,
  82. connectionState: `OFF`,
  83. MessageToBePublished: null,
  84. MessageToBeReceived: request.client!.messageToBeReceivedFromRemote
  85. },
  86. connectionStatus: reportSubject!
  87. }
  88. }
  89. if (statusChain == 1) {
  90. await this.checkConnectionAttribute(connectionAttribute!).then((res) => {
  91. if (res == true) {
  92. console.log(`Connection<${connectionAttribute.ConnectionID.local}> already exists `)
  93. }
  94. if (res == false) {
  95. this.connectionAttributes.push(connectionAttribute)
  96. console.log(`Connection ${connectionAttribute.ConnectionID.local} registered...`)
  97. }
  98. console.log(`There is now ${this.connectionAttributes.length} connection Attributes`)
  99. })
  100. }
  101. if (statusChain == 1) {
  102. // This is default connection`
  103. if (!request.client!.connectionType) {
  104. request.client!.connectionType = 'GRPC'
  105. }
  106. // For each connection type:
  107. if (request.client!.connectionType == 'GRPC') {
  108. this.grpcServerStatusHandler()
  109. this.grpcClientStatusHandler()
  110. this.grpcService.create(connectionAttribute!).then(() => {
  111. // logic here
  112. }).catch(() => {
  113. errorString = `Something wrong with gRPC methods`
  114. statusChain = -1
  115. })
  116. }
  117. }
  118. if (statusChain == 1) {
  119. response = {
  120. message: "Channel Response",
  121. requestedTo: originalRequest,
  122. data: connectionAttribute!
  123. }
  124. resolve(response);
  125. } else if (statusChain == -1) {
  126. response = {
  127. message: "Channel Response Error",
  128. requestedTo: originalRequest,
  129. data: errorString! // put error string here
  130. }
  131. resolve(response);
  132. }
  133. })
  134. }
  135. private async checkConnectionAttribute(connectionAttribute: ConnectionAttribute): Promise<boolean> {
  136. return new Promise((resolve) => {
  137. let result: boolean = this.connectionAttributes.some(connection =>
  138. connection.ConnectionID.local === connectionAttribute.ConnectionID.local
  139. );
  140. resolve(result);
  141. });
  142. }
  143. private grpcServerStatusHandler() {
  144. this.grpcService.getLocalServerStatus().subscribe({
  145. next: (notification: any) => {
  146. if (notification.connectionStatus === `ON`) {
  147. let connectionAttribute = this.connectionAttributes.find(connection => connection.ConnectionID.local == notification.connectionIDlocal)
  148. if (connectionAttribute) {
  149. connectionAttribute.outGoing.connectionState = 'ON'
  150. console.log(`Connection ${notification.connectionIDlocal} updated`)
  151. } else {
  152. console.log(`Connection ${notification.connectionIDlocal} attribute is not found.`)
  153. }
  154. }
  155. },
  156. error: err => console.error(err),
  157. complete: () => { }
  158. })
  159. }
  160. private grpcClientStatusHandler() {
  161. this.grpcService.getClientRequest().subscribe({
  162. next: (clientConnectionAttribute: ConnectionAttribute) => {
  163. console.log(`Received a request from ${clientConnectionAttribute.outGoing.serverUrl}`)
  164. let connectionAttribute = this.connectionAttributes.find(connection => connection.ConnectionID.remote == clientConnectionAttribute.ConnectionID.local)
  165. if (connectionAttribute) {
  166. console.log(`Connection ${clientConnectionAttribute.ConnectionID.local} updated`)
  167. connectionAttribute.inComing.connectionState = 'ON'
  168. } else {
  169. console.log(`Connection Attribut ${clientConnectionAttribute.inComing.PublisherID} is not found`)
  170. }
  171. },
  172. error: err => console.error(err),
  173. complete: () => { }
  174. })
  175. }
  176. }