diff --git a/README.md b/README.md index c81108b..3cb92bf 100644 --- a/README.md +++ b/README.md @@ -299,6 +299,7 @@ Some errors would hit every remaining file, such as an invalid key, a monthly li | `--method=METHOD` | `fit`, `scale`, `cover`, or `thumb`. Requires `--resize` | | `--output=PATH` | Write to a folder, or to `s3://bucket/path/` | | `--recompress` | Compress images tinify already compressed again | +| `--concurrency=N` | Compress N images at once. Default `2` | | `--dry-run` | List what would happen. No API call, no key needed | | `--` | Treat everything after it as a file name | | `--json` | Force JSON output | diff --git a/src/compress.ts b/src/compress.ts index 69553b3..dd385e1 100644 --- a/src/compress.ts +++ b/src/compress.ts @@ -49,6 +49,8 @@ export interface CompressOptions { record?: CompressedRecord; /** Compress images the record knows again; existing results are still skipped. */ recompress?: boolean; + /** How many images are compressed at once, 1 or more. Default 2. */ + concurrency?: number; } /** Mirrors the Tinify API response shape, plus path metadata for CLI use. */ @@ -101,7 +103,7 @@ export interface CompressSummary { stopped?: { reason: string; notProcessed: number }; } -const CONCURRENCY = 2; +const DEFAULT_CONCURRENCY = 2; const NO_OUTPUT: CompressResult["output"] = { size: null, type: null, width: null, height: null }; @@ -662,7 +664,7 @@ export async function compressFiles( new Promise((settle) => { wake = settle; }); - const { signal } = options; + const { signal, concurrency = DEFAULT_CONCURRENCY } = options; const onAbort = () => wake?.(); signal?.addEventListener("abort", onAbort, { once: true }); const running = new Map>(); @@ -671,7 +673,7 @@ export async function compressFiles( while (next < jobs.length) { if (signal?.aborted) stopReason ??= "interrupted"; if (stopReason !== undefined) break; - if (running.size >= (probingS3 ? 1 : CONCURRENCY)) { + if (running.size >= (probingS3 ? 1 : concurrency)) { await sleep(); continue; } diff --git a/src/index.ts b/src/index.ts index 386bcf7..4a5f847 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,6 +38,7 @@ Options: --convert= Convert to format (see above) --output= Output directory or s3://bucket/path/ --recompress Compress images tinify already compressed again + --concurrency= Images to compress at once (default 2) --dry-run Show what would be done, without an API key or API calls --json Force JSON output (default in non-TTY) --no-progress Disable progress bar @@ -65,6 +66,7 @@ const OPTIONS = { output: { type: "string" }, resize: { type: "string" }, method: { type: "string" }, + concurrency: { type: "string" }, key: { type: "string" }, json: { type: "boolean", default: false }, "no-progress": { type: "boolean", default: false }, @@ -123,19 +125,23 @@ export function parseArgs(argv: string[]) { /** Turns the compress flags into options, rejecting bad values before any file or network access. */ export function buildCompressOptions(args: ParsedArgs): Omit { - const { convert, resize, method, "dry-run": dryRun, recompress } = args; + const { convert, resize, method, "dry-run": dryRun, recompress, concurrency } = args; if (convert !== undefined && !isConvertFormat(convert)) { throw new CliError(`invalid format: ${convert}. Must be one of: ${CONVERT_FORMATS.join(", ")}`); } if (method !== undefined && resize === undefined) { throw new CliError("--method requires --resize"); } + if (concurrency !== undefined && !/^[1-9]\d*$/.test(concurrency)) { + throw new CliError(`invalid --concurrency: ${concurrency}. Must be a whole number, 1 or more`); + } return { output: parseOutputTarget(args.output), ...(convert !== undefined && { convert }), ...(resize !== undefined && { resize: buildResizeOptions(resize, method) }), ...(dryRun && { dryRun }), ...(recompress && { recompress }), + ...(concurrency !== undefined && { concurrency: Number(concurrency) }), }; } diff --git a/tests/args.test.ts b/tests/args.test.ts index 249111f..8fa0a3b 100644 --- a/tests/args.test.ts +++ b/tests/args.test.ts @@ -35,6 +35,7 @@ describe("parseArgs", () => { ["--output=a=b", "output", "a=b"], ["--resize=800x600", "resize", "800x600"], ["--method=cover", "method", "cover"], + ["--concurrency=4", "concurrency", "4"], ])("%s → %s", (flag, field, value) => { expect(parse("img.png", flag)[field]).toBe(value); }); diff --git a/tests/compress.test.ts b/tests/compress.test.ts index 22a1ebb..c62e840 100644 --- a/tests/compress.test.ts +++ b/tests/compress.test.ts @@ -1210,6 +1210,30 @@ describe("concurrency", () => { // Results are reported in input order, not completion order. expect(results.map((r) => r.relativePath)).toEqual(["slow.png", "a.png", "b.png", "c.png"]); }); + + test.each([1, 3])("concurrency: %d keeps that many uploads in flight", async (concurrency) => { + const files = ["a.png", "b.png", "c.png", "d.png", "e.png"].map((n) => imageFile(dir, n)); + let inFlight = 0; + let peak = 0; + t.default.fromFile.mockImplementation(() => { + peak = Math.max(peak, ++inFlight); + const toBuffer = async () => { + // Lasts until one upload more than allowed is in flight, or 50 ms: long enough + // for the allowed ones to overlap. + const until = Date.now() + 50; + const tooMany = () => inFlight > concurrency; + while (!tooMany() && Date.now() < until) await Bun.sleep(1); + inFlight--; + return new Uint8Array(1); + }; + return { ...t.source, result: () => ({ ...t.result, toBuffer }) } as never; + }); + + const { results } = await compressFiles(files, opts({ concurrency })); + + expect(results).toHaveLength(5); + expect(peak).toBe(concurrency); + }); }); /** diff --git a/tests/e2e/commands.test.ts b/tests/e2e/commands.test.ts index fc2252e..4f86011 100644 --- a/tests/e2e/commands.test.ts +++ b/tests/e2e/commands.test.ts @@ -51,6 +51,7 @@ describe.each(BUILDS)("%s", (build) => { [[], "usage: tinify "], [["a.png", "--convert=tiff"], "invalid format: tiff"], [["a.png", "--method=cover"], "--method requires --resize"], + [["a.png", "--concurrency=0"], "invalid --concurrency: 0"], [["register", "--email=a@b.c"], "Unknown option '--email'"], [["a.png", "--convert"], "'--convert ' argument missing"], [["version", "a.png"], "use ./version"], diff --git a/tests/main.test.ts b/tests/main.test.ts index da81b40..2738936 100644 --- a/tests/main.test.ts +++ b/tests/main.test.ts @@ -110,6 +110,11 @@ describe("argument errors come before any key lookup or file access", () => { [["--resize=800x", "--method=cover"], "needs both width and height"], [["--resize=800x600", "--method=scale"], "takes one dimension"], [["--output=s3://"], "invalid S3 output"], + [["--concurrency=0"], "invalid --concurrency: 0"], + [["--concurrency=-1"], "invalid --concurrency: -1"], + [["--concurrency=1.5"], "invalid --concurrency: 1.5"], + [["--concurrency=two"], "invalid --concurrency: two"], + [["--concurrency="], "invalid --concurrency: "], ])("%p → %s", async (flags, message) => { const deps = makeDeps(); await expect(run(argv("a.png", ...flags), deps)).rejects.toThrow(message); @@ -191,6 +196,15 @@ describe("compressing", () => { expect(compressOptions(plain).recompress).toBeUndefined(); }); + test("--concurrency is passed through as a number; without it, it's left out", async () => { + const deps = makeDeps(); + await run(argv("a.png", "--concurrency=5"), deps); + expect(compressOptions(deps).concurrency).toBe(5); + const plain = makeDeps(); + await run(argv("a.png"), plain); + expect(compressOptions(plain).concurrency).toBeUndefined(); + }); + test.each([[[]], [["--dry-run"]]])( "%p: the record is loaded once and passed on", async (flags) => {