Skip to content

Commit

Permalink
Support cas callback with prev being null
Browse files Browse the repository at this point in the history
  • Loading branch information
LuKks committed Aug 8, 2023
1 parent e21bde2 commit 4efbd1e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,8 @@ class Batch {
node = await node.getChildNode(i)
}

if (!node.block && cas && !(await cas(null, newNode))) return this._unlockMaybe()

let needsSplit = !(await node.insertKey(target, null, newNode, encoding, cas))
if (!node.changed) return this._unlockMaybe()

Expand Down
58 changes: 58 additions & 0 deletions test/cas.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,64 @@ const test = require('brittle')
const b4a = require('b4a')
const { create } = require('./helpers')

test('cas is called when prev does not exists', async function (t) {
t.plan(5)

const db = create()

t.comment('first put')

await db.put('/a', '1', {
cas: function (prev, next) {
t.comment('first cb')

t.is(prev, null)
t.alike(next, { seq: 1, key: '/a', value: '1' })

return true
}
})

t.comment('second put')

await db.put('/a', '1', {
cas: function (prev, next) {
t.comment('second cb')

t.alike(prev, { seq: 1, key: '/a', value: '1' })
t.alike(next, { seq: 2, key: '/a', value: '1' })

return true
}
})

t.alike(await db.get('/a'), { seq: 2, key: '/a', value: '1' })
})

test('cas is respected when prev does not exists', async function (t) {
t.plan(5)

const db = create()

await db.put('/a', '1', {
cas: function (prev, next) {
t.is(prev, null)
t.alike(next, { seq: 1, key: '/a', value: '1' })
return false
}
})

await db.put('/a', '1', {
cas: function (prev, next) {
t.is(prev, null)
t.alike(next, { seq: 1, key: '/a', value: '1' })
return false
}
})

t.is(await db.get('/a'), null)
})

test('bee.put({ cas }) succeds if cas(last, next) returns truthy', async function (t) {
const key = 'key'
const value = 'value'
Expand Down

0 comments on commit 4efbd1e

Please sign in to comment.