emscripten Humble Cloud interface
Aaron Mandle
2014-08-22 943ba1a780347d98f7cb53f972218668709ed0d2
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
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;
            } else {
                mount.opts.disabled = true;
                Module.print("WARNING: Cloud provider not available. Disabling Sync");
            }
            return MEMFS.mount.apply(null, arguments);
        },
        syncfs: function(mount, populate, callback) {
            if (mount.opts.disabled) {
                return callback(new Error("Syncing Disabled"));
            }
 
            // re-use IDBFS.getLocalSet for now
            CLOUDFS.getLocalSet(mount, function(err, local) {
                if (err) return callback(err);
 
                CLOUDFS.getRemoteSet(mount, function(err, remote) {
                    if (err) return callback(err);
 
                    var src = populate ? remote : local;
                    var dst = populate ? local : remote;
 
                    console.log('source', src);
                    console.log('destination', dst);
 
                    CLOUDFS.reconcile(mount, src, dst, callback);
                });
            });
        },
        // Utility functions
        validateProvider: function(provider_name) {
            var provider = CLOUD_PROVIDERS[provider_name];
            if (provider === undefined) return false;
 
          var requiredMethods = ['allFiles', 'read', 'write', 'rm'];
          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 ) ) {
                var provider = CLOUD_PROVIDERS[mount.opts.provider];
                Module.print('Cloud provider vendor: ' + provider.vendor);
                return provider;
            } else {
                return false;
            }
        },
        // Getting list of entities
        getLocalSet: function(mount, callback) {
            var entries = {};
 
            function isRealDir(p) {
                return p !== '.' && p !== '..';
            };
            function toAbsolute(root) {
                return function(p) {
                    return PATH.join2(root, p);
                }
            };
 
            var check = FS.readdir(mount.mountpoint).filter(isRealDir);
 
            while (check.length) {
                var path = check.pop();
                var stat;
                var 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)));
                }
 
                entries[abs_path] = {
                    timestamp: stat.mtime,
                    path: path
                };
            }
 
            return callback(null, { type: 'local', entries: entries });
        },
        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];
 
              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;
                  });
              }
              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'));
          });
        },
        // Fetching local and remote files
        loadLocalEntry: function(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'));
            }
        },
        loadRemoteEntry: function(mount, pathinfo, callback) {
            if (pathinfo.type == 'file') {
                mount.opts.provider.read(mount.opts.cloud, pathinfo.url,
                    function(data) {
                        callback(null, { contents: data, timestamp: pathinfo.timestamp, mode: {{{ cDefine('S_IFREG') | 0777 }}} });
                    },
                    function(e) {
                        callback(e);
                    });
            } else {
                callback(null, { timestamp: pathinfo.timestamp, mode: {{{ cDefine('S_IFDIR') | 0777 }}} });
            }
        },
        // storing local and remote files
        storeLocalEntry: function(path, entry, callback) {
            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);
        },
        storeRemoteEntry: function(mount, 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);
                })
            }
        },
        // 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);
                }
            };
 
            // 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];
                if (dst.type === 'local') {
                    CLOUDFS.loadRemoteEntry(mount, pathinfo, function (err, entry) {
                        if (err) return done(err);
                        CLOUDFS.storeLocalEntry(path, entry, done);
                    });
                } else {
                    CLOUDFS.loadLocalEntry(path, function (err, entry) {
                        if (err) return done(err);
                        CLOUDFS.storeRemoteEntry(mount, pathinfo, entry, done);
                    });
                }
            });
 
            return;
 
            // sort paths in descending order so files are deleted before their
            // parent directories
            remove.sort().reverse().forEach(function(path) {
                var info = dst.entries[path];
                if (dst.type === 'local') {
                    CLOUDFS.removeLocalEntry(path, info, done);
                } else {
                    CLOUDFS.removeRemoteEntry(path, info, done);
                }
            });
        }
    }
};
 
autoAddDeps(LibraryCLOUDFS, '$CLOUDFS');
mergeInto(LibraryManager.library, LibraryCLOUDFS);