Bug 1858509 add thread-safety annotations around MediaSourceDemuxer::mMonitor r=alwu
[gecko.git] / services / settings / SharedUtils.sys.mjs
blob1eeaf0bed9c48dcb9a3a2284c064bd355730572a
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
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 /**
6  * Common logic shared by RemoteSettingsWorker.js (Worker) and the main thread.
7  */
9 export var SharedUtils = {
10   /**
11    * Check that the specified content matches the expected size and SHA-256 hash.
12    * @param {ArrayBuffer} buffer binary content
13    * @param {Number} size expected file size
14    * @param {String} size expected file SHA-256 as hex string
15    * @returns {boolean}
16    */
17   async checkContentHash(buffer, size, hash) {
18     const bytes = new Uint8Array(buffer);
19     // Has expected size? (saves computing hash)
20     if (bytes.length !== size) {
21       return false;
22     }
23     // Has expected content?
24     const hashBuffer = await crypto.subtle.digest("SHA-256", bytes);
25     const hashBytes = new Uint8Array(hashBuffer);
26     const toHex = b => b.toString(16).padStart(2, "0");
27     const hashStr = Array.from(hashBytes, toHex).join("");
28     return hashStr == hash;
29   },
31   /**
32    * Load (from disk) the JSON file distributed with the release for this collection.
33    * @param {String}  bucket
34    * @param {String}  collection
35    */
36   async loadJSONDump(bucket, collection) {
37     // When using the preview bucket, we still want to load the main dump.
38     // But we store it locally in the preview bucket.
39     const jsonBucket = bucket.replace("-preview", "");
40     const fileURI = `resource://app/defaults/settings/${jsonBucket}/${collection}.json`;
41     let response;
42     try {
43       response = await fetch(fileURI);
44     } catch (e) {
45       // Return null if file is missing.
46       return { data: null, timestamp: null };
47     }
48     // Will throw if JSON is invalid.
49     return response.json();
50   },