Skip to content

Commit

Permalink
feat: integration of js-ipfs-repo-migrations
Browse files Browse the repository at this point in the history
Integration of js-ipfs-repo-migrations brings automatic repo migrations
to ipfs-repo (both in-browser and fs). It is possible to control the
automatic migration using either config's setting
'repoDisableAutoMigration' or IPFSRepo's option 'disableAutoMigration'.

BREAKING CHANGE: repo.blocks.query() now returns multihashes as a key
instead of CID. If you want to have CID returned call it as query({},
true), which will constructs CIDv1 using IPLD's RAW codec. This means
that this constructed CID might not equal to the one that the block was originally
saved. Related to ipfs/js-ipfs#2415

Co-authored-by: achingbrain <alex@achingbrain.net>
  • Loading branch information
AuHau and achingbrain committed Jun 19, 2020
1 parent 4692a47 commit 71503ac
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 97 deletions.
55 changes: 39 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,20 @@ This is the implementation of the [IPFS repo spec](https://github.com/ipfs/specs
- [`Promise<Buffer> repo.get(key)`](#promisebuffer-repogetkey)
- [Blocks](#blocks)
- [`Promise<Block> repo.blocks.put(block:Block)`](#promiseblock-repoblocksputblockblock)
- [`AsyncIterator<Block> repo.blocks.putMany(source)`](#asynciteratorblock-repoblocksputmanysource)
- [`Promise<Buffer> repo.blocks.get(cid)`](#promisebuffer-repoblocksgetcid)
- [`AsyncIterable<Buffer> repo.blocks.getMany(source)`](#asynciterablebuffer-repoblocksgetmanysource)
- [`AsyncIterator<Block> repo.blocks.putMany(source:AsyncIterable<Block>)`](#asynciteratorblock-repoblocksputmanysourceasynciterableblock)
- [`Promise<Block> repo.blocks.get(cid:CID)`](#promiseblock-repoblocksgetcidcid)
- [`AsyncIterable<Block> repo.blocks.getMany(source:AsyncIterable<CID>)`](#asynciterableblock-repoblocksgetmanysourceasynciterablecid)
- [`Promise<boolean> repo.blocks.has (cid:CID)`](#promiseboolean-repoblockshas-cidcid)
- [`Promise<boolean> repo.blocks.delete (cid:CID)`](#promiseboolean-repoblocksdelete-cidcid)
- [`Promise<Array<Object>> repo.blocks.query (query)`](#promisearrayobject-repoblocksquery-query)
- [`Promise<CID> repo.blocks.delete(cid:CID)`](#promisecid-repoblocksdeletecidcid)
- [`AsyncIterator<CID> repo.blocks.deleteMany(source)`](#asynciteratorcid-repoblocksdeletemanysource)
- [`AsyncIterator<CID> repo.blocks.deleteMany(source:AsyncIterable<CID>)`](#asynciteratorcid-repoblocksdeletemanysourceasynciterablecid)
- [Datastore](#datastore)
- [`repo.datastore`](#repodatastore)
- [Config](#config)
- [`Promise repo.config.set(key:string, value)`](#promise-repoconfigsetkeystring-value)
- [`Promise repo.config.replace(value)`](#promise-repoconfigreplacevalue)
- [`Promise<?> repo.config.get(key:string)`](#promise-repoconfiggetkeystring)
- [`Promise repo.config.set(key:String, value:Object)`](#promise-repoconfigsetkeystring-valueobject)
- [`Promise repo.config.replace(value:Object)`](#promise-repoconfigreplacevalueobject)
- [`Promise<?> repo.config.get(key:String)`](#promise-repoconfiggetkeystring)
- [`Promise<Object> repo.config.getAll()`](#promiseobject-repoconfiggetall)
- [`Promise<boolean> repo.config.exists()`](#promiseboolean-repoconfigexists)
- [Version](#version)
Expand Down Expand Up @@ -229,31 +232,51 @@ Get a value at the root of the repo

* `block` should be of type [Block][]

#### `AsyncIterator<Block> repo.blocks.putMany(source)`
#### `AsyncIterator<Block> repo.blocks.putMany(source:AsyncIterable<Block>)`

Put many blocks.

* `source` should be an AsyncIterable that yields entries of type [Block][]

#### `Promise<Buffer> repo.blocks.get(cid)`
#### `Promise<Block> repo.blocks.get(cid:CID)`

Get block.

* `cid` is the content id of type [CID][]

#### `AsyncIterable<Buffer> repo.blocks.getMany(source)`
#### `AsyncIterable<Block> repo.blocks.getMany(source:AsyncIterable<CID>)`

Get block.
Get many blocks

* `source` should be an AsyncIterable that yields entries of type [CID][]

#### `Promise<boolean> repo.blocks.has (cid:CID)`

Indicate if a block is present for the passed CID

* `cid` should be of the type [CID][]

#### `Promise<boolean> repo.blocks.delete (cid:CID)`

Deletes a block

* `cid` should be of the type [CID][]

#### `Promise<Array<Object>> repo.blocks.query (query)`

Query what blocks are available in blockstore.

* `query` is a object as specified in [interface-datastore](https://github.com/ipfs/interface-datastore#query).

Datastore:

#### `Promise<CID> repo.blocks.delete(cid:CID)`

* `cid` should be of the type [CID][]

Delete a block

#### `AsyncIterator<CID> repo.blocks.deleteMany(source)`
#### `AsyncIterator<CID> repo.blocks.deleteMany(source:AsyncIterable<CID>)`

* `source` should be an Iterable or AsyncIterable that yields entries of the type [CID][]

Expand All @@ -269,7 +292,7 @@ This contains a full implementation of [the `interface-datastore` API](https://g

Instead of using `repo.set('config')` this exposes an API that allows you to set and get a decoded config object, as well as, in a safe manner, change any of the config values individually.

#### `Promise repo.config.set(key:string, value)`
#### `Promise repo.config.set(key:String, value:Object)`

Set a config value. `value` can be any object that is serializable to JSON.

Expand All @@ -281,11 +304,11 @@ const config = await repo.config.get()
assert.equal(config.a.b.c, 'c value')
```

#### `Promise repo.config.replace(value)`
#### `Promise repo.config.replace(value:Object)`

Set the whole config value. `value` can be any object that is serializable to JSON.

#### `Promise<?> repo.config.get(key:string)`
#### `Promise<?> repo.config.get(key:String)`

Get a config value. Returned promise resolves to the same type that was set before.

Expand Down Expand Up @@ -379,7 +402,7 @@ Returned promise resolves to a `boolean` indicating the existence of the lock.

### Migrations

When there is a new repo migration and the version of repo is increased, don't
When there is a new repo migration and the version of the repo is increased, don't
forget to propagate the changes into the test repo (`test/test-repo`).

**For tools that run mainly in the browser environment, be aware that disabling automatic
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,10 @@
"debug": "^4.1.0",
"err-code": "^2.0.0",
"interface-datastore": "^1.0.2",
"ipfs-repo-migrations": "^0.2.1",
"ipfs-repo-migrations": "github:ipfs/js-ipfs-repo-migrations#migration/8-multihash_and_keys",
"ipfs-utils": "^2.2.0",
"ipld-block": "^0.9.1",
"it-map": "^1.0.2",
"it-pipe": "^1.1.0",
"just-safe-get": "^2.0.0",
"just-safe-set": "^2.1.0",
"multibase": "^0.7.0",
Expand Down
7 changes: 5 additions & 2 deletions src/blockstore-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,18 @@ exports.cidToKey = cid => {
throw errcode(new Error('Not a valid cid'), 'ERR_INVALID_CID')
}

return new Key('/' + multibase.encode('base32', cid.buffer).toString().slice(1).toUpperCase(), false)
return new Key('/' + multibase.encode('base32', cid.multihash).toString().slice(1).toUpperCase(), false)
}

/**
* Transform a datastore Key instance to a CID
* As Key is a multihash of the CID, it is reconstructed using IPLD's RAW codec.
* Hence it is highly probable that stored CID will differ from a CID retrieved from blockstore.
*
* @param {Key} key
* @returns {CID}
*/
exports.keyToCid = key => {
return new CID(multibase.decode('b' + key.toString().slice(1).toLowerCase()))
// Block key is of the form /<base32 encoded string>
return new CID(1, 'raw', multibase.decode('b' + key.toString().slice(1).toLowerCase()))
}
93 changes: 28 additions & 65 deletions src/blockstore.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
const core = require('datastore-core')
const ShardingStore = core.ShardingDatastore
const Block = require('ipld-block')
const { cidToKey, keyToCid } = require('./blockstore-utils')
const { cidToKey } = require('./blockstore-utils')
const map = require('it-map')
const pipe = require('it-pipe')

module.exports = async (filestore, options) => {
const store = await maybeWithSharding(filestore, options)
Expand All @@ -32,6 +31,7 @@ function createBaseStore (store) {
async * query (query, options) { // eslint-disable-line require-await
yield * store.query(query, options)
},

/**
* Get a single block by CID.
*
Expand All @@ -41,27 +41,11 @@ function createBaseStore (store) {
*/
async get (cid, options) {
const key = cidToKey(cid)
let blockData
try {
blockData = await store.get(key, options)
return new Block(blockData, cid)
} catch (err) {
if (err.code === 'ERR_NOT_FOUND') {
const otherCid = cidToOtherVersion(cid)

if (!otherCid) {
throw err
}

const otherKey = cidToKey(otherCid)
const blockData = await store.get(otherKey, options)
await store.put(key, blockData)
return new Block(blockData, cid)
}
const blockData = await store.get(key, options)

throw err
}
return new Block(blockData, cid)
},

/**
* Like get, but for more.
*
Expand All @@ -74,6 +58,7 @@ function createBaseStore (store) {
yield this.get(cid, options)
}
},

/**
* Write a single block to the store.
*
Expand All @@ -86,14 +71,13 @@ function createBaseStore (store) {
throw new Error('invalid block')
}

const exists = await this.has(block.cid)
const key = cidToKey(block.cid)
const exists = await store.has(key, options)

if (exists) {
return this.get(block.cid, options)
if (!exists) {
await store.put(key, block.data, options)
}

await store.put(cidToKey(block.cid), block.data, options)

return block
},

Expand All @@ -104,41 +88,30 @@ function createBaseStore (store) {
* @param {Object} options
* @returns {AsyncIterable<Block>}
*/
async * putMany (blocks, options) { // eslint-disable-line require-await
yield * pipe(
blocks,
(source) => {
// turn them into a key/value pair
return map(source, (block) => {
return { key: cidToKey(block.cid), value: block.data }
})
},
(source) => {
// put them into the datastore
return store.putMany(source, options)
},
(source) => {
// map the returned key/value back into a block
return map(source, ({ key, value }) => {
return new Block(value, keyToCid(key))
})
async * putMany (blocks, options) {
for await (const block of blocks) {
const key = cidToKey(block.cid)
const exists = await store.has(key, options)

if (!exists) {
await store.put(key, block.data, options)
}
)

yield block
}
},

/**
* Does the store contain block with this cid?
* Does the store contain block with this CID?
*
* @param {CID} cid
* @param {Object} options
* @returns {Promise<bool>}
*/
async has (cid, options) {
const exists = await store.has(cidToKey(cid), options)
if (exists) return exists
const otherCid = cidToOtherVersion(cid)
if (!otherCid) return false
return store.has(cidToKey(otherCid), options)
async has (cid, options) { // eslint-disable-line require-await
return store.has(cidToKey(cid), options)
},

/**
* Delete a block from the store
*
Expand All @@ -149,6 +122,7 @@ function createBaseStore (store) {
async delete (cid, options) { // eslint-disable-line require-await
return store.delete(cidToKey(cid), options)
},

/**
* Delete a block from the store
*
Expand All @@ -157,12 +131,9 @@ function createBaseStore (store) {
* @returns {Promise<void>}
*/
async * deleteMany (cids, options) { // eslint-disable-line require-await
yield * store.deleteMany((async function * () {
for await (const cid of cids) {
yield cidToKey(cid)
}
}()), options)
yield * store.deleteMany(map(cids, cid => cidToKey(cid)), options)
},

/**
* Close the store
*
Expand All @@ -173,11 +144,3 @@ function createBaseStore (store) {
}
}
}

function cidToOtherVersion (cid) {
try {
return cid.version === 0 ? cid.toV1() : cid.toV0()
} catch (err) {
return null
}
}
2 changes: 1 addition & 1 deletion src/constants.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict'

module.exports = {
repoVersion: 7
repoVersion: 8
}
10 changes: 5 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ const lockers = {
*/
class IpfsRepo {
/**
* @param {string} repoPath - path where the repo is stored
* @param {object} options - Configuration
* @param {String} repoPath - path where the repo is stored
* @param {Object} options - Configuration
*/
constructor (repoPath, options) {
if (typeof repoPath !== 'string') {
Expand Down Expand Up @@ -185,7 +185,7 @@ class IpfsRepo {
* Creates a lock on the repo if a locker is specified. The lockfile object will
* be returned in the callback if one has been created.
*
* @param {string} path
* @param {String} path
* @returns {Promise<lockfile>}
*/
async _openLock (path) {
Expand Down Expand Up @@ -354,7 +354,7 @@ class IpfsRepo {
count = count.plus(1)
size = size
.plus(block.value.byteLength)
.plus(block.key._buf.byteLength)
.plus(block.key.toBuffer().byteLength)
}

return { count, size }
Expand All @@ -365,7 +365,7 @@ async function getSize (queryFn) {
const sum = new Big(0)
for await (const block of queryFn.query({})) {
sum.plus(block.value.byteLength)
.plus(block.key._buf.byteLength)
.plus(block.key.toBuffer().byteLength)
}
return sum
}
Expand Down
4 changes: 2 additions & 2 deletions src/lock-memory.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const LOCKS = {}
/**
* Lock the repo in the given dir.
*
* @param {string} dir
* @param {String} dir
* @returns {Promise<Object>}
*/
exports.lock = async (dir) => { // eslint-disable-line require-await
Expand All @@ -37,7 +37,7 @@ exports.lock = async (dir) => { // eslint-disable-line require-await
/**
* Check if the repo in the given directory is locked.
*
* @param {string} dir
* @param {String} dir
* @returns {bool}
*/
exports.locked = async (dir) => { // eslint-disable-line require-await
Expand Down
2 changes: 1 addition & 1 deletion src/lock.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const STALE_TIME = 20000
/**
* Lock the repo in the given dir.
*
* @param {string} dir
* @param {String} dir
* @returns {Promise<Object>}
*/
exports.lock = async (dir) => {
Expand Down
Loading

0 comments on commit 71503ac

Please sign in to comment.