This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathwrite.js
277 lines (227 loc) · 7.65 KB
/
write.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
'use strict'
const log = require('debug')('ipfs:mfs:write')
const importer = require('ipfs-unixfs-importer')
const stat = require('./stat')
const mkdir = require('./mkdir')
const addLink = require('./utils/add-link')
const applyDefaultOptions = require('./utils/apply-default-options')
const createLock = require('./utils/create-lock')
const toAsyncIterator = require('./utils/to-async-iterator')
const toMfsPath = require('./utils/to-mfs-path')
const toPathComponents = require('./utils/to-path-components')
const toTrail = require('./utils/to-trail')
const updateTree = require('./utils/update-tree')
const updateMfsRoot = require('./utils/update-mfs-root')
const errCode = require('err-code')
const {
MAX_CHUNK_SIZE
} = require('./utils/constants')
const last = require('it-last')
const defaultOptions = {
offset: 0, // the offset in the file to begin writing
length: undefined, // how many bytes from the incoming buffer to write
create: false, // whether to create the file if it does not exist
truncate: false, // whether to truncate the file first
rawLeaves: false,
reduceSingleLeafToSelf: false,
cidVersion: 0,
hashAlg: 'sha2-256',
parents: false, // whether to create intermediate directories if they do not exist
progress: () => {},
strategy: 'trickle',
flush: true,
leafType: 'raw',
shardSplitThreshold: 1000,
mode: undefined,
mtime: undefined
}
module.exports = (context) => {
return async function mfsWrite (path, content, options) {
options = applyDefaultOptions(options, defaultOptions)
let source, destination, parent
log('Reading source, destination and parent')
await createLock().readLock(async () => {
source = await toAsyncIterator(content, options)
destination = await toMfsPath(context, path)
parent = await toMfsPath(context, destination.mfsDirectory)
})()
log('Read source, destination and parent')
if (!options.parents && !parent.exists) {
throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST')
}
if (!options.create && !destination.exists) {
throw errCode(new Error('file does not exist'), 'ERR_NO_EXIST')
}
return updateOrImport(context, path, source, destination, options)
}
}
const updateOrImport = async (context, path, source, destination, options) => {
const child = await write(context, source, destination, options)
// The slow bit is done, now add or replace the DAGLink in the containing directory
// re-reading the path to the containing folder in case it has changed in the interim
await createLock().writeLock(async () => {
const pathComponents = toPathComponents(path)
const fileName = pathComponents.pop()
let parentExists = false
try {
await stat(context)(`/${pathComponents.join('/')}`, options)
parentExists = true
} catch (err) {
if (err.code !== 'ERR_NOT_FOUND') {
throw err
}
}
if (!parentExists) {
await mkdir(context)(`/${pathComponents.join('/')}`, options)
}
// get an updated mfs path in case the root changed while we were writing
const updatedPath = await toMfsPath(context, path)
const trail = await toTrail(context, updatedPath.mfsDirectory, options)
const parent = trail[trail.length - 1]
if (!parent.type.includes('directory')) {
throw errCode(new Error(`cannot write to ${parent.name}: Not a directory`), 'ERR_NOT_A_DIRECTORY')
}
const parentNode = await context.ipld.get(parent.cid)
const result = await addLink(context, {
parent: parentNode,
name: fileName,
cid: child.cid,
size: child.size,
flush: options.flush,
shardSplitThreshold: options.shardSplitThreshold,
hashAlg: options.hashAlg,
cidVersion: options.cidVersion
})
parent.cid = result.cid
// update the tree with the new child
const newRootCid = await updateTree(context, trail, options)
// Update the MFS record with the new CID for the root of the tree
await updateMfsRoot(context, newRootCid)
})()
}
const write = async (context, source, destination, options) => {
if (destination.exists) {
log(`Overwriting file ${destination.cid} offset ${options.offset} length ${options.length}`)
} else {
log(`Writing file offset ${options.offset} length ${options.length}`)
}
const sources = []
// pad start of file if necessary
if (options.offset > 0) {
if (destination.unixfs) {
log(`Writing first ${options.offset} bytes of original file`)
sources.push(
() => {
return destination.content({
offset: 0,
length: options.offset
})
}
)
if (destination.unixfs.fileSize() < options.offset) {
const extra = options.offset - destination.unixfs.fileSize()
log(`Writing zeros for extra ${extra} bytes`)
sources.push(
asyncZeroes(extra)
)
}
} else {
log(`Writing zeros for first ${options.offset} bytes`)
sources.push(
asyncZeroes(options.offset)
)
}
}
sources.push(
limitAsyncStreamBytes(source, options.length)
)
const content = countBytesStreamed(catAsyncIterators(sources), (bytesWritten) => {
if (destination.unixfs && !options.truncate) {
// if we've done reading from the new source and we are not going
// to truncate the file, add the end of the existing file to the output
const fileSize = destination.unixfs.fileSize()
if (fileSize > bytesWritten) {
log(`Writing last ${fileSize - bytesWritten} of ${fileSize} bytes from original file starting at offset ${bytesWritten}`)
return destination.content({
offset: bytesWritten
})
} else {
log('Not writing last bytes from original file')
}
}
return {
[Symbol.asyncIterator]: async function * () {}
}
})
let mode
if (options.mode !== undefined && options.mode !== null) {
mode = options.mode
} else if (destination && destination.unixfs) {
mode = destination.unixfs.mode
}
let mtime
if (options.mtime !== undefined && options.mtine !== null) {
mtime = options.mtime
} else if (destination && destination.unixfs) {
mtime = destination.unixfs.mtime
}
const result = await last(importer([{
content: content,
// persist mode & mtime if set previously
mode,
mtime
}], context.ipld, {
progress: options.progress,
hashAlg: options.hashAlg,
cidVersion: options.cidVersion,
strategy: options.strategy,
rawLeaves: options.rawLeaves,
reduceSingleLeafToSelf: options.reduceSingleLeafToSelf,
leafType: options.leafType
}))
log(`Wrote ${result.cid}`)
return {
cid: result.cid,
size: result.size
}
}
const limitAsyncStreamBytes = (stream, limit) => {
return async function * _limitAsyncStreamBytes () {
let emitted = 0
for await (const buf of stream) {
emitted += buf.length
if (emitted > limit) {
yield buf.slice(0, limit - emitted)
return
}
yield buf
}
}
}
const asyncZeroes = (count, chunkSize = MAX_CHUNK_SIZE) => {
const buf = Buffer.alloc(chunkSize, 0)
const stream = {
[Symbol.asyncIterator]: function * _asyncZeroes () {
while (true) {
yield buf.slice()
}
}
}
return limitAsyncStreamBytes(stream, count)
}
const catAsyncIterators = async function * (sources) { // eslint-disable-line require-await
for (let i = 0; i < sources.length; i++) {
yield * sources[i]()
}
}
const countBytesStreamed = async function * (source, notify) {
let wrote = 0
for await (const buf of source) {
wrote += buf.length
yield buf
}
for await (const buf of notify(wrote)) {
wrote += buf.length
yield buf
}
}