buffer.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { BehaviorSubject, buffer, distinct, distinctUntilChanged, from, Observable, Subject, takeWhile } from "rxjs";
  2. import { v4 as uuidV4 } from 'uuid';
  3. import ConsoleLogger from "./log.utils";
  4. import { WrappedMessage } from "../types";
  5. import { sortMessageBasedOnDate } from "./message-ordering";
  6. export class BufferService {
  7. private console: ConsoleLogger = new ConsoleLogger(`RetransmissionService`, ['retransmission'])
  8. private currentMessageId!: string | null
  9. private sortMessage: boolean = false
  10. private bufferReleaseSignal: Subject<void> = new Subject()
  11. private receiverConnectionState: BehaviorSubject<ConnectionState> = new BehaviorSubject<ConnectionState>('OFFLINE')
  12. private transmissionState: BehaviorSubject<TransmissionState> = new BehaviorSubject<TransmissionState>('ARRAY EMPTY')
  13. private arrayToBeTransmitted: Subject<WrappedMessage[]> = new Subject()
  14. private toBeWrapped: Subject<any> = new Subject()
  15. private wrappedMessageToBeBuffered: Subject<WrappedMessage> = new Subject()
  16. private messageToBeTransmitted: Subject<WrappedMessage> = new Subject()
  17. // Interface
  18. public implementRetransmission(payloadToBeTransmitted: Observable<any>, eventListener: Observable<ConnectionState>, wantMessageOrdering?: boolean) {
  19. if (wantMessageOrdering) {
  20. this.sortMessage = true
  21. this.console.log({ message: `Message ordering is set to ${this.sortMessage}` })
  22. }
  23. eventListener.pipe(distinctUntilChanged()).subscribe(event => this.receiverConnectionState.next(event))
  24. this.startWrappingOperation()
  25. this.startBufferTransmisionProcess()
  26. this.linkEventListenerToBufferSignal()
  27. payloadToBeTransmitted.subscribe((message) => {
  28. this.toBeWrapped.next(message)
  29. })
  30. }
  31. public returnSubjectForBufferedItems(): Observable<WrappedMessage> {
  32. return this.messageToBeTransmitted.asObservable()
  33. }
  34. private startWrappingOperation() {
  35. this.toBeWrapped.subscribe(message => {
  36. this.wrappedMessageToBeBuffered.next(this.wrapMessageWithTimeReceived(message, this.currentMessageId ? this.currentMessageId : null))
  37. })
  38. // wrappedMessageToBeBuffered will then be pushed to buffer
  39. this.wrappedMessageToBeBuffered.pipe(buffer(this.bufferReleaseSignal)).subscribe((bufferedMessages: WrappedMessage[]) => {
  40. this.console.log({ message: `${bufferedMessages.length > 0 ? `${bufferedMessages.length} buffered messages` : `No buffered messages at the moment`} ` })
  41. // console.log(`Released buffered message: ${bufferedMessages.length} total messages. To Be sorted.`)
  42. this.arrayToBeTransmitted.next(sortMessageBasedOnDate(bufferedMessages))
  43. // this.arrayToBeTransmitted.next((this.sortMessage && bufferedMessages.length > 0) ? sortMessageBasedOnDate(bufferedMessages) : bufferedMessages)
  44. });
  45. }
  46. private wrapMessageWithTimeReceived(message: any, previousMessageID: string | null): WrappedMessage {
  47. // check if message has already a time received property if so no need to add anymore
  48. if (!message.timeReceived) {
  49. let WrappedMessage: WrappedMessage = {
  50. timeReceived: new Date(),
  51. payload: message,
  52. thisMessageID: uuidV4(),
  53. previousMessageID: previousMessageID
  54. }
  55. // console.log(`Current`, WrappedMessage.thisMessageID, 'Previous for this message:', WrappedMessage.previousMessageID)
  56. this.currentMessageId = WrappedMessage.thisMessageID as string
  57. // console.log(`Updating: `, this.currentMessageId)
  58. return WrappedMessage
  59. } else {
  60. return message as WrappedMessage
  61. }
  62. }
  63. private startBufferTransmisionProcess() {
  64. this.console.log({ message: `StartBufferTransmissionProcess` })
  65. this.arrayToBeTransmitted.subscribe(array => {
  66. if (array.length > 0) {
  67. this.transmissionState.next('TRANSMITTING')
  68. from(array).subscribe({
  69. next: (message: WrappedMessage) => {
  70. if (this.receiverConnectionState.getValue() == 'OFFLINE') {
  71. // buffer this message. Flush it back to buffer
  72. this.wrappedMessageToBeBuffered.next(message)
  73. }
  74. if (this.receiverConnectionState.getValue() == 'ONLINE') {
  75. this.messageToBeTransmitted.next(message)
  76. }
  77. },
  78. error: err => console.error(err),
  79. complete: () => {
  80. // update transmission state to indicate this batch is completed
  81. this.transmissionState.next('ARRAY EMPTY');
  82. if (this.receiverConnectionState.getValue() === 'ONLINE' && this.transmissionState.getValue() === 'ARRAY EMPTY') {
  83. setTimeout(() => {
  84. this.bufferReleaseSignal.next()
  85. }, 1000)
  86. }
  87. // Do nothing if the receiver connection is offline
  88. }
  89. });
  90. } else {
  91. // If I don't do setTimeout, then bufferrelasesignal will be overloaded
  92. if (this.receiverConnectionState.getValue() === 'ONLINE') {
  93. setTimeout(() => {
  94. this.bufferReleaseSignal.next()
  95. }, 3000)
  96. }
  97. }
  98. }
  99. )
  100. }
  101. private linkEventListenerToBufferSignal() {
  102. this.receiverConnectionState.pipe(
  103. distinctUntilChanged()
  104. ).subscribe(clientState => {
  105. this.console.log({ message: `Client is now ${clientState}. ${(clientState === 'OFFLINE') ? 'Buffering Mode Active...' : 'Releasing Buffered Messages...'}` })
  106. if (clientState == 'OFFLINE') {
  107. this.console.log({ message: `Current transmission state: ${this.transmissionState.getValue()}` })
  108. // just keep buffering
  109. }
  110. if (clientState == 'ONLINE') {
  111. this.console.log({ message: `Current transmission state: ${this.transmissionState.getValue()}` })
  112. // get the stored messages to pump it back into the buffer to be ready to be processed immediately
  113. if (this.transmissionState.getValue() == 'ARRAY EMPTY') {
  114. this.bufferReleaseSignal.next()
  115. }
  116. }
  117. })
  118. }
  119. }
  120. type ConnectionState = 'ONLINE' | 'OFFLINE'
  121. type TransmissionState = 'TRANSMITTING' | 'IDLE' | 'ARRAY EMPTY' | 'STORING DATA' | 'GETTING STORED DATA'