From 4efbd1e19ccabb7289aab11dcc01f1f5b96fc740 Mon Sep 17 00:00:00 2001 From: Lucas Barrena Date: Tue, 8 Aug 2023 15:06:20 -0300 Subject: [PATCH] Support cas callback with prev being null --- index.js | 2 ++ test/cas.js | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/index.js b/index.js index 96790d01..082d5559 100644 --- a/index.js +++ b/index.js @@ -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() diff --git a/test/cas.js b/test/cas.js index 777f9cb0..04c34289 100644 --- a/test/cas.js +++ b/test/cas.js @@ -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'