Skip to content
This repository was archived by the owner on Feb 12, 2024. It is now read-only.

Commit 61e7f86

Browse files
Jacob Heundaviddias
Jacob Heun
authored andcommitted
docs: Tutorial - How to customize the IPFS Repo
* docs: add example to show how to customize ipfs repo * feat: allow repo options to be passed in the ipfs constructor * docs: update repo creation in custom repo example * docs: update custom repo example remove ability to add repoOptions in favor of just supplying a repo chore: remove outdated options * docs: fix incorrect description in custom repo example automatically stop the node in the custom repo example docs: update custom repo example * docs: clarify custom-repo docs chore: bump custom repo example ipfs-repo version * docs: add a step to have users check their local repo fix: resolve bugs in the custom s3 lock
1 parent c3d2d1e commit 61e7f86

File tree

5 files changed

+255
-0
lines changed

5 files changed

+255
-0
lines changed

examples/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Let us know if you find any issue or if you want to contribute and add a new tut
2121
- [js-ipfs in the browser with a `<script>` tag](./browser-script-tag)
2222
- [js-ipfs in electron](./run-in-electron)
2323
- [Using streams to add a directory of files to ipfs](./browser-add-readable-stream)
24+
- [Customizing the ipfs repository](./custom-ipfs-repo)
2425

2526
## Understanding the IPFS Stack
2627

