diff --git a/wasm/CMakeLists.txt b/wasm/CMakeLists.txt index b3058f2fe..b2cce4060 100644 --- a/wasm/CMakeLists.txt +++ b/wasm/CMakeLists.txt @@ -2,7 +2,12 @@ add_executable(PackingSolver_wasm) target_sources(PackingSolver_wasm PRIVATE src/packingsolver_wasm.cpp) target_link_libraries(PackingSolver_wasm PRIVATE - PackingSolver_rectangle) + PackingSolver_rectangleguillotine + PackingSolver_rectangle + PackingSolver_box + PackingSolver_boxstacks + PackingSolver_onedimensional + PackingSolver_irregular) target_link_options(PackingSolver_wasm PRIVATE -lembind # Load with 'await PackingSolver()', in the browser, a web worker or Node. diff --git a/wasm/js/packingsolver_worker.js b/wasm/js/packingsolver_worker.js new file mode 100644 index 000000000..5e5bb0118 --- /dev/null +++ b/wasm/js/packingsolver_worker.js @@ -0,0 +1,94 @@ +// Web Worker solving PackingSolver instances with the WebAssembly module, +// without blocking the page. +// +// Messages to the worker: +// - {type: "solve", problemType, instance, parameters}: solve an instance +// ('instance' is a JSON string or an object in the JSON format of +// PackingSolver, 'parameters' an object, see 'packingsolver_wasm.cpp'); +// - {type: "stop"}: stop the optimization; it then sends its best solution. +// +// Messages from the worker: +// - {type: "ready"}: the module is loaded; +// - {type: "solution", output, certificate}: the best solution or a bound has +// improved (the solution may be empty, e.g. a bound found first); +// - {type: "done", output, certificate}: the optimization has ended; +// - {type: "error", error}: the optimization failed. +// +// In a browser, it is a classic worker: 'new Worker("packingsolver_worker.js")', +// next to 'packingsolver.js' and 'packingsolver.wasm'. In Node, it can be run +// with 'worker_threads', with the path of 'packingsolver.js' in +// 'workerData.modulePath'. + +"use strict"; + +// Delay between two polls of the session, in milliseconds. +const POLL_INTERVAL = 100; + +let postToPage; +let modulePromise; +if (typeof importScripts === "function") { + // Browser. + importScripts("packingsolver.js"); + postToPage = (message) => self.postMessage(message); + self.onmessage = (event) => onMessage(event.data); + modulePromise = PackingSolver(); +} else { + // Node. + const {parentPort, workerData} = require("node:worker_threads"); + postToPage = (message) => parentPort.postMessage(message); + parentPort.on("message", (message) => onMessage(message)); + modulePromise = require(workerData.modulePath)(); +} + +modulePromise.then(() => postToPage({type: "ready"})); + +let session = null; +let pollTimer = null; + +async function onMessage(message) { + if (message.type === "solve") { + const module = await modulePromise; + if (session !== null) { + postToPage({type: "error", error: "an optimization is already running."}); + return; + } + const instance = (typeof message.instance === "string")? + message.instance: + JSON.stringify(message.instance); + session = new module.Session(); + const startError = session.start( + message.problemType, instance, JSON.stringify(message.parameters || {})); + if (startError !== "") { + postToPage({type: "error", error: JSON.parse(startError).error}); + endSession(); + return; + } + pollTimer = setInterval(poll, POLL_INTERVAL); + } else if (message.type === "stop") { + if (session !== null) + session.stop(); + } +} + +function poll() { + const pollResult = JSON.parse(session.poll()); + for (const solution of pollResult.solutions) + postToPage({type: "solution", ...solution}); + if (!pollResult.done) + return; + const result = pollResult.result; + if (result.error !== undefined) { + postToPage({type: "error", error: result.error}); + } else { + postToPage({type: "done", ...result}); + } + endSession(); +} + +function endSession() { + if (pollTimer !== null) + clearInterval(pollTimer); + pollTimer = null; + session.delete(); + session = null; +} diff --git a/wasm/src/packingsolver_wasm.cpp b/wasm/src/packingsolver_wasm.cpp index 611a643a3..da5fd9b9d 100644 --- a/wasm/src/packingsolver_wasm.cpp +++ b/wasm/src/packingsolver_wasm.cpp @@ -1,33 +1,61 @@ /** * WebAssembly module: JavaScript API of PackingSolver. * - * 'solve(problemType, instanceJson, parametersJson)' reads an instance in the - * JSON format of PackingSolver, solves it and returns a JSON string: + * Problem types: "rectangleguillotine", "rectangle", "box", "boxstacks", + * "onedimensional" and "irregular". Instances are in the JSON format of + * PackingSolver. + * + * Results are JSON strings: * * { * "output": ..., // 'Output::to_json()' * "certificate": ... // the solution, in the CSV certificate format * } * - * 'solve' blocks the calling thread: in a browser, call it from a Web Worker - * (the main thread can't block). The threads of the algorithms run in a pool - * of Web Workers started when the module is loaded. + * or '{"error": ...}'. + * + * Two APIs: + * - 'solve(problemType, instanceJson, parametersJson)' solves the instance + * and returns the result. It blocks the calling thread: in a browser, call + * it from a Web Worker (the main thread can't block). + * - 'Session' solves an instance in a thread of its own, without blocking: + * 'start(problemType, instanceJson, parametersJson)' starts the + * optimization, 'poll()' returns the updates since the previous call and, + * at the end, the result, and 'stop()' stops the optimization. There is an + * update each time the best solution or a bound improves: an update may + * have the same solution as the previous one, or an empty solution. + * + * The threads of the algorithms run in a pool of Web Workers started when + * the module is loaded. * * Parameters (all optional): * - "optimization_mode": "anytime" (default), "not-anytime", * "not-anytime-deterministic" or "not-anytime-sequential" (single-threaded); * in "anytime" mode, the algorithms run until the time limit, unless the - * solution is proven optimal; + * solution is proven optimal or the session is stopped; * - "time_limit": time limit in seconds; * - "verbosity_level": verbosity level, printed on the console. */ +#include "packingsolver/rectangleguillotine/instance_builder.hpp" +#include "packingsolver/rectangleguillotine/optimize.hpp" #include "packingsolver/rectangle/instance_builder.hpp" #include "packingsolver/rectangle/optimize.hpp" +#include "packingsolver/box/instance_builder.hpp" +#include "packingsolver/box/optimize.hpp" +#include "packingsolver/boxstacks/instance_builder.hpp" +#include "packingsolver/boxstacks/optimize.hpp" +#include "packingsolver/onedimensional/instance_builder.hpp" +#include "packingsolver/onedimensional/optimize.hpp" +#include "packingsolver/irregular/instance_builder.hpp" +#include "packingsolver/irregular/optimize.hpp" #include +#include +#include #include +#include using namespace packingsolver; @@ -62,62 +90,233 @@ OptimizeParameters read_parameters(const std::string& parameters_json) } template -std::string to_result(const Output& output) +nlohmann::json to_result(const Output& output) { std::stringstream certificate; output.solution_pool.best().write(certificate); nlohmann::json result; result["output"] = output.to_json(); result["certificate"] = certificate.str(); - return result.dump(); + return result; } -std::string solve_rectangle( +/** + * Called with the result each time the best solution or a bound improves. + */ +using SolutionCallback = std::function; + +/** + * Read an instance of a problem type, solve it and return the result. + * + * 'end', if not null, stops the optimization when set to 'true'. + */ +template +nlohmann::json run( + OptimizeFunction optimize_function, const std::string& instance_json, - const std::string& parameters_json) + const std::string& parameters_json, + const SolutionCallback& solution_callback, + bool* end) { - rectangle::InstanceBuilder instance_builder; + InstanceBuilder instance_builder; std::istringstream instance_stream(instance_json); instance_builder.read(instance_stream); - const rectangle::Instance instance = instance_builder.build(); - const rectangle::OptimizeParameters parameters - = read_parameters(parameters_json); - const rectangle::Output output = rectangle::optimize(instance, parameters); + const auto instance = instance_builder.build(); + OptimizeParameters parameters = read_parameters(parameters_json); + // The timer starts when the parameters are constructed; start it now. + parameters.timer.reset_time(); + if (end != nullptr) + parameters.timer.add_end_boolean(end); + if (solution_callback) { + parameters.new_solution_callback = [&solution_callback](const auto& output) + { + solution_callback(to_result(output)); + }; + } + const auto output = optimize_function(instance, parameters); return to_result(output); } -std::string solve( +nlohmann::json run( const std::string& problem_type, const std::string& instance_json, - const std::string& parameters_json) + const std::string& parameters_json, + const SolutionCallback& solution_callback = nullptr, + bool* end = nullptr) { - if (problem_type == "rectangle") - return solve_rectangle(instance_json, parameters_json); +#define PACKINGSOLVER_WASM_RUN(problem_type_namespace) \ + if (problem_type == #problem_type_namespace) { \ + return run( \ + [](const problem_type_namespace::Instance& instance, \ + const problem_type_namespace::OptimizeParameters& parameters) \ + { \ + return problem_type_namespace::optimize(instance, parameters); \ + }, \ + instance_json, \ + parameters_json, \ + solution_callback, \ + end); \ + } + PACKINGSOLVER_WASM_RUN(rectangleguillotine) + PACKINGSOLVER_WASM_RUN(rectangle) + PACKINGSOLVER_WASM_RUN(box) + PACKINGSOLVER_WASM_RUN(boxstacks) + PACKINGSOLVER_WASM_RUN(onedimensional) + PACKINGSOLVER_WASM_RUN(irregular) +#undef PACKINGSOLVER_WASM_RUN throw std::invalid_argument( "solve: unsupported problem type: \"" + problem_type + "\"."); } +nlohmann::json error_result(const std::exception& e) +{ + nlohmann::json result; + result["error"] = e.what(); + return result; +} + /** - * Wrapper returning errors as a JSON string: C++ exceptions only reach - * JavaScript as opaque pointers. + * Errors are returned as JSON: C++ exceptions only reach JavaScript as + * opaque pointers. */ -std::string solve_or_error( +std::string solve( const std::string& problem_type, const std::string& instance_json, const std::string& parameters_json) { try { - return solve(problem_type, instance_json, parameters_json); + return run(problem_type, instance_json, parameters_json).dump(); } catch (const std::exception& e) { - nlohmann::json result; - result["error"] = e.what(); - return result.dump(); + return error_result(e).dump(); } } +/** + * Optimization running in a thread of its own. + * + * The new solutions are found in the threads of the algorithms, which can't + * call JavaScript functions of the thread owning the session: they are + * queued, and returned by 'poll'. + */ +class Session +{ + +public: + + ~Session() + { + stop(); + if (thread_.joinable()) + thread_.join(); + } + + /** + * Start solving an instance. + * + * Returns an empty string, or an error as JSON if the session was + * already started. + */ + std::string start( + const std::string& problem_type, + const std::string& instance_json, + const std::string& parameters_json) + { + if (started_) { + nlohmann::json result; + result["error"] = "Session.start: the session was already started."; + return result.dump(); + } + started_ = true; + thread_ = std::thread([this, problem_type, instance_json, parameters_json]() + { + nlohmann::json result; + try { + result = run( + problem_type, + instance_json, + parameters_json, + [this](const nlohmann::json& solution) + { + std::lock_guard lock(mutex_); + solutions_.push_back(solution); + }, + &end_); + } catch (const std::exception& e) { + result = error_result(e); + } + std::lock_guard lock(mutex_); + result_ = result; + done_ = true; + }); + return ""; + } + + /** + * Return, as JSON: + * - "solutions": the updates since the previous call (each time the best + * solution or a bound improved); + * - "done": 'true' once the optimization has ended; + * - "result": then, the final result (or "error"). + */ + std::string poll() + { + nlohmann::json poll_result; + poll_result["solutions"] = nlohmann::json::array(); + bool done = false; + { + std::lock_guard lock(mutex_); + for (nlohmann::json& solution: solutions_) + poll_result["solutions"].push_back(std::move(solution)); + solutions_.clear(); + done = done_; + if (done) + poll_result["result"] = result_; + } + poll_result["done"] = done; + if (done && thread_.joinable()) + thread_.join(); + return poll_result.dump(); + } + + /** Stop the optimization: it then returns its best solution. */ + void stop() + { + end_ = true; + } + +private: + + /** Thread of the optimization. */ + std::thread thread_; + + /** 'true' once 'start' has been called. */ + bool started_ = false; + + /** Set to 'true' to stop the optimization. */ + bool end_ = false; + + /** Protects the members below. */ + std::mutex mutex_; + + /** Updates, not returned by 'poll' yet. */ + std::vector solutions_; + + /** 'true' once the optimization has ended. */ + bool done_ = false; + + /** Final result. */ + nlohmann::json result_; + +}; + } EMSCRIPTEN_BINDINGS(packingsolver) { - emscripten::function("solve", &solve_or_error); + emscripten::function("solve", &solve); + emscripten::class_("Session") + .constructor<>() + .function("start", &Session::start) + .function("poll", &Session::poll) + .function("stop", &Session::stop); } diff --git a/wasm/tests/helpers.js b/wasm/tests/helpers.js new file mode 100644 index 000000000..8a865c5ec --- /dev/null +++ b/wasm/tests/helpers.js @@ -0,0 +1,74 @@ +// Shared by the tests of the WebAssembly module. +// The module path can be set with PACKINGSOLVER_WASM (default: +// build_wasm/wasm/packingsolver.js). + +const fs = require("node:fs"); +const path = require("node:path"); + +const MODULE_PATH = process.env.PACKINGSOLVER_WASM + || path.join(__dirname, "..", "..", "build_wasm", "wasm", "packingsolver.js"); + +let modulePromise = null; +function loadModule() { + if (modulePromise === null) + modulePromise = require(MODULE_PATH)(); + return modulePromise; +} + +const DATA_DIR = path.join(__dirname, "..", "..", "data"); + +function readData(...parts) { + return JSON.parse(fs.readFileSync(path.join(DATA_DIR, ...parts), "utf8")); +} + +// An instance of each problem type. +const INSTANCES = { + rectangleguillotine: readData( + "rectangleguillotine", "tests", + "bin_packing_merge_identical_items_respects_resources", "instance.json"), + rectangle: readData( + "rectangle", "tests", + "variable_sized_bin_packing_remove_dominated_bin_types_not_removed_with_negative_penalty_resource_on_b", + "instance.json"), + box: readData( + "box", "tests", + "bin_packing_merge_identical_items_respects_resources", "instance.json"), + boxstacks: { + objective: "bin-packing", + bin_types: [{x: 100, y: 60, z: 40, copies: 2}], + item_types: [{x: 40, y: 30, z: 20, copies: 3}], + }, + onedimensional: readData( + "onedimensional", "tests", + "bin_packing_merge_identical_items_respects_resources", "instance.json"), + irregular: readData( + "irregular", "tests", + "periodic_packing_single_item_exact_fit_rectangle.json"), +}; + +// The 'rectangle' example of the README. Its objective has no bound: in +// anytime mode, it only ends when stopped (or with a time limit). +const README_INSTANCE = { + objective: "bin-packing-with-leftovers", + bin_types: [{x: 1000, y: 500, copies: 10}], + item_types: [ + {x: 300, y: 200, copies: 10}, + {x: 250, y: 150, copies: 10}, + ], +}; + +// Four 5x5 squares fill a 10x10 bin: the bound proves the solution optimal, +// so the anytime mode stops without a time limit. +const PROVEN_OPTIMAL_INSTANCE = { + objective: "bin-packing", + bin_types: [{x: 10, y: 10, copies: 4}], + item_types: [{x: 5, y: 5, copies: 4}], +}; + +module.exports = { + MODULE_PATH, + loadModule, + INSTANCES, + README_INSTANCE, + PROVEN_OPTIMAL_INSTANCE, +}; diff --git a/wasm/tests/rectangle.test.js b/wasm/tests/rectangle.test.js deleted file mode 100644 index 8da2bbbc8..000000000 --- a/wasm/tests/rectangle.test.js +++ /dev/null @@ -1,85 +0,0 @@ -// Run with: node --test wasm/tests/ -// The module path can be set with PACKINGSOLVER_WASM (default: -// build_wasm/wasm/packingsolver.js). - -const assert = require("node:assert"); -const path = require("node:path"); -const test = require("node:test"); - -const MODULE_PATH = process.env.PACKINGSOLVER_WASM - || path.join(__dirname, "..", "..", "build_wasm", "wasm", "packingsolver.js"); - -let modulePromise = null; -function loadModule() { - if (modulePromise === null) - modulePromise = require(MODULE_PATH)(); - return modulePromise; -} - -// The 'rectangle' example of the README. -const README_INSTANCE = { - objective: "bin-packing-with-leftovers", - bin_types: [{x: 1000, y: 500, copies: 10}], - item_types: [ - {x: 300, y: 200, copies: 10}, - {x: 250, y: 150, copies: 10}, - ], -}; - -// Four 5x5 squares fill a 10x10 bin: the bound proves the solution optimal, -// so the anytime mode stops without a time limit. -const PROVEN_OPTIMAL_INSTANCE = { - objective: "bin-packing", - bin_types: [{x: 10, y: 10, copies: 4}], - item_types: [{x: 5, y: 5, copies: 4}], -}; - -function solve(module, instance, parameters) { - const result = JSON.parse(module.solve( - "rectangle", JSON.stringify(instance), JSON.stringify(parameters))); - assert.strictEqual(result.error, undefined); - return result; -} - -test("rectangle: anytime mode (default)", async () => { - const module = await loadModule(); - const result = solve(module, PROVEN_OPTIMAL_INSTANCE, {}); - assert.strictEqual(result.output.Solution.NumberOfBins, 1); - assert.strictEqual(result.output.BinPackingBound, 1); -}); - -for (const optimizationMode of [ - "not-anytime", "not-anytime-deterministic", "not-anytime-sequential"]) { - test(`rectangle: README example, ${optimizationMode}`, async () => { - const module = await loadModule(); - const result = solve(module, README_INSTANCE, { - optimization_mode: optimizationMode}); - assert.strictEqual(result.output.Solution.NumberOfItems, 20); - assert.ok(result.output.Solution.NumberOfBins >= 1); - // The certificate lists every bin and item. - const lines = result.certificate.trim().split("\n"); - assert.strictEqual(lines[0], "TYPE,ID,COPIES,BIN,X,Y,LX,LY,GROUP_ID"); - assert.strictEqual( - lines.filter((line) => line.startsWith("ITEM,")).length, 20); - }); -} - -test("rectangle: invalid optimization mode", async () => { - const module = await loadModule(); - const result = JSON.parse(module.solve( - "rectangle", JSON.stringify(README_INSTANCE), - JSON.stringify({optimization_mode: "fast"}))); - assert.match(result.error, /optimization mode/); -}); - -test("rectangle: invalid instance", async () => { - const module = await loadModule(); - const result = JSON.parse(module.solve("rectangle", "{}", "{}")); - assert.match(result.error, /objective/); -}); - -test("unsupported problem type", async () => { - const module = await loadModule(); - const result = JSON.parse(module.solve("unknown", "{}", "{}")); - assert.match(result.error, /unsupported problem type/); -}); diff --git a/wasm/tests/session.test.js b/wasm/tests/session.test.js new file mode 100644 index 000000000..6d0517215 --- /dev/null +++ b/wasm/tests/session.test.js @@ -0,0 +1,94 @@ +// Run with: node --test wasm/tests/ + +const assert = require("node:assert"); +const test = require("node:test"); +const {setTimeout: sleep} = require("node:timers/promises"); + +const { + loadModule, INSTANCES, README_INSTANCE, PROVEN_OPTIMAL_INSTANCE, +} = require("./helpers.js"); + +// Poll a session until it ends; 'onSolutions' is called with each batch of +// new solutions. Returns the final result and all the solutions. +async function pollUntilDone(session, onSolutions = () => {}) { + const solutions = []; + for (;;) { + const pollResult = JSON.parse(session.poll()); + solutions.push(...pollResult.solutions); + if (pollResult.solutions.length > 0) + onSolutions(pollResult.solutions); + if (pollResult.done) + return {result: pollResult.result, solutions}; + await sleep(20); + } +} + +test("session: anytime mode, proven optimal", async () => { + const module = await loadModule(); + const session = new module.Session(); + assert.strictEqual(session.start( + "rectangle", JSON.stringify(PROVEN_OPTIMAL_INSTANCE), "{}"), ""); + const {result, solutions} = await pollUntilDone(session); + session.delete(); + assert.strictEqual(result.error, undefined); + assert.strictEqual(result.output.Solution.NumberOfBins, 1); + assert.ok(solutions.length >= 1); + // The last new solution is the final one. + assert.strictEqual( + solutions[solutions.length - 1].output.Solution.NumberOfBins, 1); +}); + +test("session: stop", async () => { + const module = await loadModule(); + const session = new module.Session(); + // No bound for this objective: in anytime mode, it only ends when + // stopped. + assert.strictEqual(session.start( + "rectangle", JSON.stringify(README_INSTANCE), "{}"), ""); + const {result, solutions} = await pollUntilDone( + session, () => session.stop()); + session.delete(); + assert.strictEqual(result.error, undefined); + assert.ok(solutions.length >= 1); + assert.strictEqual(result.output.Solution.NumberOfItems, 20); +}); + +for (const [problemType, instance] of Object.entries(INSTANCES)) { + test(`session: ${problemType}, anytime mode, stopped`, async () => { + const module = await loadModule(); + const session = new module.Session(); + assert.strictEqual(session.start( + problemType, JSON.stringify(instance), "{}"), ""); + // Stopped at the first solution, unless it already ended (solution + // proven optimal). The updates also report new bounds, possibly + // before any solution is found. + const {result} = await pollUntilDone(session, (solutions) => { + if (solutions.some((s) => s.output.Solution.NumberOfItems > 0)) + session.stop(); + }); + session.delete(); + assert.strictEqual(result.error, undefined); + assert.ok(result.output.Solution.NumberOfItems > 0); + }); +} + +test("session: error", async () => { + const module = await loadModule(); + const session = new module.Session(); + assert.strictEqual(session.start("rectangle", "{}", "{}"), ""); + const {result} = await pollUntilDone(session); + session.delete(); + assert.match(result.error, /objective/); +}); + +test("session: started twice", async () => { + const module = await loadModule(); + const session = new module.Session(); + assert.strictEqual(session.start( + "rectangle", JSON.stringify(PROVEN_OPTIMAL_INSTANCE), "{}"), ""); + const error = JSON.parse(session.start( + "rectangle", JSON.stringify(PROVEN_OPTIMAL_INSTANCE), "{}")).error; + assert.match(error, /already started/); + await pollUntilDone(session); + session.delete(); +}); diff --git a/wasm/tests/solve.test.js b/wasm/tests/solve.test.js new file mode 100644 index 000000000..00b2625cf --- /dev/null +++ b/wasm/tests/solve.test.js @@ -0,0 +1,69 @@ +// Run with: node --test wasm/tests/ + +const assert = require("node:assert"); +const test = require("node:test"); + +const { + loadModule, INSTANCES, README_INSTANCE, PROVEN_OPTIMAL_INSTANCE, +} = require("./helpers.js"); + +function solve(module, problemType, instance, parameters) { + return JSON.parse(module.solve( + problemType, JSON.stringify(instance), JSON.stringify(parameters))); +} + +for (const [problemType, instance] of Object.entries(INSTANCES)) { + for (const optimizationMode of ["not-anytime", "not-anytime-sequential"]) { + test(`${problemType}, ${optimizationMode}`, async () => { + const module = await loadModule(); + const result = solve(module, problemType, instance, { + optimization_mode: optimizationMode}); + assert.strictEqual(result.error, undefined); + assert.ok(result.output.Solution.NumberOfItems > 0); + assert.ok(result.certificate.length > 0); + }); + } +} + +test("rectangle: anytime mode (default)", async () => { + const module = await loadModule(); + const result = solve(module, "rectangle", PROVEN_OPTIMAL_INSTANCE, {}); + assert.strictEqual(result.error, undefined); + assert.strictEqual(result.output.Solution.NumberOfBins, 1); + assert.strictEqual(result.output.BinPackingBound, 1); +}); + +for (const optimizationMode of [ + "not-anytime", "not-anytime-deterministic", "not-anytime-sequential"]) { + test(`rectangle: README example, ${optimizationMode}`, async () => { + const module = await loadModule(); + const result = solve(module, "rectangle", README_INSTANCE, { + optimization_mode: optimizationMode}); + assert.strictEqual(result.error, undefined); + assert.strictEqual(result.output.Solution.NumberOfItems, 20); + // The certificate lists every bin and item. + const lines = result.certificate.trim().split("\n"); + assert.strictEqual(lines[0], "TYPE,ID,COPIES,BIN,X,Y,LX,LY,GROUP_ID"); + assert.strictEqual( + lines.filter((line) => line.startsWith("ITEM,")).length, 20); + }); +} + +test("invalid optimization mode", async () => { + const module = await loadModule(); + const result = solve(module, "rectangle", README_INSTANCE, { + optimization_mode: "fast"}); + assert.match(result.error, /optimization mode/); +}); + +test("invalid instance", async () => { + const module = await loadModule(); + const result = solve(module, "rectangle", {}, {}); + assert.match(result.error, /objective/); +}); + +test("unsupported problem type", async () => { + const module = await loadModule(); + const result = solve(module, "unknown", {}, {}); + assert.match(result.error, /unsupported problem type/); +}); diff --git a/wasm/tests/worker.test.js b/wasm/tests/worker.test.js new file mode 100644 index 000000000..b335cd652 --- /dev/null +++ b/wasm/tests/worker.test.js @@ -0,0 +1,61 @@ +// Run with: node --test wasm/tests/ +// The Web Worker, run with 'worker_threads'. + +const assert = require("node:assert"); +const path = require("node:path"); +const test = require("node:test"); +const {Worker} = require("node:worker_threads"); + +const {MODULE_PATH, README_INSTANCE} = require("./helpers.js"); + +const WORKER_PATH = path.join(__dirname, "..", "js", "packingsolver_worker.js"); + +// Run the worker with a list of messages; 'onMessage(message, worker)' is +// called for each message from the worker. Resolves with all the messages, +// once a "done" or "error" message is received. +function runWorker(messages, onMessage = () => {}) { + const worker = new Worker(WORKER_PATH, {workerData: {modulePath: MODULE_PATH}}); + for (const message of messages) + worker.postMessage(message); + const received = []; + return new Promise((resolve, reject) => { + worker.on("error", reject); + worker.on("message", (message) => { + received.push(message); + onMessage(message, worker); + if (message.type === "done" || message.type === "error") { + worker.terminate().then(() => resolve(received)); + } + }); + }); +} + +test("worker: solutions, stop and result", async () => { + // No bound for this objective: in anytime mode, it only ends when + // stopped. + const received = await runWorker( + [{type: "solve", problemType: "rectangle", instance: README_INSTANCE}], + (message, worker) => { + // The updates also report new bounds, possibly before any + // solution is found. + if (message.type === "solution" + && message.output.Solution.NumberOfItems > 0) { + worker.postMessage({type: "stop"}); + } + }); + const types = received.map((message) => message.type); + assert.strictEqual(types[0], "ready"); + assert.ok(types.includes("solution")); + const done = received[received.length - 1]; + assert.strictEqual(done.type, "done"); + assert.strictEqual(done.output.Solution.NumberOfItems, 20); + assert.ok(done.certificate.startsWith("TYPE,")); +}); + +test("worker: error", async () => { + const received = await runWorker( + [{type: "solve", problemType: "unknown", instance: {}}]); + const last = received[received.length - 1]; + assert.strictEqual(last.type, "error"); + assert.match(last.error, /unsupported problem type/); +});