Skip to content

Commit

Permalink
add autoclose flag and make sessions public
Browse files Browse the repository at this point in the history
  • Loading branch information
chm-diederichs committed Sep 5, 2024
1 parent 15b205f commit 758ea21
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,11 +248,11 @@ class ReadBatch {
}

module.exports = class CoreStorage {
constructor (dir) {
constructor (dir, { autoClose = true } = {}) {
this.db = new RocksDB(dir)
this.mutex = new RW()

this._sessions = 0
this.sessions = 0
}

// just a helper to make tests easier
Expand Down Expand Up @@ -318,22 +318,22 @@ module.exports = class CoreStorage {
}

get (discoveryKey) {
return new HypercoreStorage(this.db, this.mutex, discoveryKey, this)
return new HypercoreStorage(this, this.mutex, discoveryKey)
}

_onclose () {
if (--this._sessions > 0) return
if (!this.autoClose || --this.sessions > 0) return Promise.resolve()
return this.db.close()
}
}

class HypercoreStorage {
constructor (db, mutex, discoveryKey, root) {
this.db = db
constructor (root, mutex, discoveryKey) {
this.root = root
this.db = root.db
this.mutex = mutex

this.root = root
this.root._sessions++
this.root.sessions++

this.discoveryKey = discoveryKey || null

Expand All @@ -342,6 +342,8 @@ class HypercoreStorage {
// pointers
this.corePointer = -1
this.dataPointer = -1

this.closed = false
}

async open () {
Expand Down Expand Up @@ -420,7 +422,7 @@ class HypercoreStorage {
async registerBatch (name, length, overwrite) {
// todo: make sure opened
const existing = await this.db.get(encodeBatch(this.corePointer, CORE.BATCHES, name))
const storage = new HypercoreStorage(this.db, this.mutex, this.discoveryKey, this.root)
const storage = new HypercoreStorage(this.root, this.mutex, this.discoveryKey)

storage.corePointer = this.corePointer

Expand Down Expand Up @@ -608,7 +610,7 @@ class HypercoreStorage {
}

close () {
if (this.closed) return
if (this.closed) return Promise.resolve()
this.closed = true

return this.root._onclose()
Expand Down

0 comments on commit 758ea21

Please sign in to comment.