message-auditor.service.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import { map, Observable, of, Subject } from "rxjs";
  2. import { ErrorTrigger, MessageAuditorServiceInterface, MessageSynchronisationServiceSetting } from "../type/datatype";
  3. import { MessageLog } from "../dependencies/log/type/datatype";
  4. import { _ } from 'lodash'
  5. import { LoggingService } from "../dependencies/log/interface/export";
  6. import { BaseMessage } from "../dependencies/log/dependencies/msgutil/interface/export";
  7. export class MessageAuditorService implements MessageAuditorServiceInterface {
  8. private settings: MessageSynchronisationServiceSetting
  9. private sourceSrc: LoggingService = new LoggingService()
  10. private targetSrc: LoggingService = new LoggingService()
  11. private missingMessageSubject: Subject<MessageLog> = new Subject()
  12. /* Set up the targets or points of synchronization. This is where it will register the 2 different location of
  13. the data to be synchronized */
  14. public init(settings: MessageSynchronisationServiceSetting): void {
  15. this.settings = settings;
  16. if (settings.filters) {
  17. console.log(`Integrating filters: ${Object.keys(this.settings.filters)} in AuditMessage service`)
  18. }
  19. }
  20. /* This is the main interface of the message sync service. The argument will take in an observable stream of
  21. error notifications, prompting it to perform the subscription of the targeted sources and it's corresponding
  22. target. Essentially, this does not synchronize, but rather it checks against the two sources and compare
  23. and return the missing data, which will then be passed into the targeted subject stream as specified by the
  24. respective client. They can choose how they want to handle the missing messages returned. */
  25. public subscribe(obsTrigger: Observable<ErrorTrigger>): Observable<MessageLog> {
  26. // Subsribe to the errorTrigger obs to listen to any notification.
  27. obsTrigger.subscribe({
  28. next: obsTrigger => {
  29. console.log(obsTrigger.message)// just checking the message
  30. if (!this.settings.filters) {
  31. console.log(`No filters applies`)
  32. } else {
  33. console.log(`Synchronizating with filters: ${Object.keys(this.settings.filters)}: ${Object.values(this.settings.filters)}`)
  34. }
  35. let missingMsg: Observable<MessageLog> = this.synchronize()
  36. missingMsg.subscribe({
  37. next: element => {
  38. this.missingMessageSubject.next(element)
  39. console.log(`AuditService: Returning missing messages ${element.appData.msgId} ....`)
  40. }
  41. })
  42. }
  43. })
  44. return this.missingMessageSubject
  45. }
  46. /* ________________ Private Functions _________________ */
  47. // Filtering functions to filters out messages
  48. private filterData(filters: any, message: MessageLog): boolean {
  49. let response: boolean = true //Just using this like a statemanagement
  50. let payload: BaseMessage = JSON.parse(message.appData.msgPayload as string) // Extract the payload from the messageLog first
  51. // Making a separate function to cater to different multi filters conditions are coded below
  52. function checkValues(filters): boolean { //FYI, all parameters are string
  53. let key = Object.keys(filters)
  54. console.log(Object.values(filters))
  55. let value = Object.values(filters)[0]
  56. let res = _.get(payload, key[0])
  57. // Check first if the payload has the filtering properties/path
  58. if (_.has(payload, key[0])) {
  59. // check if value is equal to fitler's
  60. let strarray: string[]
  61. // check array
  62. if (Array.isArray(value)) {
  63. strarray = value as string[]
  64. }
  65. else {
  66. strarray = [value as string]
  67. }
  68. // compare array with that string
  69. if (strarray.includes(res)) {
  70. return true
  71. } else {
  72. return false
  73. }
  74. } else {
  75. console.log(`${key} does not exists in payload`)
  76. return false
  77. }
  78. }
  79. if (filters) { // if filters is not null
  80. if (Object.keys(filters).length > 1) {
  81. let totalCount = Object.keys(filters).length
  82. let matchedCount = 0
  83. Object.entries(filters).forEach(([key, value]) => {
  84. let filters = { [key]: value }
  85. // console.log(filters)
  86. if (checkValues(filters) == true) matchedCount++
  87. })
  88. if (totalCount == matchedCount) {
  89. response = true
  90. } else {
  91. response = false
  92. }
  93. } else {
  94. if (checkValues(filters) == true) {
  95. response = true
  96. } else {
  97. response = false
  98. }
  99. }
  100. } else {
  101. response = true
  102. }
  103. return response
  104. }
  105. /* This is where the 'synching' operation takes place. */
  106. private synchronize(): Subject<MessageLog> {
  107. let subjectOutput: Subject<MessageLog> = new Subject()
  108. // Acquire the data from both location and return them as an array respectively.
  109. this.acquireData().then((data: { arr1: MessageLog[], arr2: MessageLog[] }) => {
  110. // In the case where there are differences in the array length, then extensive comparison
  111. // will be carried out to filters out the differences. Differences are the missing data.
  112. this.checkArrayDifferences(data).then((data: MessageLog[]) => {
  113. data.forEach(msgElement => {
  114. let refined = JSON.parse(JSON.stringify(msgElement))
  115. // Once the missing data has been weeded out, it is then passed into the Subject
  116. // to be returned for the subscribe method.`
  117. subjectOutput.next(refined)
  118. })
  119. })
  120. }).catch((e) => console.error(e))
  121. return subjectOutput
  122. }
  123. /* This is where the targeted data is queried. The process is pretty straightforward. */
  124. private async acquireData(): Promise<any> {
  125. const promiseQuery: Promise<any> = new Promise((resolve, reject) => {
  126. // declare what to expect.
  127. let allSets: {
  128. arr1: MessageLog[],
  129. arr2: MessageLog[]
  130. } = {
  131. arr1: [],
  132. arr2: []
  133. }
  134. let set1: MessageLog[] = []
  135. let set2: MessageLog[] = []
  136. // Initiate the source to find the location of the targeted data to be synched.
  137. this.sourceSrc.init(this.settings.incomingSource).then(() => {
  138. this.targetSrc.init(this.settings.target).then(() => {
  139. // Filter also carries out the query aspect of the operation, allowing it to acquire all the relevant data.
  140. this.sourceSrc.filter({ msgTag: this.settings.incomingSource.tags[0] }).then((data: MessageLog[]) => {
  141. data.forEach((message: MessageLog) => {
  142. if (this.filterData(this.settings.filters, message)) set1.push(message)
  143. })
  144. }).catch((err) => {
  145. console.error(err.message)
  146. }).then(() => {
  147. this.targetSrc.filter({ msgTag: this.settings.target.tags[0] }).then((data: MessageLog[]) => {
  148. data.forEach(message => {
  149. if (this.filterData(this.settings.filters, message)) set2.push(message)
  150. })
  151. allSets.arr1 = set1
  152. allSets.arr2 = set2
  153. resolve(allSets)
  154. })
  155. })
  156. })
  157. })
  158. })
  159. return promiseQuery
  160. }
  161. // compare results and return differences
  162. private async checkArrayDifferences(args: { arr1: MessageLog[], arr2: MessageLog[] }): Promise<MessageLog[]> {
  163. return new Promise((resolve, reject) => {
  164. let missingMsg: MessageLog[] = []
  165. args.arr1.forEach((msgElement: MessageLog) => {
  166. // In this case, we are just checking if the msgId matches within the given the array.
  167. // Just to save time, there's no need to check the entire message structure unless
  168. // the circumstances necessitates it.
  169. if (args.arr2.some(obj => obj.appData.msgId === msgElement.appData.msgId)) {
  170. console.log(`Item Found!`)
  171. } else {
  172. console.log(`This ${msgElement.appData.msgId} is missing`)
  173. missingMsg.push(msgElement)
  174. resolve(missingMsg)
  175. }
  176. })
  177. })
  178. }
  179. }