buffer.service.ts 12 KB

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