"use strict"; // Swapoff safety rule of the fixed remote swap helper, run locally with a fake /proc (no swap is touched). const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const { spawnSync } = require("node:child_process"); const SCRIPT = path.join(__dirname, "../src/main/system/remoteSwap.sh"); const MiB = 1024; // The helper is a POSIX shell script; Windows hosts have no /bin/sh. const skip = process.platform === "win32" ? "POSIX sh is not available on Windows." : false; function check({ totalMiB, availableMiB, areas }) { const proc = fs.mkdtempSync(path.join(os.tmpdir(), "chj-swap-proc-")); try { fs.writeFileSync(path.join(proc, "meminfo"), `MemTotal: ${totalMiB * MiB} kB\nMemAvailable: ${availableMiB * MiB} kB\n`); fs.writeFileSync(path.join(proc, "swaps"), "Filename\tType\tSize\tUsed\tPriority\n" + areas.map(([name, sizeMiB, usedMiB]) => `${name}\tfile\t${sizeMiB * MiB}\t${usedMiB * MiB}\t-2`).join("\n") + "\n"); const result = spawnSync("sh", [SCRIPT, "safety-check", areas[0][0]], { encoding: "utf8", env: { ...process.env, CHJ_SWAP_TEST_PROC: proc } }); return result.stdout.includes("safe\n") ? "safe" : (result.stdout.match(/CHJ_ERR=(\w+)/) || [])[1]; } finally { fs.rmSync(proc, { recursive: true, force: true }); } } test("swapoff is refused when the used swap cannot fit into RAM minus the reserve", { skip }, () => { assert.equal(check({ totalMiB: 4096, availableMiB: 1024, areas: [["/swapfile", 2048, 900]] }), "SWAPOFF_UNSAFE"); assert.equal(check({ totalMiB: 4096, availableMiB: 1024, areas: [["/swapfile", 2048, 400]] }), "safe"); }); test("free space in other active swap areas counts towards the room", { skip }, () => { assert.equal(check({ totalMiB: 4096, availableMiB: 1024, areas: [["/swapfile", 2048, 900], ["/swap/b", 1024, 0]] }), "safe"); }); test("an unused swap area can always be deactivated, even on a small server", { skip }, () => { assert.equal(check({ totalMiB: 468, availableMiB: 408, areas: [["/swapfile", 128, 0]] }), "safe"); }); test("the reserve never exceeds a quarter of RAM on small servers", { skip }, () => { // 468 MiB RAM: reserve 117 MiB instead of 512 MiB. assert.equal(check({ totalMiB: 468, availableMiB: 400, areas: [["/swapfile", 256, 200]] }), "safe"); assert.equal(check({ totalMiB: 468, availableMiB: 300, areas: [["/swapfile", 256, 200]] }), "SWAPOFF_UNSAFE"); }); test("the test-only operation is unavailable without the test /proc override", { skip }, () => { const result = spawnSync("sh", [SCRIPT, "safety-check", "/swapfile"], { encoding: "utf8", env: { PATH: process.env.PATH } }); assert.match(result.stdout, /CHJ_ERR=ACTION_INVALID/); });