-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
277 lines (258 loc) · 9.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import debug from 'debug'
import { CID } from 'multiformats/cid'
import * as dagPB from '@ipld/dag-pb'
import * as Block from 'multiformats/block'
import { exporter, walkPath } from 'ipfs-unixfs-exporter'
import { transform } from 'streaming-iterables'
import { Decoders, Hashers } from './defaults.js'
import { identity } from 'multiformats/hashes/identity'
const log = debug('dagula')
export class Dagula {
/** @type {import('./index').Blockstore} */
#blockstore
/** @type {import('./index').BlockDecoders} */
#decoders
/** @type {import('./index').MultihashHashers} */
#hashers
/**
* @param {import('./index').Blockstore} blockstore
* @param {{
* decoders?: import('./index').BlockDecoders,
* hashers?: import('./index').MultihashHashers
* }} [options]
*/
constructor (blockstore, options = {}) {
this.#blockstore = blockstore
this.#decoders = options.decoders || Decoders
this.#hashers = options.hashers || Hashers
}
/**
* @param {CID[]|CID|string} cid
* @param {object} [options]
* @param {AbortSignal} [options.signal]
* @param {(block: import('multiformats').BlockView) => CID[]} [options.search]
*/
async * get (cid, options = {}) {
cid = typeof cid === 'string' ? CID.parse(cid) : cid
log('getting DAG %s', cid)
let cids = Array.isArray(cid) ? cid : [cid]
const search = options.search || breadthFirstSearch()
/** @type {AbortController[]} */
let aborters = []
const { signal } = options
signal?.addEventListener('abort', () => aborters.forEach(a => a.abort(signal.reason)))
while (cids.length > 0) {
log('fetching %d CIDs', cids.length)
const fetchBlocks = transform(cids.length, async cid => {
if (signal) {
const aborter = new AbortController()
aborters.push(aborter)
const block = await this.getBlock(cid, { signal: aborter.signal })
aborters = aborters.filter(a => a !== aborter)
return block
}
return this.getBlock(cid)
})
let nextCids = []
for await (const { cid, bytes } of fetchBlocks(cids)) {
const decoder = this.#decoders[cid.code]
if (!decoder) {
yield { cid, bytes }
throw new Error(`unknown codec: ${cid.code}`)
}
const hasher = this.#hashers[cid.multihash.code]
if (!hasher) {
yield { cid, bytes }
throw new Error(`unknown multihash codec: ${cid.multihash.code}`)
}
log('decoding block %s', cid)
// bitswap-fetcher _must_ verify hashes on receipt of a block, but we
// cannot guarantee the blockstore passed is a bitswap so cannot use
// createUnsafe here.
const block = await Block.create({ bytes, cid, codec: decoder, hasher })
yield block
nextCids = nextCids.concat(search(block))
}
log('%d CIDs in links', nextCids.length)
cids = nextCids
}
}
/**
* Yield all blocks traversed to resolve the ipfs path.
* Then use carScope to determine the set of blocks of the targeted dag to yield.
* Yield all blocks by default.
* Use carScope: 'block' to yield the termimal block.
* Use carScope: 'file' to yield all the blocks of a unixfs file, or enough blocks to list a directory.
*
* @param {string} cidPath
* @param {object} [options]
* @param {AbortSignal} [options.signal]
* @param {'all'|'file'|'block'} [options.carScope] control how many layers of the dag are returned
* 'all': return the entire dag starting at path. (default)
* 'block': return the block identified by the path.
* 'file': Mimic gateway semantics: Return All blocks for a multi-block file or just enough blocks to enumerate a dir/map but not the dir contents.
* Where path points to a single block file, all three selectors would return the same thing.
* where path points to a sharded hamt: 'file' returns the blocks of the hamt so the dir can be listed. 'block' returns the root block of the hamt.
*/
async * getPath (cidPath, options = {}) {
const carScope = options.carScope ?? 'all'
/**
* The resolved dag root at the terminus of the cidPath
* @type {import('ipfs-unixfs-exporter').UnixFSEntry}
*/
let base
/**
* Cache of blocks required to resove the cidPath
* @type {import('./index').Block[]}
*/
let traversed = []
/**
* Adapter for unixfs-exporter to track the blocks it loads as it resolves the path.
* `walkPath` emits a single unixfs entry for multiblock structures, but we need the individual blocks.
* TODO: port logic to @web3-storage/ipfs-path to make this less ugly.
*/
const blockstore = {
/**
* @param {CID} cid
* @param {{ signal?: AbortSignal }} [options]
*/
get: async (cid, options) => {
const block = await this.getBlock(cid, options)
traversed.push(block)
return block.bytes
}
}
for await (const item of walkPath(cidPath, blockstore, { signal: options.signal })) {
base = item
yield * traversed
traversed = []
}
if (carScope === 'all' || (carScope === 'file' && base.type !== 'directory')) {
const links = getLinks(base, this.#decoders)
// fetch the entire dag rooted at the end of the provided path
if (links.length) {
yield * this.get(links, { signal: options.signal })
}
}
// non-files, like directories, and IPLD Maps only return blocks necessary for their enumeration
if (carScope === 'file' && base.type === 'directory') {
// the single block for the root has already been yielded.
// For a hamt we must fetch all the blocks of the (current) hamt.
if (base.unixfs.type === 'hamt-sharded-directory') {
const hamtLinks = base.node.Links?.filter(l => l.Name.length === 2).map(l => l.Hash) || []
if (hamtLinks.length) {
yield * this.get(hamtLinks, { search: hamtSearch, signal: options.signal })
}
}
}
}
/**
* @param {import('multiformats').CID|string} cid
* @param {{ signal?: AbortSignal }} [options]
*/
async getBlock (cid, options = {}) {
cid = typeof cid === 'string' ? CID.parse(cid) : cid
log('getting block %s', cid)
if (cid.code === identity.code) {
return { cid, bytes: cid.multihash.digest }
}
const block = await this.#blockstore.get(cid, { signal: options.signal })
if (!block) {
throw Object.assign(new Error(`peer does not have: ${cid}`), { code: 'ERR_DONT_HAVE' })
}
return block
}
/**
* @param {string|import('multiformats').CID} path
* @param {{ signal?: AbortSignal }} [options]
*/
async getUnixfs (path, options = {}) {
log('getting unixfs %s', path)
const blockstore = {
/**
* @param {CID} cid
* @param {{ signal?: AbortSignal }} [options]
*/
get: async (cid, options) => {
const block = await this.getBlock(cid, options)
return block.bytes
}
}
// @ts-ignore exporter requires Blockstore but only uses `get`
return exporter(path, blockstore, { signal: options.signal })
}
/**
* @param {string} cidPath
* @param {{ signal?: AbortSignal }} [options]
*/
async * walkUnixfsPath (cidPath, options = {}) {
log('walking unixfs %s', cidPath)
const blockstore = {
/**
* @param {CID} cid
* @param {{ signal?: AbortSignal }} [options]
*/
get: async (cid, options) => {
const block = await this.getBlock(cid, options)
return block.bytes
}
}
yield * walkPath(cidPath, blockstore, { signal: options.signal })
}
}
/**
* Create a search function that given a decoded Block
* will return an array of CIDs to fetch next.
*
* @param {([name, cid]: [string, Link]) => boolean} linkFilter
*/
export function breadthFirstSearch (linkFilter = () => true) {
/**
* @param {import('multiformats').BlockView} block
*/
return function (block) {
const nextCids = []
if (block.cid.code === dagPB.code) {
for (const { Name, Hash } of block.value.Links) {
if (linkFilter([Name, Hash])) {
nextCids.push(Hash)
}
}
} else {
// links() paths dagPb in the ipld style so name is e.g `Links/0/Hash`, and not what we want here.
for (const link of block.links()) {
if (linkFilter(link)) {
nextCids.push(link[1])
}
}
}
return nextCids
}
}
export const hamtSearch = breadthFirstSearch(([name]) => name.length === 2)
/**
* Get links as array of CIDs for a UnixFS entry.
* @param {import('ipfs-unixfs-exporter').UnixFSEntry} entry
* @param {import('multiformats').BlockDecoder[]} decoders
*/
function getLinks (entry, decoders) {
if (entry.type === 'file' || entry.type === 'directory') {
return entry.node.Links.map(l => l.Hash)
}
if (entry.type === 'object' || entry.type === 'identity') {
// UnixFSEntry `node` is Uint8Array for objects and identity blocks!
// so we have to decode them again to get the links here.
const decoder = decoders[entry.cid.code]
if (!decoder) {
throw new Error(`unknown codec: ${entry.cid.code}`)
}
const decoded = Block.createUnsafe({ bytes: entry.node, cid: entry.cid, codec: decoder })
const links = []
for (const [, cid] of decoded.links()) {
links.push(cid)
}
return links
}
// raw! no links!
return []
}