decentralized-internet
Version:
An NPM library of programs to create decentralized web and distributed computing projects
1 lines • 1.15 kB
JavaScript
;const http=require("http"),https=require("https"),_=require("lodash"),flaschenpost=require("flaschenpost"),parse=require("parse-duration"),Timer=require("timer2"),Peer=require("./Peer"),logger=flaschenpost.getLogger(),p2p={peer:function(e){if(!e)throw new Error("Options are missing.");if(!e.privateKey&&e.certificate)throw new Error("Private key is missing.");if(e.privateKey&&!e.certificate)throw new Error("Certificate is missing.");const r=!!e.privateKey&&!!e.certificate;e.protocol=r?"https":"http";const t=new Peer(e),i=parse(e.serviceInterval||"30s"),s=.5*i;return r?https.createServer({key:e.privateKey,cert:e.certificate},t.app).listen(t.self.port,()=>{logger.info("Server started.",{endpoint:t.self,status:t.status()})}):http.createServer(t.app).listen(t.self.port,()=>{logger.info("Server started.",{endpoint:t.self,status:t.status()})}),["stabilize","fix-successors","fix-fingers","fix-predecessor"].forEach(e=>{new Timer(i,{variation:s}).on("tick",()=>{t.remote(t.self).run(e,()=>{})})}),new Timer(i,{variation:s}).on("tick",()=>{t.remote(t.self).run("join",_.sample(t.wellKnownPeers.get()),()=>{})}),t}};module.exports=p2p;