From 2ee01cbeaa9019b7ee46da43a78448d7e62c4a8b Mon Sep 17 00:00:00 2001 From: Jared Grippe Date: Thu, 4 Aug 2022 14:45:50 -0700 Subject: [PATCH] added core.update({ minLength: n }) and core.waitForLength(n) --- index.js | 17 ++++++++++++++++ test/replicate.js | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/index.js b/index.js index 2117088..2169880 100644 --- a/index.js +++ b/index.js @@ -626,11 +626,28 @@ module.exports = class Hypercore extends EventEmitter { if (!upgraded) upgraded = this.contiguousLength !== contig } + if (opts && typeof opts.minLength === 'number') { + await this.waitForLength(opts.minLength) + } + if (!upgraded) return false if (this.snapshotted) return this._updateSnapshot() return true } + waitForLength (minLength = 0) { + return new Promise(resolve => { + if (this.length >= minLength) return resolve(this.length) + const onAppend = () => { + if (this.length >= minLength) { + this.removeListener('append', onAppend) + resolve(this.length) + } + } + this.on('append', onAppend) + }) + } + async seek (bytes, opts) { if (this.opened === false) await this.opening diff --git a/test/replicate.js b/test/replicate.js index 2234ad6..de700bf 100644 --- a/test/replicate.js +++ b/test/replicate.js @@ -840,3 +840,55 @@ test('sparse replication without gossiping', async function (t) { t.alike(await c.seek(4), [4, 0]) }) }) + +test('sparse update with minLength', async function (t) { + const a = await create() + const b = await create(a.key) + replicate(a, b, t) + + await a.append(['1', '2']) + await b.update() + t.is(b.length, 2) + + const updateLength5 = t.test('updateLength5') + updateLength5.plan(1) + + b.update({ minLength: 5 }).then(() => { + updateLength5.pass() + }) + + await a.append(['3']) + await eventFlush() + await a.append(['4']) + await eventFlush() + await a.append(['5']) + + await updateLength5 + t.is(b.length, 5) +}) + +test('non-sparse update with minLength', async function (t) { + const a = await create() + const b = await create(a.key, { sparse: false }) + replicate(a, b, t) + + await a.append(['1', '2']) + await b.update() + t.is(b.length, 2) + + const updateLength5 = t.test('updateLength5') + updateLength5.plan(1) + + b.update({ minLength: 5 }).then(() => { + updateLength5.pass() + }) + + await a.append(['3']) + await eventFlush() + await a.append(['4']) + await eventFlush() + await a.append(['5']) + + await updateLength5 + t.is(b.length, 5) +})