test4.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /* ----------------------- TEST4 {Mongo to Mongo} ----------------------- */
  2. /* Same with test 3 but this one it will be working with CDMS or any other potential data.
  3. Highly advisable to refer to test3c for the overall explanation of the logic flow in these
  4. test cases. Test4 is an adjusted version of test3 to cater for the need to deal with
  5. different types of data aside from messageLogs. */
  6. /* Note: MessageAudit will not work if storage is FIle. Search does not work at logging service
  7. does not cater for File system storage */
  8. import * as mongoose from 'mongoose'
  9. import { Subject } from "rxjs";
  10. import { ErrorTrigger, MessageSynchronisationServiceSetting } from "../type/datatype";
  11. import { MessageAuditorService } from "../services/message-auditor.service";
  12. import { LoggingService } from '../dependencies/log/interface/export';
  13. import { LogSetting, MessageLog } from '../dependencies/log/type/datatype';
  14. import * as fs from "fs"
  15. /* Convert all the non message data in the database into messageLog type. This is to ensure it's compatibility
  16. to be used by the interface from logging and audit message features. */
  17. const Schema = mongoose.Schema;
  18. // Use existing schema.
  19. const messageSchema = require('../dependencies/log/type/schemas/message.schema')
  20. // Create the fingerprint schema. This is the type of the data to be transformed into messageLog type
  21. const fingerPrintSchema = new Schema({
  22. uuid: { type: String, required: true, lowercase: true, unique: true },
  23. fileName: { type: String, required: true, lowercase: true },
  24. fileType: { type: String, required: true, lowercase: true },
  25. entityName: { type: String, required: true, lowercase: true },
  26. fileData: { type: Object, required: true },
  27. });
  28. /* For basic explanation, pleas refer to test3c. Here we are just instantiating audit and logging service for both
  29. the primary and the secondary soures. And then the instantiation of the corresponding subjects.
  30. The idea is that the subject will receive the missing info provided by the auditor and then log the
  31. missing data in the designated database location.
  32. */
  33. const auditor = new MessageAuditorService()
  34. const primary_Log = new LoggingService()
  35. const primary: Subject<MessageLog> = new Subject()
  36. primary.subscribe((element) => {
  37. console.log(`Primary Received ${element.appData.msgId}`)
  38. })
  39. const secondary_log = new LoggingService()
  40. const secondary: Subject<MessageLog> = new Subject()
  41. secondary.subscribe((element: MessageLog) => {
  42. console.log(`Secondary Received ${element.appData.msgId}`)
  43. convertMessageLogToCDMS(element)
  44. })
  45. /* For basic explanation, please refer to test3c. Declaration of the source and target location. */
  46. let primary_storage: LogSetting = {
  47. cacheMessageLimit: 0,
  48. storage: "MongoDB",
  49. setting: {
  50. appName: 'Default from client',
  51. appLocName: 'To be generated in client',
  52. logLocName: 'To be generated in client',
  53. },
  54. customSetting: {
  55. url: 'mongodb://192.168.100.59:27017/primary'
  56. // server: "192.168.100.59:27017",
  57. // database: "primary"
  58. }
  59. }
  60. let secondary_storage: LogSetting = {
  61. cacheMessageLimit: 0,
  62. storage: "MongoDB",
  63. setting: {
  64. appName: 'Default from client',
  65. appLocName: 'To be generated in client',
  66. logLocName: 'To be generated in client',
  67. },
  68. customSetting: {
  69. url: 'mongodb+srv://testDB:h1nt1OyXw6QeUnzS@cluster0.29sklte.mongodb.net/secondary'
  70. // srv: true,
  71. // user: "testDB",
  72. // password: "h1nt1OyXw6QeUnzS",
  73. // server: "cluster0.29sklte.mongodb.net",
  74. // database: "secondary",
  75. }
  76. }
  77. // Combine source and target storage to form MessageSynchronisationServiceSetting. This is required in messageAudit initialization
  78. let settings: MessageSynchronisationServiceSetting = {
  79. incomingSource: {
  80. //all of the settings to be combined here
  81. ...primary_storage,
  82. tags: ['default']
  83. }, //LogSetting & {tags:string[] },
  84. target: {
  85. ...secondary_storage,
  86. tags: ['default']
  87. } //LogSetting & {tags:string[] }
  88. }
  89. /* -------- SYNCHRONIZATION --------- */
  90. // Primary will call the syncrhonization service
  91. auditor.init(settings)
  92. /* This is where the synchronization logic is called. The errorSubject will act as a trigger
  93. mechanism to execute the synchronization. */
  94. let errorSubject: Subject<ErrorTrigger> = new Subject()
  95. // Subscribe to errorSubject notification
  96. let sync = auditor.subscribe(errorSubject)
  97. sync.subscribe({
  98. next: (msgToBeSynchronized: MessageLog) => {
  99. console.log(`passing missing message: ${msgToBeSynchronized.appData.msgId} into target/secondary subject.`)
  100. // the missing data returned will be pushed (next(message)) into the target payload.
  101. secondary.next(msgToBeSynchronized)
  102. }
  103. })
  104. // Set time oout for 5 seconds to allow the initial logging stage to complete it's logging
  105. // implementation first before proceedint to trigger the sync
  106. setTimeout(() => {
  107. // This wil act as the trigger error.Although the definition of this error is
  108. // still subject for enhancements in the near future.
  109. let sampleError: ErrorTrigger = {
  110. status: 1,
  111. message: "NO. I dont want to work"
  112. }
  113. errorSubject.next(sampleError)
  114. }, 3000)
  115. countdown()
  116. // Convert all the existing cdms into message log
  117. convertDataInMongo(primary_storage.customSetting.url)
  118. convertDataInMongo(secondary_storage.customSetting.url)
  119. // These declaration are for the secondary to log the converted missing data back in it's own collection at their corresponding servers
  120. const dbConnection = mongoose.createConnection("mongodb+srv://testDB:h1nt1OyXw6QeUnzS@cluster0.29sklte.mongodb.net/secondary")
  121. const dataModel = dbConnection.model('genericdata', fingerPrintSchema)
  122. // Manually log the missing data given by audit
  123. primary_Log.init(settings.incomingSource).then(() => {
  124. primary_Log.subscribe(primary)
  125. })
  126. secondary_log.init(settings.target).then(() => {
  127. secondary_log.subscribe(secondary)
  128. })
  129. // This function is used for convert existing generic data in the designated database to be prepared for
  130. // AuditMessage service.
  131. function convertDataInMongo(url: string) {
  132. // Create a subject to stream data received from query at mongo, instantiate convert service and also the database location to read the datas
  133. let data: Subject<any> = new Subject()
  134. let convertService = new LoggingService()
  135. let dbConnection = mongoose.createConnection(url)
  136. let dataModel = dbConnection.model('genericdata', fingerPrintSchema)
  137. // Once the data is queried, it will be streamed into the data Subject declared earlier
  138. dataModel.find().then((res) => {
  139. // console.log(res)
  140. res.forEach((element) => {
  141. data.next(element)
  142. })
  143. })
  144. // Assign a `handler` so to speak to handle the element receivd in the data Subject
  145. // This is where the transformation happens. The logic is written on the logging service side.
  146. // Once that is done, the transformed data will be saved again bacn in the mongo database in a different databse/collection
  147. data.subscribe((element) => {
  148. convertService.convertCDMStoMessageLog(element, settings.incomingSource.tags).then((result: MessageLog) => {
  149. console.log(`Converting fingerprint .... ${result.appData.msgId}`)
  150. primary.next(result)
  151. }).catch((err) => {
  152. console.error(err.message)
  153. });
  154. })
  155. }
  156. // TO be used by the secondary Subject to convert the message log it receives to complete the synchronization process.
  157. function convertMessageLogToCDMS(args: MessageLog) {
  158. secondary_log.convertMessageLogtoCDMS(args).then((result) => {
  159. dataModel.create(result)
  160. }).catch((err) => {
  161. console.error(err.message)
  162. });
  163. }
  164. /* THis is testing for generating error message to be fed into the error subject
  165. to act as additional trigger to exectute the synchronization when there's no internet
  166. connection. */ // THis part is not mandatory and can be commented out---
  167. const dns = require('dns');
  168. // Function to check internet connectivity. Basically just look up the site of example.com
  169. // using the built in libray of DNS.
  170. function checkInternetConnectivity() {
  171. dns.lookup('example.com', (err) => {
  172. if (err && err.code === 'ENOTFOUND') {
  173. let errorMsg: ErrorTrigger = {
  174. status: 0,
  175. message: `No internet connection`
  176. }
  177. errorSubject.next(errorMsg)
  178. } else {
  179. // Emit a message indicating internet connectivity
  180. // console.log('Internet connection is available');
  181. }
  182. });
  183. }
  184. // Interval time (in milliseconds) for checking connectivity
  185. const intervalTime = 1000; // Check every 1 second
  186. // Start checking connectivity at intervals
  187. const interval = setInterval(checkInternetConnectivity, intervalTime);
  188. // Stop checking connectivity after a certain duration (e.g., 1 minute)
  189. const duration = 60000; // 1 minute
  190. setTimeout(function () {
  191. clearInterval(interval);
  192. console.log('Internet connectivity monitoring stopped');
  193. }, duration);
  194. function countdown() {
  195. let seconds = 0;
  196. const countUpInterval = setInterval(() => {
  197. console.log(`Elapsed seconds: ${seconds}`);
  198. seconds++;
  199. }, 1000); // Update every second (1000 milliseconds)
  200. }