summaryrefslogtreecommitdiff
path: root/common/modules/cache.jsm
blob: 719611d598c9b85a447cb43be5a532503ac6c301 (plain)
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
// Copyright (c) 2011 by Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

defineModule("cache", {
    exports: ["Cache", "cache"],
    require: ["config", "services", "util"]
});

lazyRequire("overlay", ["overlay"]);
lazyRequire("storage", ["File"]);

var Cache = Module("Cache", XPCOM(Ci.nsIRequestObserver), {
    init: function init() {
        this.queue = [];
        this.cache = {};
        this.providers = {};
        this.globalProviders = this.providers;
        this.providing = {};
        this.localProviders = {};

        if (JSMLoader.cacheFlush)
            this.flush();

        update(services["dactyl:"].providers, {
            "cache": function (uri, path) {
                let contentType = "text/plain";
                try {
                    contentType = services.mime.getTypeFromURI(uri)
                }
                catch (e) {}

                if (!cache.cacheReader || !cache.cacheReader.hasEntry(path))
                    return [contentType, cache.force(path)];

                let channel = services.StreamChannel(uri);
                channel.contentStream = cache.cacheReader.getInputStream(path);
                channel.contentType = contentType;
                channel.contentCharset = "UTF-8";
                return channel;
            }
        });
    },

    Local: function Local(dactyl, modules, window) ({
        init: function init() {
            delete this.instance;
            this.providers = {};
        },

        isLocal: true
    }),

    parse: function parse(str) {
        if (~'{['.indexOf(str[0]))
            return JSON.parse(str);
        return str;
    },

    stringify: function stringify(obj) {
        if (isString(obj))
            return obj;
        return JSON.stringify(obj);
    },

    compression: 9,

    cacheFile: Class.Memoize(function () {
        let dir = File(services.directory.get("ProfD", Ci.nsIFile))
                    .child("dactyl");
        if (!dir.exists())
            dir.create(dir.DIRECTORY_TYPE, octal(777));
        return dir.child("cache.zip");
    }),

    get cacheReader() {
        if (!this._cacheReader && this.cacheFile.exists()
                && !this.inQueue)
            try {
                this._cacheReader = services.ZipReader(this.cacheFile);
            }
            catch (e if e.result == Cr.NS_ERROR_FILE_CORRUPTED) {
                util.reportError(e);
                this.closeWriter();
                this.cacheFile.remove(false);
            }

        return this._cacheReader;
    },

    get inQueue() this._cacheWriter && this._cacheWriter.inQueue,

    getCacheWriter: function () {
        if (!this._cacheWriter)
            try {
                let mode = File.MODE_RDWR;
                if (!this.cacheFile.exists())
                    mode |= File.MODE_CREATE;

                cache._cacheWriter = services.ZipWriter(this.cacheFile, mode);
            }
            catch (e if e.result == Cr.NS_ERROR_FILE_CORRUPTED) {
                util.reportError(e);
                this.cacheFile.remove(false);

                mode |= File.MODE_CREATE;
                cache._cacheWriter = services.ZipWriter(this.cacheFile, mode);
            }
        return this._cacheWriter;
    },

    closeReader: function closeReader() {
        if (cache._cacheReader) {
            this.cacheReader.close();
            delete cache._cacheReader;
        }
    },

    closeWriter: util.wrapCallback(function closeWriter() {
        this.closeReader();

        if (this._cacheWriter) {
            this._cacheWriter.close();
            delete cache._cacheWriter;

            // ZipWriter bug.
            if (this.cacheFile.fileSize <= 22)
                this.cacheFile.remove(false);
        }
    }),

    flush: function flush() {
        cache.cache = {};
        if (this.cacheFile.exists()) {
            this.closeReader();

            this.flushJAR(this.cacheFile);
            this.cacheFile.remove(false);
        }
    },

    flushAll: function flushAll(file) {
        this.flushStartup();
        this.flush();
    },

    flushEntry: function flushEntry(name, time) {
        if (this.cacheReader && this.cacheReader.hasEntry(name)) {
            if (time && this.cacheReader.getEntry(name).lastModifiedTime / 1000 >= time)
                return;

            this.queue.push([null, name]);
            cache.processQueue();
        }

        delete this.cache[name];
    },

    flushJAR: function flushJAR(file) {
        services.observer.notifyObservers(file, "flush-cache-entry", "");
    },

    flushStartup: function flushStartup() {
        services.observer.notifyObservers(null, "startupcache-invalidate", "");
    },

    force: function force(name, localOnly) {
        util.waitFor(function () !this.inQueue, this);

        if (this.cacheReader && this.cacheReader.hasEntry(name)) {
            return this.parse(File.readStream(
                this.cacheReader.getInputStream(name)));
        }

        if (Set.has(this.localProviders, name) && !this.isLocal) {
            for each (let { cache } in overlay.modules)
                if (cache._has(name))
                    return cache.force(name, true);
        }

        if (Set.has(this.providers, name)) {
            util.assert(!Set.add(this.providing, name),
                        "Already generating cache for " + name,
                        false);
            try {
                let [func, self] = this.providers[name];
                this.cache[name] = func.call(self || this, name);
            }
            finally {
                delete this.providing[name];
            }

            cache.queue.push([Date.now(), name]);
            cache.processQueue();

            return this.cache[name];
        }

        if (this.isLocal && !localOnly)
            return cache.force(name);
    },

    get: function get(name, callback, self) {
        if (!Set.has(this.cache, name)) {
            if (callback && !(Set.has(this.providers, name) ||
                              Set.has(this.localProviders, name)))
                this.register(name, callback, self);

            this.cache[name] = this.force(name);
            util.assert(this.cache[name] !== undefined,
                        "No such cache key", false);
        }

        return this.cache[name];
    },

    _has: function _has(name) Set.has(this.providers, name) || set.has(this.cache, name),

    has: function has(name) [this.globalProviders, this.cache, this.localProviders]
            .some(function (obj) Set.has(obj, name)),

    register: function register(name, callback, self) {
        if (this.isLocal)
            Set.add(this.localProviders, name);

        this.providers[name] = [callback, self];
    },

    processQueue: function processQueue() {
        this.closeReader();
        this.closeWriter();

        if (this.queue.length && !this.inQueue) {
            // removeEntry does not work properly with queues.
            for each (let [, entry] in this.queue)
                if (this.getCacheWriter().hasEntry(entry)) {
                    this.getCacheWriter().removeEntry(entry, false);
                    this.closeWriter();
                }

            this.queue.splice(0).forEach(function ([time, entry]) {
                if (time && Set.has(this.cache, entry)) {
                    let stream = services.CharsetConv("UTF-8")
                                         .convertToInputStream(this.stringify(this.cache[entry]));

                    this.getCacheWriter().addEntryStream(entry, time * 1000,
                                                         this.compression, stream,
                                                         true);
                }
            }, this);

            if (this._cacheWriter)
                this.getCacheWriter().processQueue(this, null);
        }
    },

    onStopRequest: function onStopRequest() {
        this.processQueue();
    }
});

endModule();

// catch(e){ if (typeof e === "string") e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }

// vim: set fdm=marker sw=4 sts=4 et ft=javascript: