buffer.service.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // bufferService.ts
  2. import { BehaviorSubject, Observable, Subject, from } from "rxjs";
  3. import mongoose, { Connection, Model } from "mongoose";
  4. import { ConnectionState, Message, MessageLog, } from "../interfaces/general.interface";
  5. export class BufferService {
  6. private bufferIdentifier!: string
  7. private messageStream: Subject<Message>;
  8. private connectionState: BehaviorSubject<ConnectionState>;
  9. private messageBuffer: Message[] = [];
  10. private messageModel!: Model<Message>
  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.bufferIdentifier = dbName
  18. this.messageStream = messageFromApp;
  19. this.connectionState = connectionStateSubject;
  20. this.setupSubscriptions(); // Note: The handle buffer will push the data in local array before pushing to mongo via initial check up model
  21. /* Disabled for now due to missing data not during transmision. The issue was suspected to be it's async nature of confusing timing
  22. when it was queued into the event queue. Sometimes the messages will be late to be saved */
  23. // this.initializeDatabaseConnection(dbName)
  24. // .then(async (connection: mongoose.Connection) => {
  25. // const grpcMessageSchema = require("../models/message.schema");
  26. // this.messageModel = connection.model<Message>(
  27. // "Message",
  28. // grpcMessageSchema
  29. // );
  30. // await this.transferLocalBufferToMongoDB(); // transfer all data from local array into mongodb after the mongo setup is complete
  31. // })
  32. // .catch((error) => {
  33. // console.error("Database initialization failed:", error);
  34. // // Implement retry logic or additional error handling here. Perhaps retry logic in the future...
  35. // });
  36. }
  37. // to be exposed to acquire the messages
  38. public getMessages(): Observable<Message> {
  39. return this.messageStream as Observable<Message>;
  40. }
  41. public getStateObservable(): BehaviorSubject<ConnectionState> {
  42. return this.connectionState;
  43. }
  44. // To subscrcibe for the message stream as well as the connection state
  45. private setupSubscriptions(): void {
  46. this.messageStream.subscribe({
  47. next: (message: Message) => this.handleIncomingMessage(message),
  48. error: (err) =>
  49. console.error("Error in messageToBePublished subject:", err),
  50. complete: () =>
  51. console.log("messageToBePublished subscription completed"),
  52. });
  53. this.connectionState.subscribe({
  54. next: (state: ConnectionState) => this.handleConnectionStateChanges(state),
  55. error: (err) => console.error("Error in connectionState subject:", err),
  56. complete: () => console.log("connectionState subscription completed"),
  57. });
  58. }
  59. private async initializeDatabaseConnection(
  60. dbName: string
  61. ): Promise<Connection> {
  62. try {
  63. console.log(`${this.dbUrl}${dbName}`);
  64. const connection: mongoose.Connection = await mongoose.createConnection(
  65. `${this.dbUrl}${dbName}`
  66. );
  67. console.log(`Connected to ${this.dbUrl}${dbName}`);
  68. return connection;
  69. } catch (error) {
  70. console.error("Error connecting to MongoDB:", error);
  71. throw error;
  72. }
  73. }
  74. private handleIncomingMessage(message: Message): void {
  75. if (this.connectionState.getValue().status === "BUFFER") {
  76. this.bufferMessage(message);
  77. }
  78. if (this.connectionState.getValue().status === "DIRECT_PUBLISH") {
  79. /* Note: Since the main outGoingMessage is being published irregardless
  80. of the connection state, so there's no need to do anything aside from
  81. releasing buffered messages which will be handled by handleConnectionStateChange */
  82. // additional logic here
  83. }
  84. }
  85. private handleConnectionStateChanges(state: ConnectionState): void {
  86. console.log(`${this.bufferIdentifier}: ${this.connectionState.getValue().status}`);
  87. if (state.status === "BUFFER") {
  88. if (state.payload && typeof state.payload !== "string") {
  89. this.bufferMessage(state.payload); // Buffer the last message immediately
  90. }
  91. }
  92. if (state.status === "DIRECT_PUBLISH") {
  93. // Relese the messages by inserting them into the outgoing Messages together.
  94. this.releaseBufferedMessages(this.messageStream);
  95. }
  96. }
  97. private async bufferMessage(message: Message): Promise<void> {
  98. if (this.messageModel) {
  99. try {
  100. // const newMessage = new this.messageModel(message);
  101. await this.messageModel.create(message);
  102. this.messageModel.countDocuments({}).then((count) => {
  103. console.log(`Message${(message.message as MessageLog).appData.msgId} saved to MongoDB buffer. There is ${count} messages in datatbase under ${this.bufferIdentifier} at the moment.`);
  104. // if connection status okay
  105. // if(this.connectionState.getValue().status == "DIRECT_PUBLISH")
  106. // {
  107. // console.log("Message count release " + count);
  108. // // Then release back to message stream
  109. // this.releaseBufferedMessages(this.messageStream);
  110. // }
  111. });
  112. } catch (error) {
  113. console.error("Error saving message to MongoDB:", error);
  114. // Implement retry logic or additional error handling here
  115. }
  116. } else {
  117. this.messageBuffer.push(message); // Fallback to local buffer if model is not defined
  118. console.log(`pushing ${(message.message as MessageLog).appData.msgId} into local array buffer under ${this.bufferIdentifier}.... There is now ${this.messageBuffer.length} messages`);
  119. }
  120. }
  121. private releaseBufferedMessages(
  122. messageFromBuffer: Subject<Message>
  123. ): Promise<boolean> {
  124. return new Promise(async (resolve, reject) => {
  125. if (this.messageModel) {
  126. try {
  127. // use then
  128. let countPromise = checkMessageCount(this.messageModel, this.bufferIdentifier);
  129. countPromise.then(async (amount) => {
  130. console.log("Amount1:" + amount);
  131. // let countPromise = checkMessageCount(this.messageModel, this.bufferIdentifier);
  132. // countPromise.then(async (amount)=>{
  133. // console.log("Amount2:"+amount);
  134. // })
  135. while (amount > 0) {
  136. console.log("AmountInLoop1:" + amount)
  137. try {
  138. await extractData(messageFromBuffer, this.messageModel); // New function to process a batch
  139. } catch (processError) {
  140. console.error('Error processing batch:', processError);
  141. }
  142. console.log('Checking again...');
  143. amount = await checkMessageCount(this.messageModel, this.bufferIdentifier);
  144. console.log("AmountInLoop:" + amount)
  145. }
  146. console.log('All messages extracted.');
  147. })
  148. let amount: number = await countPromise
  149. resolve(true);
  150. } catch (error) {
  151. console.error('Error in releaseBufferedMessages:', error);
  152. reject(false);
  153. }
  154. async function checkMessageCount(messageModel: Model<Message>, bufferIdentifier: string): Promise<any> {
  155. return new Promise((resolve, reject) => {
  156. messageModel.countDocuments({}).then((count) => {
  157. console.log(`There is ${count} messages in database under ${bufferIdentifier} at the moment. Releasing them....`);
  158. resolve(count)
  159. }).catch((error) => {
  160. console.error(error)
  161. reject(error)
  162. })
  163. })
  164. }
  165. // Stream all the data inside the database out and deleting them
  166. async function extractData(messageFromBuffer: Subject<Message>, messageModel: Model<Message>): Promise<any> {
  167. return new Promise((resolve, reject) => {
  168. const stream = messageModel.find().cursor();
  169. stream.on("data", async (message) => {
  170. // Process each message individually`
  171. messageFromBuffer.next(message);
  172. });
  173. stream.on("error", (error) => {
  174. console.error("Error streaming messages from MongoDB:", error);
  175. reject(error);
  176. });
  177. stream.on("end", async () => {
  178. // Delete the data once it has been streamed
  179. try {
  180. if (messageModel) {
  181. await messageModel.deleteMany({});
  182. console.log("Data in Mongo deleted successfully.");
  183. } else {
  184. console.log(`Message Mongoose Model is not intiated properly...`);
  185. }
  186. } catch (err) {
  187. console.error("Error deleting data:", err);
  188. }
  189. resolve(true);
  190. });
  191. })
  192. }
  193. }
  194. if (!this.messageModel) {
  195. // If MongoDB model is not defined, use the local buffer
  196. console.log(`Releasing buffer Message under ${this.bufferIdentifier}: currently there is ${this.messageBuffer.length} messages to be released`);
  197. this.messageBuffer.forEach((message) =>
  198. this.messageStream.next(message)
  199. );
  200. this.messageBuffer.length = 0; // Clear the local buffer after transferring
  201. if (this.messageBuffer.length < 1) {
  202. resolve(true);
  203. } else {
  204. reject(`Somehow the array is not emptied. This should not happen`);
  205. }
  206. }
  207. });
  208. }
  209. private async transferLocalBufferToMongoDB(): Promise<void> {
  210. return new Promise((resolve, reject) => {
  211. console.log(`Transferring local array buffered Message under ${this.bufferIdentifier}: currently there is ${this.messageBuffer.length}. Transferring to database...`);
  212. if (this.messageModel) {
  213. let locallyBufferedMessage: Observable<Message> = from(this.messageBuffer);
  214. locallyBufferedMessage.subscribe({
  215. next: async (message: Message) => {
  216. try {
  217. if (this.messageModel) {
  218. await this.messageModel.create(message);
  219. console.log(`Transferring ${(message.message as MessageLog).appData.msgId} into database.`);
  220. }
  221. } catch (error) {
  222. console.error("Error transferring message to MongoDB:", error);
  223. }
  224. },
  225. error: (err) => console.error(err),
  226. complete: () => {
  227. if (this.messageModel) {
  228. this.messageModel.countDocuments({}).then((count) => {
  229. console.log(`Local buffered message transfer completed. There is a total of ${count} messages in database ${this.bufferIdentifier} at the moment.`)
  230. this.messageBuffer = [] // Clear local buffer after transferring
  231. });
  232. }
  233. },
  234. });
  235. }
  236. });
  237. }
  238. // Additional methods as required...
  239. }