buffer.service.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // bufferService.ts
  2. import { BehaviorSubject, Observable, Subject, from, map, switchMap } from 'rxjs';
  3. import mongoose, { Connection, Model, Document } from 'mongoose';
  4. import { ConnectionState, Message, MessageLog } from '../interfaces/general.interface';
  5. import { resolve } from 'path';
  6. export class BufferService {
  7. private messageStream: Subject<Message>
  8. // private messageFromApplication: Subject<Message>;
  9. // private messageFromBuffer: Subject<Message>
  10. private connectionState: BehaviorSubject<ConnectionState>
  11. // private currentSource: Subject<Message>
  12. private messageBuffer: Message[] = [];
  13. private messageModel: Model<Message> | undefined;
  14. private readonly dbUrl: string = process.env.MONGO as string;
  15. constructor(
  16. messageFromApp: Subject<Message>,
  17. connectionStateSubject: BehaviorSubject<ConnectionState>,
  18. dbName: string
  19. ) {
  20. this.messageStream = messageFromApp;
  21. // this.messageFromBuffer = new Subject<Message>();
  22. // this.messageFromApplication = messageFromApp;
  23. // this.currentSource = this.messageFromBuffer
  24. this.connectionState = connectionStateSubject;
  25. this.setupSubscriptions(); // Note: The handle buffer will push the data in local array before pushing to mongo via initial check up model
  26. /* Disable for now. Use local array first */
  27. // this.initializeDatabaseConnection(dbName).then((connection: mongoose.Connection) => {
  28. // const grpcMessageSchema = require('../models/message.schema');
  29. // this.messageModel = connection.model<Message>('Message', grpcMessageSchema)
  30. // this.transferLocalBufferToMongoDB() // transfer all data from local array into mongodb after the mongo setup is complete
  31. // }).catch(error => {
  32. // console.error('Database initialization failed:', error);
  33. // // Implement retry logic or additional error handling here
  34. // });
  35. }
  36. public getMessages(): Observable<Message> {
  37. return this.messageStream as Observable<Message>
  38. }
  39. private setupSubscriptions(): void {
  40. this.messageStream.subscribe({
  41. next: (message: Message) => this.handleIncomingMessage(message),
  42. error: (err) => console.error('Error in messageToBePublished subject:', err),
  43. complete: () => console.log('messageToBePublished subscription completed')
  44. });
  45. this.connectionState.subscribe({
  46. next: (state: ConnectionState) => this.handleConnectionStateChanges(state),
  47. error: (err) => console.error('Error in connectionState subject:', err),
  48. complete: () => console.log('connectionState subscription completed')
  49. });
  50. }
  51. private async initializeDatabaseConnection(dbName: string): Promise<Connection> {
  52. try {
  53. console.log(`${this.dbUrl}${dbName}`)
  54. const connection: mongoose.Connection = await mongoose.createConnection(`${this.dbUrl}${dbName}`);
  55. console.log(`Connected to ${this.dbUrl}${dbName}`)
  56. return connection;
  57. } catch (error) {
  58. console.error('Error connecting to MongoDB:', error);
  59. throw error;
  60. }
  61. }
  62. private handleIncomingMessage(message: Message): void {
  63. if (this.connectionState.getValue().status === 'BUFFER') {
  64. this.bufferMessage(message);
  65. }
  66. if (this.connectionState.getValue().status === 'DIRECT_PUBLISH') {
  67. // console.log(`There is ${this.messageBuffer.length} messages in the buffer`) // somehw this is called repeatedly
  68. // do nothing for now
  69. // Start releasing buffered messages, but don't wait for it to complete
  70. // this.isBufferNotEmpty().then(isNotEmpty => {
  71. // if (isNotEmpty) {
  72. // // this.releaseBufferedMessages(this.messageFromBuffer);
  73. // // Continue to buffer new incoming message during the release process
  74. // this.bufferMessage(message);
  75. // } else {
  76. // // If buffer is empty, switch source and handle the message directly
  77. // this.messageToBePublished.next(message); // Handle the message directly
  78. // }
  79. // });
  80. }
  81. }
  82. private handleConnectionStateChanges(state: ConnectionState): void {
  83. console.log(this.connectionState.getValue().status)
  84. if (state.status === 'BUFFER') {
  85. if (state.payload && typeof state.payload !== 'string') {
  86. this.bufferMessage(state.payload); // Buffer the last message immediately
  87. }
  88. }
  89. if (state.status === 'DIRECT_PUBLISH') {
  90. this.releaseBufferedMessages(this.messageStream)
  91. /* This is for mongo */
  92. // this.isBufferNotEmpty().then(isNotEmpty => {
  93. // if (isNotEmpty) {
  94. // this.currentMessageSource = this.messageFromBuffer
  95. // } else {
  96. // this.currentMessageSource = this.messageToBePublished
  97. // }
  98. // })
  99. }
  100. }
  101. private async isBufferNotEmpty(): Promise<boolean> {
  102. if (this.messageModel) {
  103. // Check the count in MongoDB
  104. const count = await this.messageModel.estimatedDocumentCount().exec();
  105. return count > 0;
  106. } else {
  107. // Check the local buffer
  108. return this.messageBuffer.length > 0;
  109. }
  110. }
  111. private async bufferMessage(message: Message): Promise<void> {
  112. if (this.messageModel) {
  113. try {
  114. // const newMessage = new this.messageModel(message);
  115. await this.messageModel.create(message);
  116. console.log(`Message${(message.message as MessageLog).appData.msgId} saved to MongoDB buffer`);
  117. } catch (error) {
  118. console.error('Error saving message to MongoDB:', error);
  119. // Implement retry logic or additional error handling here
  120. }
  121. } else {
  122. this.messageBuffer.push(message); // Fallback to local buffer if model is not defined
  123. console.log(`pushing ${(message.message as MessageLog).appData.msgId} into local array buffer.... There is now ${this.messageBuffer.length} messages`)
  124. }
  125. }
  126. private releaseBufferedMessages(messageFromBuffer: Subject<Message>): Promise<boolean> {
  127. return new Promise((resolve, reject) => {
  128. if (this.messageModel) {
  129. const stream = this.messageModel.find().cursor();
  130. stream.on('data', async (message) => {
  131. // Process each message individually
  132. messageFromBuffer.next(message);
  133. });
  134. stream.on('error', (error) => {
  135. console.error('Error streaming messages from MongoDB:', error);
  136. reject(error)
  137. });
  138. stream.on('end', async () => {
  139. // Delete the data once it has been streamed
  140. try {
  141. if (this.messageModel) {
  142. await this.messageModel.deleteMany({});
  143. console.log('Data in Mongo deleted successfully.');
  144. } else {
  145. console.log(`Message Mongoose Model is not intiated properly...`)
  146. }
  147. } catch (err) {
  148. console.error('Error deleting data:', err);
  149. }
  150. resolve(true)
  151. });
  152. }
  153. if (!this.messageModel) {
  154. // If MongoDB model is not defined, use the local buffer
  155. console.log(`Releasing buffer Message: currently there is ${this.messageBuffer.length} messages to be released`)
  156. this.messageBuffer.forEach(message => this.messageStream.next(message));
  157. this.messageBuffer.length = 0 // Clear the local buffer after transferring
  158. if (this.messageBuffer.length < 1) {
  159. resolve(true)
  160. } else {
  161. reject(`Somehow the array is not emptied. This should not happen`)
  162. }
  163. }
  164. })
  165. }
  166. public getStateObservable(): BehaviorSubject<ConnectionState> {
  167. return this.connectionState;
  168. }
  169. private async transferLocalBufferToMongoDB(): Promise<void> {
  170. if (this.messageModel) {
  171. this.messageBuffer.forEach(async message => {
  172. try {
  173. if (this.messageModel) {
  174. await this.messageModel.create(message);
  175. }
  176. } catch (error) {
  177. console.error('Error transferring message to MongoDB:', error);
  178. }
  179. })
  180. this.messageBuffer = []; // Clear local buffer after transferring
  181. }
  182. }
  183. // Additional methods as required...
  184. }