Quellcode durchsuchen

introduce basic error notif trigger

Enzo vor 1 Jahr
Ursprung
Commit
7ee5e182e2
2 geänderte Dateien mit 78 neuen und 24 gelöschten Zeilen
  1. 29 8
      services/synchronization.service.ts
  2. 49 16
      test/test3c.ts

+ 29 - 8
services/synchronization.service.ts

@@ -1,4 +1,3 @@
-import { resolve } from "path";
 import { map, Observable, of, Subject } from "rxjs";
 import { BaseMessage } from "../dependencies/fisappmessagejsutilty/dependencies/dependencies";
 import { LoggingService } from "../dependencies/fisloggingservice/services/logging-service";
@@ -11,12 +10,17 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
     private sourceSrc: LoggingService = new LoggingService()
     private targetSrc: LoggingService = new LoggingService()
 
+    /* Set up the targets or points of synchronization. This is where it will register the 2 different location of 
+    the data to be synchronized */
     public init(settings: MessageSynchronisationServiceSetting): void {
         this.settings = settings;
     }
 
-    /* This functions will subsribe to the designated error triggers. The error will trigger the need to
-    sync, should the user or circumstances necessitates it. */
+    /* This is the main interface of the message sync service. The argument will take in an observable stream of 
+    error notifications, prompting it to perform the subscription of the targeted sources and it's corresponding 
+    target. Essentially, this does not in synchronize, but rather it checks against the two sources and compare
+    and return the missing data, which will then be passed into the targeted subject stream as specified by the
+    respective client. They can choose how they want to handle the missing messages returned. */
     public subscribe(obsTrigger: Observable<ErrorTrigger>): Observable<BaseMessage> {
         // Create a subject as a means to return the missing messages if there's any.
         let msg: Subject<BaseMessage> = new Subject()
@@ -24,6 +28,8 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
         // Subsribe to the errorTrigger obs to listen to any notification.
         obsTrigger.subscribe({
             next: obsTrigger => {
+                console.log(obsTrigger.message)// just checking the message
+
                 let missingMsg = this.dataConversion()
                 missingMsg.subscribe({
                     next: element => {
@@ -32,13 +38,15 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
                 })
             }
         })
-        if (!obsTrigger) {
-            this.dataConversion()
-        }
+        // Not sure why this piece of code is here. It generally doesn't affect the function
+        // if (!obsTrigger) {
+        //     this.dataConversion()
+        // }
         let result: Observable<BaseMessage> = msg.asObservable()
         return result
     }
 
+    // Need to change the data to json format first
     private dataConversion(): Observable<BaseMessage> {
         // let subjectOutput = this.syncrhonize()
         let obsOutput: Observable<BaseMessage> = this.synchronize().pipe(
@@ -51,15 +59,22 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
     }
 
 
-    // Returns all the missing data to be synchronized in the observables later
+    /* This is where the 'synching' operation takes place. */
     private synchronize(): Subject<any> {
         let subjectOutput = new Subject()
+        // Acquire the data from both location and return them as an array respectively.
         this.acquireData().then((data: { arr1: MessageLog[], arr2: MessageLog[] }) => {
+            // Check for length first. If the length matches, then there's no need to sync
+            // since there's nothing missing.
             if (data.arr1.length === data.arr2.length) {
                 console.log(`No synchronization needed`)
             } else {
+                // In the case where there are differences in the array lengthh, then extensive comparison
+                // will be carried to filter out the differences. Differences are the missing data.
                 this.checkArrayDifferences(data).then((data: MessageLog[]) => {
                     data.forEach(msgElement => {
+                        // Once the missing data has been weeded out, it is then passed into the Subject 
+                        // to be returned for the subscribe method.
                         subjectOutput.next(msgElement)
                     })
                 })
@@ -68,9 +83,10 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
         return subjectOutput
     }
 
-    // Acquires the available data from designated target and source storage
+    /* This is where the targeted data is queried. The process is pretty straightforward. */
     private async acquireData(): Promise<any> {
         const promiseQuery: Promise<any> = new Promise((resolve, reject) => {
+            // declare what to expect.
             let allSets: {
                 arr1: MessageLog[],
                 arr2: MessageLog[]
@@ -81,8 +97,10 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
             let set1
             let set2
 
+            // Initiate the source to find the location of the targeted data to be synched.
             this.sourceSrc.init(this.settings.incomingSource).then(() => {
                 this.targetSrc.init(this.settings.target).then(() => {
+                    // Filter also carries out the query aspect of the operation, allowing it to acquire all the relevant data.
                     this.sourceSrc.filter({ msgTag: this.settings.incomingSource.tags[0] }).then((data: MessageLog[]) => {
                         set1 = data
                     }).then(() => {
@@ -104,6 +122,9 @@ export class MessageSyncrhonizationService implements MessageSynchronisationServ
         return new Promise((resolve, reject) => {
             let missingMsg: MessageLog[] = []
             args.arr1.forEach((msgElement: MessageLog) => {
+                // In this case, we are just checking if the msgId matches within the given the array.
+                // Just to save time, there's no need to check the entire message structure unless
+                // the circumstances necessitates it.
                 if (args.arr2.some(obj => obj.appData.msgId === msgElement.appData.msgId)) {
                     console.log(`Item Found!`)
                 } else {

+ 49 - 16
test/test3c.ts

@@ -125,30 +125,63 @@ function initializeData() { // To store the data into the designated databases.
 initializeData() // Call the function to store the data into the designated databases.
 source_synchronize.init(settings)
 
-/* This is where the synchronizatin happens. Upon initializin ghe target earlier, we
-will put in a trigger to execute the synching. It will check for missing datas and
-publish the missing messages accordingly. For this test purpose, we purposely set to
-7 seconds to allow the logging process earlier to take place first before engaging
-in synching activity to prevent confusion and interference of the pre-logging stage. */
-setTimeout(() => {
+/* This is where the synchronization logic is called. The errorSubject will act as a trigger
+mechanism to execute the synchronization. */
+
+let errorSubject: Subject<ErrorTrigger> = new Subject()
+// Subscribe to errorSubject notification 
+let sync = source_synchronize.subscribe(errorSubject)
+sync.subscribe({
+    next: (msgToBeSynched) => {
+        console.log(`synching ... ${msgToBeSynched.header.messageID}`)
+        // the missing data returned will be pushed (next(message)) into the target payload.
+        target_payload_subject.next(msgToBeSynched)
+    }
+})
 
-    // This wil act as the trigger error. Although the definition of this error is 
+// Set time oout for 5 seconds to allow the initial logging stage to complete it's logging
+// implementation first before proceedint to trigger the sync
+setTimeout(() => {
+    // This wil act as the trigger error.Although the definition of this error is 
     // still subject for enhancements in the near future.
     let sampleError: ErrorTrigger = {
         status: 1,
         message: "NO. I dont want to work"
     }
+    errorSubject.next(sampleError)
+}, 5000)
 
-    let triggerSync: Observable<ErrorTrigger> = from([sampleError])
-
-    let sync = source_synchronize.subscribe(triggerSync)
-    sync.subscribe({
-        next: (msgToBeSynched) => {
-            console.log(`synching ... ${msgToBeSynched.header.messageID}`)
-            target_payload_subject.next(msgToBeSynched)
+/* THis is testing for generating error message to be fed into the error subject
+to act as additional trigger to exectute the synchronization when there's no internet
+connection. */
+const dns = require('dns');
+
+// Function to check internet connectivity. Basically just look up the site of example.com
+// using the built in libray of DNS.
+function checkInternetConnectivity() {
+    dns.lookup('example.com', (err) => {
+        if (err && err.code === 'ENOTFOUND') {
+            let errorMsg: ErrorTrigger = {
+                status: 0,
+                message: `No internet connection`
+            }
+            errorSubject.next(errorMsg)
+        } else {
+            // Emit a message indicating internet connectivity
+            // console.log('Internet connection is available');
         }
-    })
+    });
+}
 
-}, 5000)
+// Interval time (in milliseconds) for checking connectivity
+const intervalTime = 1000; // Check every 1 second
 
+// Start checking connectivity at intervals
+const interval = setInterval(checkInternetConnectivity, intervalTime);
 
+// Stop checking connectivity after a certain duration (e.g., 1 minute)
+const duration = 60000; // 1 minute
+setTimeout(function () {
+    clearInterval(interval);
+    console.log('Internet connectivity monitoring stopped');
+}, duration);