browser/components/sessionstore/src/SessionSaver.jsm

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/browser/components/sessionstore/src/SessionSaver.jsm	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,274 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this file,
     1.6 + * You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +"use strict";
     1.9 +
    1.10 +this.EXPORTED_SYMBOLS = ["SessionSaver"];
    1.11 +
    1.12 +const Cu = Components.utils;
    1.13 +const Cc = Components.classes;
    1.14 +const Ci = Components.interfaces;
    1.15 +
    1.16 +Cu.import("resource://gre/modules/Timer.jsm", this);
    1.17 +Cu.import("resource://gre/modules/Services.jsm", this);
    1.18 +Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
    1.19 +Cu.import("resource://gre/modules/TelemetryStopwatch.jsm", this);
    1.20 +
    1.21 +XPCOMUtils.defineLazyModuleGetter(this, "console",
    1.22 +  "resource://gre/modules/devtools/Console.jsm");
    1.23 +XPCOMUtils.defineLazyModuleGetter(this, "PrivacyFilter",
    1.24 +  "resource:///modules/sessionstore/PrivacyFilter.jsm");
    1.25 +XPCOMUtils.defineLazyModuleGetter(this, "SessionStore",
    1.26 +  "resource:///modules/sessionstore/SessionStore.jsm");
    1.27 +XPCOMUtils.defineLazyModuleGetter(this, "SessionFile",
    1.28 +  "resource:///modules/sessionstore/SessionFile.jsm");
    1.29 +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
    1.30 +  "resource://gre/modules/PrivateBrowsingUtils.jsm");
    1.31 +
    1.32 +// Minimal interval between two save operations (in milliseconds).
    1.33 +XPCOMUtils.defineLazyGetter(this, "gInterval", function () {
    1.34 +  const PREF = "browser.sessionstore.interval";
    1.35 +
    1.36 +  // Observer that updates the cached value when the preference changes.
    1.37 +  Services.prefs.addObserver(PREF, () => {
    1.38 +    this.gInterval = Services.prefs.getIntPref(PREF);
    1.39 +
    1.40 +    // Cancel any pending runs and call runDelayed() with
    1.41 +    // zero to apply the newly configured interval.
    1.42 +    SessionSaverInternal.cancel();
    1.43 +    SessionSaverInternal.runDelayed(0);
    1.44 +  }, false);
    1.45 +
    1.46 +  return Services.prefs.getIntPref(PREF);
    1.47 +});
    1.48 +
    1.49 +// Notify observers about a given topic with a given subject.
    1.50 +function notify(subject, topic) {
    1.51 +  Services.obs.notifyObservers(subject, topic, "");
    1.52 +}
    1.53 +
    1.54 +// TelemetryStopwatch helper functions.
    1.55 +function stopWatch(method) {
    1.56 +  return function (...histograms) {
    1.57 +    for (let hist of histograms) {
    1.58 +      TelemetryStopwatch[method]("FX_SESSION_RESTORE_" + hist);
    1.59 +    }
    1.60 +  };
    1.61 +}
    1.62 +
    1.63 +let stopWatchStart = stopWatch("start");
    1.64 +let stopWatchCancel = stopWatch("cancel");
    1.65 +let stopWatchFinish = stopWatch("finish");
    1.66 +
    1.67 +/**
    1.68 + * The external API implemented by the SessionSaver module.
    1.69 + */
    1.70 +this.SessionSaver = Object.freeze({
    1.71 +  /**
    1.72 +   * Immediately saves the current session to disk.
    1.73 +   */
    1.74 +  run: function () {
    1.75 +    return SessionSaverInternal.run();
    1.76 +  },
    1.77 +
    1.78 +  /**
    1.79 +   * Saves the current session to disk delayed by a given amount of time. Should
    1.80 +   * another delayed run be scheduled already, we will ignore the given delay
    1.81 +   * and state saving may occur a little earlier.
    1.82 +   */
    1.83 +  runDelayed: function () {
    1.84 +    SessionSaverInternal.runDelayed();
    1.85 +  },
    1.86 +
    1.87 +  /**
    1.88 +   * Sets the last save time to the current time. This will cause us to wait for
    1.89 +   * at least the configured interval when runDelayed() is called next.
    1.90 +   */
    1.91 +  updateLastSaveTime: function () {
    1.92 +    SessionSaverInternal.updateLastSaveTime();
    1.93 +  },
    1.94 +
    1.95 +  /**
    1.96 +   * Sets the last save time to zero. This will cause us to
    1.97 +   * immediately save the next time runDelayed() is called.
    1.98 +   */
    1.99 +  clearLastSaveTime: function () {
   1.100 +    SessionSaverInternal.clearLastSaveTime();
   1.101 +  },
   1.102 +
   1.103 +  /**
   1.104 +   * Cancels all pending session saves.
   1.105 +   */
   1.106 +  cancel: function () {
   1.107 +    SessionSaverInternal.cancel();
   1.108 +  }
   1.109 +});
   1.110 +
   1.111 +/**
   1.112 + * The internal API.
   1.113 + */
   1.114 +let SessionSaverInternal = {
   1.115 +  /**
   1.116 +   * The timeout ID referencing an active timer for a delayed save. When no
   1.117 +   * save is pending, this is null.
   1.118 +   */
   1.119 +  _timeoutID: null,
   1.120 +
   1.121 +  /**
   1.122 +   * A timestamp that keeps track of when we saved the session last. We will
   1.123 +   * this to determine the correct interval between delayed saves to not deceed
   1.124 +   * the configured session write interval.
   1.125 +   */
   1.126 +  _lastSaveTime: 0,
   1.127 +
   1.128 +  /**
   1.129 +   * Immediately saves the current session to disk.
   1.130 +   */
   1.131 +  run: function () {
   1.132 +    return this._saveState(true /* force-update all windows */);
   1.133 +  },
   1.134 +
   1.135 +  /**
   1.136 +   * Saves the current session to disk delayed by a given amount of time. Should
   1.137 +   * another delayed run be scheduled already, we will ignore the given delay
   1.138 +   * and state saving may occur a little earlier.
   1.139 +   *
   1.140 +   * @param delay (optional)
   1.141 +   *        The minimum delay in milliseconds to wait for until we collect and
   1.142 +   *        save the current session.
   1.143 +   */
   1.144 +  runDelayed: function (delay = 2000) {
   1.145 +    // Bail out if there's a pending run.
   1.146 +    if (this._timeoutID) {
   1.147 +      return;
   1.148 +    }
   1.149 +
   1.150 +    // Interval until the next disk operation is allowed.
   1.151 +    delay = Math.max(this._lastSaveTime + gInterval - Date.now(), delay, 0);
   1.152 +
   1.153 +    // Schedule a state save.
   1.154 +    this._timeoutID = setTimeout(() => this._saveStateAsync(), delay);
   1.155 +  },
   1.156 +
   1.157 +  /**
   1.158 +   * Sets the last save time to the current time. This will cause us to wait for
   1.159 +   * at least the configured interval when runDelayed() is called next.
   1.160 +   */
   1.161 +  updateLastSaveTime: function () {
   1.162 +    this._lastSaveTime = Date.now();
   1.163 +  },
   1.164 +
   1.165 +  /**
   1.166 +   * Sets the last save time to zero. This will cause us to
   1.167 +   * immediately save the next time runDelayed() is called.
   1.168 +   */
   1.169 +  clearLastSaveTime: function () {
   1.170 +    this._lastSaveTime = 0;
   1.171 +  },
   1.172 +
   1.173 +  /**
   1.174 +   * Cancels all pending session saves.
   1.175 +   */
   1.176 +  cancel: function () {
   1.177 +    clearTimeout(this._timeoutID);
   1.178 +    this._timeoutID = null;
   1.179 +  },
   1.180 +
   1.181 +  /**
   1.182 +   * Saves the current session state. Collects data and writes to disk.
   1.183 +   *
   1.184 +   * @param forceUpdateAllWindows (optional)
   1.185 +   *        Forces us to recollect data for all windows and will bypass and
   1.186 +   *        update the corresponding caches.
   1.187 +   */
   1.188 +  _saveState: function (forceUpdateAllWindows = false) {
   1.189 +    // Cancel any pending timeouts.
   1.190 +    this.cancel();
   1.191 +
   1.192 +    if (PrivateBrowsingUtils.permanentPrivateBrowsing) {
   1.193 +      // Don't save (or even collect) anything in permanent private
   1.194 +      // browsing mode
   1.195 +
   1.196 +      this.updateLastSaveTime();
   1.197 +      return Promise.resolve();
   1.198 +    }
   1.199 +
   1.200 +    stopWatchStart("COLLECT_DATA_MS", "COLLECT_DATA_LONGEST_OP_MS");
   1.201 +    let state = SessionStore.getCurrentState(forceUpdateAllWindows);
   1.202 +    PrivacyFilter.filterPrivateWindowsAndTabs(state);
   1.203 +
   1.204 +    // Make sure that we keep the previous session if we started with a single
   1.205 +    // private window and no non-private windows have been opened, yet.
   1.206 +    if (state.deferredInitialState) {
   1.207 +      state.windows = state.deferredInitialState.windows || [];
   1.208 +      delete state.deferredInitialState;
   1.209 +    }
   1.210 +
   1.211 +#ifndef XP_MACOSX
   1.212 +    // We want to restore closed windows that are marked with _shouldRestore.
   1.213 +    // We're doing this here because we want to control this only when saving
   1.214 +    // the file.
   1.215 +    while (state._closedWindows.length) {
   1.216 +      let i = state._closedWindows.length - 1;
   1.217 +
   1.218 +      if (!state._closedWindows[i]._shouldRestore) {
   1.219 +        // We only need to go until _shouldRestore
   1.220 +        // is falsy since we're going in reverse.
   1.221 +        break;
   1.222 +      }
   1.223 +
   1.224 +      delete state._closedWindows[i]._shouldRestore;
   1.225 +      state.windows.unshift(state._closedWindows.pop());
   1.226 +    }
   1.227 +#endif
   1.228 +
   1.229 +    stopWatchFinish("COLLECT_DATA_MS", "COLLECT_DATA_LONGEST_OP_MS");
   1.230 +    return this._writeState(state);
   1.231 +  },
   1.232 +
   1.233 +  /**
   1.234 +   * Saves the current session state. Collects data asynchronously and calls
   1.235 +   * _saveState() to collect data again (with a cache hit rate of hopefully
   1.236 +   * 100%) and write to disk afterwards.
   1.237 +   */
   1.238 +  _saveStateAsync: function () {
   1.239 +    // Allow scheduling delayed saves again.
   1.240 +    this._timeoutID = null;
   1.241 +
   1.242 +    // Write to disk.
   1.243 +    this._saveState();
   1.244 +  },
   1.245 +
   1.246 +  /**
   1.247 +   * Write the given state object to disk.
   1.248 +   */
   1.249 +  _writeState: function (state) {
   1.250 +    // Inform observers
   1.251 +    notify(null, "sessionstore-state-write");
   1.252 +
   1.253 +    stopWatchStart("SERIALIZE_DATA_MS", "SERIALIZE_DATA_LONGEST_OP_MS", "WRITE_STATE_LONGEST_OP_MS");
   1.254 +    let data = JSON.stringify(state);
   1.255 +    stopWatchFinish("SERIALIZE_DATA_MS", "SERIALIZE_DATA_LONGEST_OP_MS");
   1.256 +
   1.257 +    // We update the time stamp before writing so that we don't write again
   1.258 +    // too soon, if saving is requested before the write completes. Without
   1.259 +    // this update we may save repeatedly if actions cause a runDelayed
   1.260 +    // before writing has completed. See Bug 902280
   1.261 +    this.updateLastSaveTime();
   1.262 +
   1.263 +    // Write (atomically) to a session file, using a tmp file. Once the session
   1.264 +    // file is successfully updated, save the time stamp of the last save and
   1.265 +    // notify the observers.
   1.266 +    stopWatchStart("SEND_SERIALIZED_STATE_LONGEST_OP_MS");
   1.267 +    let promise = SessionFile.write(data);
   1.268 +    stopWatchFinish("WRITE_STATE_LONGEST_OP_MS",
   1.269 +                    "SEND_SERIALIZED_STATE_LONGEST_OP_MS");
   1.270 +    promise = promise.then(() => {
   1.271 +      this.updateLastSaveTime();
   1.272 +      notify(null, "sessionstore-state-write-complete");
   1.273 +    }, console.error);
   1.274 +
   1.275 +    return promise;
   1.276 +  },
   1.277 +};

mercurial