MeasurementUtils.sys.mjs (1855B)
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/. */ 4 5 export const BYTES_IN_KILOBYTE = 1000; 6 export const BYTES_IN_MEGABYTE = 1000000; 7 8 export const BYTES_IN_KIBIBYTE = 1024; 9 export const BYTES_IN_MEBIBYTE = 1048576; 10 11 export const MeasurementUtils = { 12 /** 13 * Rounds byte sizes of user files in order to provide protection 14 * against fingerprinting. 15 * 16 * @param {number} bytes 17 * Number of bytes to fuzz 18 * @param {number} nearest 19 * Nearest number of bytes to round to 20 * @returns {number} 21 * Number of bytes rounded to the `nearest` granularity 22 * 23 * @example fuzzByteSize(1500, 1000) === 2000 24 * @example fuzzByteSize(1001, 1000) === 1000 25 * @example fuzzByteSize(1024, 10) === 1020 26 * @example fuzzByteSize(512, 1000) === 1000 27 * @example fuzzByteSize(256, 1000) === 1000 28 */ 29 fuzzByteSize(bytes, nearest) { 30 const fuzzed = Math.round(bytes / nearest) * nearest; 31 return Math.max(fuzzed, nearest); 32 }, 33 34 /** 35 * Helper wrapper for timing an async operation with Glean. This style of 36 * helper is available in some Glean SDKs, but not JavaScript yet. 37 * 38 * @see https://mozilla.github.io/glean/book/reference/metrics/timing_distribution.html#measure 39 * 40 * @template T 41 * @param {GleanTimingDistribution} timer 42 * Glean TimingDistribution object 43 * @param {Promise<T>} operation 44 * Async operation to time 45 * @returns {Promise<T>} 46 * Result of `operation` 47 */ 48 async measure(timer, operation) { 49 const timerId = timer.start(); 50 51 try { 52 const result = await operation; 53 timer.stopAndAccumulate(timerId); 54 return result; 55 } catch (err) { 56 timer.cancel(timerId); 57 throw err; 58 } 59 }, 60 };