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

Commit 462d2f4

Browse files
committed
End import stream after all writes.
Previously it would be possible for certain writes to the DAG Service to occur *after* the stream had ended, meaning the Importer would return objects that did not yet exist in the DAG Service. This change defers stream termination until after those writes have occurred, to preserve the powerful invariant of "element emission => written to dag service".
1 parent b177a08 commit 462d2f4

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

src/importer.js

+24-11
Original file line numberDiff line numberDiff line change
@@ -238,13 +238,15 @@ function Importer (dagService, options) {
238238
// If the value is not an object
239239
// add as a link to the dirNode
240240

241-
function traverse (tree, base) {
241+
let pendingWrites = 0
242+
243+
function traverse (tree, base, done) {
242244
const keys = Object.keys(tree)
243245
let tmpTree = tree
244246
keys.map((key) => {
245247
if (typeof tmpTree[key] === 'object' &&
246248
!Buffer.isBuffer(tmpTree[key])) {
247-
tmpTree[key] = traverse.call(this, tmpTree[key], base ? base + '/' + key : key)
249+
tmpTree[key] = traverse.call(this, tmpTree[key], base ? base + '/' + key : key, done)
248250
}
249251
})
250252

@@ -264,28 +266,39 @@ function Importer (dagService, options) {
264266
})
265267

266268
n.data = d.marshal()
269+
270+
pendingWrites++
267271
dagService.add(n, (err) => {
272+
pendingWrites--
268273
if (err) {
269274
this.push({error: 'failed to store dirNode'})
275+
} else if (base) {
276+
const el = {
277+
path: base,
278+
multihash: n.multihash(),
279+
yes: 'no',
280+
size: n.size()
281+
}
282+
this.push(el)
283+
}
284+
285+
if (pendingWrites <= 0) {
286+
done()
270287
}
271288
})
272289

273290
if (!base) {
274291
return
275292
}
276293

277-
const el = {
278-
path: base,
279-
multihash: n.multihash(),
280-
size: n.size()
281-
}
282-
this.push(el)
283-
284294
mhIndex[bs58.encode(n.multihash())] = { size: n.size() }
285295
return n.multihash()
286296
}
287-
/* const rootHash = */ traverse.call(this, fileTree)
288-
this.push(null)
297+
298+
let self = this
299+
/* const rootHash = */ traverse.call(this, fileTree, null, function () {
300+
self.push(null)
301+
})
289302
}
290303
}
291304
}

0 commit comments

Comments
 (0)