diff --git a/CHANGELOG.md b/CHANGELOG.md index 29921d2e..125c714c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,53 @@ tool under `tools/` keeps its own. ## [Unreleased] +## [v0.12.0] - 2026-11-29 + +This release lets `stages.Build` run soffice on the host, so a host without a docker socket has the +office and picture routes; `stages.Options.LibreOfficeExec`'s zero value keeps soffice in +`picture.LibreOfficeImage`. It also renders SVG through librsvg's rsvg-convert in place of magick, +so docproc never follows an SVG's references to files and URLs, whatever magick was built with. +The office and picture stages require rsvg-convert, and their identities change: each `Version` +carries rsvg-convert's version line. `dispatch.Version` stays "1", and the run directory's schema +stays "2". + +### Added + +- `picture.RsvgConvertSpec` and `picture.RsvgConvertMinimum`, 2.58, declaring librsvg's + rsvg-convert, and `picture.Config.RsvgConvert`, which `picture.NewConverter` requires, panicking + on a nil one, and version-checks through `Tool.AtLeast`, refusing one older than the minimum with + a `*tool.VersionError` wrapping `tool.ErrTooOld`. 2.58 is Ubuntu 24.04 LTS's, after 2.56.3 fixed + CVE-2023-38633; Debian 13 ships 2.60. +- `stages.Build` builds rsvg-convert through the exec runner, found through the lookup as + `rsvg-convert`, as it builds magick, and the office and vision-converted routes require it: a host + without it, or with one older than 2.58, has those routes Missing, their rows saying why. + rsvg-convert's row in `Set.Tools` carries its minimum, and `Options.Timeout` bounds its runs. +- `stages.Options.LibreOfficeExec`, which runs soffice on the host through the exec runner, found + through the lookup as `soffice`, under `stages.Options.LibreOfficeMemory`, the run's own + directory, and the fixed environment every exec-run tool runs under; docker is never looked up + for it, and soffice's row in `Set.Tools` names its path. False, its zero value, runs soffice in + `picture.LibreOfficeImage` through the container runner, found through the lookup as `docker`, + under `Options.Memory`, as before. +- `stages.Options.LibreOfficeMemory`, soffice's memory bound in bytes when `LibreOfficeExec` is set, + its RLIMIT_AS in place of `Options.Memory`, since soffice needs a far larger RLIMIT_AS than the + other tools. It has no default: zero is none, and `stages.Build` refuses one below zero with an + error matching `stages.ErrRequest`. A soffice run killed by a signal under it is recorded with + this bound. +- The `settings` key `soffice_memory`, whole bytes, zero or more, assembled into + `stages.Options.LibreOfficeMemory`, and its field `settings.Settings.SofficeMemory`. It is + optional: unset, it assembles to `tool_memory`'s value, so soffice keeps the bound it had before + the key existed, and one below zero is refused by name with a `settings.KeyError`. `cmd/docproc`, + which runs soffice in its container, doesn't read it. + ### Changed +- An SVG is rendered through rsvg-convert, `--zoom= --background-color=white + --format=png`, never through magick's `rsvg:` coder, which a magick built without librsvg, as + Debian 13's is, reads through ImageMagick's own MSVG renderer, following an `` to a + local file or a URL. The PNG is the same size at the same `Density`, opaque on white, and the same + bytes each time it is converted. An rsvg-convert run carries none of `picture.Limits`; the Tool's + memory bound and timeout hold it. A failed run's error names rsvg-convert, `picture: + rsvg-convert: : ...`, where it named magick. - Each package's unit tests sit in its `test/` directory as an external test package (`/test/*_test.go`), the helper packages `dispatch/dispatchtest`, `internal/tooltest`, and `internal/goldentest` included, with each package's fixtures in `/test/testdata/`. A test @@ -676,7 +721,8 @@ fixtures scripts stay in the spike. The [limits page](docs/limits.md) states them: each stage's tool's limits, docproc-ooxml's behavior under a memory bound, the Threader's memory, and the formats no stage reads. -[Unreleased]: https://github.com/standards-lab/docproc/compare/v0.11.0...HEAD +[Unreleased]: https://github.com/standards-lab/docproc/compare/v0.12.0...HEAD +[v0.12.0]: https://github.com/standards-lab/docproc/compare/v0.11.0...v0.12.0 [v0.11.0]: https://github.com/standards-lab/docproc/compare/v0.10.0...v0.11.0 [v0.10.0]: https://github.com/standards-lab/docproc/compare/v0.9.0...v0.10.0 [v0.9.0]: https://github.com/standards-lab/docproc/compare/v0.8.0...v0.9.0 diff --git a/README.md b/README.md index 117a8bb5..ce9a83dd 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ tags. ## Install ```sh -go get github.com/standards-lab/docproc@v0.11.0 +go get github.com/standards-lab/docproc@v0.12.0 ``` The module's releases are tagged `vX.Y.Z`, and [`CHANGELOG.md`](CHANGELOG.md) states what each @@ -100,6 +100,7 @@ made fails before the tool starts. | `pdfinfo` | poppler-utils | 22.02 | document | | `magick` | ImageMagick | 7.1 | office, picture, vision | | `soffice` | LibreOffice | 24.2 | office, picture | +| `rsvg-convert` | librsvg | 2.58 | office, picture | | `7zz` | 7-Zip | 26.06 | archive | | `ffmpeg`, `ffprobe` | FFmpeg | 9.0 | audio, video | @@ -107,8 +108,22 @@ made fails before the tool starts. CVE-2026-14266 in xz's, and 26.03 through 26.06 fix vulnerabilities they don't name. The text stage runs no tool. -The container runner runs a tool inside a digest-pinned image through the docker CLI, 20.10 or -later: `audio.FFmpegImage` for ffmpeg and ffprobe, `picture.LibreOfficeImage` for soffice. +rsvg-convert renders every SVG, never magick: a magick built without librsvg, as Debian 13's is, +renders SVG through ImageMagick's own MSVG renderer, which follows an SVG's references to files +and URLs. rsvg-convert's minimum, 2.58, is Ubuntu 24.04 LTS's version, after 2.56.3 fixed +CVE-2023-38633, a path traversal through an SVG's reference. The office stage runs no +rsvg-convert, since it hands an Office document's SVGs on as stored, but it requires one, because +it shares the picture package's Converter. + +`stages.Build` runs soffice by default inside `picture.LibreOfficeImage`, a digest-pinned image, +through the container runner and the docker CLI, 20.10 or later, which it finds through the lookup +as `docker`. With `stages.Options.LibreOfficeExec` set, it runs soffice on the host through the +exec runner instead and never looks up docker: it finds soffice through the lookup as `soffice`, +runs it under every exec-run tool's bounds except the memory bound, which +`stages.Options.LibreOfficeMemory` sets, and names soffice's path in its row in `Set.Tools`. +`stages.Build` runs every other tool, ffmpeg and ffprobe among them, through the exec runner alone. +`audio.FFmpegImage` is the image for a host that builds ffmpeg and ffprobe itself through +`tool.NewContainer`. ### The memory bound @@ -119,4 +134,10 @@ runs: `prlimit` must then be on PATH, and `tool.NewExec` refuses a bounded tool tool that dies by a signal under the bound is recorded with both, as in "killed by SIGABRT under a 256 MiB memory bound". +Run through the exec runner, soffice takes its own bound, `stages.Options.LibreOfficeMemory`, in +place of `Memory`. It has no default either: zero runs soffice with no bound. soffice needs a far +larger RLIMIT_AS than the other tools: soffice 26.8 fails to write its output under 4 GiB on a +host where it converts under 8 GiB. Run in the container, soffice stays under `Memory`, the +container's `--memory`. + Apache-2.0. diff --git a/context/bunrei.md b/context/bunrei.md index aef5b4fc..4f009789 100644 --- a/context/bunrei.md +++ b/context/bunrei.md @@ -3,8 +3,8 @@ Bunrei, the data-intelligence capstone's processing service, is planned. It runs docinfer's jobs over docproc's dispatcher, stages, and stores, which it wires, and builds the go-ai clients docinfer calls. The capstone root's notes hold its contracts; this note holds what Bunrei keeps to itself: -its input, its jobs and their fencing, and its state, which the `state` task settles -(`standards-lab/context/data-intelligence.md`, "Design"). +its input, its jobs and their fencing, its tools and routes, and its state, which the `state` task +settles (`standards-lab/context/data-intelligence.md`, "Design"). ## Queries and Commands @@ -31,6 +31,19 @@ subject under the expected-last-subject-sequence check, which is its transaction refused append reads the subject's tail and acts on either alike. - **The profile** resolves to a `docinfer.Pipeline`, one per profile. +## Tools and routes + +Bunrei wires docproc's `stages` and `dispatch` from a `settings.Run` assembled from its `docproc` +block, as `cmd/docproc` does, and its dispatcher works under `work_dir`, one volume per replica that +the deployment mounts. Bunrei's service image holds every tool docproc's routes run, and Bunrei +builds its stages with `stages.Options.LibreOfficeExec` set, so every tool, soffice included, runs +through the exec runner. soffice runs under the `soffice_memory` settings key's bound, every other +tool under `tool_memory`'s. rsvg-convert renders SVG, from Debian's librsvg2-bin. Startup requires +every route not in Bunrei's `jobs.exclude` and refuses to run while one has no processor, naming its +stage row's reason. Bunrei's +[`docs/image.md`](https://github.com/JaimeStill/capstone-bunrei/blob/main/docs/image.md) describes +the image. + ## State and subjects Bunrei holds only its jobs, its uploads, and each job's event stream. docproc's index and content @@ -76,8 +89,6 @@ data-intelligence.md queues these asks of go-messaging's NATS provider, sized by ## Assumptions -- Assumes Bunrei wires docproc's `stages` and `dispatch` from a `settings.Run`, as `cmd/docproc` - does. - Assumes one `docinfer.Bounds` per replica, shared by its pipelines, one per profile. - Assumes Bunrei speaks Chat Completions to the gateway, its consumer key the bearer token. - Assumes the consumer stores chunks by their identity, so a batch a redelivered job repeats changes diff --git a/docs/api.md b/docs/api.md index 724a0356..de5fba87 100644 --- a/docs/api.md +++ b/docs/api.md @@ -336,7 +336,7 @@ How `office` converts through LibreOffice, and why: `.tif` and `.tiff` of one stem are each swapped whole, and a swapped-in name is never swapped again. -How `picture` runs magick and soffice, and why: +How `picture` runs magick, soffice, and rsvg-convert, and why: - An output stem is ASCII letters, digits, `.`, `-`, and `_`, beginning with a letter or digit, so magick reads no part of a name made from it as a format prefix, a frame suffix, or a pattern. @@ -371,6 +371,18 @@ How `picture` runs magick and soffice, and why: picture at its own size at its center, so rendering the page at a scale renders the picture at that scale; a page of another shape than the pixel size would stretch it. `-trim` then crops to what differs from the corners' color and `+repage` drops the crop's offset, PNG in and out. +- An SVG is rendered by librsvg's own command, rsvg-convert, never by magick: a magick built + without librsvg, as Debian 13's is, reads an SVG named `rsvg:` through its own MSVG renderer, + which follows an `` to a local file or a URL. librsvg runs no script, fetches no URL, + and loads only a file beside the SVG or below its directory, which holds the copy alone. The run + is `--zoom= --background-color=white --format=png --output= `: the zoom + scales the SVG's CSS pixels, a 96th of an inch, to the density, as magick's `-density` did, and + leaves its physical units true, a fractional size rounded up where magick rounded down; the + white background leaves no transparent pixel, and librsvg writes no time chunk, so the PNG is + the same bytes each time. It works in the batch's `picture-*` directory, its HOME under the exec + runner, so fontconfig's cache is removed with it and never lands in the caller's directory. + `--unlimited` is never passed, so librsvg's own bounds on the XML it parses hold; magick's limits + don't apply, and the tool's memory bound and timeout do. How `audio` and `media` run ffmpeg, and why: @@ -792,11 +804,17 @@ type Options struct { // the zero value wires every route, with no bound Exclude []route.Route Inspect inspect.Options // validated once; the archive and document stages' bomb rule Timeout time.Duration // Spec.Timeout of the unit tools: gs, qpdf, pdfdetach, - // pdftotext, pdfinfo, magick, soffice, docproc-ooxml, ffprobe + // pdftotext, pdfinfo, magick, soffice, rsvg-convert, + // docproc-ooxml, ffprobe Idle time.Duration // Spec.Idle of the stream tools: ffmpeg, docproc-mail, // docproc-onenote, 7zz - Memory int64 // tool.Spec.MemoryLimit for every Spec Build builds + Memory int64 // tool.Spec.MemoryLimit for every Spec Build builds, but + // soffice's under LibreOfficeExec Env []string // tool.Spec.Env + LibreOfficeExec bool // soffice on the host through the exec runner, found as soffice; + // false runs it in picture.LibreOfficeImage, found as docker + LibreOfficeMemory int64 // soffice's tool.Spec.MemoryLimit under LibreOfficeExec; zero + // is none, below zero matches ErrRequest Concurrency int // a PDF's pages and an audio part's windows held; zero is one Document document.ImagesRequest // each stage's request, its own defaults where zero; Picture picture.Request // a part's own fields (Dir, Path, Kind, Stem) are the @@ -1053,13 +1071,14 @@ How the stages are built, and why: `settings` holds a run's settings as one flat JSON object, so a host that takes its bounds as JSON, rather than as `cmd/docproc`'s `DOCPROC_` variables, reads and validates them in one step and hands them to `stages.Build` and `dispatch.New` as they are. Each key is named for the -variable `cmd/docproc` reads it from, without the prefix and in snake case. It imports the -standard library and docproc's own packages alone. +variable `cmd/docproc` reads it from, without the prefix and in snake case, except +`soffice_memory`, which `cmd/docproc` doesn't read, since it runs soffice in its container. It +imports the standard library and docproc's own packages alone. ```go package settings type Settings struct { // one pointer field per key, nil when unset; the json tags are the keys - ToolMemory *int64; UnitTimeout, StreamIdle *time.Duration + ToolMemory, SofficeMemory *int64; UnitTimeout, StreamIdle *time.Duration MaxParts *int; MaxBytes *int64; MaxDepth *int BombRatio *float64; BombSize *uint64; ArchiveEntries *int ClaimRelease *time.Duration; Concurrency, PDFDPI *int; PDFText *bool; PDFMaxPixels *int64 @@ -1089,6 +1108,7 @@ The keys, their formats, where each lands, and whether it is required: ```text key JSON field required tool_memory whole bytes stages.Options.Memory yes +soffice_memory whole bytes stages.Options.LibreOfficeMemory no, tool_memory unit_timeout duration stages.Options.Timeout yes stream_idle duration stages.Options.Idle yes max_parts whole number dispatch.Limits.Parts yes @@ -1111,23 +1131,26 @@ audio_limit duration, over 4s audio.Request.Limit no, output_writes whole number, from 1 dispatch.Config.Puts no, 1 ``` -The library ships no policy, so every key but four is required, and zero is no bound: a required -key left unset is refused, never defaulted. The four optional keys are the ones whose library value -already has a default: an unset `pdf_dpi` assembles to `document.DefaultDPI`, 150; an unset -`audio_limit` to `audio.DefaultWindowLimit`, 30s; and an unset `concurrency` or `output_writes`, -the most outputs one part writes to the content store at once, to 1. A set `pdf_dpi`, +The library ships no policy, so every key but five is required, and zero is no bound: a required +key left unset is refused, never defaulted. An unset `soffice_memory` assembles to `tool_memory`'s +value, so soffice runs under the bound the host already chose for every tool; set, it is zero or +more, soffice's own bound when `LibreOfficeExec` runs it through the exec runner. The other four +optional keys are the ones whose library value already has a default: an unset `pdf_dpi` +assembles to `document.DefaultDPI`, 150; an unset `audio_limit` to `audio.DefaultWindowLimit`, +30s; and an unset `concurrency` or `output_writes`, the most outputs one part writes to the +content store at once, to 1. A set `pdf_dpi`, `concurrency`, or `output_writes` is at least 1, and a set `audio_limit` is over 4s, twice `audio.DefaultOverlap`, the shortest window the audio cutter takes. A duration is a Go duration string, such as `"90s"` or `"10m"`, as `time.ParseDuration` reads it, and a number in its place is refused; every value is zero or more, and `bomb_ratio` and `bomb_size` are both zero, for no bomb rule, or both above it. -`Run.Stages` sets only the fields the table names. `Exclude`, `Env`, `Inspect.Policy`, `Picture`, -`Document.PagesPerProcess`, and every other field of the video, audio, and ImageMagick requests -stay the zero value, each host's own to set before `Build`. A host passes `Run.Limits` and -`Release` to `dispatch.New` in its `Config`, and `OutputWrites` as its `Puts`, with the -`stages.Set`'s `Inspect` as its `Inspect`, so the dispatcher and the stages share one validated -value of the inspection options. +`Run.Stages` sets only the fields the table names. `Exclude`, `Env`, `LibreOfficeExec`, +`Inspect.Policy`, `Picture`, `Document.PagesPerProcess`, and every other field of the video, audio, +and ImageMagick requests stay the zero value, each host's own to set before `Build`. A host +passes `Run.Limits` and `Release` to `dispatch.New` in its `Config`, and `OutputWrites` as its +`Puts`, with the `stages.Set`'s `Inspect` as its `Inspect`, so the dispatcher and the stages share +one validated value of the inspection options. ## Content diff --git a/docs/development.md b/docs/development.md index 41bb6c53..cf7bbc19 100644 --- a/docs/development.md +++ b/docs/development.md @@ -21,8 +21,8 @@ tool under `tools/` pins its own. Tasks run from the repository root, `mise run run directory it writes, read back through `rundir`; and `integration`, below. Run it on your machine before each Go tag; CI doesn't. The other programs come from the host, each at its minimum or later: `gs`, `qpdf`, `pdfdetach`, `pdftotext`, `pdfinfo`, `ffmpeg`, `ffprobe`, - `magick`, `soffice`, util-linux's `prlimit`, and `docker`, which runs the compose harness and - pulls `audio.FFmpegImage` and `picture.LibreOfficeImage` for the tools tier. + `magick`, `soffice`, `rsvg-convert`, util-linux's `prlimit`, and `docker`, which runs the compose + harness and pulls `audio.FFmpegImage` and `picture.LibreOfficeImage` for the tools tier. - `integration`: the providers' live tiers, `integration:postgres` then `integration:storage`, every one even after one fails; CI runs it on a push to main that needs it and on demand. `integration:postgres` runs the postgres module's suite against the harness's PostgreSQL, and diff --git a/docs/packages.md b/docs/packages.md index 161bb7d5..f7d07b68 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -7,14 +7,14 @@ | `tool` | Runs a system tool behind one contract, through the exec runner (Linux) or the container runner (the docker CLI), each reporting a run's exit code, signal, and time bound, and applying a memory bound when one is set. | | `office`, `email`, `onenote` | The readers of docproc-ooxml, docproc-mail, and docproc-onenote, each decoding its tool's schema `"2"` JSON Lines; `email` also threads a store's messages. | | `document` | A PDF's pages rendered to PNG files through Ghostscript, with their text layer through pdftotext, its password requirement, form, and embedded files through qpdf and pdfdetach, and its metadata through pdfinfo. | -| `picture` | A TIFF's pages, and EMF, WMF, SVG, HEIC, WebP, and AVIF pictures, converted to PNG through ImageMagick and LibreOffice, and a picture's EXIF metadata read through ImageMagick. | +| `picture` | A TIFF's pages, and EMF, WMF, SVG, HEIC, WebP, and AVIF pictures, converted to PNG through ImageMagick, LibreOffice, and librsvg, and a picture's EXIF metadata read through ImageMagick. | | `audio` | Speech cut into windows that end in a silence, from one ffmpeg decode, and the audio plan record beside them; the source's metadata record from the same ffprobe run that finds its stream. | | `media` | A file's audio windows and its video frames, at its scene changes and at least every so often, from one ffmpeg run, and the video plan record beside them; the file's metadata record from the same ffprobe run that finds its streams. | | `sevenzip` | 7z, RAR4, RAR5, zstd, xz, cabinet, and a ZIP's entries of methods `archive/zip` doesn't read, listed and read through 7-Zip's 7zz. | | `dispatch` | The walk over an input's parts to their stages; the Stage contract and its error classes; the content store and its layout, and the index, each with a file and a memory implementation; the shapes of its events, parts, outputs, and warnings; and the Meta keys every stage sets and the record media types. It imports `route` and `inspect` alone. | | `dispatch/dispatchtest` | The Index and Content conformance suites, for every store, the module's own and a provider's, and the fixture stage a host's tests dispatch over. | | `stages` | `Build` and its `Options`: docproc's shipped wiring, each route's stage over its format package and tools, found on the host, under the host's run bounds and requests, with the one failure classification and each stage's identity. `cmd/docproc` is its first caller. | -| `settings` | A run's settings as one flat JSON object, each key named for its `DOCPROC_` variable: `Decode` reads and validates them, refusing every unset required key in one error, and `Settings.Assemble` returns their `Run`, the `stages.Options`, `dispatch.Limits`, and release and output-writes bounds a host passes `stages.Build` and `dispatch.New`, each unset optional key at its default. It imports no package outside the standard library and docproc. | +| `settings` | A run's settings as one flat JSON object, each key but `soffice_memory` named for its `DOCPROC_` variable: `Decode` reads and validates them, refusing every unset required key in one error, and `Settings.Assemble` returns their `Run`, the `stages.Options`, `dispatch.Limits`, and release and output-writes bounds a host passes `stages.Build` and `dispatch.New`, each unset optional key at its default. It imports no package outside the standard library and docproc. | | `rundir` | `cmd/docproc`'s run directory, read and written: `Open` to read it and `Create` to write it, its runs, the latest that ended, each run's manifest and record, its content store and the path of a content's file, its index, a quarantined part's kept file, and a run's report directory, `runs//report/`. One process writes a run directory. | | `rundir/schema` | The run directory's schema `"2"`: the shapes `cmd/docproc` writes and a reader decodes, a record line, a manifest, an input's file, and a time, each in UTC. It imports no docproc package but `dispatch` and `inspect`. | | `metadata` | The metadata records' shapes, one per format, each a JSON value under a versioned media type `dispatch` declares: `Office`, an office package's properties and the format it was converted from; `PDF`, a PDF's information dictionary, XMP metadata, and version; `Media`, an audio or video file's container format, duration, bit rate, and tags, and its streams; and `Picture`, a picture's EXIF capture time, camera, orientation, size, GPS position, and properties. It imports no docproc package but `dispatch`, so a reader decodes a record without compiling the stages. | diff --git a/office/test/main_test.go b/office/test/main_test.go index 8a4165b9..da9f19c5 100644 --- a/office/test/main_test.go +++ b/office/test/main_test.go @@ -77,6 +77,7 @@ func TestMain(m *testing.M) { "docproc-ooxml": withSettings(standin), "soffice": withSettings(sofficeStandin), "magick": withSettings(magickStandin), + "rsvg-convert": withSettings(rsvgStandin), "docker": withSettings(dockerStandin), }) } @@ -100,6 +101,15 @@ func lookupSetting(key string) (string, bool) { return v, ok } +func rsvgStandin(args []string) int { + if len(args) == 1 && args[0] == "--version" { + fmt.Println("rsvg-convert version 2.60.0") + return 0 + } + fmt.Fprintf(os.Stderr, "stand-in: office converts no SVG, got %q\n", args) + return 2 +} + func standin(args []string) int { if len(args) == 1 && args[0] == "--version" { schema := setting(schemaKey) @@ -377,7 +387,7 @@ func installStandin(t *testing.T, version string) *standins { s := &standins{t: t, links: map[string]string{}, log: filepath.Join(t.TempDir(), "runs.jsonl")} s.settings = map[string]string{versionKey: version, sofficeVersionKey: "26.8.1.1", magickVersionKey: "7.1.2-34", logKey: s.log} dir := t.TempDir() - for _, name := range []string{"docproc-ooxml", "soffice", "magick"} { + for _, name := range []string{"docproc-ooxml", "soffice", "magick", "rsvg-convert"} { s.links[name] = tooltest.Link(t, dir, name, s.settings) } return s @@ -472,7 +482,11 @@ func (s *standins) pictures() *picture.Converter { if err != nil { s.t.Fatal(err) } - c, err := picture.NewConverter(s.t.Context(), picture.Config{Magick: mg, LibreOffice: lo}) + rs, err := tool.NewExec(s.t.Context(), s.spec(picture.RsvgConvertSpec())) + if err != nil { + s.t.Fatal(err) + } + c, err := picture.NewConverter(s.t.Context(), picture.Config{Magick: mg, LibreOffice: lo, RsvgConvert: rs}) if err != nil { s.t.Fatal(err) } diff --git a/office/test/pictures_integration_test.go b/office/test/pictures_integration_test.go index 6363d629..38d16a13 100644 --- a/office/test/pictures_integration_test.go +++ b/office/test/pictures_integration_test.go @@ -101,8 +101,12 @@ func fullConverters(t *testing.T) (*office.Converter, *picture.Converter) { if err != nil { t.Fatalf("magick, a host prerequisite for TIFF: %v", err) } + rs, err := tool.NewExec(t.Context(), picture.RsvgConvertSpec()) + if err != nil { + t.Fatalf("rsvg-convert, a host prerequisite: %v", err) + } t.Logf("soffice %s in %s, magick %s", lo.Version(), picture.LibreOfficeImage, mg.Version()) - pc, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: lo}) + pc, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: lo, RsvgConvert: rs}) if err != nil { t.Fatal(err) } diff --git a/office/test/real_integration_test.go b/office/test/real_integration_test.go index 5538d1e8..abc7e307 100644 --- a/office/test/real_integration_test.go +++ b/office/test/real_integration_test.go @@ -90,8 +90,12 @@ func realConverter(t *testing.T) *office.Converter { if err != nil { t.Fatalf("magick, a host prerequisite: %v", err) } + rs, err := tool.NewExec(t.Context(), picture.RsvgConvertSpec()) + if err != nil { + t.Fatalf("rsvg-convert, a host prerequisite: %v", err) + } t.Logf("soffice %s and magick %s on the host", lo.Version(), mg.Version()) - pc, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: lo, Limits: hostLimits}) + pc, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: lo, RsvgConvert: rs, Limits: hostLimits}) if err != nil { t.Fatal(err) } diff --git a/picture/convert.go b/picture/convert.go index cad12d55..ef721d7b 100644 --- a/picture/convert.go +++ b/picture/convert.go @@ -56,17 +56,20 @@ func checkDensity(density int) (int, error) { return cmp.Or(density, DefaultDensity), nil } -// Config is what a Converter is built over: the Tools the caller built, both required, and +// Config is what a Converter is built over: the Tools the caller built, each required, and // magick's limits. type Config struct { - // Magick is ImageMagick's magick, typically built from MagickSpec. It converts TIFF, SVG, - // HEIC, WebP, and AVIF to PNG and trims an EMF's or WMF's rendered page to its picture. It is + // Magick is ImageMagick's magick, typically built from MagickSpec. It converts TIFF, HEIC, + // WebP, and AVIF to PNG and trims an EMF's or WMF's rendered page to its picture. It is // required. Magick *tool.Tool // LibreOffice is LibreOffice's soffice, typically built from LibreOfficeSpec through the // container runner in LibreOfficeImage. It renders EMF and WMF to PNG, with Magick, and runs // every RunLibreOffice. It is required. LibreOffice *tool.Tool + // RsvgConvert is librsvg's rsvg-convert, typically built from RsvgConvertSpec. It renders SVG + // to PNG. It is required. + RsvgConvert *tool.Tool // Limits are the -limit options every magick run carries; the zero value passes none. Limits Limits } @@ -76,17 +79,19 @@ type Config struct { type Converter struct { magick *tool.Tool libreoffice *tool.Tool + rsvg *tool.Tool limits []string readers map[route.Kind]bool } -// NewConverter builds a Converter over cfg's Tools. A nil Magick or LibreOffice is the caller's -// mistake, and panics naming the field; a negative limit is an error matching ErrRequest. It -// refuses a Magick older than MagickMinimum and a LibreOffice older than LibreOfficeMinimum, -// whatever minimum the Tool's own Spec declared, with a *tool.VersionError wrapping -// tool.ErrTooOld. It runs magick's format listing, magick -list format, once, under ctx, with -// cfg's limits, and keeps which of HEIC, WebP, and AVIF it reads: a kind it doesn't read is -// refused with ErrNoReader. A listing that fails is an error, and no Converter is built. +// NewConverter builds a Converter over cfg's Tools. A nil Magick, LibreOffice, or RsvgConvert is +// the caller's mistake, and panics naming the field; a negative limit is an error matching +// ErrRequest. It refuses a Magick older than MagickMinimum, a LibreOffice older than +// LibreOfficeMinimum, and an RsvgConvert older than RsvgConvertMinimum, whatever minimum the Tool's +// own Spec declared, with a *tool.VersionError wrapping tool.ErrTooOld. It runs magick's format +// listing, magick -list format, once, under ctx, with cfg's limits, and keeps which of HEIC, WebP, +// and AVIF it reads: a kind it doesn't read is refused with ErrNoReader. A listing that fails is an +// error, and no Converter is built. func NewConverter(ctx context.Context, cfg Config) (*Converter, error) { if cfg.Magick == nil { panic("picture: Config.Magick is nil") @@ -94,6 +99,9 @@ func NewConverter(ctx context.Context, cfg Config) (*Converter, error) { if cfg.LibreOffice == nil { panic("picture: Config.LibreOffice is nil") } + if cfg.RsvgConvert == nil { + panic("picture: Config.RsvgConvert is nil") + } limits, err := cfg.Limits.args() if err != nil { return nil, err @@ -104,11 +112,14 @@ func NewConverter(ctx context.Context, cfg Config) (*Converter, error) { if err := cfg.LibreOffice.AtLeast(LibreOfficeMinimum); err != nil { return nil, err } + if err := cfg.RsvgConvert.AtLeast(RsvgConvertMinimum); err != nil { + return nil, err + } readers, err := listReaders(ctx, cfg.Magick, limits) if err != nil { return nil, err } - return &Converter{magick: cfg.Magick, libreoffice: cfg.LibreOffice, limits: limits, readers: readers}, nil + return &Converter{magick: cfg.Magick, libreoffice: cfg.LibreOffice, rsvg: cfg.RsvgConvert, limits: limits, readers: readers}, nil } // Request is one picture's conversion to PNG, such as a standalone picture's. @@ -166,11 +177,11 @@ func checkStem(stem string) error { // req.Stem, "-page", the page's number from 1, and .png; any other kind to the one PNG named by // req.Stem and .png, through ConvertBatch, as a batch of one: an EMF or WMF rendered at // req.MetafileScale through soffice and trimmed to its picture through magick; an SVG rendered at -// req.Density through magick's librsvg and flattened onto white; a HEIC's primary image, or a -// WebP's or AVIF's first frame, through magick, turned upright by its stored orientation. It -// returns the PNGs' absolute paths in req.Dir, in page order, replacing an earlier conversion's of -// the same names. Every PNG is written without the time of the run, as every conversion is, so a -// picture converted twice is the same bytes. +// req.Density through rsvg-convert onto white; a HEIC's primary image, or a WebP's or AVIF's first +// frame, through magick, turned upright by its stored orientation. It returns the PNGs' absolute +// paths in req.Dir, in page order, replacing an earlier conversion's of the same names. Every PNG +// is written without the time of the run, as every conversion is, so a picture converted twice is +// the same bytes. // // A kind the package doesn't convert, a stem that isn't one, an empty req.Dir, a MetafileScale // below zero or above MaxMetafileScale, and a negative Density are each an error matching @@ -260,27 +271,27 @@ type Picture struct { // picture-* directory in b.Dir, which holds nothing else, so an SVG's relative references find // nothing, and its converter reads the copy; a metafile's copy is RunLibreOffice's, in its own // directory. A TIFF's first image is converted through magick, read as TIFF whatever its content, -// one run each. An SVG is rendered through magick's librsvg coder at b.Density and flattened onto -// white, one run each; librsvg runs no script and fetches nothing -// over a network, and reads no file the SVG names outside its directory, which holds the copy -// alone. A HEIC's primary image, or a WebP's or AVIF's first frame, is converted through magick, -// read through the coder its kind names whatever its content and turned upright by its stored -// orientation, one run each. Every EMF and WMF is rendered in one RunLibreOffice run, whose profile gives -// LibreOffice a British English locale, so Draw places each on an A4 page at b.MetafileScale times -// 96 dpi, and each page is trimmed to its picture through magick, one run each. Each writes PNG, so -// nothing is encoded lossily, and without the time of the run, so a picture converted twice is the -// same bytes both times. Each PNG is written beside its copy and then moved to its Picture's PNG, -// so no PNG is written in part. The picture-* directory is removed when ConvertBatch returns, +// one run each. An SVG is rendered through rsvg-convert, librsvg's own command, at b.Density onto +// white, one run each, working in the picture-* directory, so whatever it writes under its HOME, +// such as fontconfig's cache, is removed with it; librsvg runs no script and fetches nothing over a +// network, and reads no file the SVG names outside its directory, which holds the copy alone. A +// HEIC's primary image, or a WebP's or AVIF's first frame, is converted through magick, read +// through the coder its kind names whatever its content and turned upright by its stored +// orientation, one run each. Every EMF and WMF is rendered in one RunLibreOffice run, whose profile +// gives LibreOffice a British English locale, so Draw places each on an A4 page at b.MetafileScale +// times 96 dpi, and each page is trimmed to its picture through magick, one run each. Each writes +// PNG, so nothing is encoded lossily, and without the time of the run, so a picture converted twice +// is the same bytes both times. Each PNG is written beside its copy and then moved to its Picture's +// PNG, so no PNG is written in part. The picture-* directory is removed when ConvertBatch returns, // however it ends. // -// Every magick run carries the Converter's limits. A picture of no converted kind, a PNG stem that -// isn't a plain name, two pictures that share a PNG stem, an empty b.Dir, a MetafileScale -// CheckMetafileScale refuses, and a negative Density are each an error matching ErrRequest before -// anything runs, and a HEIC, WebP, or AVIF whose reader magick lacks one matching ErrNoReader. A -// conversion -// that fails, or writes no PNG, is an error naming the picture by its copy's name, with the -// converter's message, and the PNGs the batch wrote are removed. When ctx ends a run, the error -// matches ctx's, as every Tool run's does. +// Every magick run carries the Converter's limits; an rsvg-convert run takes none. A picture of no +// converted kind, a PNG stem that isn't a plain name, two pictures that share a PNG stem, an empty +// b.Dir, a MetafileScale CheckMetafileScale refuses, and a negative Density are each an error +// matching ErrRequest before anything runs, and a HEIC, WebP, or AVIF whose reader magick lacks one +// matching ErrNoReader. A conversion that fails, or writes no PNG, is an error naming the picture +// by its copy's name, with the converter's message, and the PNGs the batch wrote are removed. When +// ctx ends a run, the error matches ctx's, as every Tool run's does. func (c *Converter) ConvertBatch(ctx context.Context, b Batch) error { scale, err := CheckMetafileScale(b.MetafileScale) if err != nil { @@ -362,14 +373,7 @@ func (c *Converter) convertBatch(ctx context.Context, dir, work string, scale, d if err != nil { return err } - args := tiffArgs(s) - switch { - case p.Kind == route.SVG: - args = svgArgs(s, density) - case raster(p.Kind): - args = rasterArgs(s) - } - if err := c.runMagick(ctx, dir, s.name, args, s.png); err != nil { + if err := c.convertOne(ctx, dir, work, s, density); err != nil { return err } if err := place(s, written); err != nil { @@ -382,6 +386,16 @@ func (c *Converter) convertBatch(ctx context.Context, dir, work string, scale, d return c.metafilesToPNG(ctx, dir, scale, metafiles, written) } +func (c *Converter) convertOne(ctx context.Context, dir, work string, s staged, density int) error { + switch { + case s.Kind == route.SVG: + return c.run(ctx, c.rsvg, "rsvg-convert", work, s.name, svgArgs(s, density), s.png) + case raster(s.Kind): + return c.runMagick(ctx, dir, s.name, rasterArgs(s), s.png) + } + return c.runMagick(ctx, dir, s.name, tiffArgs(s), s.png) +} + func ownDir(work string, i int, p Picture) (staged, error) { own := filepath.Join(work, strconv.Itoa(i)) if err := os.Mkdir(own, 0o700); err != nil { @@ -418,18 +432,24 @@ func tiffArgs(s staged) []string { return slices.Concat([]string{"tiff:" + s.copied + "[0]"}, reproducible, []string{"png:" + s.png}) } +// See docs/api.md, "Running the tools". func svgArgs(s staged, density int) []string { - return slices.Concat( - []string{"-density", strconv.Itoa(density), "-background", "white", "rsvg:" + s.copied, "-alpha", "remove", "-alpha", "off"}, - reproducible, []string{"png:" + s.png}) + zoom := strconv.FormatFloat(float64(density)/cssDPI, 'f', -1, 64) + return []string{"--zoom=" + zoom, "--background-color=white", "--format=png", "--output=" + s.png, s.copied} } -const magickOutputLimit = 64 << 10 +const cssDPI = 96 + +const outputLimit = 64 << 10 func (c *Converter) runMagick(ctx context.Context, dir, name string, args []string, png string) error { - out := &cli.LimitedBuffer{Limit: magickOutputLimit} - err := c.magick.Run(ctx, tool.Invocation{ - Args: slices.Concat(c.limits, args), + return c.run(ctx, c.magick, "magick", dir, name, slices.Concat(c.limits, args), png) +} + +func (c *Converter) run(ctx context.Context, t *tool.Tool, program, dir, name string, args []string, png string) error { + out := &cli.LimitedBuffer{Limit: outputLimit} + err := t.Run(ctx, tool.Invocation{ + Args: args, Dir: dir, Stdout: out, Stderr: out, @@ -438,7 +458,7 @@ func (c *Converter) runMagick(ctx context.Context, dir, name string, args []stri err = checkPNG(png) } if err != nil { - err = fmt.Errorf("picture: magick: %s: %w", name, err) + err = fmt.Errorf("picture: %s: %s: %w", program, name, err) if msg := firstLine(out.String()); msg != "" { err = fmt.Errorf("%w: %s", err, msg) } diff --git a/picture/doc.go b/picture/doc.go index 19be3e5e..a1705a0c 100644 --- a/picture/doc.go +++ b/picture/doc.go @@ -3,10 +3,11 @@ // model. The package builds on every 64-bit platform, on the standard library and this module's // tool, route, and metadata packages; every program // it runs is a tool.Tool the caller built: ImageMagick's magick, MagickSpec declaring it, minimum -// 7.1, and LibreOffice's soffice, LibreOfficeSpec declaring it, minimum 24.2, which the container -// runner runs in LibreOfficeImage under its full lockdown. +// 7.1; LibreOffice's soffice, LibreOfficeSpec declaring it, minimum 24.2, which the container +// runner runs in LibreOfficeImage under its full lockdown; and librsvg's rsvg-convert, +// RsvgConvertSpec declaring it, minimum 2.58. // -// A Converter, built over a Config of the two Tools, both required, and magick's Limits, converts +// A Converter, built over a Config of the three Tools, each required, and magick's Limits, converts // the kinds a vision model decodes only once converted, route.VisionConverted's TIFF, EMF, WMF, // SVG, HEIC, WebP, and AVIF, to PNG, and no conversion encodes a picture lossily: each writes PNG, // without the time of the run, so a picture converted twice is the same bytes both times. Every @@ -25,16 +26,18 @@ // default and at most MaxMetafileScale, 8, the run's profile giving LibreOffice a British English // locale so the page is A4 whatever the system's paper, and the page is trimmed to the picture // through magick: what differs from the page corners' color. An SVG is rendered at a request's -// Density, DefaultDensity, 150 dpi, by default, through magick's rsvg coder, librsvg, named so that -// magick never falls back to its own renderer or a delegate, and flattened onto white. +// Density, DefaultDensity, 150 dpi, by default, onto white, through rsvg-convert, librsvg's own +// command, never through magick, whose own renderer, which it falls back to when built without +// librsvg, follows an SVG's references to files and URLs. An rsvg-convert run carries none of +// magick's Limits; the Tool's own bounds hold it. // // Each picture is converted in a directory of its own: it is copied, under its PNG's stem and its // kind's extension, into a fresh directory in the caller's working directory, which holds the copy // alone, and its converter reads the copy, so an SVG's relative references find nothing; the // directory is removed however the conversion ends, and the picture's own file is never changed. // librsvg runs no script, an SVG's script element and event handlers included, fetches no URL -// over a network, and loads no file but one beside the SVG it reads, which here is none: a -// script-bearing or referencing SVG converts to the PNG of what it draws itself. +// over a network, and loads no file but one beside the SVG it reads or below its directory, which +// here is none: a script-bearing or referencing SVG converts to the PNG of what it draws itself. // // RunLibreOffice is the one LibreOffice runner: it renders a batch's metafiles, and the office // package's legacy conversion runs it too. Each run works in a directory of its own in the @@ -68,7 +71,10 @@ // - [LibreOfficeSpec] declares LibreOffice's soffice for either runner's constructor. // - [LibreOfficeMinimum] is the oldest LibreOffice the package accepts, 24.2. // - [LibreOfficeImage] is the default image soffice runs in through the container runner. -// - [Config] is what a Converter is built over: magick, LibreOffice, and magick's limits. +// - [RsvgConvertSpec] declares librsvg's rsvg-convert for either runner's constructor. +// - [RsvgConvertMinimum] is the oldest rsvg-convert the package accepts, 2.58. +// - [Config] is what a Converter is built over: magick, LibreOffice, rsvg-convert, and magick's +// limits. // - [Limits] are ImageMagick's resource limits every magick run carries. // - [Converter] converts TIFF, EMF, WMF, SVG, HEIC, WebP, and AVIF to PNG. // - [NewConverter] builds a Converter over a Config, reading magick's format listing. diff --git a/picture/exif.go b/picture/exif.go index b1408c78..8ef9b52d 100644 --- a/picture/exif.go +++ b/picture/exif.go @@ -89,7 +89,7 @@ func (r *EXIFReader) Metadata(ctx context.Context, path string, kind route.Kind) } defer func() { _ = f.Close() }() out := &cappedWriter{limit: exifOutputLimit} - stderr := &cli.LimitedBuffer{Limit: magickOutputLimit} + stderr := &cli.LimitedBuffer{Limit: outputLimit} err = r.magick.Run(ctx, tool.Invocation{ Args: slices.Concat(r.limits, []string{coder + ":-[0]", "-format", exifFormat, "info:"}), Stdin: f, diff --git a/picture/spec.go b/picture/spec.go index df0432a1..46a8daff 100644 --- a/picture/spec.go +++ b/picture/spec.go @@ -50,3 +50,22 @@ func LibreOfficeSpec() tool.Spec { Minimum: LibreOfficeMinimum, } } + +// RsvgConvertMinimum is the oldest librsvg the package accepts: 2.58, the release Ubuntu 24.04 LTS +// ships, the oldest in a current long-term distribution, and after 2.56.3, which fixed +// CVE-2023-38633, a path traversal in the URL resolver that let an SVG's reference read a file +// outside its directory. The options the SVG conversion names are far older; Debian 13 ships 2.60. +const RsvgConvertMinimum = "2.58" + +// RsvgConvertSpec declares librsvg's rsvg-convert, minimum 2.58, for either runner's constructor. +// rsvg-convert --version prints "rsvg-convert version 2.60.0", and the pattern takes the dotted +// numbers after it. A caller that needs another program path or a KillAfter period sets them on +// the Spec returned. +func RsvgConvertSpec() tool.Spec { + return tool.Spec{ + Program: "rsvg-convert", + VersionArgs: []string{"--version"}, + VersionPattern: regexp.MustCompile(`rsvg-convert version (\d+(?:\.\d+)*)`), + Minimum: RsvgConvertMinimum, + } +} diff --git a/picture/test/convert_integration_test.go b/picture/test/convert_integration_test.go index efafdf68..3079b840 100644 --- a/picture/test/convert_integration_test.go +++ b/picture/test/convert_integration_test.go @@ -79,6 +79,15 @@ func (r *recorder) limited() int { return len(runs) } +func hostRsvg(t *testing.T) *tool.Tool { + t.Helper() + rs, err := tool.NewExec(t.Context(), picture.RsvgConvertSpec()) + if err != nil { + t.Fatal(err) + } + return rs +} + func hostConverter(t *testing.T) *picture.Converter { t.Helper() r, spec := newRecorder(t) @@ -90,7 +99,9 @@ func hostConverter(t *testing.T) *picture.Converter { if err != nil { t.Fatal(err) } - c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: so, Limits: hostLimits}) + rs := hostRsvg(t) + t.Logf("recorded: %s", rs.VersionLine()) + c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: so, RsvgConvert: rs, Limits: hostLimits}) if err != nil { t.Fatal(err) } @@ -169,9 +180,9 @@ func TestConvertSVGHost(t *testing.T) { width, height int }{ {"shapes.svg", 0, 500, 250}, - {"ink.svg", 0, 236, 118}, + {"ink.svg", 0, 237, 119}, {"shapes.svg", 300, 1000, 500}, - {"ink.svg", 300, 472, 236}, + {"ink.svg", 300, 473, 237}, } { t.Run(fmt.Sprintf("%s at %d", tc.name, tc.density), func(t *testing.T) { data, err := os.ReadFile(filepath.Join("testdata", tc.name)) @@ -197,8 +208,8 @@ func TestConvertSVGScriptHost(t *testing.T) { t.Fatal(err) } img := convertHost(t, c, "script-bearing.svg", data, 0) - if b := img.Bounds(); b.Dx() != 625 || b.Dy() != 187 { - t.Errorf("PNG is %dx%d, want 625x187, 400x120 at 150 dpi, rounded down", b.Dx(), b.Dy()) + if b := img.Bounds(); b.Dx() != 625 || b.Dy() != 188 { + t.Errorf("PNG is %dx%d, want 625x188, 400x120 at 150 dpi, rounded up", b.Dx(), b.Dy()) } if _, dark, _, translucent := census(img); dark == 0 || translucent != 0 { t.Errorf("PNG has %d dark and %d translucent pixels; want its text, opaque", dark, translucent) @@ -232,11 +243,12 @@ func TestConvertSVGReferencesHost(t *testing.T) { if err := os.WriteFile(elsewhere, red, 0o600); err != nil { t.Fatal(err) } - svg := fmt.Sprintf(``+ + svg := fmt.Sprintf(``+ ``+ ``+ - ``+ - ``, elsewhere, ln.Addr()) + ``+ + ``+ + ``, elsewhere, elsewhere, ln.Addr()) path := filepath.Join(beside, "references.svg") if err := os.WriteFile(path, []byte(svg), 0o600); err != nil { t.Fatal(err) @@ -287,12 +299,12 @@ func TestLimitsHost(t *testing.T) { if err != nil { t.Fatal(err) } - c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: so, Limits: picture.Limits{Width: 400}}) + c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: so, RsvgConvert: hostRsvg(t), Limits: picture.Limits{Width: 32}}) if err != nil { t.Fatal(err) } dir := t.TempDir() - pngs, err := c.ConvertPages(t.Context(), picture.Request{Dir: dir, Path: filepath.Join("testdata", "shapes.svg"), Kind: route.SVG, Stem: "shapes"}) + pngs, err := c.ConvertPages(t.Context(), picture.Request{Dir: dir, Path: filepath.Join("testdata", "scanned-g4.tiff"), Kind: route.TIFF, Stem: "scanned"}) if pngs != nil || err == nil || !strings.Contains(err.Error(), "width or height exceeds limit") { t.Fatalf("got %q, %v; want magick's width limit refusing the picture", pngs, err) } @@ -301,7 +313,7 @@ func TestLimitsHost(t *testing.T) { t.Errorf("working directory holds %q, want nothing", got) } for _, args := range r.runs() { - if !slices.Equal(args[:3], []string{"-limit", "width", "400"}) { + if !slices.Equal(args[:3], []string{"-limit", "width", "32"}) { t.Errorf("magick ran with %q, want the width limit first", args) } } diff --git a/picture/test/convert_test.go b/picture/test/convert_test.go index 26e562d7..afe927ac 100644 --- a/picture/test/convert_test.go +++ b/picture/test/convert_test.go @@ -105,8 +105,9 @@ func TestConvertSVG(t *testing.T) { density int want string }{ - {"the default density", "diagram.xml", 0, "150"}, - {"a set density", "diagram.svg", 300, "300"}, + {"the default density", "diagram.xml", 0, "1.5625"}, + {"a set density", "diagram.svg", 300, "3.125"}, + {"a density of no exact zoom", "diagram.svg", 100, "1.0416666666666667"}, } { t.Run(tc.desc, func(t *testing.T) { t.Parallel() @@ -131,16 +132,16 @@ func TestConvertSVG(t *testing.T) { t.Errorf("working directory holds %q, want the PNG alone", got) } all := st.runs() - if got := programs(all); !slices.Equal(got, []string{"magick"}) { - t.Fatalf("runs: got %q, want magick alone", got) + if got := programs(all); !slices.Equal(got, []string{"rsvg-convert"}) { + t.Fatalf("runs: got %q, want rsvg-convert alone", got) } - want := []string{`-density`, tc.want, `-background`, `white`, `rsvg:` + own(dir) + `drawing\.svg`, - `-alpha`, `remove`, `-alpha`, `off`, `-define`, `png:exclude-chunks=date,time`, `png:` + own(dir) + `drawing\.png`} + want := []string{`--zoom=` + regexp.QuoteMeta(tc.want), `--background-color=white`, `--format=png`, + `--output=` + own(dir) + `drawing\.png`, own(dir) + `drawing\.svg`} if !matchArgs(all[0].Args, want) { - t.Errorf("magick's arguments: got %q, want %q", all[0].Args, want) + t.Errorf("rsvg-convert's arguments: got %q, want %q", all[0].Args, want) } - if all[0].Dir != dir || all[0].Input != svgData { - t.Errorf("magick ran in %s on %q; want in %s on the SVG", all[0].Dir, all[0].Input, dir) + if !matchArgs([]string{all[0].Dir}, []string{regexp.QuoteMeta(dir) + `/picture-[^/]+`}) || all[0].Input != svgData { + t.Errorf("rsvg-convert ran in %s on %q; want in the picture directory in %s on the SVG", all[0].Dir, all[0].Input, dir) } }) } @@ -277,12 +278,15 @@ func TestConvertFails(t *testing.T) { {"the trim exits 1", emfData(), route.EMF, func(s *settings) { s.Fail = "magick: insufficient image data\n" }, "picture: magick: pic.emf: tool: magick: exit code 1: magick: insufficient image data"}, - {"magick exits 1 on an SVG", svgData, route.SVG, - func(s *settings) { s.Fail = "magick: unable to read image data\n" }, - "picture: magick: pic.svg: tool: magick: exit code 1: magick: unable to read image data"}, - {"magick writes no PNG", svgData, route.SVG, + {"rsvg-convert exits 1 on an SVG", svgData, route.SVG, + func(s *settings) { s.Fail = "Error reading SVG pic.svg: XML parse error\n" }, + "picture: rsvg-convert: pic.svg: tool: rsvg-convert: exit code 1: Error reading SVG pic.svg: XML parse error"}, + {"rsvg-convert writes no PNG", svgData, route.SVG, func(s *settings) { s.Raw = true }, - "picture: magick: pic.svg: pic.png isn't a PNG"}, + "picture: rsvg-convert: pic.svg: pic.png isn't a PNG"}, + {"magick writes no PNG", "RIFF\x10\x00\x00\x00WEBPVP8 ", route.WebP, + func(s *settings) { s.Raw = true }, + "picture: magick: pic.webp: pic.png isn't a PNG"}, } { t.Run(tc.desc, func(t *testing.T) { t.Parallel() @@ -350,7 +354,7 @@ func TestConvertBatch(t *testing.T) { t.Errorf("PNG directory holds %q, want %q", got, want) } all := st.runs() - if got, want := programs(all), []string{"magick", "magick", "magick", "soffice", "magick", "magick"}; !slices.Equal(got, want) { + if got, want := programs(all), []string{"magick", "rsvg-convert", "magick", "soffice", "magick", "magick"}; !slices.Equal(got, want) { t.Fatalf("runs: got %q, want %q", got, want) } at := func(i int, name string) string { @@ -359,8 +363,8 @@ func TestConvertBatch(t *testing.T) { if want := []string{`tiff:` + at(1, "b2.tiff") + `\[0\]`, `-define`, `png:exclude-chunks=date,time`, `png:` + at(1, "b2.png")}; !matchArgs(all[0].Args, want) { t.Errorf("b2's arguments: got %q, want %q", all[0].Args, want) } - if !matchArgs(all[1].Args[:5], []string{`-density`, `72`, `-background`, `white`, `rsvg:` + at(3, "d4.svg")}) { - t.Errorf("d4's arguments: got %q, want its copy read through rsvg at 72 dpi", all[1].Args) + if want := []string{`--zoom=0\.75`, `--background-color=white`, `--format=png`, `--output=` + at(3, "d4.png"), at(3, "d4.svg")}; !matchArgs(all[1].Args, want) { + t.Errorf("d4's arguments: got %q, want its copy rendered at 72 dpi, %q", all[1].Args, want) } if want := []string{`tiff:` + at(4, "e5.tiff") + `\[0\]`, `-define`, `png:exclude-chunks=date,time`, `png:` + at(4, "e5.png")}; !matchArgs(all[2].Args, want) { t.Errorf("e5's arguments: got %q, want %q", all[2].Args, want) @@ -493,9 +497,9 @@ func TestLimits(t *testing.T) { } magick := 0 for _, r := range st.runs() { - if r.Program == "soffice" { + if r.Program != "magick" { if slices.Contains(r.Args, "-limit") { - t.Errorf("soffice's run carries -limit: %q", r.Args) + t.Errorf("%s's run carries -limit: %q", r.Program, r.Args) } continue } @@ -504,8 +508,8 @@ func TestLimits(t *testing.T) { t.Errorf("magick run %q doesn't begin with the limits %q alone", r.Args, tc.want) } } - if magick != 5 { - t.Errorf("%d magick runs, want 5", magick) + if magick != 4 { + t.Errorf("%d magick runs, want 4", magick) } }) } @@ -517,6 +521,7 @@ func TestLimitsNegative(t *testing.T) { c, err := picture.NewConverter(t.Context(), picture.Config{ Magick: st.mustTool(picture.MagickSpec()), LibreOffice: st.mustTool(picture.LibreOfficeSpec()), + RsvgConvert: st.mustTool(picture.RsvgConvertSpec()), Limits: picture.Limits{Map: -1}, }) if c != nil || !errors.Is(err, picture.ErrRequest) || !strings.Contains(err.Error(), "picture: magick's map limit -1 is negative") { @@ -642,30 +647,37 @@ func TestCheckMetafileScale(t *testing.T) { func TestNewConverterVersion(t *testing.T) { t.Parallel() - old := newStandins(t, "7.0.11-14", func(s *settings) { s.SofficeVersion = "7.6.4.1" }) + old := newStandins(t, "7.0.11-14", func(s *settings) { s.SofficeVersion, s.RsvgVersion = "7.6.4.1", "2.56.4" }) current := newStandins(t, "7.1.2-34") lenient := picture.MagickSpec() lenient.Minimum = "6" lo := picture.LibreOfficeSpec() lo.Minimum = "7" + rsvg := picture.RsvgConvertSpec() + rsvg.Minimum = "2.40" var verr *tool.VersionError - _, err := picture.NewConverter(t.Context(), picture.Config{Magick: old.mustTool(lenient), LibreOffice: current.mustTool(lo)}) + _, err := picture.NewConverter(t.Context(), picture.Config{Magick: old.mustTool(lenient), LibreOffice: current.mustTool(lo), RsvgConvert: current.mustTool(rsvg)}) if !errors.As(err, &verr) || verr.Minimum != picture.MagickMinimum || !errors.Is(err, tool.ErrTooOld) { t.Errorf("NewConverter over magick 7.0.11-14 returned %v, want a VersionError of minimum %s", err, picture.MagickMinimum) } - _, err = picture.NewConverter(t.Context(), picture.Config{Magick: current.mustTool(lenient), LibreOffice: old.mustTool(lo)}) + _, err = picture.NewConverter(t.Context(), picture.Config{Magick: current.mustTool(lenient), LibreOffice: old.mustTool(lo), RsvgConvert: current.mustTool(rsvg)}) if !errors.As(err, &verr) || verr.Minimum != picture.LibreOfficeMinimum || !errors.Is(err, tool.ErrTooOld) { t.Errorf("NewConverter over soffice 7.6.4.1 returned %v, want a VersionError of minimum %s", err, picture.LibreOfficeMinimum) } + _, err = picture.NewConverter(t.Context(), picture.Config{Magick: current.mustTool(lenient), LibreOffice: current.mustTool(lo), RsvgConvert: old.mustTool(rsvg)}) + if !errors.As(err, &verr) || verr.Minimum != picture.RsvgConvertMinimum || !errors.Is(err, tool.ErrTooOld) { + t.Errorf("NewConverter over rsvg-convert 2.56.4 returned %v, want a VersionError of minimum %s", err, picture.RsvgConvertMinimum) + } } func TestNewConverterNil(t *testing.T) { t.Parallel() st := newStandins(t, "7.1.2-34") - mg, so := st.mustTool(picture.MagickSpec()), st.mustTool(picture.LibreOfficeSpec()) + mg, so, rs := st.mustTool(picture.MagickSpec()), st.mustTool(picture.LibreOfficeSpec()), st.mustTool(picture.RsvgConvertSpec()) for want, cfg := range map[string]picture.Config{ - "picture: Config.Magick is nil": {LibreOffice: so}, - "picture: Config.LibreOffice is nil": {Magick: mg}, + "picture: Config.Magick is nil": {LibreOffice: so, RsvgConvert: rs}, + "picture: Config.LibreOffice is nil": {Magick: mg, RsvgConvert: rs}, + "picture: Config.RsvgConvert is nil": {Magick: mg, LibreOffice: so}, } { func() { defer func() { @@ -679,6 +691,14 @@ func TestNewConverterNil(t *testing.T) { } } +func TestRsvgConvertSpec(t *testing.T) { + t.Parallel() + rs, err := newStandins(t, "7.1.2-34").tool(picture.RsvgConvertSpec()) + if err != nil || rs.Version().String() != "2.60.0" { + t.Errorf("NewExec(RsvgConvertSpec()) = %v, %v; want rsvg-convert 2.60.0", rs, err) + } +} + func TestLibreOfficeSpec(t *testing.T) { t.Parallel() so, err := newStandins(t, "7.1.2-34").tool(picture.LibreOfficeSpec()) diff --git a/picture/test/libreoffice_integration_test.go b/picture/test/libreoffice_integration_test.go index e966dd38..5fbb1bbf 100644 --- a/picture/test/libreoffice_integration_test.go +++ b/picture/test/libreoffice_integration_test.go @@ -50,7 +50,7 @@ func TestRunLibreOfficeConcurrent(t *testing.T) { if err != nil { t.Fatal(err) } - c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: so, Limits: hostLimits}) + c, err := picture.NewConverter(t.Context(), picture.Config{Magick: mg, LibreOffice: so, RsvgConvert: hostRsvg(t), Limits: hostLimits}) if err != nil { t.Fatal(err) } diff --git a/picture/test/main_test.go b/picture/test/main_test.go index a1d1d994..c806adc6 100644 --- a/picture/test/main_test.go +++ b/picture/test/main_test.go @@ -25,6 +25,7 @@ import ( type settings struct { MagickVersion string `json:"magick_version"` SofficeVersion string `json:"soffice_version"` + RsvgVersion string `json:"rsvg_version"` Log string `json:"log"` Fail string `json:"fail,omitzero"` Raw bool `json:"raw,omitzero"` @@ -55,8 +56,9 @@ const pngSignature = "\x89PNG\r\n\x1a\n" func TestMain(m *testing.M) { tooltest.Main(m, map[string]tooltest.Program{ - "magick": withSettings(magickStandin), - "soffice": withSettings(sofficeStandin), + "magick": withSettings(magickStandin), + "soffice": withSettings(sofficeStandin), + "rsvg-convert": withSettings(rsvgStandin), }) } @@ -254,6 +256,45 @@ func sofficeStandin(s settings, args []string) int { return 0 } +func rsvgStandin(s settings, args []string) int { + if len(args) == 1 && args[0] == "--version" { + fmt.Printf("rsvg-convert version %s\n", s.RsvgVersion) + return 0 + } + var output string + for _, a := range args { + if path, ok := strings.CutPrefix(a, "--output="); ok { + output = path + } + } + if len(args) == 0 || output == "" { + fmt.Fprintln(os.Stderr, "stand-in: want an output and an input") + return 2 + } + input, err := os.ReadFile(args[len(args)-1]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + if err := appendLog(s.Log, "rsvg-convert", args, string(input), ""); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + if s.Fail != "" { + fmt.Fprint(os.Stderr, s.Fail) + return 1 + } + out := convertedPrefix + string(input) + if !s.Raw { + out = pngSignature + out + } + if err := os.WriteFile(output, []byte(out), 0o644); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } + return 0 +} + type standinRun struct { Program string `json:"program"` Dir string `json:"dir"` @@ -283,12 +324,13 @@ type standins struct { t *testing.T magick string soffice string + rsvg string settings settings } func newStandins(t *testing.T, magickVersion string, opts ...func(*settings)) *standins { t.Helper() - s := settings{MagickVersion: magickVersion, SofficeVersion: "26.8.1.1", Log: filepath.Join(t.TempDir(), "runs.jsonl")} + s := settings{MagickVersion: magickVersion, SofficeVersion: "26.8.1.1", RsvgVersion: "2.60.0", Log: filepath.Join(t.TempDir(), "runs.jsonl")} for _, opt := range opts { opt(&s) } @@ -297,6 +339,7 @@ func newStandins(t *testing.T, magickVersion string, opts ...func(*settings)) *s t: t, magick: tooltest.Link(t, dir, "magick", s), soffice: tooltest.Link(t, dir, "soffice", s), + rsvg: tooltest.Link(t, dir, "rsvg-convert", s), settings: s, } } @@ -306,6 +349,7 @@ func (st *standins) set(f func(*settings)) { f(&st.settings) tooltest.Set(st.t, st.magick, st.settings) tooltest.Set(st.t, st.soffice, st.settings) + tooltest.Set(st.t, st.rsvg, st.settings) } func (st *standins) tool(spec tool.Spec) (*tool.Tool, error) { @@ -314,6 +358,8 @@ func (st *standins) tool(spec tool.Spec) (*tool.Tool, error) { spec.Program = st.magick case "soffice": spec.Program = st.soffice + case "rsvg-convert": + spec.Program = st.rsvg } return tool.NewExec(st.t.Context(), spec) } @@ -370,6 +416,7 @@ func standinConverter(t *testing.T, limits picture.Limits, opts ...func(*setting c, err := picture.NewConverter(t.Context(), picture.Config{ Magick: st.mustTool(picture.MagickSpec()), LibreOffice: st.mustTool(picture.LibreOfficeSpec()), + RsvgConvert: st.mustTool(picture.RsvgConvertSpec()), Limits: limits, }) if err != nil { diff --git a/picture/test/pages_test.go b/picture/test/pages_test.go index 97fc2746..04e57988 100644 --- a/picture/test/pages_test.go +++ b/picture/test/pages_test.go @@ -204,7 +204,9 @@ func TestConvertNoReader(t *testing.T) { func TestNewConverterListFails(t *testing.T) { t.Parallel() st := newStandins(t, "7.1.2-34", func(s *settings) { s.ListFail = "magick: unable to open module file\n" }) - c, err := picture.NewConverter(t.Context(), picture.Config{Magick: st.mustTool(picture.MagickSpec()), LibreOffice: st.mustTool(picture.LibreOfficeSpec())}) + c, err := picture.NewConverter(t.Context(), picture.Config{ + Magick: st.mustTool(picture.MagickSpec()), LibreOffice: st.mustTool(picture.LibreOfficeSpec()), RsvgConvert: st.mustTool(picture.RsvgConvertSpec()), + }) if c != nil || err == nil || !strings.Contains(err.Error(), "picture: magick's format listing: tool: magick: exit code 1: magick: unable to open module file") { t.Errorf("got %v, %v; want the listing's error", c, err) } diff --git a/picture/test/testdata/README.md b/picture/test/testdata/README.md index cbd4b031..486c0a56 100644 --- a/picture/test/testdata/README.md +++ b/picture/test/testdata/README.md @@ -28,7 +28,8 @@ They are committed and never generated in the check; `TestFixtureSums` checks th background, 320x160 CSS pixels, so 500x250 at 150 dpi. - `ink.svg`: an ink-like drawing in the form spike-ai-pipeline-onenote writes a page's ink: a viewBox in ink units of 0.01 mm, a size in millimetres, no background, and each stroke an open - path with round caps and joins. Four strokes write "hi", 40x20 mm, so 236x118 at 150 dpi. + path with round caps and joins. Four strokes write "hi", 40x20 mm, so 237x119 at 150 dpi, + rsvg-convert rounding 236.2 up. - `script-bearing.svg`: the security fixture of the test corpus that was then at `~/docs`, copied byte for byte; its manifest marked it generated for the pool, its license status verified, and redistributable. It carries an `onload` handler, an inline `