perf(peerdb): faster store sync

This commit is contained in:
Alexey Kasyanchuk 2018-04-21 01:02:45 +03:00
parent c66dc88962
commit 0768e8d3e0
2 changed files with 19 additions and 6 deletions

View File

@ -5,10 +5,12 @@ const net = require('net')
const JsonSocket = require('json-socket') const JsonSocket = require('json-socket')
const os = require('os'); const os = require('os');
const isPortReachable = require('./isPortReachable') const isPortReachable = require('./isPortReachable')
const EventEmitter = require('events');
class p2p { class p2p {
constructor(send = () => {}) constructor(send = () => {})
{ {
this.events = new EventEmitter
this.peers = [] this.peers = []
this.ignoreAddresses = ['127.0.0.1'] this.ignoreAddresses = ['127.0.0.1']
this.messageHandlers = {} this.messageHandlers = {}
@ -263,6 +265,7 @@ class p2p {
size: this.size, size: this.size,
torrents: data.info ? data.info.torrents || 0 : 0 torrents: data.info ? data.info.torrents || 0 : 0
}) })
this.events.emit('peer', address)
console.log('new peer', address) console.log('new peer', address)
// add some other peers // add some other peers

View File

@ -6,6 +6,7 @@ module.exports = class P2PStore extends EventEmitter {
{ {
super() super()
this.id = 0 this.id = 0
this.synchronized = false
console.log('connect p2p store...') console.log('connect p2p store...')
this.p2p = p2p this.p2p = p2p
@ -20,13 +21,13 @@ module.exports = class P2PStore extends EventEmitter {
console.log('store db index', this.id) console.log('store db index', this.id)
const syncTimeout = setInterval(() => { let lock = false
if(this.p2p.size <= 0) this.p2p.events.on('peer', () => {
if(lock)
return return
lock = true
clearInterval(syncTimeout) setTimeout(() => this.sync(), 1000)
this.sync() })
}, 10000)
}) })
this.p2p.on('dbStore', (record) => { this.p2p.on('dbStore', (record) => {
@ -73,6 +74,7 @@ module.exports = class P2PStore extends EventEmitter {
data.records.forEach(record => this._syncRecord(record)) data.records.forEach(record => this._syncRecord(record))
}) })
this.synchronized = true
} }
_syncRecord(record, callback) _syncRecord(record, callback)
@ -130,6 +132,12 @@ module.exports = class P2PStore extends EventEmitter {
store(obj) store(obj)
{ {
if(!this.synchronized)
{
console.log('cant store item on unsync db')
return false
}
// clean temp from object // clean temp from object
const temp = obj._temp const temp = obj._temp
delete obj._temp delete obj._temp
@ -150,6 +158,8 @@ module.exports = class P2PStore extends EventEmitter {
// store record // store record
this.p2p.emit('dbStore', value) this.p2p.emit('dbStore', value)
}) })
return true
} }
find(index) find(index)