forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey_value_filesystem.ts
More file actions
1394 lines (1289 loc) · 43.8 KB
/
key_value_filesystem.ts
File metadata and controls
1394 lines (1289 loc) · 43.8 KB
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {BaseFileSystem, SynchronousFileSystem, BFSOneArgCallback, BFSCallback, BFSThreeArgCallback} from '../core/file_system';
import {ApiError, ErrorCode} from '../core/api_error';
import {default as Stats, FileType} from '../core/node_fs_stats';
import {File} from '../core/file';
import {FileFlag} from '../core/file_flag';
import * as path from 'path';
import Inode from '../generic/inode';
import PreloadFile from '../generic/preload_file';
import {emptyBuffer} from '../core/util';
/**
* @hidden
*/
const ROOT_NODE_ID: string = "/";
/**
* @hidden
*/
let emptyDirNode: Buffer | null = null;
/**
* Returns an empty directory node.
* @hidden
*/
function getEmptyDirNode(): Buffer {
if (emptyDirNode) {
return emptyDirNode;
}
return emptyDirNode = Buffer.from("{}");
}
/**
* Generates a random ID.
* @hidden
*/
function GenerateRandomID(): string {
// From http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* Helper function. Checks if 'e' is defined. If so, it triggers the callback
* with 'e' and returns false. Otherwise, returns true.
* @hidden
*/
function noError(e: ApiError | undefined | null, cb: (e: ApiError) => void): boolean {
if (e) {
cb(e);
return false;
}
return true;
}
/**
* Helper function. Checks if 'e' is defined. If so, it aborts the transaction,
* triggers the callback with 'e', and returns false. Otherwise, returns true.
* @hidden
*/
function noErrorTx(e: ApiError | undefined | null, tx: AsyncKeyValueRWTransaction, cb: (e: ApiError) => void): boolean {
if (e) {
tx.abort(() => {
cb(e);
});
return false;
}
return true;
}
/**
* Represents a *synchronous* key-value store.
*/
export interface SyncKeyValueStore {
/**
* The name of the key-value store.
*/
name(): string;
/**
* Empties the key-value store completely.
*/
clear(): void;
/**
* Begins a new read-only transaction.
*/
beginTransaction(type: "readonly"): SyncKeyValueROTransaction;
/**
* Begins a new read-write transaction.
*/
beginTransaction(type: "readwrite"): SyncKeyValueRWTransaction;
beginTransaction(type: string): SyncKeyValueROTransaction;
}
/**
* A read-only transaction for a synchronous key value store.
*/
export interface SyncKeyValueROTransaction {
/**
* Retrieves the data at the given key. Throws an ApiError if an error occurs
* or if the key does not exist.
* @param key The key to look under for data.
* @return The data stored under the key, or undefined if not present.
*/
get(key: string): Buffer | undefined;
}
/**
* A read-write transaction for a synchronous key value store.
*/
export interface SyncKeyValueRWTransaction extends SyncKeyValueROTransaction {
/**
* Adds the data to the store under the given key.
* @param key The key to add the data under.
* @param data The data to add to the store.
* @param overwrite If 'true', overwrite any existing data. If 'false',
* avoids storing the data if the key exists.
* @return True if storage succeeded, false otherwise.
*/
put(key: string, data: Buffer, overwrite: boolean): boolean;
/**
* Deletes the data at the given key.
* @param key The key to delete from the store.
*/
del(key: string): void;
/**
* Commits the transaction.
*/
commit(): void;
/**
* Aborts and rolls back the transaction.
*/
abort(): void;
}
/**
* An interface for simple synchronous key-value stores that don't have special
* support for transactions and such.
*/
export interface SimpleSyncStore {
get(key: string): Buffer | undefined;
put(key: string, data: Buffer, overwrite: boolean): boolean;
del(key: string): void;
}
class LRUNode {
public prev: LRUNode | null = null;
public next: LRUNode | null = null;
constructor(public key: string, public value: string) {}
}
// Adapted from https://chrisrng.svbtle.com/lru-cache-in-javascript
class LRUCache {
private size = 0;
private map: {[id: string]: LRUNode} = {};
private head: LRUNode | null = null;
private tail: LRUNode | null = null;
constructor(public readonly limit: number) {}
/**
* Change or add a new value in the cache
* We overwrite the entry if it already exists
*/
public set(key: string, value: string): void {
const node = new LRUNode(key, value);
if (this.map[key]) {
this.map[key].value = node.value;
this.remove(node.key);
} else {
if (this.size >= this.limit) {
delete this.map[this.tail!.key];
this.size--;
this.tail = this.tail!.prev;
this.tail!.next = null;
}
}
this.setHead(node);
}
/* Retrieve a single entry from the cache */
public get(key: string): string | null {
if (this.map[key]) {
const value = this.map[key].value;
const node = new LRUNode(key, value);
this.remove(key);
this.setHead(node);
return value;
} else {
return null;
}
}
/* Remove a single entry from the cache */
public remove(key: string): void {
const node = this.map[key];
if (!node) {
return;
}
if (node.prev !== null) {
node.prev.next = node.next;
} else {
this.head = node.next;
}
if (node.next !== null) {
node.next.prev = node.prev;
} else {
this.tail = node.prev;
}
delete this.map[key];
this.size--;
}
/* Resets the entire cache - Argument limit is optional to be reset */
public removeAll() {
this.size = 0;
this.map = {};
this.head = null;
this.tail = null;
}
private setHead(node: LRUNode): void {
node.next = this.head;
node.prev = null;
if (this.head !== null) {
this.head.prev = node;
}
this.head = node;
if (this.tail === null) {
this.tail = node;
}
this.size++;
this.map[node.key] = node;
}
}
/**
* A simple RW transaction for simple synchronous key-value stores.
*/
export class SimpleSyncRWTransaction implements SyncKeyValueRWTransaction {
/**
* Stores data in the keys we modify prior to modifying them.
* Allows us to roll back commits.
*/
private originalData: { [key: string]: Buffer | undefined } = {};
/**
* List of keys modified in this transaction, if any.
*/
private modifiedKeys: string[] = [];
constructor(private store: SimpleSyncStore) { }
public get(key: string): Buffer | undefined {
const val = this.store.get(key);
this.stashOldValue(key, val);
return val;
}
public put(key: string, data: Buffer, overwrite: boolean): boolean {
this.markModified(key);
return this.store.put(key, data, overwrite);
}
public del(key: string): void {
this.markModified(key);
this.store.del(key);
}
public commit(): void {/* NOP */}
public abort(): void {
// Rollback old values.
for (const key of this.modifiedKeys) {
const value = this.originalData[key];
if (!value) {
// Key didn't exist.
this.store.del(key);
} else {
// Key existed. Store old value.
this.store.put(key, value, true);
}
}
}
/**
* Stashes given key value pair into `originalData` if it doesn't already
* exist. Allows us to stash values the program is requesting anyway to
* prevent needless `get` requests if the program modifies the data later
* on during the transaction.
*/
private stashOldValue(key: string, value: Buffer | undefined) {
// Keep only the earliest value in the transaction.
if (!this.originalData.hasOwnProperty(key)) {
this.originalData[key] = value;
}
}
/**
* Marks the given key as modified, and stashes its value if it has not been
* stashed already.
*/
private markModified(key: string) {
if (this.modifiedKeys.indexOf(key) === -1) {
this.modifiedKeys.push(key);
if (!this.originalData.hasOwnProperty(key)) {
this.originalData[key] = this.store.get(key);
}
}
}
}
export interface SyncKeyValueFileSystemOptions {
/**
* The actual key-value store to read from/write to.
*/
store: SyncKeyValueStore;
/**
* Should the file system support properties (mtime/atime/ctime/chmod/etc)?
* Enabling this slightly increases the storage space per file, and adds
* atime updates every time a file is accessed, mtime updates every time
* a file is modified, and permission checks on every operation.
*
* Defaults to *false*.
*/
// supportProps?: boolean;
/**
* Should the file system support links?
*/
// supportLinks?: boolean;
}
export class SyncKeyValueFile extends PreloadFile<SyncKeyValueFileSystem> implements File {
constructor(_fs: SyncKeyValueFileSystem, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {
super(_fs, _path, _flag, _stat, contents);
}
public syncSync(): void {
if (this.isDirty()) {
this._fs._syncSync(this.getPath(), this.getBuffer(), this.getStats());
this.resetDirty();
}
}
public closeSync(): void {
this.syncSync();
}
}
/**
* A "Synchronous key-value file system". Stores data to/retrieves data from an
* underlying key-value store.
*
* We use a unique ID for each node in the file system. The root node has a
* fixed ID.
* @todo Introduce Node ID caching.
* @todo Check modes.
*/
export class SyncKeyValueFileSystem extends SynchronousFileSystem {
public static isAvailable(): boolean { return true; }
private store: SyncKeyValueStore;
constructor(options: SyncKeyValueFileSystemOptions) {
super();
this.store = options.store;
// INVARIANT: Ensure that the root exists.
this.makeRootDirectory();
}
public getName(): string { return this.store.name(); }
public isReadOnly(): boolean { return false; }
public supportsSymlinks(): boolean { return false; }
public supportsProps(): boolean { return false; }
public supportsSynch(): boolean { return true; }
/**
* Delete all contents stored in the file system.
*/
public empty(): void {
this.store.clear();
// INVARIANT: Root always exists.
this.makeRootDirectory();
}
public renameSync(oldPath: string, newPath: string): void {
const tx = this.store.beginTransaction('readwrite'),
oldParent = path.dirname(oldPath), oldName = path.basename(oldPath),
newParent = path.dirname(newPath), newName = path.basename(newPath),
// Remove oldPath from parent's directory listing.
oldDirNode = this.findINode(tx, oldParent),
oldDirList = this.getDirListing(tx, oldParent, oldDirNode);
if (!oldDirList[oldName]) {
throw ApiError.ENOENT(oldPath);
}
const nodeId: string = oldDirList[oldName];
delete oldDirList[oldName];
// Invariant: Can't move a folder inside itself.
// This funny little hack ensures that the check passes only if oldPath
// is a subpath of newParent. We append '/' to avoid matching folders that
// are a substring of the bottom-most folder in the path.
if ((newParent + '/').indexOf(oldPath + '/') === 0) {
throw new ApiError(ErrorCode.EBUSY, oldParent);
}
// Add newPath to parent's directory listing.
let newDirNode: Inode, newDirList: typeof oldDirList;
if (newParent === oldParent) {
// Prevent us from re-grabbing the same directory listing, which still
// contains oldName.
newDirNode = oldDirNode;
newDirList = oldDirList;
} else {
newDirNode = this.findINode(tx, newParent);
newDirList = this.getDirListing(tx, newParent, newDirNode);
}
if (newDirList[newName]) {
// If it's a file, delete it.
const newNameNode = this.getINode(tx, newPath, newDirList[newName]);
if (newNameNode.isFile()) {
try {
tx.del(newNameNode.id);
tx.del(newDirList[newName]);
} catch (e) {
tx.abort();
throw e;
}
} else {
// If it's a directory, throw a permissions error.
throw ApiError.EPERM(newPath);
}
}
newDirList[newName] = nodeId;
// Commit the two changed directory listings.
try {
tx.put(oldDirNode.id, Buffer.from(JSON.stringify(oldDirList)), true);
tx.put(newDirNode.id, Buffer.from(JSON.stringify(newDirList)), true);
} catch (e) {
tx.abort();
throw e;
}
tx.commit();
}
public statSync(p: string, isLstat: boolean): Stats {
// Get the inode to the item, convert it into a Stats object.
return this.findINode(this.store.beginTransaction('readonly'), p).toStats();
}
public createFileSync(p: string, flag: FileFlag, mode: number): File {
const tx = this.store.beginTransaction('readwrite'),
data = emptyBuffer(),
newFile = this.commitNewFile(tx, p, FileType.FILE, mode, data);
// Open the file.
return new SyncKeyValueFile(this, p, flag, newFile.toStats(), data);
}
public openFileSync(p: string, flag: FileFlag): File {
const tx = this.store.beginTransaction('readonly'),
node = this.findINode(tx, p),
data = tx.get(node.id);
if (data === undefined) {
throw ApiError.ENOENT(p);
}
return new SyncKeyValueFile(this, p, flag, node.toStats(), data);
}
public unlinkSync(p: string): void {
this.removeEntry(p, false);
}
public rmdirSync(p: string): void {
// Check first if directory is empty.
if (this.readdirSync(p).length > 0) {
throw ApiError.ENOTEMPTY(p);
} else {
this.removeEntry(p, true);
}
}
public mkdirSync(p: string, mode: number): void {
const tx = this.store.beginTransaction('readwrite'),
data = Buffer.from('{}');
this.commitNewFile(tx, p, FileType.DIRECTORY, mode, data);
}
public readdirSync(p: string): string[] {
const tx = this.store.beginTransaction('readonly');
return Object.keys(this.getDirListing(tx, p, this.findINode(tx, p)));
}
public _syncSync(p: string, data: Buffer, stats: Stats): void {
// @todo Ensure mtime updates properly, and use that to determine if a data
// update is required.
const tx = this.store.beginTransaction('readwrite'),
// We use the _findInode helper because we actually need the INode id.
fileInodeId = this._findINode(tx, path.dirname(p), path.basename(p)),
fileInode = this.getINode(tx, p, fileInodeId),
inodeChanged = fileInode.update(stats);
try {
// Sync data.
tx.put(fileInode.id, data, true);
// Sync metadata.
if (inodeChanged) {
tx.put(fileInodeId, fileInode.toBuffer(), true);
}
} catch (e) {
tx.abort();
throw e;
}
tx.commit();
}
/**
* Checks if the root directory exists. Creates it if it doesn't.
*/
private makeRootDirectory() {
const tx = this.store.beginTransaction('readwrite');
if (tx.get(ROOT_NODE_ID) === undefined) {
// Create new inode.
const currTime = (new Date()).getTime(),
// Mode 0666
dirInode = new Inode(GenerateRandomID(), 4096, 511 | FileType.DIRECTORY, currTime, currTime, currTime);
// If the root doesn't exist, the first random ID shouldn't exist,
// either.
tx.put(dirInode.id, getEmptyDirNode(), false);
tx.put(ROOT_NODE_ID, dirInode.toBuffer(), false);
tx.commit();
}
}
/**
* Helper function for findINode.
* @param parent The parent directory of the file we are attempting to find.
* @param filename The filename of the inode we are attempting to find, minus
* the parent.
* @return string The ID of the file's inode in the file system.
*/
private _findINode(tx: SyncKeyValueROTransaction, parent: string, filename: string): string {
const readDirectory = (inode: Inode): string => {
// Get the root's directory listing.
const dirList = this.getDirListing(tx, parent, inode);
// Get the file's ID.
if (dirList[filename]) {
return dirList[filename];
} else {
throw ApiError.ENOENT(path.resolve(parent, filename));
}
};
if (parent === '/') {
if (filename === '') {
// BASE CASE #1: Return the root's ID.
return ROOT_NODE_ID;
} else {
// BASE CASE #2: Find the item in the root ndoe.
return readDirectory(this.getINode(tx, parent, ROOT_NODE_ID));
}
} else {
return readDirectory(this.getINode(tx, parent + path.sep + filename,
this._findINode(tx, path.dirname(parent), path.basename(parent))));
}
}
/**
* Finds the Inode of the given path.
* @param p The path to look up.
* @return The Inode of the path p.
* @todo memoize/cache
*/
private findINode(tx: SyncKeyValueROTransaction, p: string): Inode {
return this.getINode(tx, p, this._findINode(tx, path.dirname(p), path.basename(p)));
}
/**
* Given the ID of a node, retrieves the corresponding Inode.
* @param tx The transaction to use.
* @param p The corresponding path to the file (used for error messages).
* @param id The ID to look up.
*/
private getINode(tx: SyncKeyValueROTransaction, p: string, id: string): Inode {
const inode = tx.get(id);
if (inode === undefined) {
throw ApiError.ENOENT(p);
}
return Inode.fromBuffer(inode);
}
/**
* Given the Inode of a directory, retrieves the corresponding directory
* listing.
*/
private getDirListing(tx: SyncKeyValueROTransaction, p: string, inode: Inode): { [fileName: string]: string } {
if (!inode.isDirectory()) {
throw ApiError.ENOTDIR(p);
}
const data = tx.get(inode.id);
if (data === undefined) {
throw ApiError.ENOENT(p);
}
return JSON.parse(data.toString());
}
/**
* Creates a new node under a random ID. Retries 5 times before giving up in
* the exceedingly unlikely chance that we try to reuse a random GUID.
* @return The GUID that the data was stored under.
*/
private addNewNode(tx: SyncKeyValueRWTransaction, data: Buffer): string {
const retries = 0;
let currId: string;
while (retries < 5) {
try {
currId = GenerateRandomID();
tx.put(currId, data, false);
return currId;
} catch (e) {
// Ignore and reroll.
}
}
throw new ApiError(ErrorCode.EIO, 'Unable to commit data to key-value store.');
}
/**
* Commits a new file (well, a FILE or a DIRECTORY) to the file system with
* the given mode.
* Note: This will commit the transaction.
* @param p The path to the new file.
* @param type The type of the new file.
* @param mode The mode to create the new file with.
* @param data The data to store at the file's data node.
* @return The Inode for the new file.
*/
private commitNewFile(tx: SyncKeyValueRWTransaction, p: string, type: FileType, mode: number, data: Buffer): Inode {
const parentDir = path.dirname(p),
fname = path.basename(p),
parentNode = this.findINode(tx, parentDir),
dirListing = this.getDirListing(tx, parentDir, parentNode),
currTime = (new Date()).getTime();
// Invariant: The root always exists.
// If we don't check this prior to taking steps below, we will create a
// file with name '' in root should p == '/'.
if (p === '/') {
throw ApiError.EEXIST(p);
}
// Check if file already exists.
if (dirListing[fname]) {
throw ApiError.EEXIST(p);
}
let fileNode: Inode;
try {
// Commit data.
const dataId = this.addNewNode(tx, data);
fileNode = new Inode(dataId, data.length, mode | type, currTime, currTime, currTime);
// Commit file node.
const fileNodeId = this.addNewNode(tx, fileNode.toBuffer());
// Update and commit parent directory listing.
dirListing[fname] = fileNodeId;
tx.put(parentNode.id, Buffer.from(JSON.stringify(dirListing)), true);
} catch (e) {
tx.abort();
throw e;
}
tx.commit();
return fileNode;
}
/**
* Remove all traces of the given path from the file system.
* @param p The path to remove from the file system.
* @param isDir Does the path belong to a directory, or a file?
* @todo Update mtime.
*/
private removeEntry(p: string, isDir: boolean): void {
const tx = this.store.beginTransaction('readwrite'),
parent: string = path.dirname(p),
parentNode = this.findINode(tx, parent),
parentListing = this.getDirListing(tx, parent, parentNode),
fileName: string = path.basename(p);
if (!parentListing[fileName]) {
throw ApiError.ENOENT(p);
}
// Remove from directory listing of parent.
const fileNodeId = parentListing[fileName];
delete parentListing[fileName];
// Get file inode.
const fileNode = this.getINode(tx, p, fileNodeId);
if (!isDir && fileNode.isDirectory()) {
throw ApiError.EISDIR(p);
} else if (isDir && !fileNode.isDirectory()) {
throw ApiError.ENOTDIR(p);
}
try {
// Delete data.
tx.del(fileNode.id);
// Delete node.
tx.del(fileNodeId);
// Update directory listing.
tx.put(parentNode.id, Buffer.from(JSON.stringify(parentListing)), true);
} catch (e) {
tx.abort();
throw e;
}
// Success.
tx.commit();
}
}
/**
* Represents an *asynchronous* key-value store.
*/
export interface AsyncKeyValueStore {
/**
* The name of the key-value store.
*/
name(): string;
/**
* Empties the key-value store completely.
*/
clear(cb: BFSOneArgCallback): void;
/**
* Begins a read-write transaction.
*/
beginTransaction(type: 'readwrite'): AsyncKeyValueRWTransaction;
/**
* Begins a read-only transaction.
*/
beginTransaction(type: 'readonly'): AsyncKeyValueROTransaction;
beginTransaction(type: string): AsyncKeyValueROTransaction;
}
/**
* Represents an asynchronous read-only transaction.
*/
export interface AsyncKeyValueROTransaction {
/**
* Retrieves the data at the given key.
* @param key The key to look under for data.
*/
get(key: string, cb: BFSCallback<Buffer>): void;
}
/**
* Represents an asynchronous read-write transaction.
*/
export interface AsyncKeyValueRWTransaction extends AsyncKeyValueROTransaction {
/**
* Adds the data to the store under the given key. Overwrites any existing
* data.
* @param key The key to add the data under.
* @param data The data to add to the store.
* @param overwrite If 'true', overwrite any existing data. If 'false',
* avoids writing the data if the key exists.
* @param cb Triggered with an error and whether or not the value was
* committed.
*/
put(key: string, data: Buffer, overwrite: boolean, cb: BFSCallback<boolean>): void;
/**
* Deletes the data at the given key.
* @param key The key to delete from the store.
*/
del(key: string, cb: BFSOneArgCallback): void;
/**
* Commits the transaction.
*/
commit(cb: BFSOneArgCallback): void;
/**
* Aborts and rolls back the transaction.
*/
abort(cb: BFSOneArgCallback): void;
}
export class AsyncKeyValueFile extends PreloadFile<AsyncKeyValueFileSystem> implements File {
constructor(_fs: AsyncKeyValueFileSystem, _path: string, _flag: FileFlag, _stat: Stats, contents?: Buffer) {
super(_fs, _path, _flag, _stat, contents);
}
public sync(cb: BFSOneArgCallback): void {
if (this.isDirty()) {
this._fs._sync(this.getPath(), this.getBuffer(), this.getStats(), (e?: ApiError) => {
if (!e) {
this.resetDirty();
}
cb(e);
});
} else {
cb();
}
}
public close(cb: BFSOneArgCallback): void {
this.sync(cb);
}
}
/**
* An "Asynchronous key-value file system". Stores data to/retrieves data from
* an underlying asynchronous key-value store.
*/
export class AsyncKeyValueFileSystem extends BaseFileSystem {
public static isAvailable(): boolean { return true; }
protected store: AsyncKeyValueStore;
private _cache: LRUCache | null = null;
constructor(cacheSize: number) {
super();
if (cacheSize > 0) {
this._cache = new LRUCache(cacheSize);
}
}
/**
* Initializes the file system. Typically called by subclasses' async
* constructors.
*/
public init(store: AsyncKeyValueStore, cb: BFSOneArgCallback) {
this.store = store;
// INVARIANT: Ensure that the root exists.
this.makeRootDirectory(cb);
}
public getName(): string { return this.store.name(); }
public isReadOnly(): boolean { return false; }
public supportsSymlinks(): boolean { return false; }
public supportsProps(): boolean { return false; }
public supportsSynch(): boolean { return false; }
/**
* Delete all contents stored in the file system.
*/
public empty(cb: BFSOneArgCallback): void {
if (this._cache) {
this._cache.removeAll();
}
this.store.clear((e?) => {
if (noError(e, cb)) {
// INVARIANT: Root always exists.
this.makeRootDirectory(cb);
}
});
}
public rename(oldPath: string, newPath: string, cb: BFSOneArgCallback): void {
// TODO: Make rename compatible with the cache.
if (this._cache) {
// Clear and disable cache during renaming process.
const c = this._cache;
this._cache = null;
c.removeAll();
const oldCb = cb;
cb = (e?: ApiError | null) => {
// Restore empty cache.
this._cache = c;
oldCb(e);
};
}
const tx = this.store.beginTransaction('readwrite');
const oldParent = path.dirname(oldPath), oldName = path.basename(oldPath);
const newParent = path.dirname(newPath), newName = path.basename(newPath);
const inodes: { [path: string]: Inode } = {};
const lists: {
[path: string]: { [file: string]: string }
} = {};
let errorOccurred: boolean = false;
// Invariant: Can't move a folder inside itself.
// This funny little hack ensures that the check passes only if oldPath
// is a subpath of newParent. We append '/' to avoid matching folders that
// are a substring of the bottom-most folder in the path.
if ((newParent + '/').indexOf(oldPath + '/') === 0) {
return cb(new ApiError(ErrorCode.EBUSY, oldParent));
}
/**
* Responsible for Phase 2 of the rename operation: Modifying and
* committing the directory listings. Called once we have successfully
* retrieved both the old and new parent's inodes and listings.
*/
const theOleSwitcharoo = (): void => {
// Sanity check: Ensure both paths are present, and no error has occurred.
if (errorOccurred || !lists.hasOwnProperty(oldParent) || !lists.hasOwnProperty(newParent)) {
return;
}
const oldParentList = lists[oldParent], oldParentINode = inodes[oldParent],
newParentList = lists[newParent], newParentINode = inodes[newParent];
// Delete file from old parent.
if (!oldParentList[oldName]) {
cb(ApiError.ENOENT(oldPath));
} else {
const fileId = oldParentList[oldName];
delete oldParentList[oldName];
// Finishes off the renaming process by adding the file to the new
// parent.
const completeRename = () => {
newParentList[newName] = fileId;
// Commit old parent's list.
tx.put(oldParentINode.id, Buffer.from(JSON.stringify(oldParentList)), true, (e: ApiError) => {
if (noErrorTx(e, tx, cb)) {
if (oldParent === newParent) {
// DONE!
tx.commit(cb);
} else {
// Commit new parent's list.
tx.put(newParentINode.id, Buffer.from(JSON.stringify(newParentList)), true, (e: ApiError) => {
if (noErrorTx(e, tx, cb)) {
tx.commit(cb);
}
});
}
}
});
};
if (newParentList[newName]) {
// 'newPath' already exists. Check if it's a file or a directory, and
// act accordingly.
this.getINode(tx, newPath, newParentList[newName], (e: ApiError, inode?: Inode) => {
if (noErrorTx(e, tx, cb)) {
if (inode!.isFile()) {
// Delete the file and continue.
tx.del(inode!.id, (e?: ApiError) => {
if (noErrorTx(e, tx, cb)) {
tx.del(newParentList[newName], (e?: ApiError) => {
if (noErrorTx(e, tx, cb)) {
completeRename();
}
});
}
});
} else {
// Can't overwrite a directory using rename.
tx.abort((e?) => {
cb(ApiError.EPERM(newPath));
});
}
}
});
} else {
completeRename();
}
}
};
/**
* Grabs a path's inode and directory listing, and shoves it into the
* inodes and lists hashes.
*/
const processInodeAndListings = (p: string): void => {
this.findINodeAndDirListing(tx, p, (e?: ApiError | null, node?: Inode, dirList?: {[name: string]: string}): void => {
if (e) {
if (!errorOccurred) {
errorOccurred = true;
tx.abort(() => {
cb(e);
});
}
// If error has occurred already, just stop here.
} else {
inodes[p] = node!;
lists[p] = dirList!;
theOleSwitcharoo();
}
});
};
processInodeAndListings(oldParent);
if (oldParent !== newParent) {
processInodeAndListings(newParent);
}
}
public stat(p: string, isLstat: boolean, cb: BFSCallback<Stats>): void {
const tx = this.store.beginTransaction('readonly');
this.findINode(tx, p, (e: ApiError, inode?: Inode): void => {
if (noError(e, cb)) {
cb(null, inode!.toStats());
}
});
}
public createFile(p: string, flag: FileFlag, mode: number, cb: BFSCallback<File>): void {
const tx = this.store.beginTransaction('readwrite'),
data = emptyBuffer();
this.commitNewFile(tx, p, FileType.FILE, mode, data, (e: ApiError, newFile?: Inode): void => {
if (noError(e, cb)) {
cb(null, new AsyncKeyValueFile(this, p, flag, newFile!.toStats(), data));
}
});