-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathlibrary_idbfs.js
392 lines (346 loc) · 12.6 KB
/
library_idbfs.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
/**
* @license
* Copyright 2013 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
addToLibrary({
$IDBFS__deps: ['$FS', '$MEMFS', '$PATH'],
$IDBFS__postset: () => {
addAtExit('IDBFS.quit();');
return '';
},
$IDBFS: {
dbs: {},
indexedDB: () => {
if (typeof indexedDB != 'undefined') return indexedDB;
var ret = null;
if (typeof window == 'object') ret = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
#if ASSERTIONS
assert(ret, 'IDBFS used, but indexedDB not supported');
#endif
return ret;
},
DB_VERSION: 21,
DB_STORE_NAME: 'FILE_DATA',
// Queues a new VFS -> IDBFS synchronization operation
queuePersist: (mount) => {
function onPersistComplete() {
if (mount.idbPersistState === 'again') startPersist(); // If a new sync request has appeared in between, kick off a new sync
else mount.idbPersistState = 0; // Otherwise reset sync state back to idle to wait for a new sync later
}
function startPersist() {
mount.idbPersistState = 'idb'; // Mark that we are currently running a sync operation
IDBFS.syncfs(mount, /*populate:*/false, onPersistComplete);
}
if (!mount.idbPersistState) {
// Programs typically write/copy/move multiple files in the in-memory
// filesystem within a single app frame, so when a filesystem sync
// command is triggered, do not start it immediately, but only after
// the current frame is finished. This way all the modified files
// inside the main loop tick will be batched up to the same sync.
mount.idbPersistState = setTimeout(startPersist, 0);
} else if (mount.idbPersistState === 'idb') {
// There is an active IndexedDB sync operation in-flight, but we now
// have accumulated more files to sync. We should therefore queue up
// a new sync after the current one finishes so that all writes
// will be properly persisted.
mount.idbPersistState = 'again';
}
},
mount: (mount) => {
// reuse core MEMFS functionality
var mnt = MEMFS.mount(mount);
// If the automatic IDBFS persistence option has been selected, then automatically persist
// all modifications to the filesystem as they occur.
if (mount?.opts?.autoPersist) {
mnt.idbPersistState = 0; // IndexedDB sync starts in idle state
var memfs_node_ops = mnt.node_ops;
mnt.node_ops = Object.assign({}, mnt.node_ops); // Clone node_ops to inject write tracking
mnt.node_ops.mknod = (parent, name, mode, dev) => {
var node = memfs_node_ops.mknod(parent, name, mode, dev);
// Propagate injected node_ops to the newly created child node
node.node_ops = mnt.node_ops;
// Remember for each IDBFS node which IDBFS mount point they came from so we know which mount to persist on modification.
node.idbfs_mount = mnt.mount;
// Remember original MEMFS stream_ops for this node
node.memfs_stream_ops = node.stream_ops;
// Clone stream_ops to inject write tracking
node.stream_ops = Object.assign({}, node.stream_ops);
// Track all file writes
node.stream_ops.write = (stream, buffer, offset, length, position, canOwn) => {
// This file has been modified, we must persist IndexedDB when this file closes
stream.node.isModified = true;
return node.memfs_stream_ops.write(stream, buffer, offset, length, position, canOwn);
};
// Persist IndexedDB on file close
node.stream_ops.close = (stream) => {
var n = stream.node;
if (n.isModified) {
IDBFS.queuePersist(n.idbfs_mount);
n.isModified = false;
}
if (n.memfs_stream_ops.close) return n.memfs_stream_ops.close(stream);
};
return node;
};
// Also kick off persisting the filesystem on other operations that modify the filesystem.
mnt.node_ops.mkdir = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.mkdir(...args));
mnt.node_ops.rmdir = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.rmdir(...args));
mnt.node_ops.symlink = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.symlink(...args));
mnt.node_ops.unlink = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.unlink(...args));
mnt.node_ops.rename = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.rename(...args));
}
return mnt;
},
syncfs: (mount, populate, callback) => {
IDBFS.getLocalSet(mount, (err, local) => {
if (err) return callback(err);
IDBFS.getRemoteSet(mount, (err, remote) => {
if (err) return callback(err);
var src = populate ? remote : local;
var dst = populate ? local : remote;
IDBFS.reconcile(src, dst, callback);
});
});
},
quit: () => {
Object.values(IDBFS.dbs).forEach((value) => value.close());
IDBFS.dbs = {};
},
getDB: (name, callback) => {
// check the cache first
var db = IDBFS.dbs[name];
if (db) {
return callback(null, db);
}
var req;
try {
req = IDBFS.indexedDB().open(name, IDBFS.DB_VERSION);
} catch (e) {
return callback(e);
}
if (!req) {
return callback("Unable to connect to IndexedDB");
}
req.onupgradeneeded = (e) => {
var db = /** @type {IDBDatabase} */ (e.target.result);
var transaction = e.target.transaction;
var fileStore;
if (db.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
} else {
fileStore = db.createObjectStore(IDBFS.DB_STORE_NAME);
}
if (!fileStore.indexNames.contains('timestamp')) {
fileStore.createIndex('timestamp', 'timestamp', { unique: false });
}
};
req.onsuccess = () => {
db = /** @type {IDBDatabase} */ (req.result);
// add to the cache
IDBFS.dbs[name] = db;
callback(null, db);
};
req.onerror = (e) => {
callback(e.target.error);
e.preventDefault();
};
},
getLocalSet: (mount, callback) => {
var entries = {};
function isRealDir(p) {
return p !== '.' && p !== '..';
};
function toAbsolute(root) {
return (p) => PATH.join2(root, p);
};
var check = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
while (check.length) {
var path = check.pop();
var stat;
try {
stat = FS.stat(path);
} catch (e) {
return callback(e);
}
if (FS.isDir(stat.mode)) {
check.push(...FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
}
entries[path] = { 'timestamp': stat.mtime };
}
return callback(null, { type: 'local', entries: entries });
},
getRemoteSet: (mount, callback) => {
var entries = {};
IDBFS.getDB(mount.mountpoint, (err, db) => {
if (err) return callback(err);
try {
var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readonly');
transaction.onerror = (e) => {
callback(e.target.error);
e.preventDefault();
};
var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
var index = store.index('timestamp');
index.openKeyCursor().onsuccess = (event) => {
var cursor = event.target.result;
if (!cursor) {
return callback(null, { type: 'remote', db, entries });
}
entries[cursor.primaryKey] = { 'timestamp': cursor.key };
cursor.continue();
};
} catch (e) {
return callback(e);
}
});
},
loadLocalEntry: (path, callback) => {
var stat, node;
try {
var lookup = FS.lookupPath(path);
node = lookup.node;
stat = FS.stat(path);
} catch (e) {
return callback(e);
}
if (FS.isDir(stat.mode)) {
return callback(null, { 'timestamp': stat.mtime, 'mode': stat.mode });
} else if (FS.isFile(stat.mode)) {
// Performance consideration: storing a normal JavaScript array to a IndexedDB is much slower than storing a typed array.
// Therefore always convert the file contents to a typed array first before writing the data to IndexedDB.
node.contents = MEMFS.getFileDataAsTypedArray(node);
return callback(null, { 'timestamp': stat.mtime, 'mode': stat.mode, 'contents': node.contents });
} else {
return callback(new Error('node type not supported'));
}
},
storeLocalEntry: (path, entry, callback) => {
try {
if (FS.isDir(entry['mode'])) {
FS.mkdirTree(path, entry['mode']);
} else if (FS.isFile(entry['mode'])) {
FS.writeFile(path, entry['contents'], { canOwn: true });
} else {
return callback(new Error('node type not supported'));
}
FS.chmod(path, entry['mode']);
FS.utime(path, entry['timestamp'], entry['timestamp']);
} catch (e) {
return callback(e);
}
callback(null);
},
removeLocalEntry: (path, callback) => {
try {
var stat = FS.stat(path);
if (FS.isDir(stat.mode)) {
FS.rmdir(path);
} else if (FS.isFile(stat.mode)) {
FS.unlink(path);
}
} catch (e) {
return callback(e);
}
callback(null);
},
loadRemoteEntry: (store, path, callback) => {
var req = store.get(path);
req.onsuccess = (event) => callback(null, event.target.result);
req.onerror = (e) => {
callback(e.target.error);
e.preventDefault();
};
},
storeRemoteEntry: (store, path, entry, callback) => {
try {
var req = store.put(entry, path);
} catch (e) {
callback(e);
return;
}
req.onsuccess = (event) => callback();
req.onerror = (e) => {
callback(e.target.error);
e.preventDefault();
};
},
removeRemoteEntry: (store, path, callback) => {
var req = store.delete(path);
req.onsuccess = (event) => callback();
req.onerror = (e) => {
callback(e.target.error);
e.preventDefault();
};
},
reconcile: (src, dst, callback) => {
var total = 0;
var create = [];
Object.keys(src.entries).forEach((key) => {
var e = src.entries[key];
var e2 = dst.entries[key];
if (!e2 || e['timestamp'].getTime() != e2['timestamp'].getTime()) {
create.push(key);
total++;
}
});
var remove = [];
Object.keys(dst.entries).forEach((key) => {
if (!src.entries[key]) {
remove.push(key);
total++;
}
});
if (!total) {
return callback(null);
}
var errored = false;
var db = src.type === 'remote' ? src.db : dst.db;
var transaction = db.transaction([IDBFS.DB_STORE_NAME], 'readwrite');
var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
function done(err) {
if (err && !errored) {
errored = true;
return callback(err);
}
};
// transaction may abort if (for example) there is a QuotaExceededError
transaction.onerror = transaction.onabort = (e) => {
done(e.target.error);
e.preventDefault();
};
transaction.oncomplete = (e) => {
if (!errored) {
callback(null);
}
};
// sort paths in ascending order so directory entries are created
// before the files inside them
create.sort().forEach((path) => {
if (dst.type === 'local') {
IDBFS.loadRemoteEntry(store, path, (err, entry) => {
if (err) return done(err);
IDBFS.storeLocalEntry(path, entry, done);
});
} else {
IDBFS.loadLocalEntry(path, (err, entry) => {
if (err) return done(err);
IDBFS.storeRemoteEntry(store, path, entry, done);
});
}
});
// sort paths in descending order so files are deleted before their
// parent directories
remove.sort().reverse().forEach((path) => {
if (dst.type === 'local') {
IDBFS.removeLocalEntry(path, done);
} else {
IDBFS.removeRemoteEntry(store, path, done);
}
});
}
}
});
if (WASMFS) {
error("using -lidbfs is not currently supported in WasmFS.");
}