Skip to content

Commit

Permalink
Defer pending ops (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
mafintosh authored Sep 20, 2024
1 parent a7d0385 commit 51ab83b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
20 changes: 20 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const RocksDB = module.exports = class RocksDB extends ReadyResource {
this.tableFormatVersion = tableFormatVersion

this._snapshots = new Set()
this._refs = 0
this._resolvePreclose = null

this._handle = binding.init()
}
Expand Down Expand Up @@ -87,6 +89,12 @@ const RocksDB = module.exports = class RocksDB extends ReadyResource {
}

async _close () {
if (this._refs > 0) {
await new Promise((resolve) => {
this._resolvePreclose = resolve
})
}

for (const snapshot of this._snapshots) snapshot.destroy()

const req = { resolve: null, reject: null, handle: null }
Expand All @@ -108,6 +116,18 @@ const RocksDB = module.exports = class RocksDB extends ReadyResource {
}
}

_incRef () {
this._refs++
}

_decRef () {
if (--this._refs === 0 && this._resolvePreclose !== null) {
const resolve = this._resolvePreclose
this._resolvePreclose = null
resolve()
}
}

snapshot (opts) {
return new Snapshot(this, opts)
}
Expand Down
6 changes: 5 additions & 1 deletion lib/batch.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const b4a = require('b4a')
const binding = require('../binding')

const empty = b4a.alloc(0)
const emptyPromise = Promise.resolve()

class RocksDBBatch {
constructor (db, opts = {}) {
Expand All @@ -13,6 +14,8 @@ class RocksDBBatch {
valueEncoding = encoding
} = opts

db._incRef()

this._db = db
this._capacity = capacity
this._operations = []
Expand All @@ -39,6 +42,7 @@ class RocksDBBatch {
this._promises = []
this._request = null
this._resolveRequest = null
this._db._decRef()

if (resolve !== null) resolve()
}
Expand Down Expand Up @@ -73,7 +77,7 @@ class RocksDBBatch {
tryFlush () {
if (this._request) throw new Error('Request already in progress')

this._request = true
this._request = emptyPromise
this._flush()
}

Expand Down
3 changes: 3 additions & 0 deletions lib/iterator.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ module.exports = class RocksDBIterator extends Readable {

super()

db._incRef()

this._db = db

this._keyEncoding = keyEncoding
Expand Down Expand Up @@ -75,6 +77,7 @@ module.exports = class RocksDBIterator extends Readable {
_onclose (err) {
const cb = this._pendingDestroy
this._pendingDestroy = null
this._db._decRef()
cb(err)
}

Expand Down

0 comments on commit 51ab83b

Please sign in to comment.