retransmission.service.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { BehaviorSubject, buffer, concatMap, distinctUntilChanged, from, Observable, Subject, takeWhile } from "rxjs";
  2. import { RetransmissionInterface } from "../interfaces/retransmission.interface";
  3. import { WrappedMessage } from "../interfaces/general.interface";
  4. import { sortMessageBasedOnDate } from "./utility/message-ordering";
  5. import { v4 as uuidV4 } from 'uuid';
  6. export class RetransmissionService implements RetransmissionInterface {
  7. private currentMessageId: string | null
  8. private sortMessage: boolean = false
  9. private bufferReleaseSignal: Subject<void> = new Subject()
  10. private receiverConnectionState: BehaviorSubject<'OFFLINE' | 'ONLINE'> = new BehaviorSubject('OFFLINE')
  11. private transmissionState: BehaviorSubject<'TRANSMITTING' | 'IDLE' | 'ARRAY EMPTY' | 'STORING DATA' | 'GETTING STORED DATA'> = new BehaviorSubject('ARRAY EMPTY')
  12. private arrayToBeTransmitted: Subject<WrappedMessage[]> = new Subject()
  13. private toBeWrapped: Subject<any> = new Subject()
  14. private wrappedMessageToBeBuffered: Subject<WrappedMessage> = new Subject()
  15. private messageToBeTransmitted: Subject<WrappedMessage> = new Subject()
  16. // Interface
  17. public retransmission(payloadToBeTransmitted: Observable<any>, eventListener: Observable<any>, messageOrdering?: boolean) {
  18. if (messageOrdering) {
  19. this.sortMessage = true
  20. console.log(`Message ordering is set to ${this.sortMessage}`)
  21. }
  22. eventListener.subscribe(event => this.receiverConnectionState.next(event))
  23. this.startWrappingOperation()
  24. this.startBufferTransmisionProcess()
  25. this.releaseSignalManager()
  26. payloadToBeTransmitted.subscribe((message) => {
  27. this.toBeWrapped.next(message)
  28. })
  29. }
  30. public returnBufferedMessages(): Observable<WrappedMessage> {
  31. return this.messageToBeTransmitted.asObservable()
  32. }
  33. private startWrappingOperation() {
  34. this.toBeWrapped.subscribe(message => {
  35. this.wrappedMessageToBeBuffered.next(this.wrapMessageWithTimeReceived(message, this.currentMessageId ? this.currentMessageId : null))
  36. })
  37. //simulate connection test
  38. // wrappedMessageToBeBuffered will then be pushed to buffer
  39. this.wrappedMessageToBeBuffered.pipe(buffer(this.bufferReleaseSignal)).subscribe((bufferedMessages: WrappedMessage[]) => {
  40. console.log(bufferedMessages.length + ' buffered messages')
  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
  57. // console.log(`Updating: `, this.currentMessageId)
  58. return WrappedMessage
  59. } else {
  60. return message as WrappedMessage
  61. }
  62. }
  63. private startBufferTransmisionProcess() {
  64. console.log(`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. // console.log(`At retransmission ${message.payload.header.messageID ?? 'undefined'}`)
  76. this.messageToBeTransmitted.next(message)
  77. }
  78. },
  79. error: err => console.error(err),
  80. complete: () => {
  81. // update transmission state to indicate this batch is completed
  82. // console.log(`Processing buffered array completed. Changing transmission state to ARRAY EMPTY`);
  83. this.transmissionState.next('ARRAY EMPTY');
  84. if (this.receiverConnectionState.getValue() === 'ONLINE' && this.transmissionState.getValue() === 'ARRAY EMPTY') {
  85. setTimeout(() => {
  86. this.bufferReleaseSignal.next()
  87. }, 1000)
  88. }
  89. // Do nothing if the receiver connection is offline
  90. }
  91. });
  92. } else {
  93. // If I don't do setTimeout, then bufferrelasesignal will be overloaded
  94. if (this.receiverConnectionState.getValue() === 'ONLINE') {
  95. setTimeout(() => {
  96. this.bufferReleaseSignal.next()
  97. }, 3000)
  98. }
  99. }
  100. }
  101. )
  102. }
  103. private releaseSignalManager() {
  104. this.receiverConnectionState.pipe(
  105. distinctUntilChanged()
  106. ).subscribe(clientState => {
  107. console.log(`Client is now ${clientState}`)
  108. if (clientState == 'OFFLINE') {
  109. console.log(`Current transmission state: ${this.transmissionState.getValue()}`)
  110. // just keep buffering
  111. }
  112. if (clientState == 'ONLINE') {
  113. console.log(`Current transmission state: ${this.transmissionState.getValue()}`)
  114. // get the stored messages to pump it back into the buffer to be ready to be processed immediately
  115. if (this.transmissionState.getValue() == 'ARRAY EMPTY') {
  116. this.bufferReleaseSignal.next()
  117. }
  118. }
  119. })
  120. }
  121. }