This repository has been archived by the owner on Jan 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathnfs.js
455 lines (429 loc) · 14.5 KB
/
nfs.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under
// the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT> or
// the Modified BSD license <LICENSE-BSD or https://opensource.org/licenses/BSD-3-Clause>,
// at your option.
//
// This file may not be copied, modified, or distributed except according to those terms.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
const lib = require('../../native/lib');
const t = require('../../native/types');
const nativeH = require('../../native/helpers');
const { pubConsts: CONSTANTS } = require('../../consts');
const errConst = require('../../error_const');
const makeError = require('../../native/_error.js');
/**
* NFS-style file operations
*/
class File {
/**
* @hideconstructor
* Instantiate a new NFS File instance.
*
* @param {Object} ref the file's metadata including the XoR-name
* of ImmutableData containing the file's content.
*/
constructor(ref, connection, fileCtx) {
this._ref = ref;
this._fileCtx = fileCtx;
this._connection = connection;
}
/**
* @private
* Return an instance of the underlying File structure used by the safe_app
* lib containing the file's metadata.
*/
get ref() {
const data = {
size: this._ref.size,
created_sec: this._ref.created_sec,
created_nsec: this._ref.created_nsec,
modified_sec: this._ref.modified_sec,
modified_nsec: this._ref.modified_nsec,
data_map_name: this.dataMapName,
user_metadata_ptr: this._ref.user_metadata_ptr,
user_metadata_len: this._ref.user_metadata_len,
user_metadata_cap: this._ref.user_metadata_cap
};
return new t.File(data);
}
/**
* Get XOR address of file's underlying {@link ImmutableData} data map
* @returns {Buffer} XOR address
*/
get dataMapName() {
return this._ref.data_map_name;
}
/**
* Get metadata passed during file insertion of update
* @returns {Buffer} user_metadata
*/
get userMetadata() {
return this._ref.user_metadata_ptr;
}
/**
* Get UTC date of file context creation
* @return {Date}
*/
get created() {
return nativeH.fromSafeLibTime(this._ref.created_sec, this._ref.created_nsec);
}
/**
* Get UTC date of file context modification
* @return {Date}
*/
get modified() {
return nativeH.fromSafeLibTime(this._ref.modified_sec, this._ref.modified_nsec);
}
/**
* Get file size
* @returns {Promise<Number>}
* @example
* // Assumes {@link MutableData} interface has been obtained
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.create('<buffer or string>');
* const fileSize = await fileContext.size();
* } catch (err) {
* throw err;
* }
* };
*/
size() {
if (!this._fileCtx) {
return Promise.resolve(this._ref.size);
}
return lib.file_size(this._connection, this._fileCtx)
.then((size) => {
this._ref.size = size;
return size;
});
}
/**
* Read the file.
* CONSTANTS.NFS_FILE_START and CONSTANTS.NFS_FILE_END may be used
* to read the entire content of the file. These constants are
* exposed by the safe-app-nodejs package.
* @param {Number|CONSTANTS.NFS_FILE_START} position
* @param {Number|CONSTANTS.NFS_FILE_END} len
* @throws {ERR_FILE_NOT_FOUND}
* @returns {Promise<{Buffer, Number}>}
* @example
* // Assumes {@link MutableData} interface has been obtained
* const position = safe.CONSTANTS.NFS_FILE_START;
* const len = safe.CONSTANTS.NFS_FILE_END;
* const openMode = safe.CONSTANTS.NFS_FILE_MODE_READ;
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* let fileContext = await nfs.create('<buffer or string>');
* fileContext = await nfs.open(fileContext, openMode);
* const data = await fileContext.read(position, len);
* } catch (err) {
* throw err;
* }
* };
*/
read(position, len) {
if (!this._fileCtx) {
return Promise
.reject(makeError(errConst.ERR_FILE_NOT_FOUND.code, errConst.ERR_FILE_NOT_FOUND.msg));
}
return lib.file_read(this._connection, this._fileCtx, position, len);
}
/**
* Write file. Does not commit file to network.
* @param {Buffer|String} content
* @throws {ERR_FILE_NOT_FOUND}
* @returns {Promise}
* @example
* // Assumes {@link MutableData} interface has been obtained
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.open();
* await fileContext.write('<buffer or string>');
* } catch (err) {
* throw err;
* }
* };
*/
write(content) {
if (!this._fileCtx) {
return Promise
.reject(makeError(errConst.ERR_FILE_NOT_FOUND.code, errConst.ERR_FILE_NOT_FOUND.msg));
}
return lib.file_write(this._connection, this._fileCtx, content);
}
/**
* Close file and commit to network.
* @throws {ERR_FILE_NOT_FOUND}
* @returns {Promise}
* @example
* // Assumes {@link MutableData} interface has been obtained
* const content = '<html><body><h1>WebSite</h1></body></html>';
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.open();
* await fileContext.write('<buffer or string>');
* await fileContext.close();
* } catch (err) {
* throw err;
* }
* };
*/
close() {
if (!this._fileCtx) {
return Promise
.reject(makeError(errConst.ERR_FILE_NOT_FOUND.code, errConst.ERR_FILE_NOT_FOUND.msg));
}
const version = this._ref.version;
return lib.file_close(this._connection, this._fileCtx)
.then((res) => {
this._ref = res;
this._ref.version = version;
this._fileCtx = null;
});
}
/**
* Which version was this? Equals the underlying MutableData's entry version.
* @return {Number}
*/
get version() {
return this._ref.version;
}
/**
* @private
* Update the file's version. This shall be only internally used and only
* when its underlying entry in the MutableData is updated
* @param {Integer} version version to set
*/
set version(version) {
this._ref.version = version;
}
}
/**
* NFS emulation on top of a {@link MutableData}
* @hideconstructor
*/
class NFS {
constructor(mData) {
this.mData = mData;
}
/**
* Helper function to create and save file to the network
* @param {String|Buffer} content
* @returns {Promise<File>} a newly created file
* @example
* // Assumes {@link MutableData} interface has been obtained
* const content = '<html><body><h1>WebSite</h1></body></html>';
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.create(content);
* } catch(err) {
* throw err;
* }
* };
*/
create(content) {
return this.open(null, CONSTANTS.NFS_FILE_MODE_OVERWRITE)
.then((file) => file.write(content)
.then(() => file.close())
.then(() => file)
);
}
/**
* Find the file of the given filename (aka keyName in the MutableData)
* @param {String} fileName - the path/file name
* @returns {Promise<File>} - the file found for that path
* @example
* // Assumes {@link MutableData} interface has been obtained
* const content = '<html><body><h1>WebSite</h1></body></html>';
* const asyncFn = async () => {
* const fileName = 'index.html';
* try {
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.create(content);
* await nfs.insert(fileName, fileContext);
* const fileContext = await nfs.fetch(fileName);
* } catch(err) {
* throw err;
* }
* };
*/
fetch(fileName) {
return lib.dir_fetch_file(this.mData.app.connection, this.mData.ref, fileName)
.then((res) => new File(res, this.mData.app.connection, null));
}
/**
* Insert the given file into the underlying {@link MutableData}, directly commit
* to the network.
*
* _Note_: As this application layer, the network does not check any
* of the metadata provided.
* @param {(String|Buffer)} fileName The path to store the file under
* @param {File} file The file to serialise and store
* @param {String|Buffer} userMetadata
* @returns {Promise<File>} The same file
* @example
* // Assumes {@link MutableData} interface has been obtained
* const content = '<html><body><h1>WebSite</h1></body></html>';
* const userMetadata = 'text/html';
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* let fileContext = await nfs.create(content);
* const fileName = 'index.html';
* fileContext = await nfs.insert(fileName, fileContext, userMetadata);
* } catch(err) {
* throw err;
* }
* };
*/
insert(fileName, file, userMetadata) {
if (userMetadata) {
const userMetadataPtr = Buffer.from(userMetadata);
const fileMeta = file._ref; // eslint-disable-line no-underscore-dangle
fileMeta.user_metadata_ptr = userMetadataPtr;
fileMeta.user_metadata_len = userMetadata.length;
fileMeta.user_metadata_cap = userMetadataPtr.length;
}
return lib.dir_insert_file(
this.mData.app.connection, this.mData.ref, fileName, file.ref.ref()
)
.then(() => {
const fileObj = file;
fileObj.version = 0;
return fileObj;
});
}
/**
* Replace a path with a new file. Directly commit to the network.
*
* CONSTANTS.GET_NEXT_VERSION: Applies update to next file version.
*
* _Note_: As this application layer, the network does not check any
* of the metadata provided.
* @param {(String|Buffer)} fileName - the path to store the file under
* @param {File} file - the file to serialise and store
* @param {Number|CONSTANTS.GET_NEXT_VERSION} version - the version successor number
* @param {String|Buffer} userMetadata - optional parameter for updating user metadata
* @returns {Promise<File>} - the same file
* @example
* // Assumes {@link MutableData} interface has been obtained
* const content = '<html><body><h1>Updated WebSite</h1></body></html>';
* const userMetadata = 'text/html';
* const asyncFn = async () => {
* try {
* const version = safe.CONSTANTS.GET_NEXT_VERSION;
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.create(content);
* const fileName = 'index.html';
* fileContext = await nfs.update(fileName, fileContext, version + 1, userMetadata);
* } catch(err) {
* throw err;
* }
* };
*/
update(fileName, file, version, userMetadata) {
if (userMetadata) {
const userMetadataPtr = Buffer.from(userMetadata);
const fileMeta = file._ref; // eslint-disable-line no-underscore-dangle
fileMeta.user_metadata_ptr = userMetadataPtr;
fileMeta.user_metadata_len = userMetadata.length;
fileMeta.user_metadata_cap = userMetadataPtr.length;
}
const fileContext = file;
return lib.dir_update_file(this.mData.app.connection, this.mData.ref, fileName,
fileContext.ref.ref(), version)
.then((newVersion) => {
fileContext.version = newVersion;
})
.then(() => fileContext);
}
/**
* Delete a file from path. Directly commit to the network.
* @param {(String|Buffer)} fileName
* @param {Number|CONSTANTS.GET_NEXT_VERSION} version - the version successor number
* @returns {Promise<Number>} - version of deleted file
* @example
* // Assumes {@link MutableData} interface has been obtained
* const content = '<html><body><h1>Updated WebSite</h1></body></html>';
* const fileName = 'index.html';
* const asyncFn = async () => {
* try {
* const version = await mData.getVersion();
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.create(content);
* fileContext = await nfs.insert(fileName, fileContext);
* const version = await nfs.delete(fileName, version + 1);
* } catch(err) {
* throw err;
* }
* };
*/
delete(fileName, version) {
return lib.dir_delete_file(this.mData.app.connection, this.mData.ref, fileName, version)
.then((newVersion) => newVersion);
}
/**
* Open a file for reading or writing.
*
* Open modes (these constants are exported by the safe-app-nodejs package):
*
* CONSTANTS.NFS_FILE_MODE_OVERWRITE: Replaces the entire content of the file when writing data.
*
* CONSTANTS.NFS_FILE_MODE_APPEND: Appends to existing data in the file.
*
* CONSTANTS.NFS_FILE_MODE_READ: Open file to read.
*
* @param {File|null} file If no {@link File} is passed,
* then a new instance is created in {@link CONSTANTS.NFS_FILE_MODE_OVERWRITE}
* @param {Number|CONSTANTS.NFS_FILE_MODE_OVERWRITE|
* CONSTANTS.NFS_FILE_MODE_APPEND|
* CONSTANTS.NFS_FILE_MODE_READ} [openMode=CONSTANTS.NFS_FILE_MODE_OVERWRITE]
* @returns {Promise<File>}
* @example
* // Assumes {@link MutableData} interface has been obtained
* const asyncFn = async () => {
* try {
* const nfs = await mData.emulateAs('NFS');
* const fileContext = await nfs.open();
* } catch(err) {
* throw err;
* }
* };
*/
open(file, openMode) {
const now = nativeH.toSafeLibTime(new Date());
const metadata = {
size: 0,
data_map_name: new Array(32).fill(0),
created_sec: now.now_sec_part,
created_nsec: now.now_nsec_part,
modified_sec: now.now_sec_part,
modified_nsec: now.now_nsec_part,
user_metadata_ptr: Buffer.from([]),
user_metadata_len: 0,
user_metadata_cap: 0
};
let fileParam = file;
let mode = openMode;
// FIXME: this is temporary as we should be able to pass a null file to the lib
if (!file) {
fileParam = new File(metadata, null, null);
mode = CONSTANTS.NFS_FILE_MODE_OVERWRITE;
}
// FIXME: free/discard the file it's already open, we are missing
// a function from the lib to perform this.
return lib.file_open(this.mData.app.connection, this.mData.ref, fileParam.ref.ref(), mode)
.then((fileCtx) => new File(fileParam.ref, this.mData.app.connection, fileCtx));
}
}
module.exports = NFS;