Files
factorio-clusterio/test/lib/zip_ops.js
T
BastiaanandClaude Opus 5.5 c28e617b22 Replace jszip with yauzl and yazl (#1011)
* Replace jszip with yauzl and yazl

jszip loads a whole archive into memory to read it and buffers the
output when writing.  Saves and mods can be several hundred megabytes,
so read zips with yauzl, which only reads the central directory and
streams entries on demand, and write them with yazl, which streams the
output.

lib gains a ZipArchive wrapper around yauzl with the lookup helpers the
callers need, findRoot() now takes it instead of a JSZip.  Saves are
patched by streaming every kept entry into a new zip, mod info.json is
read straight from the file, exports are streamed to the controller and
Factorio zip downloads go through a temp file instead of a buffer.

Patching now inflates and deflates each entry again where jszip reused
the compressed data, on a 336 MB synthetic save that is 7 s instead of
0.7 s, with peak memory going from 416 MB to 151 MB.

Closes #1002

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Copy save entries without recompressing them

yazl inflates and deflates every entry it is given, so patching a save
took ten times longer than with jszip, which reused the compressed
data.  Add a ZipWriter to lib that streams entries out as they are
added and copies entries from a ZipArchive byte for byte, with ZIP64
structures when sizes or offsets need them, and use it in patch().

On a 336 MB synthetic save patching now takes 0.4 s at 143 MB peak RSS
against 0.75 s at 417 MB with jszip.  Factorio loads the result.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Handle save write errors before the patch loop awaits them

A write error on the temporary save, such as a full disk, rejected the
pipeline promise while addEntry() or addBuffer() was still pending. Nothing
was listening yet, so the host's unhandledRejection handler exited the
process instead of failing the instance start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep the export zip cache local to each export

The cache was module level, so when two instances on one host exported at
once, the first to finish closed archives the other was still reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Start writing zips before adding files from disk

yazl reads files passed to addFile() as soon as they are added. An
unreadable file emitted an error while the directory traversal was still
running, before the output pipeline existed, and the process exited on the
uncaught error. build_mod and zipDirectory now start the pipeline first and
reject instead. build_mod also removes the partial zip on failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-17 21:44:19 +03:00

137 lines
5.0 KiB
JavaScript

import assert from "node:assert/strict";
import zlib from "node:zlib";
import { ZipArchive, ZipWriter, findRoot } from "@clusterio/lib";
import { createZipBuffer } from "../common.js";
async function readAll(stream) {
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
describe("lib/zip_ops", function() {
describe("class ZipArchive", function() {
it("should read files from a zip", async function() {
const zip = await ZipArchive.fromBuffer(await createZipBuffer([
["root/foo.txt", "foo"],
["root/bar.txt", "bar"],
]));
assert.deepEqual([...zip.entries.keys()], ["root/foo.txt", "root/bar.txt"]);
assert.equal((await zip.readFile("root/foo.txt")).toString(), "foo");
assert.equal(await zip.readFile("root/missing.txt"), null);
assert.equal(zip.file("root/missing.txt"), null);
assert.equal(zip.file("root/bar.txt").fileName, "root/bar.txt");
});
it("should reject invalid zips", async function() {
await assert.rejects(ZipArchive.fromBuffer(Buffer.from("not a zip file")));
});
});
describe("class ZipWriter", function() {
const sourceFiles = [
["root/", ""],
["root/foo.txt", "foo"],
["root/big.txt", "lorem ipsum ".repeat(10000)],
["root/ünïcode.txt", "unicode"],
];
async function roundTrip(forceZip64) {
const source = await ZipArchive.fromBuffer(await createZipBuffer(sourceFiles));
const writer = new ZipWriter({ forceZip64 });
const output = readAll(writer.outputStream);
for (const entry of source.entries.values()) {
await writer.addEntry(source, entry);
}
await writer.addBuffer(Buffer.from("added"), "root/added.txt", { mtime: new Date(2020, 0, 2, 3, 4, 6) });
await writer.end();
return { source, copy: await ZipArchive.fromBuffer(await output) };
}
async function assertRoundTrip(forceZip64) {
const { source, copy } = await roundTrip(forceZip64);
assert.deepEqual([...copy.entries.keys()], [...source.entries.keys(), "root/added.txt"]);
for (const [name, sourceEntry] of source.entries) {
const entry = copy.entries.get(name);
assert.equal(entry.compressionMethod, sourceEntry.compressionMethod, name);
assert.equal(entry.compressedSize, sourceEntry.compressedSize, name);
assert.equal(entry.uncompressedSize, sourceEntry.uncompressedSize, name);
assert.equal(entry.crc32, sourceEntry.crc32, name);
assert.deepEqual(entry.getLastModDate(), sourceEntry.getLastModDate({ forceDosFormat: true }), name);
if (!name.endsWith("/")) {
const content = await copy.readEntry(entry);
assert.deepEqual(content, await source.readEntry(sourceEntry), name);
assert.equal(zlib.crc32(content), entry.crc32, name);
}
}
const added = copy.entries.get("root/added.txt");
assert.equal((await copy.readEntry(added)).toString(), "added");
assert.equal(zlib.crc32("added"), added.crc32);
assert.deepEqual(added.getLastModDate(), new Date(2020, 0, 2, 3, 4, 6));
assert.equal(added.versionNeededToExtract, forceZip64 ? 45 : 20);
}
it("should copy entries and add files", async function() {
await assertRoundTrip(false);
});
it("should write ZIP64 structures when forced", async function() {
await assertRoundTrip(true);
});
it("should reject writes after the output stream is destroyed", async function() {
const writer = new ZipWriter();
writer.outputStream.on("error", () => {});
writer.outputStream.destroy(new Error("Test error"));
await assert.rejects(writer.addBuffer(Buffer.from(""), "foo.txt"), new Error("Test error"));
await assert.rejects(writer.end(), new Error("Test error"));
});
it("should fail when the output stream is destroyed while waiting for drain", async function() {
const writer = new ZipWriter();
writer.outputStream.pause();
const adding = writer.addBuffer(Buffer.alloc(1024 * 1024), "foo.txt");
writer.outputStream.destroy();
await assert.rejects(adding, new Error("Zip output stream was closed"));
});
});
describe("findRoot()", function() {
it("should find the root of a zip", async function() {
const zip = await ZipArchive.fromBuffer(await createZipBuffer([
["root/foo.txt", ""],
["root/bar.txt", ""],
]));
assert.equal(findRoot(zip), "root");
});
it("should throw if the first file is at the root of the zip", async function() {
const zip = await ZipArchive.fromBuffer(await createZipBuffer([
["bar.txt", ""],
["root/foo.txt", ""],
]));
assert.throws(
() => findRoot(zip),
new Error("Zip contains file 'bar.txt' in root dir")
);
});
it("should return directory of first file if there are multiple root dirs", async function() {
const zip = await ZipArchive.fromBuffer(await createZipBuffer([
["root-1/foo.txt", ""],
["root-2/bar.txt", ""],
]));
assert.equal(findRoot(zip), "root-1");
});
it("should throw if given an empty zip file", async function() {
const zip = await ZipArchive.fromBuffer(await createZipBuffer([]));
assert.throws(
() => findRoot(zip),
new Error("Empty zip file")
);
});
});
});