emscripten Humble Cloud interface
Edward Rudd
2014-10-14 41532d25d30dde3c456d652c04aa9cfe54b39541
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
var LibraryCLOUDFS = {
    $CLOUDFS__deps: ['$FS', '$MEMFS', '$PATH'],
    $CLOUDFS__postset: "var CLOUD_PROVIDERS; if (!CLOUD_PROVIDERS) CLOUD_PROVIDERS = (typeof CLOUD_PROVIDERS !== 'undefined' ? CLOUD_PROVIDERS : null) || {};",
    $CLOUDFS: {
        mount: function(mount) {
            var provider = CLOUDFS.fetchProvider(mount);
            if (provider) {
                mount.opts.provider = provider;
                if (!mount.opts.scope) {
                  // backwards compat
                  mount.opts.scope = mount.opts.cloud.applicationtoken;
                }
                mount.opts.cloud.scope = mount.opts.scope;
                Module.print('Cloud provider vendor: ' + provider.vendor);
                if (!provider.isAvailable(mount.opts.cloud)) {
                  mount.opts.disabled = true;
                  Module.print("WARNING: Cloud not available. Disabling Cloud Sync");
                }
            } else {
                mount.opts.disabled = true;
                Module.print("WARNING: Cloud provider not available. Disabling Cloud Sync");
            }
            return MEMFS.mount.apply(null, arguments);
        },
        syncfs: function(mount, populate, callback) {
          if (populate) {
            if (!mount.opts.disabled) {
              CLOUDFS.syncfs_load_from_cloud(mount, function (err) {
                if (err) return callback(err);
                CLOUDFS.syncfs_load_from_idb(mount, callback);
              });
            } else {
              CLOUDFS.syncfs_load_from_idb(mount, callback);
            }
          } else {
            CLOUDFS.syncfs_save_to_idb(mount, function(err) {
              if (err) return callback(err);
              if (!mount.opts.disabled) {
                CLOUDFS.syncfs_save_to_cloud(mount, callback);
              }
            });
          }
        },
        syncfs_load_from_cloud: function(mount, callback) {
          CLOUDFS.getRemoteSet(mount, function(err, remote) {
            if (err) return callback(err);
 
            CLOUDFS.getIDBSet(mount, function(err, idb) {
              if (err) return callback(err);
 
              CLOUDFS.reconcile(mount, remote, idb, callback);
            });
          });
        },
        syncfs_load_from_idb: function(mount, callback) {
          CLOUDFS.getIDBSet(mount, function(err, idb) {
            if (err) return callback(err);
 
            CLOUDFS.getLocalSet(mount, function(err, local) {
              if (err) return callback(err);
 
              CLOUDFS.reconcile(mount, idb, local, callback);
            });
          });
        },
        syncfs_save_to_idb: function(mount, callback) {
          CLOUDFS.getLocalSet(mount, function(err, local) {
            if (err) return callback(err);
 
            CLOUDFS.getIDBSet(mount, function(err, idb) {
              if (err) return callback(err);
 
              CLOUDFS.reconcile(mount, local, idb, callback);
            });
          });
        },
        syncfs_save_to_cloud: function(mount, callback) {
          CLOUDFS.getIDBSet(mount, function(err, idb) {
            if (err) return callback(err);
 
            CLOUDFS.getRemoteSet(mount, function(err, remote) {
              if (err) return callback(err);
 
              CLOUDFS.reconcile(mount, idb, remote, callback);
            });
          });
        },
        // handling the diffing of "haves" and "have nots"
        reconcile: function(mount, src, dst, callback) {
          var total = 0;
 
          var create = [];
          Object.keys(src.entries).forEach(function (key) {
            var e = src.entries[key];
            var e2 = dst.entries[key];
            if (!e2 || e.timestamp > e2.timestamp) {
              create.push(key);
              total++;
            }
          });
 
          var remove = [];
          Object.keys(dst.entries).forEach(function (key) {
            var e = dst.entries[key];
            var e2 = src.entries[key];
            if (!e2) {
              remove.push(key);
              total++;
            }
          });
 
          if (!total) {
            return callback(null);
          }
 
          var completed = 0;
 
          function done(err) {
            if (err) {
              if (!done.errored) {
                done.errored = true;
                return callback(err);
              }
              return;
            }
            if (++completed >= total) {
              return callback(null);
            }
          };
 
          var srcFunc = CLOUDFS.getFuncSet(src.type),
            dstFunc = CLOUDFS.getFuncSet(dst.type);
          var srcCtx = srcFunc.start(mount, src, done),
            dstCtx = dstFunc.start(mount, dst, done);
 
          // sort paths in ascending order so directory entries are created
          // before the files inside them
          create.sort().forEach(function (path) {
            var pathinfo = src.entries[path];
            srcFunc.load(mount, srcCtx, pathinfo, function(err, entry) {
              if (err) return done(err);
              dstFunc.store(mount, dstCtx, pathinfo, entry, done);
            });
          });
 
          // sort paths in descending order so files are deleted before their
          // parent directories
          remove.sort().reverse().forEach(function(path) {
            dstFunc.remove(mount, dstCtx, dst.entries[path], done);
          });
        },
        // Utility functions
        validateProvider: function(provider_name) {
            var provider = CLOUD_PROVIDERS[provider_name];
            if (provider === undefined) return false;
 
            var requiredMethods = ['allFiles', 'read', 'write', 'rm','isAvailable'];
            return requiredMethods.every(function(method) {
                return (method in provider);
            });
        },
        fetchProvider: function(mount) {
            if (mount.opts.provider === undefined || CLOUD_PROVIDERS[mount.opts.provider] === undefined) {
                return false;
            }
            if (CLOUDFS.validateProvider( mount.opts.provider ) ) {
                return CLOUD_PROVIDERS[mount.opts.provider];
            } else {
                return false;
            }
        },
        populateDirs: function(entries, f, toAbsolute) {
          if (f.path.indexOf('/') !== -1) {
            // we have folders.. stuff them in the list
            var parts = f.path.split('/'),
                prefix = '';
            // remove the "file" from the end
            parts.pop();
            // remove the empty directory from the beginning
            if (parts[0] == '') parts.shift();
 
            parts.forEach(function(e) {
              var p = prefix.length ? PATH.join2(prefix, e) : e,
                abs = toAbsolute(p);
              if (!(abs in entries)) {
                entries[abs] = {
                  path: p,
                  type: 'dir',
                  timestamp: f.timestamp
                };
              }
              prefix = p;
            });
          }
        },
        getFuncSet: function(type) {
          if (type == 'local') {
            return {
              start: function() {},
              load: CLOUDFS.loadLocalEntry,
              store: CLOUDFS.storeLocalEntry,
              remove: CLOUDFS.removeLocalEntry
            };
          } else if (type == 'remote') {
            return {
              start: function() {},
              load: CLOUDFS.loadRemoteEntry,
              store: CLOUDFS.storeRemoteEntry,
              remove: CLOUDFS.removeRemoteEntry
            };
          } else if (type == 'idb') {
            return {
              start: CLOUDFS.startIDBEntry,
              load: CLOUDFS.loadIDBEntry,
              store: CLOUDFS.storeIDBEntry,
              remove: CLOUDFS.removeIDBEntry
            };
          }
        },
        // Indexed DB Utility functions
        db: null,
        indexedDB: function() {
          if (typeof indexedDB !== 'undefined') return indexedDB;
          var ret = null;
          if (typeof window === 'object') ret = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
          assert(ret, 'CLOUDFS used, but indexedDB not supported');
          return ret;
        },
        DB_VERSION: 1,
        DB_NAME: 'CLOUDFS',
        DB_STORE_NAME: 'FILE_DATA',
        getDB: function(callback) {
          // check the cache first
          var db = CLOUDFS.db;
          if (db) {
            return callback(null, db);
          }
 
          var req;
          try {
            req = CLOUDFS.indexedDB().open(CLOUDFS.DB_NAME, CLOUDFS.DB_VERSION);
          } catch (e) {
            return callback(e);
          }
          req.onupgradeneeded = function(e) {
            var db = e.target.result;
            var transaction = e.target.transaction;
 
            var fileStore;
 
            if (db.objectStoreNames.contains(CLOUDFS.DB_STORE_NAME)) {
              fileStore = transaction.objectStore(CLOUDFS.DB_STORE_NAME);
            } else {
              fileStore = db.createObjectStore(CLOUDFS.DB_STORE_NAME);//, {keyPath: 'key'});
            }
 
            fileStore.createIndex('scope','scope',{ unique: false });
          };
          req.onsuccess = function() {
            db = req.result;
 
            // add to the cache
            CLOUDFS.db = db;
            callback(null, db);
          };
          req.onerror = function() {
            callback(this.error);
          };
        },
        // Getting list of entities
        getLocalSet: function(mount, callback) {
            function isRealDir(p) {
                return p !== '.' && p !== '..';
            };
            function toAbsolute(root) {
                return function(p) {
                    return PATH.join2(root, p);
                };
            };
            function checkPath(path) {
                for (var i = 0, l = mount.opts.filters.length; i < l; ++i) {
                    var f = mount.opts.filters[i];
                    if (typeof f == 'string') {
                        if (path.lastIndexOf(f, 0) == 0) {
                            return true;
                        }
                    } if (typeof f == 'function') {
                        if (f(path)) {
                            return true;
                        }
                    } if (f instanceof RegExp) {
                        if (f.test(path)) {
                            return true;
                        }
                    }
                }
                return false;
            };
 
            var entries = {},
                shouldFilter = false,
                check = FS.readdir(mount.mountpoint).filter(isRealDir);
 
            if (mount.opts.filters && mount.opts.filters.length) {
                shouldFilter = true;
            }
 
            while (check.length) {
                var path = check.pop(),
                    stat,
                    keep = true,
                    is_dir = false,
                    abs_path = PATH.join2(mount.mountpoint, path);
 
                try {
                    stat = FS.stat(abs_path);
                } catch (e) {
                    return callback(e);
                }
 
                if (FS.isDir(stat.mode)) {
                    check.push.apply(check, FS.readdir(abs_path).filter(isRealDir).map(toAbsolute(path)));
                    is_dir = true;
                } else if (shouldFilter) {
                    keep = checkPath(path);
                }
 
                if (keep) {
                    entries[abs_path] = {
                        timestamp: stat.mtime,
                        path: path,
                        type: is_dir ? 'dir' : 'file'
                    };
                }
            }
 
            return callback(null, { type: 'local', entries: entries });
        },
        getIDBSet: function(mount, callback) {
          var entries = {},
              toAbsolute = function(p) { return PATH.join2(mount.mountpoint, p); };
 
          CLOUDFS.getDB(function(err, db) {
            if (err) return callback(err);
 
            var transaction = db.transaction([CLOUDFS.DB_STORE_NAME], 'readonly');
            transaction.onerror = function() { callback(this.error); };
 
            var store = transaction.objectStore(CLOUDFS.DB_STORE_NAME);
            var index = store.index('scope');
 
            index.openCursor(IDBKeyRange.only(mount.opts.scope)).onsuccess = function(event) {
              var cursor = event.target.result;
 
              if (!cursor) {
                return callback(null, { type: 'idb', db: db, entries: entries });
              }
 
              entries[PATH.join2(mount.mountpoint, cursor.value.path)] = {
                path: cursor.value.path,
                type: FS.isDir(cursor.value.mode) ? 'dir' : 'file',
                timestamp: cursor.value.timestamp
              };
 
              cursor.continue();
            };
          });
        },
        getRemoteSet: function(mount, callback) {
          mount.opts.provider.allFiles(mount.opts.cloud, function(data) {
            var entries = {},
                toAbsolute = function(p) { return PATH.join2(mount.mountpoint, p); };
            for(var k in data) {
              var f = data[k];
 
              CLOUDFS.populateDirs(entries, f, toAbsolute);
 
              var p = toAbsolute(f.path);
              entries[p] = {
                url: f.url,
                path: f.path.trim('/'),
                type: 'file',
                timestamp: f.timestamp,
                size: f.size
              };
            }
            return callback(null, { type: 'remote', entries: entries } );
          }, function(e) {
            callback(e || new Error('failed request'));
          });
        },
        // Local file access
        loadLocalEntry: function(mount, ctx, pathinfo, callback) {
            var stat, node,
                path = PATH.join2(mount.mountpoint, pathinfo.path);
 
            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: function(mount, ctx, pathinfo, entry, callback) {
          var path = PATH.join2(mount.mountpoint, pathinfo.path);
          try {
            if (FS.isDir(entry.mode)) {
              try {
                FS.mkdir(path, entry.mode);
              } catch(e) {
                // ignore existing dirs
              }
            } else if (FS.isFile(entry.mode)) {
              FS.writeFile(path, entry.contents, { encoding: 'binary', canOwn: true });
            } else {
              return callback(new Error('node type not supported'));
            }
 
            FS.utime(path, entry.timestamp, entry.timestamp);
          } catch (e) {
            return callback(e);
          }
 
          callback(null);
        },
        removeLocalEntry: function(mount, ctx, pathinfo, callback) {
          var path = PATH.join2(mount.mountpoint, pathinfo.path);
          try {
            var lookup = FS.lookupPath(path);
            var stat = FS.stat(path);
 
            if (FS.isDir(stat.mode)) {
              try {
                FS.rmdir(path);
              } catch(e) {
                // it's ok if we can't remove the local folder.. it could be filtered files are in there
              }
            } else if (FS.isFile(stat.mode)) {
              FS.unlink(path);
            }
          } catch (e) {
            return callback(e);
          }
 
          callback(null);
        },
        // IDB File access
        buildIDBKey: function(mount, pathinfo) {
          return (mount.opts.scope || '') + ':' + pathinfo.path;
        },
        startIDBEntry: function(mount, dataset, ondone) {
          return {db: dataset.db};
        },
        loadIDBEntry: function(mount, ctx, pathinfo, callback) {
          var tx = ctx.db.transaction([CLOUDFS.DB_STORE_NAME], 'readwrite');
          tx.onerror = function() { callback(this.error); };
          var store = tx.objectStore(CLOUDFS.DB_STORE_NAME);
 
          var req = store.get(CLOUDFS.buildIDBKey(mount, pathinfo));
          req.onsuccess = function(event) { callback(null, event.target.result); };
          req.onerror = function() { callback(this.error); };
        },
        storeIDBEntry: function(mount, ctx, pathinfo, entry, callback) {
          var tx = ctx.db.transaction([CLOUDFS.DB_STORE_NAME], 'readwrite');
          tx.onerror = function() { callback(this.error); };
          var store = tx.objectStore(CLOUDFS.DB_STORE_NAME);
 
          // keep scope with entry
          var d = {
            scope: mount.opts.scope,
            path: pathinfo.path,
            mode: entry.mode,
            timestamp: entry.timestamp
          };
          if (entry.contents) d.contents = entry.contents;
 
          var req = store.put(d, CLOUDFS.buildIDBKey(mount, pathinfo));
          req.onsuccess = function() { callback(null); };
          req.onerror = function() { callback(this.error); };
        },
        removeIDBEntry: function(mount, ctx, pathinfo, callback) {
          var tx = ctx.db.transaction([CLOUDFS.DB_STORE_NAME], 'readwrite');
          tx.onerror = function() { callback(this.error); };
          var store = tx.objectStore(CLOUDFS.DB_STORE_NAME);
 
          var req = store.delete(CLOUDFS.buildIDBKey(mount, pathinfo));
          req.onsuccess = function() { callback(null); };
          req.onerror = function() { callback(this.error); };
        },
        // Remote file access
        loadRemoteEntry: function(mount, ctx, pathinfo, callback) {
            if (pathinfo.type == 'file') {
                mount.opts.provider.read(mount.opts.cloud, pathinfo.url,
                    function(data) {
                        // ensure data is in Uint8Array
                        var u8data = new Uint8Array(data);
                        callback(null, { contents: u8data, timestamp: pathinfo.timestamp, mode: CLOUDFS._FILE_MODE });
                    },
                    function(e) {
                        callback(e);
                    });
            } else {
                callback(null, { timestamp: pathinfo.timestamp, mode: CLOUDFS._DIR_MODE });
            }
        },
        storeRemoteEntry: function(mount, ctx, pathinfo, entry, callback) {
            if (FS.isFile(entry.mode)) {
                mount.opts.provider.write(mount.opts.cloud, pathinfo, entry.contents, function() {
                    callback(null);
                },
                function(e) {
                    callback(e);
                })
            }
        },
        removeRemoteEntry: function(mount, ctx, pathinfo, callback) {
          if (pathinfo.type == 'file') {
            mount.opts.provider.rm(mount.opts.cloud, pathinfo, function() {
              callback(null);
            },
            function(e) {
              callback(e);
            });
          }
        },
        _FILE_MODE: {{{ cDefine('S_IFREG') | 0777 }}},
        _DIR_MODE: {{{ cDefine('S_IFDIR') | 0777 }}}
    }
};
 
autoAddDeps(LibraryCLOUDFS, '$CLOUDFS');
mergeInto(LibraryManager.library, LibraryCLOUDFS);