test4.ts 8.4 KB

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