Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add running result cache #58

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 32 additions & 6 deletions lib/run-tests/worker.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
const path = require("path");
const fs = require("fs");
const crypto = require('crypto');
const lmdb = require("lmdb");
const strip = require('strip-comments');

const BabelAgent = require("./babel-agent");
const transpile = require("./transpile");

const TEST_TIMEOUT = 60 * 1000; // 1 minute

function sha1(str) {
return crypto.createHash('sha1').update(str, 'utf8').digest('hex');
}

function timeout(file, waitMs = TEST_TIMEOUT) {
return new Promise((_resolve, reject) =>
setTimeout(
Expand All @@ -14,23 +22,37 @@ function timeout(file, waitMs = TEST_TIMEOUT) {
);
}

let agent, testRoot;
let agent, testRoot, cacheDB;

exports.setup = function (opts) {
agent = new BabelAgent(opts);
testRoot = opts.testRoot;
cacheDB = new lmdb.open("cache.lmdb", {
compression: true,
});
};

exports.runTest = async function (test) {
let { attrs, contents, file } = test;
const isModule = attrs.flags.module;

const cacheKey = sha1(JSON.stringify({ attrs, file }));
const fileContents = strip(fs.readFileSync(path.join(testRoot, file), "utf8"));
const allowCache = ["eval(", "require(", "import", "evalScript("].every((keyword) => !fileContents.includes(keyword));

try {
contents = transpile(contents, { features: attrs.features, isModule, isStrict: false });
} catch (error) {
return { result: "parser error", error };
}

const hash = sha1(contents);

const cacheData = allowCache ? cacheDB.get(cacheKey) : null;
if (cacheData?.hash === hash) {
return cacheData.ret;
}

let result;
let ret;
try {
Expand All @@ -42,16 +64,20 @@ exports.runTest = async function (test) {
}),
timeout(file),
]);

if (result.error) {
ret = { result: "runtime error", error: result.error };
} else {
ret = { result: "success", output: result.stdout };
}
} catch (error) {
agent.stop(); // kill process avoid 100% cpu usage

return { result: "timeout error", error };
ret = { result: "timeout error", error };
}

if (result.error) {
ret = { result: "runtime error", error: result.error };
} else {
ret = { result: "success", output: result.stdout };
if (allowCache) {
cacheDB.put(cacheKey, { hash, ret });
}

return ret;
Expand Down