Skip to content

Commit

Permalink
Add interrupt API (#164)
Browse files Browse the repository at this point in the history
* spelling

* test and tweaks

* typo

* reset flag pre emit

* interrupt takes a reason

* better api
  • Loading branch information
mafintosh authored and andrewosh committed Jul 5, 2024
1 parent 88e6b44 commit 4f014d1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
13 changes: 13 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const CorePool = require('./lib/core-pool')
const AutoWakeup = require('./lib/wakeup')

const inspect = Symbol.for('nodejs.util.inspect.custom')
const INTERRUPT = new Error('Apply interrupted')

const AUTOBASE_VERSION = 1

Expand Down Expand Up @@ -130,6 +131,7 @@ module.exports = class Autobase extends ReadyResource {
this.view = null
this.system = null
this.version = -1
this.interrupted = null

this.maxCacheSize = handlers.maxCacheSize || 0 // 0 means the hyperbee default cache size will be used

Expand Down Expand Up @@ -348,6 +350,12 @@ module.exports = class Autobase extends ReadyResource {
}
}

interrupt (reason) {
assert(this._applying !== null, 'Interrupt is only allowed in apply')
if (reason) this.interrupted = reason
throw INTERRUPT
}

async flush () {
if (this.opened === false) await this.ready()
await this._advancing
Expand Down Expand Up @@ -614,6 +622,11 @@ module.exports = class Autobase extends ReadyResource {
if (this.closing) return
this.close().catch(safetyCatch)

if (err === INTERRUPT) {
this.emit('interrupt', this.interrupted)
return
}

// if no one is listening we should crash! we cannot rely on the EE here
// as this is wrapped in a promise so instead of nextTick throw it
if (ReadyResource.listenerCount(this, 'error') === 0) {
Expand Down
30 changes: 30 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,36 @@ test('basic - maxCacheSize has 0 default', async t => {
t.is(base.maxCacheSize, 0, 'maxCacheSize default 0')
})

test('basic - interrupt', async t => {
t.plan(2)

const { bases } = await create(1, t, { apply: applyWithInterupt })

const a = bases[0]

a.on('error', function () {
t.fail('should not error')
})
a.on('interrupt', function () {
t.pass('was interrupted')
})

await a.append({ hello: true })
await a.append({ interrupt: true })

try {
await a.append({ hello: true })
} catch {
t.pass('should throw')
}

function applyWithInterupt (nodes, view, base) {
for (const node of nodes) {
if (node.value.interrupt) base.interrupt()
}
}
})

// todo: this test is hard, probably have to rely on ff to recover
test.skip('basic - writer adds a writer while being removed', async t => {
const { bases } = await create(4, t, { apply: applyWithRemove })
Expand Down

0 comments on commit 4f014d1

Please sign in to comment.