diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index d2ca982e7..1372040c6 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -981,6 +981,14 @@ Call it from a task context instead — a native boundary, an event handler, a timer callback, or module evaluation itself. A **synchronous** graph needs no pumping and stays legal from anywhere, microtask turns included. +**An `import()` started before the require settles after it.** While a +synchronous load runs (any `require()` of an ES module, pumping or not), a +module graph that an earlier `import()` is loading is not evaluated, and that +`import()`'s promise stays pending until the require returns. A graph that +awaits such a promise cannot settle in-pump: it waits out `deadlineSeconds`, +then follows `onTimeout`. An `import()` the graph starts itself, such as +`await import("./x.mjs")` in its own code, is not held back. + ### What an HTTP module response must be A module fetched over `http(s)` is classified by status and MIME type before it diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index a20b10e03..d5d7a0933 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -151,6 +151,8 @@ require('./tests/testConcurrentProxyGeneration'); require('./tests/testEsmHttpLoader'); // What import() settles with, per importer kind and specifier shape require('./tests/testDynamicImport'); +// File modules large enough to load off the JS thread +require('./tests/testFileModuleLoad'); // Node-API addon surface require('./tests/NapiTests'); require('./tests/NapiCoverageTests'); diff --git a/test-app/app/src/main/assets/app/tests/fileModuleImportWorker.js b/test-app/app/src/main/assets/app/tests/fileModuleImportWorker.js new file mode 100644 index 000000000..3a3bb1cc9 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/fileModuleImportWorker.js @@ -0,0 +1,10 @@ +// Imports the module named by each message, reporting "loading" as soon as +// import() has returned and the module's id and line count once it settles. +onmessage = function (msg) { + import(msg.data).then(function (mod) { + postMessage("ok:" + mod.id + ":" + mod.count); + }, function (error) { + postMessage("error:" + String((error && error.message) || error)); + }); + postMessage("loading"); +}; diff --git a/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js b/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js new file mode 100644 index 000000000..73b43bd89 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js @@ -0,0 +1,743 @@ +// File modules of 32 KiB or more load off the JS thread: the file is read, +// then compiled (streamed) or its code cache consumed on a background thread, +// and only the result is finalized on the module's own thread. Every module +// here is written at run time under a name unique to this run (modules +// evaluate once per process, and code caches outlive the process), with a body +// above that threshold by construction. +describe("Large file modules", function () { + var STREAMING_THRESHOLD = 32 * 1024; + // With a fresh code cache, only modules this large load off the JS thread. + var CACHE_CONSUME_THRESHOLD = 256 * 1024; + var LINES = 1500; + var CONSUME_LINES = 5000; + var runId = String(Date.now()); + var fixtureDir = __dirname + "/esm/large-" + runId; + // import() reads a leading "/" as the app root, so imports use specifiers + // relative to this file, and require() the absolute path. + var fixtureSpec = "./esm/large-" + runId; + // Debuggable builds are the development flavor: no code caches. + var isDebugBuild = typeof require("ns:module").canonicalizeHttpUrlKey === "function"; + var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); + var originalTimeout; + + function writeModule(name, body) { + var path = fixtureDir + "/" + name + ".mjs"; + var writer = new java.io.OutputStreamWriter(new java.io.FileOutputStream(path), "UTF-8"); + try { + writer.write(body); + } finally { + writer.close(); + } + return path; + } + + function deleteTree(file) { + var children = file.listFiles(); + for (var i = 0; children && i < children.length; i++) { + deleteTree(children[i]); + } + file.delete(); + } + + // `lines` real declarations whose evaluation folds into `total`, so a + // value depends on the whole body. `stackLine` is the line of the + // `new Error` that stack() returns the trace of. + function bigModule(k, lines, options) { + options = options || {}; + var body = (options.bom ? "" : "") + "let acc = 0;\nconst strs = [];\n"; + for (var i = 0; i < lines; i++) { + body += "function f" + i + "(x) { return (x * 3 + " + i + ") % 1000; } acc += f" + i + + "(" + i + ");"; + if (options.unicode) { + body += " strs.push(\"café 日本語 😀 " + i + "\");"; + } + body += "\n"; + } + if (options.error) { + body += "export const broken = ;\n"; + } + body += "const evaluations = globalThis.__nsFileModuleEvaluations ||" + + " (globalThis.__nsFileModuleEvaluations = {});\n" + + "evaluations[\"" + k + "\"] = (evaluations[\"" + k + "\"] || 0) + 1;\n" + + "export const id = \"" + k + "\";\n" + + "export const count = " + lines + ";\n" + + "export const total = acc;\n" + + "export const first = strs[0];\n" + + "export const last = strs[strs.length - 1];\n" + + "export const token = {};\n"; + var stackLine = body.split("\n").length; + body += "export function stack() { return new Error(\"here\").stack; }\n"; + return { body: body, stackLine: stackLine }; + } + + function evaluations(k) { + return (globalThis.__nsFileModuleEvaluations || {})[k]; + } + + function expectWholeBody(mod, k, lines, evaluationCount) { + var total = 0; + for (var i = 0; i < lines; i++) { + total += (i * 3 + i) % 1000; + } + expect(mod.id).toBe(k); + expect(mod.count).toBe(lines); + expect(mod.total).toBe(total); + expect(evaluations(k)).toBe(evaluationCount || 1); + } + + function writeBig(name, k, lines, options) { + var module = bigModule(k, lines, options); + if (lines > 0) { + expect(module.body.length).toBeGreaterThan(STREAMING_THRESHOLD); + } + module.path = writeModule(name, module.body); + module.spec = fixtureSpec + "/" + name + ".mjs"; + return module; + } + + function formatError(error) { + var name = error && error.name ? error.name + ": " : ""; + return name + String((error && error.message) || error); + } + + function modifiedSeconds(path) { + var file = new java.io.File(path); + return file.exists() ? Math.floor(file.lastModified() / 1000) : -1; + } + + // Resolves once a code cache stamped with `path`'s current modification + // time exists, the one the runtime treats as fresh. + function freshCodeCache(path) { + var deadline = Date.now() + 5000; + return new Promise(function (resolve, reject) { + (function poll() { + var source = modifiedSeconds(path); + if (codeCacheEntries(path).some(function (entry) { + return modifiedSeconds(entry) === source; + })) { + resolve(); + } else if (Date.now() > deadline) { + reject(new Error("no fresh code cache for " + path)); + } else { + setTimeout(poll, 100); + } + })(); + }); + } + + // How many requests the in-process module server has received for + // `target`, read synchronously so the JS thread does not yield. + function serverRequestCount(target) { + return com.tns.tests.ModuleTestServer.requestCount(target); + } + + function failWith(done) { + return function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }; + } + + // The frame of stack()'s own `new Error`, as ":". + function errorPosition(mod) { + var frame = mod.stack().split("\n")[1] || ""; + var match = frame.match(/:(\d+):(\d+)\)?\s*$/); + return match ? match[1] + ":" + match[2] : frame; + } + + // Runs `body` from a fresh task. Jasmine may start a spec from a promise + // continuation, where V8 ignores microtask checkpoints and a pumping + // require() refuses to run. + function inTask(done, body) { + __ns__setTimeout(function () { + try { + body(); + } catch (e) { + expect("threw: " + formatError(e)).toBe("no exception"); + } + done(); + }, 0); + } + + function delay(ms) { + return new Promise(function (resolve) { + setTimeout(resolve, ms); + }); + } + + // `path`'s module code cache, which the runtime keeps beside the source. + function codeCacheEntries(path) { + return new java.io.File(path + ".mcache").exists() ? [path + ".mcache"] : []; + } + + beforeAll(function () { + new java.io.File(fixtureDir).mkdirs(); + }); + + afterAll(function () { + deleteTree(new java.io.File(fixtureDir)); + }); + + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + it("evaluates one loaded with import() after import() returns", function (done) { + var module = writeBig("dynamic", "file-dynamic", LINES); + var loading = import(module.spec); + expect(evaluations("file-dynamic")).toBeUndefined(); + loading.then(function (mod) { + expectWholeBody(mod, "file-dynamic", LINES); + done(); + }).catch(failWith(done)); + }); + + it("reports source positions as a small module does", function (done) { + var small = writeBig("positions-small", "file-positions-small", 0); + var ascii = writeBig("positions-ascii", "file-positions-ascii", LINES); + var unicode = writeBig("positions-unicode", "file-positions-unicode", LINES, + { unicode: true }); + var bom = writeBig("positions-bom", "file-positions-bom", LINES, { bom: true }); + Promise.all([ + import(small.spec), import(ascii.spec), import(unicode.spec), import(bom.spec), + ]).then(function (mods) { + var column = errorPosition(mods[0]).split(":")[1]; + expect(errorPosition(mods[0])).toBe(small.stackLine + ":" + column); + expect(errorPosition(mods[1])).toBe(ascii.stackLine + ":" + column); + expect(errorPosition(mods[2])).toBe(unicode.stackLine + ":" + column); + expect(errorPosition(mods[3])).toBe(bom.stackLine + ":" + column); + done(); + }).catch(failWith(done)); + }); + + it("evaluates non-ASCII string literals to the right values", function (done) { + var module = writeBig("unicode", "file-unicode", LINES, { unicode: true }); + import(module.spec).then(function (mod) { + expectWholeBody(mod, "file-unicode", LINES); + expect(mod.first).toBe("café 日本語 😀 0"); + expect(mod.last).toBe("café 日本語 😀 " + (LINES - 1)); + done(); + }).catch(failWith(done)); + }); + + it("evaluates one reached through a static import from a small module", function (done) { + writeBig("static-child", "file-static-child", LINES); + writeModule("static-parent", + "export * as child from \"./static-child.mjs\";\n" + + "export const parent = \"file-static-parent\";\n"); + import(fixtureSpec + "/static-parent.mjs").then(function (mod) { + expect(mod.parent).toBe("file-static-parent"); + expectWholeBody(mod.child, "file-static-child", LINES); + done(); + }).catch(failWith(done)); + }); + + it("gives a pending import() and a require() of the same module one instance", + function (done) { + var module = writeBig("shared", "file-shared", LINES); + var loading = import(module.spec); + var required = require(module.path); + expect(evaluations("file-shared")).toBe(1); + loading.then(function (mod) { + expectWholeBody(mod, "file-shared", LINES); + expect(mod.token).toBe(required.token); + done(); + }).catch(failWith(done)); + }); + + it("returns from require() with the module evaluated", function () { + var module = writeBig("required", "file-required", LINES); + var required = require(module.path); + expectWholeBody(required, "file-required", LINES); + }); + + it("returns from require() on a thread other than the runtime's with the module evaluated", + function (done) { + require("./multithreadedJavascript")().then(function (multithreaded) { + if (!multithreaded) { + done(); + return; + } + var module = writeBig("required-thread", "file-required-thread", LINES); + var outcome = null; + var mainHandler = new android.os.Handler(android.os.Looper.getMainLooper()); + new java.lang.Thread(new java.lang.Runnable({ + run: function () { + try { + var required = require(module.path); + outcome = { id: required.id, count: required.count, total: required.total }; + } catch (e) { + outcome = { error: formatError(e) }; + } + mainHandler.post(new java.lang.Runnable({ + run: function () { + expect(outcome.error).toBeUndefined(); + expectWholeBody(outcome, "file-required-thread", LINES); + done(); + } + })); + } + })).start(); + }); + }); + + it("gives a require() on another thread and a pending import() of the same module one instance", + function (done) { + require("./multithreadedJavascript")().then(function (multithreaded) { + if (!multithreaded) { + done(); + return; + } + var module = writeBig("thread-shared", "file-thread-shared", 20000); + var loading = import(module.spec); + var outcome = null; + var mainHandler = new android.os.Handler(android.os.Looper.getMainLooper()); + // Runs once this thread releases the isolate, while the import's + // background load is still in flight. + new java.lang.Thread(new java.lang.Runnable({ + run: function () { + try { + outcome = { module: require(module.path) }; + } catch (e) { + outcome = { error: formatError(e) }; + } + mainHandler.post(new java.lang.Runnable({ + run: function () { + expect(outcome.error).toBeUndefined(); + loading.then(function (mod) { + expectWholeBody(mod, "file-thread-shared", 20000); + expect(mod.token).toBe(outcome.module && outcome.module.token); + done(); + }).catch(failWith(done)); + } + })); + } + })).start(); + }); + }); + + it("runs no timers while require() waits for a large module", function (done) { + var module = writeBig("required-timer", "file-required-timer", LINES); + var fired = false; + inTask(function () { + setTimeout(function () { + expect(fired).toBe(true); + done(); + }, 0); + }, function () { + setTimeout(function () { + fired = true; + }, 0); + var required = require(module.path); + expect(fired).toBe(false); + expectWholeBody(required, "file-required-timer", LINES); + }); + }); + + it("runs no promise jobs while require() waits for a large module", function (done) { + var module = writeBig("required-microtask", "file-required-microtask", LINES); + inTask(done, function () { + var ran = false; + Promise.resolve().then(function () { + ran = true; + }); + var required = require(module.path); + expect(ran).toBe(false); + expectWholeBody(required, "file-required-microtask", LINES); + }); + }); + + it("settles a top-level await import() of a large module in a pumping require()", + function (done) { + var nsModule = require("ns:module"); + if (typeof nsModule.createPumpingRequire !== "function") { + pending("createPumpingRequire is not available in this build"); + done(); + return; + } + writeBig("tla-child", "file-tla-child", LINES); + writeModule("tla-parent", + "const child = await import(\"./tla-child.mjs\");\n" + + "export const id = child.id;\n" + + "export const total = child.total;\n" + + "export const count = child.count;\n"); + inTask(done, function () { + var pumpingRequire = nsModule.createPumpingRequire(fixtureDir + "/anything.js"); + var startedAt = Date.now(); + var mod = pumpingRequire("./tla-parent.mjs"); + expect(Date.now() - startedAt).toBeLessThan(10000); + expectWholeBody(mod, "file-tla-child", LINES); + }); + }); + + it("does not evaluate an earlier import() while a pumping require() awaits", function (done) { + var nsModule = require("ns:module"); + if (typeof nsModule.createPumpingRequire !== "function") { + pending("createPumpingRequire is not available in this build"); + done(); + return; + } + var earlier = writeBig("pumping-earlier", "file-pumping-earlier", LINES); + writeBig("pumping-child", "file-pumping-child", LINES); + writeModule("pumping-parent", + "const child = await import(\"./pumping-child.mjs\");\n" + + "export const id = child.id;\n" + + "export const total = child.total;\n" + + "export const count = child.count;\n"); + __ns__setTimeout(function () { + var loading; + try { + loading = import(earlier.spec); + // Holds the JS thread while the earlier load compiles, so its + // completion is queued when require() starts pumping. + var until = performance.now() + 300; + while (performance.now() < until) {} + var mod = nsModule.createPumpingRequire(fixtureDir + "/anything.js")( + "./pumping-parent.mjs"); + expectWholeBody(mod, "file-pumping-child", LINES); + expect(evaluations("file-pumping-earlier")).toBeUndefined(); + } catch (e) { + expect("threw: " + formatError(e)).toBe("no exception"); + } + loading.then(function (mod) { + expectWholeBody(mod, "file-pumping-earlier", LINES); + done(); + }).catch(failWith(done)); + }, 0); + }); + + it("does not evaluate a pending import() inside a require() of another module", + function (done) { + var imported = writeBig("pending-import", "file-pending-import", LINES); + var requiredModule = writeBig("pending-require", "file-pending-require", LINES); + var loading = import(imported.spec); + var required = require(requiredModule.path); + expectWholeBody(required, "file-pending-require", LINES); + expect(evaluations("file-pending-import")).toBeUndefined(); + loading.then(function (mod) { + expectWholeBody(mod, "file-pending-import", LINES); + done(); + }).catch(failWith(done)); + }); + + it("does not evaluate a pending HTTP import() inside a require() of a large module", + function (done) { + if (!isDebugBuild) { + pending("the release allowlist does not admit the loopback module server"); + } + var k = "file-pending-http-" + runId; + var target = "/esm/big.mjs?k=" + k + "&lines=10"; + var requiredModule = writeBig("pending-http-require", "file-pending-http-require", LINES); + var loading = import(origin + target); + // Holds the JS thread until the server has answered, plus a margin for + // the response to arrive, so its completion is already queued when + // require() starts waiting. + var deadline = performance.now() + 5000; + while (serverRequestCount(target) === 0 && performance.now() < deadline) {} + expect(serverRequestCount(target)).toBe(1); + var until = performance.now() + 250; + while (performance.now() < until) {} + var required = require(requiredModule.path); + expectWholeBody(required, "file-pending-http-require", LINES); + expect((globalThis.__nsBigModuleEvaluations || {})[k]).toBeUndefined(); + loading.then(function (mod) { + expect(mod.id).toBe(k); + expect(globalThis.__nsBigModuleEvaluations[k]).toBe(1); + done(); + }).catch(failWith(done)); + }); + + it("resolves one module for concurrent imports from several call sites", function (done) { + writeBig("concurrent", "file-concurrent", LINES); + writeModule("concurrent-a", "export * as child from \"./concurrent.mjs\";\n"); + writeModule("concurrent-b", "export * as child from \"./concurrent.mjs\";\n"); + var spec = fixtureSpec + "/concurrent.mjs"; + Promise.all([ + import(spec), import(fixtureSpec + "/concurrent-a.mjs"), import(spec), + import(fixtureSpec + "/concurrent-b.mjs"), + ]) + .then(function (mods) { + expectWholeBody(mods[0], "file-concurrent", LINES); + expect(mods[2]).toBe(mods[0]); + expect(mods[1].child).toBe(mods[0]); + expect(mods[3].child).toBe(mods[0]); + done(); + }).catch(failWith(done)); + }); + + it("settles concurrent imports of a module after its top-level await", function (done) { + writeModule("tla-shared", bigModule("file-tla-shared", LINES).body + + "await new Promise(function (resolve) { setTimeout(resolve, 50); });\n" + + "export const settled = true;\n"); + var spec = fixtureSpec + "/tla-shared.mjs"; + // Reads the export as each import settles: one that settles early sees + // it in its temporal dead zone. + function settledExport() { + return import(spec).then(function (mod) { + return mod.settled; + }); + } + Promise.all([settledExport(), settledExport()]).then(function (values) { + expect(values).toEqual([true, true]); + done(); + }).catch(failWith(done)); + }); + + it("rejects a syntax error with the text a small module produces", function (done) { + var small = writeBig("syntax-small", "file-syntax-small", 0, { error: true }); + var large = writeBig("syntax-large", "file-syntax-large", LINES, { error: true }); + function rejectionOf(module) { + return import(module.spec).then(function () { + return "resolved"; + }, function (error) { + return formatError(error).split(module.path).join(""); + }); + } + Promise.all([rejectionOf(small), rejectionOf(large)]).then(function (texts) { + expect(texts[0]).toContain("SyntaxError"); + expect(texts[1]).toBe(texts[0]); + done(); + }).catch(failWith(done)); + }); + + it("throws a syntax error from require() with the text a small module produces", function () { + var small = writeBig("require-syntax-small", "file-require-syntax-small", 0, { error: true }); + var large = writeBig("require-syntax-large", "file-require-syntax-large", LINES, { error: true }); + function errorOf(module) { + try { + require(module.path); + return "returned"; + } catch (e) { + return formatError(e).split(module.path).join(""); + } + } + var texts = [errorOf(small), errorOf(large)]; + expect(texts[0]).toContain("SyntaxError"); + expect(texts[1]).toBe(texts[0]); + }); + + it("loads a cycle between two large modules once each", function (done) { + // Each side reads the other through a function, after both evaluated. + function writeCycle(prefix) { + ["a", "b"].forEach(function (side) { + var peer = side === "a" ? "b" : "a"; + var k = "file-" + prefix + "-" + side; + var body = "import * as peer from \"./" + prefix + "-" + peer + ".mjs\";\n" + + "export function peerId() { return peer.id; }\n" + + bigModule(k, LINES).body; + expect(body.length).toBeGreaterThan(STREAMING_THRESHOLD); + writeModule(prefix + "-" + side, body); + }); + } + writeCycle("cycle-import"); + writeCycle("cycle-require"); + var required = require(fixtureDir + "/cycle-require-a.mjs"); + expectWholeBody(required, "file-cycle-require-a", LINES); + expect(required.peerId()).toBe("file-cycle-require-b"); + expect(evaluations("file-cycle-require-b")).toBe(1); + Promise.all([import(fixtureSpec + "/cycle-import-a.mjs"), + import(fixtureSpec + "/cycle-import-b.mjs")]).then(function (mods) { + expectWholeBody(mods[0], "file-cycle-import-a", LINES); + expectWholeBody(mods[1], "file-cycle-import-b", LINES); + expect(mods[0].peerId()).toBe("file-cycle-import-b"); + expect(mods[1].peerId()).toBe("file-cycle-import-a"); + done(); + }).catch(failWith(done)); + }); + + // Large enough that, outside the development flavor, the third load + // consumes the code cache the second one left, on a background thread. + it("loads an edited file's new source under a new query", function (done) { + var module = writeBig("edited", "file-edited-1", CONSUME_LINES); + var spec = module.spec; + var firstSource; + import(spec + "?v=1").then(function (mod) { + expectWholeBody(mod, "file-edited-1", CONSUME_LINES); + firstSource = modifiedSeconds(module.path); + return isDebugBuild ? undefined : freshCodeCache(module.path); + }).then(function () { + var edited = bigModule("file-edited-2", CONSUME_LINES + 7).body; + expect(edited.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); + writeModule("edited", edited); + // Freshness is compared in whole seconds, so an edit within the + // first source's second would leave the old cache looking fresh. + if (modifiedSeconds(module.path) === firstSource) { + new java.io.File(module.path).setLastModified((firstSource + 2) * 1000); + } + if (!isDebugBuild) { + var stale = codeCacheEntries(module.path); + expect(stale.length).toBe(1); + expect(modifiedSeconds(stale[0])).toBe(firstSource); + expect(modifiedSeconds(module.path)).not.toBe(firstSource); + } + return import(spec + "?v=2"); + }).then(function (mod) { + expectWholeBody(mod, "file-edited-2", CONSUME_LINES + 7); + return isDebugBuild ? undefined : freshCodeCache(module.path); + }).then(function () { + return import(spec + "?v=3"); + }).then(function (mod) { + expectWholeBody(mod, "file-edited-2", CONSUME_LINES + 7, 2); + done(); + }).catch(failWith(done)); + }); + + it("writes a code cache only outside the development flavor", function (done) { + var module = writeBig("cache-probe", "file-cache-probe", LINES); + import(module.spec).then(function (mod) { + expectWholeBody(mod, "file-cache-probe", LINES); + var deadline = Date.now() + 5000; + function poll() { + var entries = codeCacheEntries(module.path); + if (entries.length > 0 || Date.now() > deadline) { + expect(entries.length).toBe(isDebugBuild ? 0 : 1); + for (var i = 0; i < entries.length; i++) { + new java.io.File(entries[i]).delete(); + } + done(); + return; + } + setTimeout(poll, isDebugBuild ? 1000 : 100); + } + poll(); + }).catch(failWith(done)); + }); + + it("recompiles over a corrupt code cache and rewrites it", function (done) { + if (isDebugBuild) { + pending("debuggable builds read no code caches"); + done(); + return; + } + var module = writeBig("corrupt-cache", "file-corrupt-cache", CONSUME_LINES); + expect(module.body.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); + var cachePath = module.path + ".mcache"; + var garbage = "not a code cache"; + import(module.spec + "?v=1").then(function (mod) { + expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES); + return freshCodeCache(module.path); + }).then(function () { + var cacheFile = new java.io.File(cachePath); + var stamp = cacheFile.lastModified(); + var out = new java.io.FileOutputStream(cacheFile); + try { + out.write(new java.lang.String(garbage).getBytes("UTF-8")); + } finally { + out.close(); + } + cacheFile.setLastModified(stamp); + // Still looks fresh, so the next load consumes it. + expect(modifiedSeconds(cachePath)).toBe(modifiedSeconds(module.path)); + return import(module.spec + "?v=2"); + }).then(function (mod) { + expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES, 2); + var deadline = Date.now() + 5000; + return new Promise(function (resolve, reject) { + (function poll() { + if (new java.io.File(cachePath).length() > garbage.length && + modifiedSeconds(cachePath) === modifiedSeconds(module.path)) { + resolve(); + } else if (Date.now() > deadline) { + reject(new Error("the corrupt cache was not rewritten")); + } else { + setTimeout(poll, 100); + } + })(); + }); + }).then(function () { + return import(module.spec + "?v=3"); + }).then(function (mod) { + expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES, 3); + done(); + }).catch(failWith(done)); + }); + + it("evaluates one loaded by a worker", function (done) { + var module = writeBig("worker", "file-worker", LINES); + var worker = new Worker("./fileModuleImportWorker.js"); + worker.onmessage = function (msg) { + if (msg.data === "loading") { + return; + } + worker.terminate(); + expect(msg.data).toBe("ok:file-worker:" + LINES); + done(); + }; + worker.onerror = function (error) { + worker.terminate(); + expect("worker error: " + formatError(error)).toBe("ok"); + done(); + }; + worker.postMessage(module.spec); + }); + + it("starts a worker whose entry statically imports a large module", function (done) { + writeBig("worker-entry-child", "file-worker-entry-child", LINES); + writeModule("worker-entry", + "import { id, count } from \"./worker-entry-child.mjs\";\n" + + "postMessage(\"ok:\" + id + \":\" + count);\n"); + var worker = new Worker("./esm/large-" + runId + "/worker-entry.mjs"); + worker.onmessage = function (msg) { + worker.terminate(); + expect(msg.data).toBe("ok:file-worker-entry-child:" + LINES); + done(); + }; + worker.onerror = function (error) { + worker.terminate(); + expect("worker error: " + formatError(error)).toBe("ok"); + done(); + }; + }); + + it("survives workers terminated while their large modules load", function (done) { + // Each worker is terminated a little later after issuing its import, + // so the points fall before, during and after the background load. + var MODULE_LINES = 20000; + var STEPS = 12; + var STEP_MS = 4; + var spec = writeBig("terminated", "file-terminated", MODULE_LINES).spec; + + function importOnMain() { + var module = writeBig("after-workers", "file-after-workers", LINES); + import(module.spec).then(function (mod) { + expectWholeBody(mod, "file-after-workers", LINES); + done(); + }).catch(failWith(done)); + } + + function sweep(step) { + if (step === STEPS) { + importOnMain(); + return; + } + var worker = new Worker("./fileModuleImportWorker.js"); + var ended = false; + function next() { + if (!ended) { + ended = true; + worker.terminate(); + sweep(step + 1); + } + } + worker.onmessage = function (msg) { + if (msg.data === "loading") { + setTimeout(next, step * STEP_MS); + } else { + expect(String(msg.data)).toMatch(/^ok:file-terminated:/); + next(); + } + }; + worker.onerror = function (error) { + fail("worker " + step + " errored: " + formatError(error)); + next(); + }; + worker.postMessage(spec); + } + sweep(0); + }, 60000); +}); diff --git a/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js b/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js index ecb3bb6ca..4a321aac5 100644 --- a/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js +++ b/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js @@ -1,6 +1,9 @@ -// Needs "codeCache": true in the app's package.json; without it no runtime -// reads or writes the caches these specs race on. +// Needs "codeCache": true in the app's package.json and a build that is not +// debuggable; otherwise no runtime reads or writes the caches these specs race +// on, and only the loaded values are checked. describe("Script code caches with workers starting together", function () { + var cachesEnabled = !!require("../package.json").android.codeCache && + typeof require("ns:module").canonicalizeHttpUrlKey !== "function"; var moduleNames = ["modA", "modB", "modC", "modD", "modE", "modF"]; var entryCount = 6; var batchSize = entryCount * 2; @@ -25,7 +28,9 @@ describe("Script code caches with workers starting together", function () { // reported. A worker error terminates the whole batch and rejects only // once every worker's thread has ended (`nsworkerended`), so no worker from // a failed batch is still writing caches when the next spec drops them. - var runBatch = function () { + // A worker writes its caches only after a quiet period and drops the ones + // still queued when it ends, so `lingerMs` keeps reported workers alive. + var runBatch = function (lingerMs) { return new Promise(function (resolve, reject) { var reports = []; var workers = []; @@ -45,7 +50,13 @@ describe("Script code caches with workers starting together", function () { rejectOnceAllEnded(); }); worker.onmessage = function (msg) { - worker.terminate(); + if (lingerMs) { + setTimeout(function () { + worker.terminate(); + }, lingerMs); + } else { + worker.terminate(); + } if (failure !== null) { return; } @@ -89,8 +100,19 @@ describe("Script code caches with workers starting together", function () { }, 120000); it("publishes caches stamped with their source's mtime and leaves no temporaries", async function () { + if (!cachesEnabled) { + pending("code caches are off: debuggable build or no \"codeCache\": true"); + } dropCaches(); - expectValues(await runBatch()); + expectValues(await runBatch(3000)); + var deadline = Date.now() + 5000; + while (Date.now() < deadline && !moduleNames.every(function (name) { + return cacheFile(name).exists(); + })) { + await new Promise(function (resolve) { + setTimeout(resolve, 100); + }); + } moduleNames.forEach(function (name) { var cache = cacheFile(name); diff --git a/test-app/app/src/main/java/com/tns/RuntimeHelper.java b/test-app/app/src/main/java/com/tns/RuntimeHelper.java index fa1542966..695d9ee4d 100644 --- a/test-app/app/src/main/java/com/tns/RuntimeHelper.java +++ b/test-app/app/src/main/java/com/tns/RuntimeHelper.java @@ -2,11 +2,13 @@ import android.app.Application; import android.content.BroadcastReceiver; +import android.content.ComponentCallbacks2; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; +import android.content.res.Configuration; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; @@ -224,6 +226,10 @@ public static Runtime initRuntime(Context context) { } } + if (appConfig.getCodeCache() && !isDebuggable) { + registerScriptCacheFlush(context); + } + if (appConfig.handleTimeZoneChanges()) { // If the user sets this flag, we will register a broadcast receiver // that will listen for the TIMEZONE_CHANGED event and update V8's cache @@ -264,6 +270,28 @@ private static void waitForLiveSync(Context context) { } } + // The runtime creates code caches once loading has been quiet for a while; + // an app whose UI is hidden may be killed before that, so they are created + // when it goes to the background instead. + private static void registerScriptCacheFlush(Context context) { + context.getApplicationContext().registerComponentCallbacks(new ComponentCallbacks2() { + @Override + public void onTrimMemory(int level) { + if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { + Runtime.flushScriptCaches(); + } + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + } + + @Override + public void onLowMemory() { + } + }); + } + private static void registerTimezoneChangedListener(Context context, final Runtime runtime) { IntentFilter timezoneFilter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index 6f82650c5..f997685b7 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -122,6 +122,17 @@ public static synchronized int getPort() { return boundPort; } + /** + * Requests received for `target` (path plus query), for a spec that must not + * yield its thread to ask over HTTP. + */ + public static int requestCount(String target) { + synchronized (requestCounts) { + Integer count = requestCounts.get(target); + return count == null ? 0 : count; + } + } + /** TCP connections accepted since the server started. */ public static int connectionCount() { synchronized (connectionStatsLock) { diff --git a/test-app/runtime/src/main/cpp/EventLoop.cpp b/test-app/runtime/src/main/cpp/EventLoop.cpp index 9fed8fc91..df6a28c43 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.cpp +++ b/test-app/runtime/src/main/cpp/EventLoop.cpp @@ -101,6 +101,7 @@ void EventLoop::BindToCurrentThread() { return; } looper_ = looper; + homeTid_.store(gettid(), std::memory_order_release); ALooper_acquire(looper_); eventFd_ = eventFd; timerFd_ = timerFd; @@ -791,6 +792,45 @@ EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds, } } +EventLoop::PumpResult EventLoop::PumpNestableV8TasksUntil( + double deadlineSeconds, const std::function& settled, + const std::function& idle) { + NS_DCHECK(looper_ == nullptr || ALooper_forThread() == looper_); + PumpScope pumpScope; + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::duration(deadlineSeconds); + for (;;) { + if (terminationRequested_.load(std::memory_order_acquire) || + isolate_->IsExecutionTerminating()) { + return PumpResult::kTerminated; + } + if (settled()) { + return PumpResult::kSettled; + } + if (IsStopped()) { + return PumpResult::kTerminated; + } + if (std::chrono::steady_clock::now() >= deadline) { + return PumpResult::kDeadline; + } + { + v8::Locker locker(isolate_); + v8::Isolate::Scope isolateScope(isolate_); + v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); + RunDueInternalWork(DrainFilter::kNestableV8); + } + if (settled()) { + continue; + } + idle(kQuietPumpPollMs); + } +} + +bool EventLoop::IsOnHomeThread() const { + const pid_t home = homeTid_.load(std::memory_order_acquire); + return home != 0 && home == gettid(); +} + namespace { struct LooperCallbackScope { explicit LooperCallbackScope(int& depth) : depth_(depth) { ++depth_; } diff --git a/test-app/runtime/src/main/cpp/EventLoop.h b/test-app/runtime/src/main/cpp/EventLoop.h index 7c1b47298..8beecffe6 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.h +++ b/test-app/runtime/src/main/cpp/EventLoop.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -265,6 +266,27 @@ class EventLoop { PumpResult PumpUntil(double deadlineSeconds, const std::function& settled, bool drainLooperWork); + /** + * A quieter PumpUntil for waits whose completions all arrive as nestable + * v8 tasks: each iteration runs only those, with microtasks suppressed, + * then calls `idle(kQuietPumpPollMs)` instead of waiting on the looper's + * fds. No timer, plain post, worker message or promise job runs inside + * it. `idle` must return within that bound even when nothing signals it: + * V8 asks for the GC a background compile is blocked on with a nestable + * PostTask, which only the next iteration runs. + */ + static constexpr int kQuietPumpPollMs = 2; + PumpResult PumpNestableV8TasksUntil(double deadlineSeconds, + const std::function& settled, + const std::function& idle); + + /** + * True on the thread BindToCurrentThread ran on. Any thread may ask: with + * multithreaded JavaScript, JS also runs on threads that only hold the + * isolate's Locker, and those must not wait on work this loop delivers. + */ + bool IsOnHomeThread() const; + /** * True while the calling thread is inside PumpUntil. Callback code that * would arm a pending Java exception (env.Throw) must defer it through @@ -432,6 +454,8 @@ class EventLoop { // internal lane: EFD_SEMAPHORE eventfd (one unit = run one due entry) and // a timerfd armed to the earliest delayed due time ALooper* looper_ = nullptr; + // gettid() of the bound thread, 0 before the bind + std::atomic homeTid_{0}; int eventFd_ = -1; int timerFd_ = -1; bool stopped_ = false; diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 1fba2fa3b..5ec3645f6 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -24,16 +24,24 @@ #include "CallbackHandlers.h" #include "ManualInstrumentation.h" #include "Runtime.h" +#include "RuntimeState.h" #include "TraceLog.h" #include #include #include +#include #include #include #include #include #include +#include #include +#include +#include +#include +#include +#include using namespace v8; using namespace std; @@ -979,11 +987,13 @@ Local