examples/custom-ipfs-repo/README.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Customizing the IPFS Repo
2+
3+
This example shows you how to customize your repository, including where your data is stored and how the repo locking is managed. Customizing your repo makes it easier to extend IPFS for your particular needs. You may want to customize your repo if:
4+
5+
* If you want to store data somewhere that’s not on your local disk, like S3, a Redis instance, a different machine on your local network, or in your own database system, like MongoDB or Postgres, you might use a custom datastore.
6+
* If you have multiple browser windows or workers sharing the same IPFS storage, you might want to use a custom lock to coordinate between them. (Locking is currently only used to ensure a single IPFS instance can access a repo at a time. This check is done on `repo.open()`. A more complex lock, coupled with a custom datastore, could allow for safe writes to a single datastore from multiple IPFS nodes.)
7+
8+
You can find full details on customization in the [IPFS Repo Docs](https://github.com./ipfs/js-ipfs-repo#setup).
9+
10+
## Run this example
11+
12+
```
13+
> npm install
14+
> npm start
15+
```
16+
17+
## Other Options
18+
19+
### Custom `storageBackends`
20+
This example leverages [datastore-fs](https://github.com./ipfs/js-datastore-fs) to store all data in the IPFS Repo. You can customize each of the 4 `storageBackends` to meet the needs of your project. For an example on how to manage your entire IPFS REPO on S3, you can see the [datastore-s3 example](https://github.com./ipfs/js-datastore-s3/tree/master/examples/full-s3-repo).
21+
22+
### Custom Repo Lock
23+
This example uses one of the locks that comes with IPFS Repo. If you would like to control how locking happens, such as with a centralized S3 IPFS Repo, you can pass in your own custom lock. See [custom-lock.js](./custom-lock.js) for an example of a custom lock that can be used for [datastore-s3](https://github.com./ipfs/js-datastore-s3). This is also being used in the [full S3 example](https://github.com./ipfs/js-datastore-s3/tree/master/examples/full-s3-repo).
24+
25+
```js
26+
const S3Lock = require('./custom-lock')
27+
28+
const repo = new Repo('/tmp/.ipfs', {
29+
...
30+
lock: new S3Lock(s3DatastoreInstance)
31+
})
32+
```
+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
'use strict'
2+
3+
const PATH = require('path')
4+
5+
/**
6+
* Uses an object in an S3 bucket as a lock to signal that an IPFS repo is in use.
7+
* When the object exists, the repo is in use. You would normally use this to make
8+
* sure multiple IPFS nodes don’t use the same S3 bucket as a datastore at the same time.
9+
*/
10+
class S3Lock {
11+
constructor (s3Datastore) {
12+
this.s3 = s3Datastore
13+
}
14+
15+
/**
16+
* Returns the location of the lock file given the path it should be located at
17+
*
18+
* @private
19+
* @param {string} dir
20+
* @returns {string}
21+
*/
22+
getLockfilePath (dir) {
23+
return PATH.join(dir, 'repo.lock')
24+
}
25+
26+
/**
27+
* Creates the lock. This can be overriden to customize where the lock should be created
28+
*
29+
* @param {string} dir
30+
* @param {function(Error, LockCloser)} callback
31+
* @returns {void}
32+
*/
33+
lock (dir, callback) {
34+
const lockPath = this.getLockfilePath(dir)
35+
36+
this.locked(dir, (err, alreadyLocked) => {
37+
if (err || alreadyLocked) {
38+
return callback(new Error('The repo is already locked'))
39+
}
40+
41+
// There's no lock yet, create one
42+
this.s3.put(lockPath, Buffer.from(''), (err, data) => {
43+
if (err) {
44+
return callback(err, null)
45+
}
46+
47+
callback(null, this.getCloser(lockPath))
48+
})
49+
})
50+
}
51+
52+
/**
53+
* Returns a LockCloser, which has a `close` method for removing the lock located at `lockPath`
54+
*
55+
* @param {string} lockPath
56+
* @returns {LockCloser}
57+
*/
58+
getCloser (lockPath) {
59+
return {
60+
/**
61+
* Removes the lock. This can be overriden to customize how the lock is removed. This
62+
* is important for removing any created locks.
63+
*
64+
* @param {function(Error)} callback
65+
* @returns {void}
66+
*/
67+
close: (callback) => {
68+
this.s3.delete(lockPath, (err) => {
69+
if (err && err.statusCode !== 404) {
70+
return callback(err)
71+
}
72+
73+
callback(null)
74+
})
75+
}
76+
}
77+
}
78+
79+
/**
80+
* Calls back on whether or not a lock exists. Override this method to customize how the check is made.
81+
*
82+
* @param {string} dir
83+
* @param {function(Error, boolean)} callback
84+
* @returns {void}
85+
*/
86+
locked (dir, callback) {
87+
this.s3.get(this.getLockfilePath(dir), (err, data) => {
88+
if (err && err.message.match(/not found/)) {
89+
return callback(null, false)
90+
} else if (err) {
91+
return callback(err)
92+
}
93+
94+
callback(null, true)
95+
})
96+
}
97+
}
98+
99+
module.exports = S3Lock

examples/custom-ipfs-repo/index.js

+107
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
'use strict'
2+
3+
const IPFS = require('ipfs')
4+
const Repo = require('ipfs-repo')
5+
const fsLock = require('ipfs-repo/src/lock')
6+
7+
// Create our custom options
8+
const customRepositoryOptions = {
9+
10+
/**
11+
* IPFS nodes store different information in separate storageBackends, or datastores.
12+
* Each storage backend can use the same type of datastore or a different one — you
13+
* could store your keys in a levelDB database while everything else is in files,
14+
* for example. (See https://github.com./ipfs/interface-datastore for more about datastores.)
15+
*/
16+
storageBackends: {
17+
root: require('datastore-fs'), // version and config data will be saved here
18+
blocks: require('datastore-fs'),
19+
keys: require('datastore-fs'),
20+
datastore: require('datastore-fs')
21+
},
22+
23+
/**
24+
* Storage Backend Options will get passed into the instantiation of their counterpart
25+
* in `storageBackends`. If you create a custom datastore, this is where you can pass in
26+
* custom constructor arguments. You can see an S3 datastore example at:
27+
* https://github.com./ipfs/js-datastore-s3/tree/master/examples/full-s3-repo
28+
*
29+
* NOTE: The following options are being overriden for demonstration purposes only.
30+
* In most instances you can simply use the default options, by not passing in any
31+
* overrides, which is recommended if you have no need to override.
32+
*/
33+
storageBackendOptions: {
34+
root: {
35+
extension: '.ipfsroot', // Defaults to ''. Used by datastore-fs; Appended to all files
36+
errorIfExists: false, // Used by datastore-fs; If the datastore exists, don't throw an error
37+
createIfMissing: true // Used by datastore-fs; If the datastore doesn't exist yet, create it
38+
},
39+
blocks: {
40+
sharding: false, // Used by IPFSRepo Blockstore to determine sharding; Ignored by datastore-fs
41+
extension: '.ipfsblock', // Defaults to '.data'.
42+
errorIfExists: false,
43+
createIfMissing: true
44+
},
45+
keys: {
46+
extension: '.ipfskey', // No extension by default
47+
errorIfExists: false,
48+
createIfMissing: true
49+
},
50+
datastore: {
51+
extension: '.ipfsds', // No extension by default
52+
errorIfExists: false,
53+
createIfMissing: true
54+
}
55+
},
56+
57+
/**
58+
* A custom lock can be added here. Or the build in Repo `fs` or `memory` locks can be used.
59+
* See https://github.com./ipfs/js-ipfs-repo for more details on setting the lock.
60+
*/
61+
lock: fsLock
62+
}
63+
64+
// Initialize our IPFS node with the custom repo options
65+
const node = new IPFS({
66+
repo: new Repo('/tmp/custom-repo/.ipfs', customRepositoryOptions)
67+
})
68+
69+
// Test the new repo by adding and fetching some data
70+
node.on('ready', () => {
71+
console.log('Ready')
72+
node.version()
73+
.then((version) => {
74+
console.log('Version:', version.version)
75+
})
76+
// Once we have the version, let's add a file to IPFS
77+
.then(() => {
78+
return node.files.add({
79+
path: 'test-data.txt',
80+
content: Buffer.from('We are using a customized repo!')
81+
})
82+
})
83+
// Log out the added files metadata and cat the file from IPFS
84+
.then((filesAdded) => {
85+
console.log('\nAdded file:', filesAdded[0].path, filesAdded[0].hash)
86+
return node.files.cat(filesAdded[0].hash)
87+
})
88+
// Print out the files contents to console
89+
.then((data) => {
90+
console.log('\nFetched file content:')
91+
process.stdout.write(data)
92+
})
93+
// Log out the error, if there is one
94+
.catch((err) => {
95+
console.log('File Processing Error:', err)
96+
})
97+
// After everything is done, shut the node down
98+
// We don't need to worry about catching errors here
99+
.then(() => {
100+
console.log('\n\nStopping the node')
101+
return node.stop()
102+
})
103+
// Let users know where they can inspect the repo
104+
.then(() => {
105+
console.log('Check "/tmp/custom-repo/.ipfs" to see what your customized repository looks like on disk.')
106+
})
107+
})
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "custom-ipfs-repo",
3+
"version": "0.1.0",
4+
"description": "Customizing your ipfs repo",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1",
8+
"start": "node index.js"
9+
},
10+
"license": "MIT",
11+
"dependencies": {
12+
"datastore-fs": "~0.4.2",
13+
"ipfs": "file:../../",
14+
"ipfs-repo": "^0.20.0"
15+
}
16+
}

0 commit comments

Comments
 (0)