@test-org122/hypernet-core
Version:
Hypernet Core. Represents the SDK for running the Hypernet Protocol.
78 lines • 3.05 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ControlService = void 0;
const objects_1 = require("@interfaces/objects");
class ControlService {
constructor(contextProvider, messagingRepo) {
this.contextProvider = contextProvider;
this.messagingRepo = messagingRepo;
this.claimPeriod = 1000 * 60 * 5; // 5 minutes
this.timeout = null;
this.lastControlClaim = null;
this.checkControlInterval = null;
}
claimControl() {
let context;
let controlClaim;
return this.contextProvider
.getInitializedContext()
.andThen((myContext) => {
context = myContext;
// Create a new claim
controlClaim = new objects_1.ControlClaim(context.account, new Date().getTime());
// Send the claim out to the other cores
return this.messagingRepo.sendControlClaim(controlClaim);
})
.andThen(() => {
// Update the context
context.inControl = true;
return this.contextProvider.setContext(context);
})
.map(() => {
// We will continue to send control claims every 5 minutes
this.timeout = setInterval(() => {
// this.messagingRepo.sendControlClaim(controlClaim);
}, this.claimPeriod);
// Notify the world.
context.onControlClaimed.next(controlClaim);
});
}
/**
* Processes an incoming control claim. Basically, if we get one,
* SHUT DOWN EVERYTHING
* @param controlClaim
*/
processControlClaim(controlClaim) {
let context;
return this.contextProvider
.getInitializedContext()
.andThen((myContext) => {
context = myContext;
// set the last control claim time
this.lastControlClaim = controlClaim;
// Update the context
context.inControl = false;
return this.contextProvider.setContext(context);
})
.map(() => {
// Cancel any notifications
if (this.timeout != null) {
clearInterval(this.timeout);
}
// While we are not in control, we are going to set a timeout
// to try and regain control. If whoever is in control stops posting,
// if we haven't heard from them after claimPeriod, then we will try
// and take control
const now = new Date().getTime();
this.checkControlInterval = setInterval(() => {
if (this.lastControlClaim != null && now - (this.lastControlClaim.timestamp + this.claimPeriod) > 5000) {
// TODO: take control of our lives
}
}, this.claimPeriod);
// Notify the world.
context.onControlYielded.next(controlClaim);
});
}
}
exports.ControlService = ControlService;
//# sourceMappingURL=ControlService.js.map