Skip to content

Commit

Permalink
Implement timed replicator
Browse files Browse the repository at this point in the history
  • Loading branch information
Mutugiii committed Oct 25, 2024
1 parent 01f4da3 commit 678921f
Showing 1 changed file with 54 additions and 9 deletions.
63 changes: 54 additions & 9 deletions src/app/manager-dashboard/manager-sync.component.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,81 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CouchService } from '../shared/couchdb.service';
import { DialogsLoadingService } from '../shared/dialogs/dialogs-loading.service';
import { forkJoin } from 'rxjs';
import { forkJoin, interval, Subscription, BehaviorSubject, pipe } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { PlanetMessageService } from '../shared/planet-message.service';

@Component({
templateUrl: './manager-sync.component.html'
})

export class ManagerSyncComponent implements OnInit {
export class ManagerSyncComponent implements OnInit, OnDestroy {

replicators = [];
private syncSubscription: Subscription;
private replicatorsSubject = new BehaviorSubject<any[]>([]);
replicators$ = this.replicatorsSubject.asObservable();

private readonly SYNC_INTERVAL = 3600000;
private readonly LAST_SYNC_KEY = 'lastSyncTime';

constructor(
private couchService: CouchService,
private planetMessageService: PlanetMessageService,
private dialogsLoadingService: DialogsLoadingService
) {}
) { }

ngOnInit() {
this.getReplicators();
private timedSync() {
const lastSync = parseInt(localStorage.getItem(this.LAST_SYNC_KEY) || '0', 10);
const now = Date.now();

if (now - lastSync >= this.SYNC_INTERVAL) {
this.syncReplicators();
}

this.syncSubscription = interval(this.SYNC_INTERVAL)
.subscribe(() => {
this.syncReplicators();
});
}

getReplicators() {
private syncReplicators() {
this.dialogsLoadingService.start();
forkJoin([
this.couchService.get('_scheduler/docs'),
this.couchService.findAll('_replicator')
])
.pipe(catchError(
error => {
this.planetMessageService.showMessage($localize`Error during synchronization ${error}`);
this.dialogsLoadingService.stop();
throw error;
})
)
.subscribe(([ reps, data ]) => {
const jobs = reps.docs.filter(replicator => replicator.database === '_replicator');
this.replicators = data.map((rep: any) => ({ ...rep, ...jobs.find(n => n.doc_id === rep._id) }));
const updatedReplicators = data.map((rep: any) => ({
...rep,
...jobs.find(n => n.doc_id === rep._id)
}));
this.replicatorsSubject.next(updatedReplicators);
this.dialogsLoadingService.stop();
localStorage.setItem(this.LAST_SYNC_KEY, Date.now().toString());
});
}

ngOnInit() {
this.timedSync();
this.getReplicators();
}

getReplicators(): BehaviorSubject<any[]> {
return this.replicatorsSubject;
}

ngOnDestroy() {
if (this.syncSubscription) {
this.syncSubscription.unsubscribe();
}
}

}

0 comments on commit 678921f

Please sign in to comment.