-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathdir-sharded.ts
265 lines (214 loc) · 6.71 KB
/
dir-sharded.ts
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
import { encode, type PBLink, prepare } from '@ipld/dag-pb'
import { murmur3128 } from '@multiformats/murmur3'
import { createHAMT, Bucket, type BucketChild } from 'hamt-sharding'
import { UnixFS } from 'ipfs-unixfs'
import { Dir, CID_V0, CID_V1, type DirProps } from './dir.js'
import { persist, type PersistOptions } from './utils/persist.js'
import type { ImportResult, InProgressImportResult } from './index.js'
import type { Blockstore } from 'interface-blockstore'
async function hamtHashFn (buf: Uint8Array): Promise<Uint8Array> {
return (await murmur3128.encode(buf))
// Murmur3 outputs 128 bit but, accidentally, IPFS Go's
// implementation only uses the first 64, so we must do the same
// for parity..
.slice(0, 8)
// Invert buffer because that's how Go impl does it
.reverse()
}
const HAMT_HASH_CODE = BigInt(0x22)
const DEFAULT_FANOUT_BITS = 8
export interface DirShardedOptions extends PersistOptions {
shardFanoutBits: number
}
class DirSharded extends Dir {
private readonly _bucket: Bucket<InProgressImportResult | Dir>
constructor (props: DirProps, options: DirShardedOptions) {
super(props, options)
this._bucket = createHAMT({
hashFn: hamtHashFn,
bits: options.shardFanoutBits ?? DEFAULT_FANOUT_BITS
})
}
async put (name: string, value: InProgressImportResult | Dir): Promise<void> {
this.cid = undefined
this.size = undefined
this.nodeSize = undefined
await this._bucket.put(name, value)
}
async get (name: string): Promise<InProgressImportResult | Dir | undefined> {
return this._bucket.get(name)
}
childCount (): number {
return this._bucket.leafCount()
}
directChildrenCount (): number {
return this._bucket.childrenCount()
}
onlyChild (): Bucket<InProgressImportResult | Dir> | BucketChild<InProgressImportResult | Dir> {
return this._bucket.onlyChild()
}
async * eachChildSeries (): AsyncGenerator<{ key: string, child: InProgressImportResult | Dir }> {
for await (const { key, value } of this._bucket.eachLeafSeries()) {
yield {
key,
child: value
}
}
}
estimateNodeSize (): number {
if (this.nodeSize !== undefined) {
return this.nodeSize
}
this.nodeSize = calculateSize(this._bucket, this, this.options)
return this.nodeSize
}
async * flush (blockstore: Blockstore): AsyncGenerator<ImportResult> {
for await (const entry of flush(this._bucket, blockstore, this, this.options)) {
yield {
...entry,
path: this.path
}
}
}
}
export default DirSharded
async function * flush (bucket: Bucket<Dir | InProgressImportResult>, blockstore: Blockstore, shardRoot: DirSharded | null, options: PersistOptions): AsyncIterable<ImportResult> {
const children = bucket._children
const padLength = (bucket.tableSize() - 1).toString(16).length
const links: PBLink[] = []
let childrenSize = 0n
for (let i = 0; i < children.length; i++) {
const child = children.get(i)
if (child == null) {
continue
}
const labelPrefix = i.toString(16).toUpperCase().padStart(padLength, '0')
if (child instanceof Bucket) {
let shard
for await (const subShard of flush(child, blockstore, null, options)) {
shard = subShard
}
if (shard == null) {
throw new Error('Could not flush sharded directory, no subshard found')
}
links.push({
Name: labelPrefix,
Tsize: Number(shard.size),
Hash: shard.cid
})
childrenSize += shard.size
} else if (isDir(child.value)) {
const dir = child.value
let flushedDir: ImportResult | undefined
for await (const entry of dir.flush(blockstore)) {
flushedDir = entry
yield flushedDir
}
if (flushedDir == null) {
throw new Error('Did not flush dir')
}
const label = labelPrefix + child.key
links.push({
Name: label,
Tsize: Number(flushedDir.size),
Hash: flushedDir.cid
})
childrenSize += flushedDir.size
} else {
const value = child.value
if (value.cid == null) {
continue
}
const label = labelPrefix + child.key
const size = value.size
links.push({
Name: label,
Tsize: Number(size),
Hash: value.cid
})
childrenSize += BigInt(size ?? 0)
}
}
// go-ipfs uses little endian, that's why we have to
// reverse the bit field before storing it
const data = Uint8Array.from(children.bitField().reverse())
const dir = new UnixFS({
type: 'hamt-sharded-directory',
data,
fanout: BigInt(bucket.tableSize()),
hashType: HAMT_HASH_CODE,
mtime: shardRoot?.mtime,
mode: shardRoot?.mode
})
const node = {
Data: dir.marshal(),
Links: links
}
const buffer = encode(prepare(node))
const cid = await persist(buffer, blockstore, options)
const size = BigInt(buffer.byteLength) + childrenSize
yield {
cid,
unixfs: dir,
size
}
}
function isDir (obj: any): obj is Dir {
return typeof obj.flush === 'function'
}
function calculateSize (bucket: Bucket<any>, shardRoot: DirSharded | null, options: PersistOptions): number {
const children = bucket._children
const padLength = (bucket.tableSize() - 1).toString(16).length
const links: PBLink[] = []
for (let i = 0; i < children.length; i++) {
const child = children.get(i)
if (child == null) {
continue
}
const labelPrefix = i.toString(16).toUpperCase().padStart(padLength, '0')
if (child instanceof Bucket) {
const size = calculateSize(child, null, options)
links.push({
Name: labelPrefix,
Tsize: Number(size),
Hash: options.cidVersion === 0 ? CID_V0 : CID_V1
})
} else if (typeof child.value.flush === 'function') {
const dir = child.value
const size = dir.nodeSize()
links.push({
Name: labelPrefix + child.key,
Tsize: Number(size),
Hash: options.cidVersion === 0 ? CID_V0 : CID_V1
})
} else {
const value = child.value
if (value.cid == null) {
continue
}
const label = labelPrefix + child.key
const size = value.size
links.push({
Name: label,
Tsize: Number(size),
Hash: value.cid
})
}
}
// go-ipfs uses little endian, that's why we have to
// reverse the bit field before storing it
const data = Uint8Array.from(children.bitField().reverse())
const dir = new UnixFS({
type: 'hamt-sharded-directory',
data,
fanout: BigInt(bucket.tableSize()),
hashType: HAMT_HASH_CODE,
mtime: shardRoot?.mtime,
mode: shardRoot?.mode
})
const buffer = encode(prepare({
Data: dir.marshal(),
Links: links
}))
return buffer.length
}