Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: add DataStore.writeRaw method #334

Merged
merged 4 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/datastore/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,26 @@ export class DataStore extends TypedEmitter {
if (!block) throw new Error('Not Found')
return decode(block, { coreDiscoveryKey, index })
}

/** @param {Buffer} buf} */
async writeRaw(buf) {
const { length } = await this.#writerCore.append(buf)
const index = length - 1
const coreDiscoveryKey = this.#writerCore.discoveryKey
if (!coreDiscoveryKey) {
throw new Error('Writer core is not ready')
}
const versionId = getVersionId({ coreDiscoveryKey, index })
return versionId
}

/** @param {string} versionId */
async readRaw(versionId) {
const { coreDiscoveryKey, index } = parseVersionId(versionId)
const core = this.#coreManager.getCoreByDiscoveryKey(coreDiscoveryKey)
if (!core) throw new Error('Invalid versionId')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is actually a not found error, because the versionId parsed ok so it is valid.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would happen when a peer has not synced the core that has the data.

const block = await core.get(index, { wait: false })
if (!block) throw new Error('Not Found')
return block
}
}
18 changes: 18 additions & 0 deletions tests/datastore.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,24 @@ test('read and write', async (t) => {
)
})

test('writeRaw and read', async (t) => {
const cm = createCoreManager()
const writerCore = cm.getWriterCore('config').core
await writerCore.ready()
const dataStore = new DataStore({
coreManager: cm,
namespace: 'config',
batch: async () => {
await new Promise((res) => setTimeout(res, 10))
},
storage: () => new RAM(),
})
const buf = Buffer.from('myblob')
const versionId = await dataStore.writeRaw(buf)
const expectedBuf = await dataStore.readRaw(versionId)
t.alike(buf, expectedBuf)
})

test('index events', async (t) => {
const cm = createCoreManager()
const writerCore = cm.getWriterCore('data').core
Expand Down