From b65ed25b29788f3f66ec25a7291bac5e2ba0e7d7 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 21 Jan 2016 03:48:39 -0800 Subject: [PATCH] chaindb: fix async. --- lib/bcoin/chain.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index 161bdadd..7a921dbb 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -714,7 +714,6 @@ function ChainDB(chain, options) { this.tip = -1; this.size = 0; this.fd = null; - this._writing = 0; // Need to cache up to the retarget interval // if we're going to be checking the damn @@ -863,7 +862,6 @@ ChainDB.prototype.saveAsync = function save(entry, callback) { // Speed up writes by doing them asynchronously // and keeping the data to be written in memory. this._queue[entry.height] = entry; - this._writing++; // Write asynchronously to the db. raw = entry.toRaw(); @@ -877,14 +875,13 @@ ChainDB.prototype.saveAsync = function save(entry, callback) { // Something tried to write here but couldn't. // Synchronously write it and get it over with. try { - if (item !== entry) + if (item && item !== entry) success = self._write(item.toRaw(), offset); } catch (e) { err = e; } delete self._queue[entry.height]; - self._writing--; if (err) { if (callback) @@ -901,7 +898,13 @@ ChainDB.prototype.saveAsync = function save(entry, callback) { ChainDB.prototype.remove = function remove(height) { assert(height >= 0); + if (this._queue[height]) { + utils.debug('Warning: write job in progress.'); + delete this._queue[height]; + } + this._write(this._nullBlock, height * BLOCK_SIZE); + delete this._cache[height]; // If we deleted several blocks at the end, go back // to the last non-null block and truncate the file @@ -959,6 +962,8 @@ ChainDB.prototype._writeAsync = function _writeAsync(data, offset, callback) { if (offset < 0 || offset == null) return false; + self.size += added; + (function callee() { fs.write(self.fd, data, index, size, offset, function(err, bytes) { if (err) @@ -968,10 +973,8 @@ ChainDB.prototype._writeAsync = function _writeAsync(data, offset, callback) { size -= bytes; offset += bytes; - if (index === data.length) { - self.size += added; + if (index === data.length) return callback(null, true); - } callee(); });