little refactored peerdb

This commit is contained in:
Alexey Kasyanchuk 2018-04-18 00:46:02 +03:00
parent 9dc7319cad
commit 25727296e6

View File

@ -3,7 +3,7 @@ const objectHash = require('object-hash');
module.exports = class P2PStore { module.exports = class P2PStore {
constructor(p2p, sphinx) constructor(p2p, sphinx)
{ {
this.id = 1 this.id = 0
console.log('connect p2p store...') console.log('connect p2p store...')
this.p2p = p2p this.p2p = p2p
@ -14,7 +14,7 @@ module.exports = class P2PStore {
return return
if(rows[0] && rows[0].mx >= 1) if(rows[0] && rows[0].mx >= 1)
this.id = rows[0].mx + 1; this.id = rows[0].mx;
console.log('store db index', this.id) console.log('store db index', this.id)
@ -27,34 +27,18 @@ module.exports = class P2PStore {
}, 10000) }, 10000)
}) })
this.p2p.on('dbStore', (record, callback) => { this.p2p.on('dbStore', (record) => this._syncRecord(record))
if(!record)
return
if(typeof record !== 'object')
return
if(!record.id)
return
if(record.id <= this.id)
return
// store
console.log('store record', record.id)
this._pushToDb(record)
})
this.p2p.on('dbSync', ({id} = {}, callback) => { this.p2p.on('dbSync', ({id} = {}, callback) => {
console.log('ask to sync db from', id, 'version') console.log('ask to sync db from', id, 'version')
if(!id || this.id <= id) if(typeof id === 'undefined' || id >= this.id)
{ {
callback(false) callback(false)
return return
} }
// back // back
this.sphinx.query(`select * from store where id >= ${id}`, (err, records) => { this.sphinx.query(`select * from store where id > ${id}`, (err, records) => {
if(err) if(err)
{ {
console.log(err) console.log(err)
@ -74,29 +58,36 @@ module.exports = class P2PStore {
if(!data || !data.records) if(!data || !data.records)
return return
for(const record of data.records) data.records.forEach(record => this._syncRecord(record))
{
if(!record.id)
return
if(record.id < this.id)
return
record.data = JSON.parse(record.data)
// check hash
if(objectHash(record.data) !== record.hash)
{
console.log('wrong hash for sync peerdb')
return
}
// push to db
this._pushToDb(record)
}
}) })
} }
_syncRecord(record)
{
if(!record)
return
if(!record.id)
return
if(record.id <= this.id)
return
if(typeof record.data !== 'object')
record.data = JSON.parse(record.data)
// check hash
if(objectHash(record.data) !== record.hash)
{
console.log('wrong hash for sync peerdb')
return
}
// push to db
console.log('sync peerdb record', record.id)
this._pushToDb(record)
}
_pushToDb(value, callback) _pushToDb(value, callback)
{ {
const data = this.sphinx.escape(JSON.stringify(value.data)) const data = this.sphinx.escape(JSON.stringify(value.data))
@ -118,7 +109,7 @@ module.exports = class P2PStore {
store(obj) store(obj)
{ {
const value = { const value = {
id: this.id++, id: ++this.id,
hash: objectHash(obj), hash: objectHash(obj),
data: obj, data: obj,
index: obj._index, index: obj._index,