message-auditor.service.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. if (filters) { // if filters is not null
  53. if (Object.keys(filters).length > 1) {
  54. let totalCount = Object.keys(filters).length
  55. let matchedCount = 0
  56. Object.entries(filters).forEach(([key, value]) => {
  57. let filters = { [key]: value }
  58. // console.log(filters)
  59. if (this.checkValues(payload, filters) == true) matchedCount++
  60. })
  61. if (totalCount == matchedCount) { // check if all the criterias are met
  62. response = true
  63. } else {
  64. response = false
  65. }
  66. } else {
  67. if (this.checkValues(payload, filters) == true) {
  68. response = true
  69. } else {
  70. response = false
  71. }
  72. }
  73. } else { // if not filters is provided. Then the just let response be true so that the data can be further processed
  74. response = true
  75. }
  76. return response
  77. }
  78. /* This is where the 'synching' operation takes place. */
  79. private synchronize(): Subject<MessageLog> {
  80. let subjectOutput: Subject<MessageLog> = new Subject()
  81. // Acquire the data from both location and return them as an array respectively.
  82. this.acquireData().then((data: { arr1: MessageLog[], arr2: MessageLog[] }) => {
  83. // In the case where there are differences in the array length, then extensive comparison
  84. // will be carried out to filters out the differences. Differences are the missing data.
  85. this.checkArrayDifferences(data).then((data: MessageLog[]) => {
  86. data.forEach(msgElement => {
  87. let refined = JSON.parse(JSON.stringify(msgElement))
  88. // Once the missing data has been weeded out, it is then passed into the Subject
  89. // to be returned for the subscribe method.`
  90. subjectOutput.next(refined)
  91. })
  92. })
  93. }).catch((e) => console.error(e))
  94. return subjectOutput
  95. }
  96. /* This is where the targeted data is queried. The process is pretty straightforward. */
  97. private async acquireData(): Promise<any> {
  98. const promiseQuery: Promise<any> = new Promise((resolve, reject) => {
  99. // declare what to expect.
  100. let allSets: { arr1: MessageLog[], arr2: MessageLog[] } = {
  101. arr1: [],
  102. arr2: []
  103. }
  104. let set1: MessageLog[] = []
  105. let set2: MessageLog[] = []
  106. // Initiate the source to find the location of the targeted data to be synched.
  107. this.sourceSrc.init(this.settings.incomingSource).then(() => {
  108. this.targetSrc.init(this.settings.target).then(() => {
  109. // Filter also carries out the query aspect of the operation, allowing it to acquire all the relevant data.
  110. this.sourceSrc.filter({ msgTag: this.settings.incomingSource.tags[0] }).then((data: MessageLog[]) => {
  111. data.forEach((message: MessageLog) => {
  112. if (this.filterData(this.settings.filters, message)) set1.push(message)
  113. })
  114. }).catch((err) => {
  115. console.error(err.message)
  116. }).then(() => {
  117. this.targetSrc.filter({ msgTag: this.settings.target.tags[0] }).then((data: MessageLog[]) => {
  118. data.forEach(message => {
  119. if (this.filterData(this.settings.filters, message)) set2.push(message)
  120. })
  121. allSets.arr1 = set1
  122. allSets.arr2 = set2
  123. resolve(allSets)
  124. })
  125. })
  126. })
  127. })
  128. })
  129. return promiseQuery
  130. }
  131. // compare results and return differences
  132. private async checkArrayDifferences(args: { arr1: MessageLog[], arr2: MessageLog[] }): Promise<MessageLog[]> {
  133. return new Promise((resolve, reject) => {
  134. let missingMsg: MessageLog[] = []
  135. args.arr1.forEach((msgElement: MessageLog) => {
  136. // In this case, we are just checking if the msgId matches within the given the array.
  137. // Just to save time, there's no need to check the entire message structure unless
  138. // the circumstances necessitates it.
  139. if (args.arr2.some(obj => obj.appData.msgId === msgElement.appData.msgId)) {
  140. console.log(`Item Found!`)
  141. } else {
  142. console.log(`This ${msgElement.appData.msgId} is missing`)
  143. missingMsg.push(msgElement)
  144. resolve(missingMsg)
  145. }
  146. })
  147. })
  148. }
  149. // To be used by the filterData function to check between payload values and filter conditions
  150. private checkValues(payload, filters): boolean { //FYI, all parameters are string
  151. let key = Object.keys(filters)
  152. // console.log(Object.values(filters))
  153. let value = Object.values(filters)[0]
  154. let res = _.get(payload, key[0])
  155. // Check first if the payload has the filtering properties/path
  156. if (_.has(payload, key[0])) {
  157. let strarray: string[]
  158. // check array
  159. if (Array.isArray(value)) {
  160. strarray = value as string[]
  161. }
  162. else {
  163. strarray = [value as string]
  164. }
  165. // compare array with that string
  166. if (strarray.includes(res)) {
  167. return true
  168. } else {
  169. return false
  170. }
  171. } else {
  172. console.log(`${key} does not exists in payload`)
  173. return false
  174. }
  175. }
  176. }