Bug 1795082 - Part 2/2: Drop post-processing from getURL() r=zombie
[gecko.git] / netwerk / protocol / http / HPKEConfigManager.sys.mjs
blob05120a66020e0bfbf16b9776efdadb70842fb9c3
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 let knownConfigs = new Map();
7 export class HPKEConfigManager {
8   static async get(aURL, aOptions = {}) {
9     // If we're in a child, forward to the parent.
10     let { remoteType } = Services.appinfo;
11     if (remoteType) {
12       if (remoteType != "privilegedabout") {
13         // The remoteTypes definition in the actor definition will enforce
14         // that calling getActor fails, this is a more readable error:
15         throw new Error(
16           "HPKEConfigManager cannot be used outside of the privilegedabout process."
17         );
18       }
19       let actor = ChromeUtils.domProcessChild.getActor("HPKEConfigManager");
20       return actor.sendQuery("getconfig", { url: aURL, options: aOptions });
21     }
22     try {
23       let config = await this.#getInternal(aURL, aOptions);
24       return new Uint8Array(config);
25     } catch (ex) {
26       console.error(ex);
27       return null;
28     }
29   }
31   static async #getInternal(aURL, aOptions = {}) {
32     let { maxAge = -1 } = aOptions;
33     let knownConfig = knownConfigs.get(aURL);
34     if (
35       knownConfig &&
36       (maxAge < 0 || Date.now() - knownConfig.fetchDate < maxAge)
37     ) {
38       return knownConfig.config;
39     }
40     return this.#fetchAndStore(aURL, aOptions);
41   }
43   static async #fetchAndStore(aURL, aOptions = {}) {
44     let fetchDate = Date.now();
45     let resp = await fetch(aURL, { signal: aOptions.abortSignal });
46     if (!resp?.ok) {
47       throw new Error(
48         `Fetching HPKE config from ${aURL} failed with error ${resp.status}`
49       );
50     }
51     let config = await resp.blob().then(b => b.arrayBuffer());
52     knownConfigs.set(aURL, { config, fetchDate });
53     return config;
54   }
57 export class HPKEConfigManagerParent extends JSProcessActorParent {
58   receiveMessage(msg) {
59     if (msg.name == "getconfig") {
60       return HPKEConfigManager.get(msg.data.url, msg.data.options);
61     }
62     return null;
63   }