buffer.service.ts 8.9 KB

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