summaryrefslogtreecommitdiffstats
path: root/services/sync/modules/resource.sys.mjs
blob: 537ffd521998a033c78555d2fa2b951af1f5e00d (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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

import { Log } from "resource://gre/modules/Log.sys.mjs";

import { Observers } from "resource://services-common/observers.sys.mjs";
import { CommonUtils } from "resource://services-common/utils.sys.mjs";
import { Utils } from "resource://services-sync/util.sys.mjs";
import { setTimeout, clearTimeout } from "resource://gre/modules/Timer.sys.mjs";

/* global AbortController */

/*
 * Resource represents a remote network resource, identified by a URI.
 * Create an instance like so:
 *
 *   let resource = new Resource("http://foobar.com/path/to/resource");
 *
 * The 'resource' object has the following methods to issue HTTP requests
 * of the corresponding HTTP methods:
 *
 *   get(callback)
 *   put(data, callback)
 *   post(data, callback)
 *   delete(callback)
 */
export function Resource(uri) {
  this._log = Log.repository.getLogger(this._logName);
  this._log.manageLevelFromPref("services.sync.log.logger.network.resources");
  this.uri = uri;
  this._headers = {};
}

// (static) Caches the latest server timestamp (X-Weave-Timestamp header).
Resource.serverTime = null;

XPCOMUtils.defineLazyPreferenceGetter(
  Resource,
  "SEND_VERSION_INFO",
  "services.sync.sendVersionInfo",
  true
);
Resource.prototype = {
  _logName: "Sync.Resource",

  /**
   * Callback to be invoked at request time to add authentication details.
   * If the callback returns a promise, it will be awaited upon.
   *
   * By default, a global authenticator is provided. If this is set, it will
   * be used instead of the global one.
   */
  authenticator: null,

  // Wait 5 minutes before killing a request.
  ABORT_TIMEOUT: 300000,

  // Headers to be included when making a request for the resource.
  // Note: Header names should be all lower case, there's no explicit
  // check for duplicates due to case!
  get headers() {
    return this._headers;
  },
  set headers(_) {
    throw new Error("headers can't be mutated directly. Please use setHeader.");
  },
  setHeader(header, value) {
    this._headers[header.toLowerCase()] = value;
  },

  // URI representing this resource.
  get uri() {
    return this._uri;
  },
  set uri(value) {
    if (typeof value == "string") {
      this._uri = CommonUtils.makeURI(value);
    } else {
      this._uri = value;
    }
  },

  // Get the string representation of the URI.
  get spec() {
    if (this._uri) {
      return this._uri.spec;
    }
    return null;
  },

  /**
   * @param {string} method HTTP method
   * @returns {Headers}
   */
  async _buildHeaders(method) {
    const headers = new Headers(this._headers);

    if (Resource.SEND_VERSION_INFO) {
      headers.append("user-agent", Utils.userAgent);
    }

    if (this.authenticator) {
      const result = await this.authenticator(this, method);
      if (result && result.headers) {
        for (const [k, v] of Object.entries(result.headers)) {
          headers.append(k.toLowerCase(), v);
        }
      }
    } else {
      this._log.debug("No authenticator found.");
    }

    // PUT and POST are treated differently because they have payload data.
    if (("PUT" == method || "POST" == method) && !headers.has("content-type")) {
      headers.append("content-type", "text/plain");
    }

    if (this._log.level <= Log.Level.Trace) {
      for (const [k, v] of headers) {
        if (k == "authorization" || k == "x-client-state") {
          this._log.trace(`HTTP Header ${k}: ***** (suppressed)`);
        } else {
          this._log.trace(`HTTP Header ${k}: ${v}`);
        }
      }
    }

    if (!headers.has("accept")) {
      headers.append("accept", "application/json;q=0.9,*/*;q=0.2");
    }

    return headers;
  },

  /**
   * @param {string} method HTTP method
   * @param {string} data HTTP body
   * @param {object} signal AbortSignal instance
   * @returns {Request}
   */
  async _createRequest(method, data, signal) {
    const headers = await this._buildHeaders(method);
    const init = {
      cache: "no-store", // No cache.
      headers,
      method,
      signal,
      mozErrors: true, // Return nsresult error codes instead of a generic
      // NetworkError when fetch rejects.
    };

    if (data) {
      if (!(typeof data == "string" || data instanceof String)) {
        data = JSON.stringify(data);
      }
      this._log.debug(`${method} Length: ${data.length}`);
      this._log.trace(`${method} Body: ${data}`);
      init.body = data;
    }
    return new Request(this.uri.spec, init);
  },

  /**
   * @param {string} method HTTP method
   * @param {string} [data] HTTP body
   * @returns {Response}
   */
  async _doRequest(method, data = null) {
    const controller = new AbortController();
    const request = await this._createRequest(method, data, controller.signal);
    const responsePromise = fetch(request); // Rejects on network failure.
    let didTimeout = false;
    const timeoutId = setTimeout(() => {
      didTimeout = true;
      this._log.error(
        `Request timed out after ${this.ABORT_TIMEOUT}ms. Aborting.`
      );
      controller.abort();
    }, this.ABORT_TIMEOUT);
    let response;
    try {
      response = await responsePromise;
    } catch (e) {
      this._log.warn(`${method} request to ${this.uri.spec} failed`, e);
      if (!didTimeout) {
        throw e;
      }
      throw Components.Exception(
        "Request aborted (timeout)",
        Cr.NS_ERROR_NET_TIMEOUT
      );
    } finally {
      clearTimeout(timeoutId);
    }
    return this._processResponse(response, method);
  },

  async _processResponse(response, method) {
    const data = await response.text();
    this._logResponse(response, method, data);
    this._processResponseHeaders(response);

    const ret = {
      data,
      url: response.url,
      status: response.status,
      success: response.ok,
      headers: {},
    };
    for (const [k, v] of response.headers) {
      ret.headers[k] = v;
    }

    // Make a lazy getter to convert the json response into an object.
    // Note that this can cause a parse error to be thrown far away from the
    // actual fetch, so be warned!
    ChromeUtils.defineLazyGetter(ret, "obj", () => {
      try {
        return JSON.parse(ret.data);
      } catch (ex) {
        this._log.warn("Got exception parsing response body", ex);
        // Stringify to avoid possibly printing non-printable characters.
        this._log.debug(
          "Parse fail: Response body starts",
          (ret.data + "").slice(0, 100)
        );
        throw ex;
      }
    });

    return ret;
  },

  _logResponse(response, method, data) {
    const { status, ok: success, url } = response;

    // Log the status of the request.
    this._log.debug(
      `${method} ${success ? "success" : "fail"} ${status} ${url}`
    );

    // Additionally give the full response body when Trace logging.
    if (this._log.level <= Log.Level.Trace) {
      this._log.trace(`${method} body`, data);
    }

    if (!success) {
      this._log.warn(
        `${method} request to ${url} failed with status ${status}`
      );
    }
  },

  _processResponseHeaders({ headers, ok: success }) {
    if (headers.has("x-weave-timestamp")) {
      Resource.serverTime = parseFloat(headers.get("x-weave-timestamp"));
    }
    // This is a server-side safety valve to allow slowing down
    // clients without hurting performance.
    if (headers.has("x-weave-backoff")) {
      let backoff = headers.get("x-weave-backoff");
      this._log.debug(`Got X-Weave-Backoff: ${backoff}`);
      Observers.notify("weave:service:backoff:interval", parseInt(backoff, 10));
    }

    if (success && headers.has("x-weave-quota-remaining")) {
      Observers.notify(
        "weave:service:quota:remaining",
        parseInt(headers.get("x-weave-quota-remaining"), 10)
      );
    }
  },

  get() {
    return this._doRequest("GET");
  },

  put(data) {
    return this._doRequest("PUT", data);
  },

  post(data) {
    return this._doRequest("POST", data);
  },

  delete() {
    return this._doRequest("DELETE");
  },
};