Skip to content

Instantly share code, notes, and snippets.

@rhelmer
Last active April 26, 2024 21:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhelmer/0304f5a0d107441af5d161078ddfb86c to your computer and use it in GitHub Desktop.
Save rhelmer/0304f5a0d107441af5d161078ddfb86c to your computer and use it in GitHub Desktop.
ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.import("resource://gre/modules/Services.jsm");
const ENABLE_PROB = 0.01;
const ADDON_ID = "telemetry-coverage-bug1487578@mozilla.org";
const TOTAL_SAMPLES = 100000;
Cu.importGlobalProperties(["crypto", "TextEncoder"]);
XPCOMUtils.defineLazyServiceGetters(this, {
uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
async function generateVariate(seed, label) {
const hasher = crypto.subtle;
const hash = await hasher.digest("SHA-256", new TextEncoder("utf-8").encode(seed + label));
let view = new DataView(hash);
return view.getUint32(0) / 0xffffffff;
}
async function start() {
let counter = 0;
let samples = [];
while (samples.length < TOTAL_SAMPLES) {
let uuid = uuidGen.generateUUID().number;
uuid = uuid.substring(1, uuid.length - 1);
let variate = await generateVariate(uuid, ADDON_ID);
if (variate < ENABLE_PROB) {
counter++;
} else {
counter = 0;
}
samples.push(counter);
}
const average = samples.reduce((total, amount, index, array) => {
total += amount;
if ( index === array.length - 1) {
return total / array.length;
} else {
return total;
}
});
return average;
}
// Since xpcshell will exit before the promise is resolved, spin the event loop until it is.
function awaitPromise(promise) {
let done = false;
let result;
let error;
promise.then(
val => { result = val; },
err => { error = err; }
).then(() => {
done = true;
});
Services.tm.spinEventLoopUntil(() => done);
if (error !== undefined) {
throw error;
}
return result;
}
let avg = awaitPromise(start());
result = (avg - ENABLE_PROB) / ENABLE_PROB * 100;
result = parseFloat(result).toFixed(2);
dump(`
Average result over ${TOTAL_SAMPLES} samples is ${avg},
${result}% change from target probability ${ENABLE_PROB}.
\n`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment