message-auditor.service.ts 9.8 KB

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