From 3404cf3340cbeda143a7aae7558abe7d5f2ace95 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 15:22:22 -0500 Subject: [PATCH 1/6] =?UTF-8?q?tool-packaging=20=C2=B7=20docproc=20=C2=B7?= =?UTF-8?q?=20slice=201:=20stages.Options.LibreOfficeExec=20runs=20soffice?= =?UTF-8?q?=20through=20the=20exec=20runner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stages.Options.LibreOfficeExec: set, Build looks up soffice on PATH and builds it with tool.NewExec under the same Memory, Timeout, and Env as every other exec-run tool; docker is never looked up for it, and soffice's Set.Tools row names its path. False, the zero value, keeps soffice in picture.LibreOfficeImage through the container runner. cmd/docproc is unchanged. - Unit tier: TestBuildLibreOfficeExec, over the tooltest stand-ins, records the lookups: soffice and never docker when set, docker and never soffice when unset, office and vision-converted wired or missing accordingly. - Integration tier: TestLibreOfficeExec builds the office route with the option through exec.LookPath, fails on a docker lookup, and prepares office/test/testdata/rtf/memo.rtf through the host's soffice. - README: the setting, and the correction that Build runs ffmpeg and ffprobe through the exec runner alone; the go get line names v0.12.0. docs/api.md lists the field. CHANGELOG: Unreleased becomes [v0.12.0] - 2026-11-29 with the setting under Added, an empty Unreleased above, and the compare links extended, as b2ccbba did. Not tagged. Decisions: - The option is a bool named for the program's package spec (LibreOfficeSpec/LibreOfficeImage) rather than a general per-tool runner choice: soffice is the only tool Build runs in a container, so nothing else needs one. - The integration test sets no memory bound: on this host soffice 26.8.1 fails to write its output under a 4 GiB RLIMIT_AS and succeeds under 8 GiB, so a bound in the test would hold a host-specific floor. mise run check passes. --- CHANGELOG.md | 18 ++++++- README.md | 11 ++-- docs/api.md | 2 + stages/stages.go | 8 +++ stages/test/libreoffice_integration_test.go | 58 ++++++++++++++++++++ stages/test/stages_test.go | 59 +++++++++++++++++++++ 6 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 stages/test/libreoffice_integration_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 29921d2..33fc5df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,21 @@ 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. The option's zero value keeps soffice in `picture.LibreOfficeImage`, so +a host that doesn't set it wires the same stages from the same tools. No stage identity changes, +`dispatch.Version` stays "1", and the run directory's schema stays "2". + +### Added + +- `stages.Options.LibreOfficeExec`, which runs soffice on the host through the exec runner, found + through the lookup as `soffice`, under the memory bound, 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`, as before. + ### Changed - Each package's unit tests sit in its `test/` directory as an external test package @@ -676,7 +691,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 117a8bb..dc0d464 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 @@ -107,8 +107,13 @@ 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. +`stages.Build` runs soffice 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, found through the lookup as `soffice` under the bounds every exec-run tool runs under, and +never looks up docker; soffice's row in `Set.Tools` names its path. It 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 diff --git a/docs/api.md b/docs/api.md index 724a035..224af68 100644 --- a/docs/api.md +++ b/docs/api.md @@ -797,6 +797,8 @@ type Options struct { // the zero value wires every route, with no bound // docproc-onenote, 7zz Memory int64 // tool.Spec.MemoryLimit for every Spec Build builds 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 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 diff --git a/stages/stages.go b/stages/stages.go index a640758..fe4e1ac 100644 --- a/stages/stages.go +++ b/stages/stages.go @@ -55,6 +55,11 @@ type Options struct { Memory int64 // Env is added to every exec-run tool's fixed environment, tool.Spec.Env. Env []string + // LibreOfficeExec runs soffice on the host through the exec runner, found through the lookup + // as soffice, under the bounds every exec-run tool runs under, and docker is never looked up + // for it. False runs soffice in picture.LibreOfficeImage through the container runner, found + // through the lookup as docker. + LibreOfficeExec bool // Concurrency is how many of a PDF's pages and an audio part's windows are held at once, // overriding the Document and Audio requests' own. Zero is 1, one at a time. Concurrency int @@ -226,6 +231,9 @@ func Build(ctx context.Context, lookup Lookup, opts Options) (Set, error) { continue } sp.MemoryLimit, sp.Env = opts.Memory, slices.Clone(opts.Env) + if sp.Program == "soffice" && opts.LibreOfficeExec { + sp.image = "" + } if sp.stream { sp.Idle = opts.Idle } else { diff --git a/stages/test/libreoffice_integration_test.go b/stages/test/libreoffice_integration_test.go new file mode 100644 index 0000000..3d397e0 --- /dev/null +++ b/stages/test/libreoffice_integration_test.go @@ -0,0 +1,58 @@ +//go:build linux && integration + +package stages_test + +import ( + "os/exec" + "slices" + "testing" + + "github.com/standards-lab/docproc/dispatch" + "github.com/standards-lab/docproc/internal/tooltest" + "github.com/standards-lab/docproc/route" + "github.com/standards-lab/docproc/stages" + "github.com/standards-lab/docproc/stages/internal/stagestest" +) + +func TestLibreOfficeExec(t *testing.T) { + soffice, err := exec.LookPath("soffice") + if err != nil { + t.Fatal(err) + } + lookup := func(program string) (string, error) { + if program == "docker" { + t.Errorf("looked up docker") + } + return exec.LookPath(program) + } + others := slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.Office }) + set, err := stages.Build(t.Context(), lookup, stages.Options{Exclude: others, LibreOfficeExec: true}) + if err != nil { + t.Fatal(err) + } + row := set.Rows[slices.Index(stages.Routes(), route.Office)] + if row.State != dispatch.Wired { + t.Fatalf("office: %s, %q; want wired", row.State, row.Reason) + } + for _, tl := range set.Tools { + if tl.Program == "soffice" && tl.From != soffice { + t.Errorf("soffice from %q, want %q", tl.From, soffice) + } + } + d, err := dispatch.New(dispatch.Config{ + Stages: set.Stages, Inspect: set.Inspect, Index: dispatch.NewMemoryIndex(0), Content: dispatch.NewMemoryContent(), + Puts: 1, Dir: t.TempDir(), + }) + if err != nil { + t.Fatal(err) + } + path := tooltest.Testdata(t, "office", "rtf", "memo.rtf") + for _, ev := range stagestest.DispatchAll(t, d, path, nil) { + if ev.Part.Depth != 0 { + continue + } + if ev.Outcome != dispatch.Prepared || len(ev.Outputs) == 0 { + t.Errorf("memo.rtf: %s, %q, %d outputs; want it prepared", ev.Outcome, ev.Reason, len(ev.Outputs)) + } + } +} diff --git a/stages/test/stages_test.go b/stages/test/stages_test.go index 93f2d20..8d0a59c 100644 --- a/stages/test/stages_test.go +++ b/stages/test/stages_test.go @@ -184,6 +184,65 @@ func TestBuildShim(t *testing.T) { } } +func TestBuildLibreOfficeExec(t *testing.T) { + t.Parallel() + soffice := []route.Route{route.Office, route.VisionConverted} + others := slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return slices.Contains(soffice, r) }) + for name, c := range map[string]struct { + exec bool + looked []string + want dispatch.State + }{ + "on the host": {exec: true, looked: []string{"magick", "soffice", "docproc-ooxml"}, want: dispatch.Wired}, + "in a container": {looked: []string{"magick", "docker", "docproc-ooxml"}, want: dispatch.Missing}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + links := map[string]string{ + "magick": tooltest.Link(t, t.TempDir(), "magick", stagestest.PictureSettings{Formats: stagestest.PictureListing}), + "soffice": tooltest.Link(t, t.TempDir(), "soffice", struct{}{}), + "docproc-ooxml": tooltest.Link(t, t.TempDir(), "docproc-ooxml", stagestest.EnvelopeSettings{}), + } + var looked []string + lookup := func(program string) (string, error) { + looked = append(looked, program) + if link, ok := links[program]; ok { + return link, nil + } + return "", errors.New("not here") + } + set, err := stages.Build(t.Context(), lookup, stages.Options{Exclude: others, LibreOfficeExec: c.exec}) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(looked, c.looked) { + t.Errorf("looked up %q, want %q", looked, c.looked) + } + for _, r := range soffice { + row := set.Rows[slices.Index(stages.Routes(), r)] + _, wired := set.Stages[r] + if row.State != c.want || wired != (c.want == dispatch.Wired) { + t.Errorf("%s: %s, %q, wired %t; want %s", r, row.State, row.Reason, wired, c.want) + } + if c.want == dispatch.Missing && !strings.Contains(row.Reason, "soffice: docker not found") { + t.Errorf("%s: reason %q, want docker not found", r, row.Reason) + } + } + for _, tl := range set.Tools { + if tl.Program != "soffice" { + continue + } + if c.exec && (tl.From != links["soffice"] || tl.Err != nil || tl.Version == "") { + t.Errorf("soffice %+v: want it built from %s", tl, links["soffice"]) + } + if !c.exec && (tl.From != "" || tl.Err == nil) { + t.Errorf("soffice %+v: want docker not found", tl) + } + } + }) + } +} + func TestBuildRefuses(t *testing.T) { t.Parallel() lookup := func(program string) (string, error) { From e8a7b4e9e75da9aabcb60b38fc80c1d5ebfef92f Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 15:43:21 -0500 Subject: [PATCH 2/6] =?UTF-8?q?tool-packaging=20=C2=B7=20docproc=20=C2=B7?= =?UTF-8?q?=20slice=201=20follow-up:=20stages.Options.LibreOfficeMemory=20?= =?UTF-8?q?bounds=20soffice=20run=20through=20the=20exec=20runner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stages.Options.LibreOfficeMemory: with LibreOfficeExec set, soffice's tool.Spec.MemoryLimit (its RLIMIT_AS through prlimit) in place of Memory; every other tool keeps Memory. No library default: zero is none, as Memory's zero is, and Build refuses one below zero through ErrRequest. With LibreOfficeExec unset, soffice stays under Memory in the container, as before. - The office and picture stages' configs carry LibreOfficeMemory beside Memory, and a part failure whose ExitError is soffice's names soffice's bound ("soffice: killed by SIGABRT under a 16 GiB memory bound"); other tools' failures keep naming Memory. - Unit tier: TestBuildLibreOfficeExec gains a case with Memory 8 GiB and LibreOfficeMemory 16 GiB, whose stand-in magick and soffice refuse their version commands unless their RLIMIT_AS is their own bound (PictureSettings.Limit, new SofficeSettings.Limit). TestLibreOfficeMemoryReason kills a stand-in soffice converting an EMF and reads the 16 GiB bound in the reason. TestBuildRefuses covers a negative soffice bound. Each fails with the soffice bound routed as Memory. - Integration tier: TestLibreOfficeExec runs with Memory 2 GiB and LibreOfficeMemory 8 GiB and prepares memo.rtf; at 4 GiB it fails, as measured. - README's memory-bound section, docs/api.md's Options, and the v0.12.0 CHANGELOG entry describe the bound. Decisions: - A sibling field, LibreOfficeMemory, beside the LibreOfficeExec bool rather than a struct: one added field, the bool from slice 1 kept, and the pair reads as one setting by name. - A nonzero LibreOfficeMemory with LibreOfficeExec unset is ignored, not refused: the container path's behavior stays unchanged, and the field documents it bounds soffice only through the exec runner. - The stage adapters pick soffice's bound by the ExitError's program name, one unexported helper (runMemory), rather than changing Classify's signature for every stage. mise run check passes. --- CHANGELOG.md | 14 +++-- README.md | 11 +++- docs/api.md | 5 +- stages/internal/adapter/classify.go | 7 +++ stages/internal/adapter/office.go | 17 +++--- stages/internal/adapter/picture.go | 19 ++++--- stages/internal/stagestest/picture.go | 46 +++++++++++++++- stages/stages.go | 34 ++++++++---- stages/test/libreoffice_integration_test.go | 4 +- stages/test/stages_test.go | 59 ++++++++++++++++++--- 10 files changed, 175 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33fc5df..def3b5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,10 +19,16 @@ a host that doesn't set it wires the same stages from the same tools. No stage i ### Added - `stages.Options.LibreOfficeExec`, which runs soffice on the host through the exec runner, found - through the lookup as `soffice`, under the memory bound, 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`, as before. + 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. ### Changed diff --git a/README.md b/README.md index dc0d464..6c05c33 100644 --- a/README.md +++ b/README.md @@ -110,8 +110,9 @@ runs no tool. `stages.Build` runs soffice 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, found through the lookup as `soffice` under the bounds every exec-run tool runs under, and -never looks up docker; soffice's row in `Set.Tools` names its path. It runs every other tool, +instead, found through the lookup as `soffice` under the bounds every exec-run tool runs under but +the memory bound, which is `stages.Options.LibreOfficeMemory`, and never looks up docker; soffice's +row in `Set.Tools` names its path. It 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`. @@ -124,4 +125,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". +soffice run through the exec runner takes its own bound, `stages.Options.LibreOfficeMemory`, in +place of `Memory`, with no default either: zero runs it with none. 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/docs/api.md b/docs/api.md index 224af68..b9f9784 100644 --- a/docs/api.md +++ b/docs/api.md @@ -795,10 +795,13 @@ type Options struct { // the zero value wires every route, with no bound // pdftotext, pdfinfo, magick, soffice, 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 diff --git a/stages/internal/adapter/classify.go b/stages/internal/adapter/classify.go index 8beefc2..ce15922 100644 --- a/stages/internal/adapter/classify.go +++ b/stages/internal/adapter/classify.go @@ -85,6 +85,13 @@ func PartErr(ctx context.Context, err error, memory int64) error { return &refused{reason: reason, err: err} } +func runMemory(err error, memory, soffice int64) int64 { + if exit, ok := errors.AsType[*tool.ExitError](err); ok && exit.Program == "soffice" { + return soffice + } + return memory +} + func unitWarning(ctx context.Context, program, where string, err error, memory int64) (dispatch.Warning, error) { content, reason := Classify(ctx, err, memory) if !content { diff --git a/stages/internal/adapter/office.go b/stages/internal/adapter/office.go index 5dd5d61..e2c206a 100644 --- a/stages/internal/adapter/office.go +++ b/stages/internal/adapter/office.go @@ -22,12 +22,14 @@ const officeVersion = "3" // OfficeConfig is what [NewOfficeStage] builds the office stage over: Converter is required; // Version is its tools' version lines; MetafileScale is a metafile's scale, zero for the default; -// and Memory is the tools' memory bound in bytes, zero for none. +// Memory is the other tools' memory bound in bytes, zero for none; and LibreOfficeMemory is +// soffice's, zero for none. type OfficeConfig struct { - Converter *office.Converter - Version string - MetafileScale int - Memory int64 + Converter *office.Converter + Version string + MetafileScale int + Memory int64 + LibreOfficeMemory int64 } // OfficeStage is the office stage, route.Office's: a document's and each sheet's Markdown, each @@ -36,6 +38,7 @@ type OfficeStage struct { converter *office.Converter scale int memory int64 + soffice int64 id dispatch.Identity } @@ -45,7 +48,7 @@ func NewOfficeStage(cfg OfficeConfig) *OfficeStage { panic("stages: OfficeConfig.Converter is nil") } scale := cmp.Or(cfg.MetafileScale, picture.DefaultMetafileScale) - return &OfficeStage{converter: cfg.Converter, scale: scale, memory: cfg.Memory, id: identity("office", cfg.Version, struct { + return &OfficeStage{converter: cfg.Converter, scale: scale, memory: cfg.Memory, soffice: cfg.LibreOfficeMemory, id: identity("office", cfg.Version, struct { Stage string `json:"stage"` Schema string `json:"schema"` Request office.Request `json:"request"` @@ -70,7 +73,7 @@ func (s *OfficeStage) Prepare(ctx context.Context, p dispatch.Part, dir string) } if err != nil { if !errors.Is(err, errStopped) { - yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("office stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("office stage: %w", err), runMemory(err, s.memory, s.soffice))) } return } diff --git a/stages/internal/adapter/picture.go b/stages/internal/adapter/picture.go index be562ae..f975d16 100644 --- a/stages/internal/adapter/picture.go +++ b/stages/internal/adapter/picture.go @@ -17,13 +17,15 @@ const pictureVersion = "2" // PictureConfig is what [NewPictureStage] builds the picture stage over: Converter and EXIF are // required; Version is its tools' version lines; Request is every picture's conversion request; -// and Memory is the tools' memory bound in bytes, zero for none. +// Memory is magick's memory bound in bytes, zero for none; and LibreOfficeMemory is soffice's, zero +// for none. type PictureConfig struct { - Converter *picture.Converter - EXIF exifReader - Version string - Request picture.Request - Memory int64 + Converter *picture.Converter + EXIF exifReader + Version string + Request picture.Request + Memory int64 + LibreOfficeMemory int64 } // PictureStage is the picture stage, route.VisionConverted's: a picture's metadata record, then @@ -33,6 +35,7 @@ type PictureStage struct { exif exifReader request picture.Request memory int64 + soffice int64 id dispatch.Identity } @@ -48,7 +51,7 @@ func NewPictureStage(cfg PictureConfig) *PictureStage { MetafileScale: cmp.Or(cfg.Request.MetafileScale, picture.DefaultMetafileScale), Density: cmp.Or(cfg.Request.Density, picture.DefaultDensity), } - return &PictureStage{converter: cfg.Converter, exif: cfg.EXIF, request: req, memory: cfg.Memory, id: identity("picture", cfg.Version, struct { + return &PictureStage{converter: cfg.Converter, exif: cfg.EXIF, request: req, memory: cfg.Memory, soffice: cfg.LibreOfficeMemory, id: identity("picture", cfg.Version, struct { Stage string `json:"stage"` Request picture.Request `json:"request"` }{pictureVersion, req})} @@ -71,7 +74,7 @@ func (s *PictureStage) Prepare(ctx context.Context, p dispatch.Part, dir string) yield(dispatch.Item{}, fmt.Errorf("picture stage: %w: %w", dispatch.ErrNoProcessor, err)) return case err != nil: - yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("picture stage: %w", err), s.memory)) + yield(dispatch.Item{}, PartErr(ctx, fmt.Errorf("picture stage: %w", err), runMemory(err, s.memory, s.soffice))) return } if !pictureMetadata(ctx, "picture", s.exif, p, s.memory, yield) { diff --git a/stages/internal/stagestest/picture.go b/stages/internal/stagestest/picture.go index dc7675d..e8db151 100644 --- a/stages/internal/stagestest/picture.go +++ b/stages/internal/stagestest/picture.go @@ -10,6 +10,7 @@ import ( "os" "slices" "strings" + "syscall" "testing" "github.com/standards-lab/docproc/internal/tooltest" @@ -19,13 +20,22 @@ import ( "github.com/standards-lab/docproc/tool" ) -// PictureSettings is a stand-in magick's settings: its format listing, the pages it converts, and -// the EXIF it reports by its input's SHA-256, or fails with. +// PictureSettings is a stand-in magick's settings: its format listing, the pages it converts, the +// EXIF it reports by its input's SHA-256, or fails with, and the RLIMIT_AS its version command +// requires, any when zero. type PictureSettings struct { Formats string `json:"formats"` Pages int `json:"pages"` EXIF map[string]string `json:"exif,omitzero"` EXIFFail string `json:"exif_fail,omitzero"` + Limit int64 `json:"limit,omitzero"` +} + +// SofficeSettings is a stand-in soffice's settings: the RLIMIT_AS its version command requires, +// any when zero, and the signal a conversion dies by; without one, a conversion exits 2. +type SofficeSettings struct { + Limit int64 `json:"limit,omitzero"` + Signal string `json:"signal,omitzero"` } // PictureListing is a magick format listing that reads AVIF, HEIC, and WebP. @@ -45,6 +55,10 @@ func pictureStandin(r tooltest.Run) int { args := r.Args switch { case len(args) == 1 && args[0] == "-version": + if err := requireLimit(settings.Limit); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } fmt.Println("Version: ImageMagick 7.1.2-34 Q16-HDRI x86_64 https://imagemagick.org") return 0 case slices.Equal(args, []string{"-list", "format", "null:"}): @@ -74,14 +88,42 @@ func pictureStandin(r tooltest.Run) int { } func sofficeStandin(r tooltest.Run) int { + var settings SofficeSettings + if err := r.Settings(&settings); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } if len(r.Args) == 1 && r.Args[0] == "--version" { + if err := requireLimit(settings.Limit); err != nil { + fmt.Fprintln(os.Stderr, err) + return 2 + } fmt.Println("LibreOffice 26.8.1.1 680(Build:1)") return 0 } + if settings.Signal != "" { + err := syscall.Exec("/bin/sh", []string{"sh", "-c", "kill -s " + settings.Signal + " $$"}, nil) + fmt.Fprintln(os.Stderr, err) + return 2 + } fmt.Fprintf(os.Stderr, "stand-in: unexpected arguments %q\n", r.Args) return 2 } +func requireLimit(want int64) error { + if want == 0 { + return nil + } + var l syscall.Rlimit + if err := syscall.Getrlimit(syscall.RLIMIT_AS, &l); err != nil { + return err + } + if l.Cur != uint64(want) { + return fmt.Errorf("stand-in: RLIMIT_AS %d, want %d", l.Cur, want) + } + return nil +} + const noEXIF = "1 1\n" func pictureEXIFStandin(settings PictureSettings) int { diff --git a/stages/stages.go b/stages/stages.go index fe4e1ac..f885d5b 100644 --- a/stages/stages.go +++ b/stages/stages.go @@ -49,17 +49,20 @@ type Options struct { // docproc-mail, docproc-onenote, and 7zz, each ended once it writes nothing for this long. // Zero is none. Idle time.Duration - // Memory is every tool's memory bound in bytes, tool.Spec.MemoryLimit: the exec runner's - // RLIMIT_AS through prlimit, which must then be on PATH, and the container runner's --memory. - // Zero is none. + // Memory is every tool's memory bound in bytes, tool.Spec.MemoryLimit, but soffice's when + // LibreOfficeExec is set: the exec runner's RLIMIT_AS through prlimit, which must then be on + // PATH, and the container runner's --memory. Zero is none. Memory int64 // Env is added to every exec-run tool's fixed environment, tool.Spec.Env. Env []string // LibreOfficeExec runs soffice on the host through the exec runner, found through the lookup - // as soffice, under the bounds every exec-run tool runs under, and docker is never looked up - // for it. False runs soffice in picture.LibreOfficeImage through the container runner, found - // through the lookup as docker. + // as soffice, under LibreOfficeMemory and the other bounds every exec-run tool runs under, and + // docker is never looked up for it. False runs soffice in picture.LibreOfficeImage through the + // container runner, found through the lookup as docker, under Memory. LibreOfficeExec bool + // LibreOfficeMemory is soffice's memory bound in bytes when LibreOfficeExec is set, its + // RLIMIT_AS through prlimit, which must then be on PATH, in place of Memory. Zero is none. + LibreOfficeMemory int64 // Concurrency is how many of a PDF's pages and an audio part's windows are held at once, // overriding the Document and Audio requests' own. Zero is 1, one at a time. Concurrency int @@ -91,6 +94,8 @@ func (o Options) check() error { return refuse("a time bound is below zero") case o.Memory < 0: return refuse("memory bound %d is below zero", o.Memory) + case o.LibreOfficeMemory < 0: + return refuse("soffice's memory bound %d is below zero", o.LibreOfficeMemory) case o.Concurrency < 0: return refuse("concurrency %d is below zero", o.Concurrency) case o.Document.DPI < 0, o.Document.MaxPixels < 0, o.Document.PagesPerProcess < 0: @@ -111,6 +116,13 @@ func (o Options) check() error { func (o Options) concurrency() int { return max(o.Concurrency, 1) } +func (o Options) sofficeMemory() int64 { + if o.LibreOfficeExec { + return o.LibreOfficeMemory + } + return o.Memory +} + // Set is what Build made of the host: the stages to register, every tool it tried, in a fixed // order, one row per route, in [Routes] order, and the inspection options it validated, for // dispatch.Config.Inspect. @@ -231,8 +243,11 @@ func Build(ctx context.Context, lookup Lookup, opts Options) (Set, error) { continue } sp.MemoryLimit, sp.Env = opts.Memory, slices.Clone(opts.Env) - if sp.Program == "soffice" && opts.LibreOfficeExec { - sp.image = "" + if sp.Program == "soffice" { + sp.MemoryLimit = opts.sofficeMemory() + if opts.LibreOfficeExec { + sp.image = "" + } } if sp.stream { sp.Idle = opts.Idle @@ -349,7 +364,7 @@ func buildOffice(ctx context.Context, t tools, opts Options) (dispatch.Stage, er } return adapter.NewOfficeStage(adapter.OfficeConfig{ Converter: c, Version: adapter.Versions(of, t["soffice"], t["magick"]), - MetafileScale: opts.Picture.MetafileScale, Memory: opts.Memory, + MetafileScale: opts.Picture.MetafileScale, Memory: opts.Memory, LibreOfficeMemory: opts.sofficeMemory(), }), nil } @@ -364,6 +379,7 @@ func buildPicture(ctx context.Context, t tools, opts Options) (dispatch.Stage, e } return adapter.NewPictureStage(adapter.PictureConfig{ Converter: p, EXIF: r, Version: adapter.Versions(t["magick"], t["soffice"]), Request: opts.Picture, Memory: opts.Memory, + LibreOfficeMemory: opts.sofficeMemory(), }), nil } diff --git a/stages/test/libreoffice_integration_test.go b/stages/test/libreoffice_integration_test.go index 3d397e0..d8f71b6 100644 --- a/stages/test/libreoffice_integration_test.go +++ b/stages/test/libreoffice_integration_test.go @@ -26,7 +26,9 @@ func TestLibreOfficeExec(t *testing.T) { return exec.LookPath(program) } others := slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.Office }) - set, err := stages.Build(t.Context(), lookup, stages.Options{Exclude: others, LibreOfficeExec: true}) + set, err := stages.Build(t.Context(), lookup, stages.Options{ + Exclude: others, LibreOfficeExec: true, Memory: 2 << 30, LibreOfficeMemory: 8 << 30, + }) if err != nil { t.Fatal(err) } diff --git a/stages/test/stages_test.go b/stages/test/stages_test.go index 8d0a59c..912fc07 100644 --- a/stages/test/stages_test.go +++ b/stages/test/stages_test.go @@ -188,19 +188,25 @@ func TestBuildLibreOfficeExec(t *testing.T) { t.Parallel() soffice := []route.Route{route.Office, route.VisionConverted} others := slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return slices.Contains(soffice, r) }) + host := []string{"magick", "soffice", "docproc-ooxml"} for name, c := range map[string]struct { - exec bool + opts stages.Options looked []string want dispatch.State }{ - "on the host": {exec: true, looked: []string{"magick", "soffice", "docproc-ooxml"}, want: dispatch.Wired}, + "on the host": {opts: stages.Options{LibreOfficeExec: true}, looked: host, want: dispatch.Wired}, + "on the host under its own bound": { + opts: stages.Options{LibreOfficeExec: true, Memory: tooltest.Memory, LibreOfficeMemory: 2 * tooltest.Memory}, + looked: host, want: dispatch.Wired, + }, "in a container": {looked: []string{"magick", "docker", "docproc-ooxml"}, want: dispatch.Missing}, } { t.Run(name, func(t *testing.T) { t.Parallel() links := map[string]string{ - "magick": tooltest.Link(t, t.TempDir(), "magick", stagestest.PictureSettings{Formats: stagestest.PictureListing}), - "soffice": tooltest.Link(t, t.TempDir(), "soffice", struct{}{}), + "magick": tooltest.Link(t, t.TempDir(), "magick", + stagestest.PictureSettings{Formats: stagestest.PictureListing, Limit: c.opts.Memory}), + "soffice": tooltest.Link(t, t.TempDir(), "soffice", stagestest.SofficeSettings{Limit: c.opts.LibreOfficeMemory}), "docproc-ooxml": tooltest.Link(t, t.TempDir(), "docproc-ooxml", stagestest.EnvelopeSettings{}), } var looked []string @@ -211,7 +217,9 @@ func TestBuildLibreOfficeExec(t *testing.T) { } return "", errors.New("not here") } - set, err := stages.Build(t.Context(), lookup, stages.Options{Exclude: others, LibreOfficeExec: c.exec}) + opts := c.opts + opts.Exclude = others + set, err := stages.Build(t.Context(), lookup, opts) if err != nil { t.Fatal(err) } @@ -232,10 +240,10 @@ func TestBuildLibreOfficeExec(t *testing.T) { if tl.Program != "soffice" { continue } - if c.exec && (tl.From != links["soffice"] || tl.Err != nil || tl.Version == "") { + if c.opts.LibreOfficeExec && (tl.From != links["soffice"] || tl.Err != nil || tl.Version == "") { t.Errorf("soffice %+v: want it built from %s", tl, links["soffice"]) } - if !c.exec && (tl.From != "" || tl.Err == nil) { + if !c.opts.LibreOfficeExec && (tl.From != "" || tl.Err == nil) { t.Errorf("soffice %+v: want docker not found", tl) } } @@ -243,6 +251,42 @@ func TestBuildLibreOfficeExec(t *testing.T) { } } +func TestLibreOfficeMemoryReason(t *testing.T) { + t.Parallel() + links := map[string]string{ + "magick": tooltest.Link(t, t.TempDir(), "magick", stagestest.PictureSettings{Formats: stagestest.PictureListing}), + "soffice": tooltest.Link(t, t.TempDir(), "soffice", stagestest.SofficeSettings{Signal: "ABRT"}), + } + lookup := func(program string) (string, error) { + if link, ok := links[program]; ok { + return link, nil + } + return "", errors.New("not here") + } + others := slices.DeleteFunc(stages.Routes(), func(r route.Route) bool { return r == route.VisionConverted }) + set, err := stages.Build(t.Context(), lookup, stages.Options{ + Exclude: others, LibreOfficeExec: true, Memory: tooltest.Memory, LibreOfficeMemory: 2 * tooltest.Memory, + }) + if err != nil { + t.Fatal(err) + } + d, err := dispatch.New(dispatch.Config{ + Stages: set.Stages, Inspect: set.Inspect, Index: dispatch.NewMemoryIndex(0), Content: dispatch.NewMemoryContent(), + Puts: 1, Dir: t.TempDir(), + }) + if err != nil { + t.Fatal(err) + } + emf := make([]byte, 44) + emf[0] = 1 + copy(emf[40:], " EMF") + events := stagestest.DispatchAll(t, d, stagestest.Input(t, "diagram.emf", string(emf)), nil) + want := "soffice: killed by SIGABRT under a 16 GiB memory bound" + if len(events) != 1 || events[0].Outcome != dispatch.Failed || !strings.Contains(events[0].Reason, want) { + t.Errorf("events %+v, want one failed with %q", events, want) + } +} + func TestBuildRefuses(t *testing.T) { t.Parallel() lookup := func(program string) (string, error) { @@ -254,6 +298,7 @@ func TestBuildRefuses(t *testing.T) { "a negative timeout": {Timeout: -time.Second}, "a negative idle bound": {Idle: -time.Second}, "a negative memory bound": {Memory: -1}, + "a negative soffice bound": {LibreOfficeMemory: -1}, "a negative concurrency": {Concurrency: -1}, "a negative DPI": {Document: document.ImagesRequest{DPI: -1}}, "a negative MaxPixels": {Document: document.ImagesRequest{MaxPixels: -1}}, From d638bd3a2733eafea210a6b182673596699c1911 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 15:51:59 -0500 Subject: [PATCH 3/6] =?UTF-8?q?tool-packaging=20=C2=B7=20docproc=20=C2=B7?= =?UTF-8?q?=20slice=202:=20settings=20key=20soffice=5Fmemory=20assembles?= =?UTF-8?q?=20into=20stages.Options.LibreOfficeMemory?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit settings gains the optional key soffice_memory (Settings.SofficeMemory), whole bytes, zero or more, assembled into stages.Options.LibreOfficeMemory. Unset, it assembles to tool_memory's value, so soffice keeps the bound the host already chose; below zero it is refused by name as a KeyError. Decisions: - cmd/docproc reads each DOCPROC_ variable through its own readEnv line, not generically, and runs soffice in its container (LibreOfficeExec unset), so the key would be inert there. cmd/docproc gains no DOCPROC_SOFFICE_MEMORY; settings/doc.go, docs/api.md, and docs/packages.md say soffice_memory is the one key it doesn't read. - Run.Stages' doc names LibreOfficeExec among the options left to the host. - cmd/docproc's checked build requires docproc v0.11.0, so its bounds tests are unchanged; once it requires v0.12.0, its expected starting Run carries LibreOfficeMemory equal to Memory. mise run check passes. --- CHANGELOG.md | 5 +++ docs/api.md | 20 +++++++----- docs/packages.md | 2 +- settings/doc.go | 10 ++++-- settings/run.go | 15 ++++----- settings/settings.go | 8 +++-- settings/test/run_test.go | 56 +++++++++++++++++++++++----------- settings/test/settings_test.go | 16 ++++++---- 8 files changed, 88 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index def3b5f..9a211d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,11 @@ a host that doesn't set it wires the same stages from the same tools. No stage i 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 diff --git a/docs/api.md b/docs/api.md index b9f9784..89d0548 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1058,13 +1058,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 +variable `cmd/docproc` reads it from, without the prefix and in snake case, but `soffice_memory`, +which `cmd/docproc`, running soffice in its container, doesn't read. 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 @@ -1094,6 +1095,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 @@ -1116,9 +1118,11 @@ 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 +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 @@ -1127,9 +1131,9 @@ string, such as `"90s"` or `"10m"`, as `time.ParseDuration` reads it, and a numb 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 +`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. diff --git a/docs/packages.md b/docs/packages.md index 161bb7d..303bc27 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -14,7 +14,7 @@ | `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/settings/doc.go b/settings/doc.go index 666ff8c..ea73ce0 100644 --- a/settings/doc.go +++ b/settings/doc.go @@ -2,15 +2,17 @@ // this module's own packages alone: the run bounds a host passes stages.Build in its Options, // the dispatch.Limits and the release and output-writes bounds it passes dispatch.New in its // Config, and the PDF, video, ImageMagick, and audio bounds of the stages' requests. Each key is -// named for the DOCPROC_ variable cmd/docproc reads it from, without the prefix and in snake case. +// named for the DOCPROC_ variable cmd/docproc reads it from, without the prefix and in snake case, +// but soffice_memory, which cmd/docproc, running soffice in its container, doesn't read. // // [Decode] reads the settings from JSON and validates them in one step; [Settings.Validate] // validates settings a Go caller built, each unset key nil, set with new, such as new(int64(0)). -// The library sets no bound of its own, so every key but four is required, and zero is no bound: +// The library sets no bound of its own, so every key but five is required, and zero is no bound: // a required key left unset is refused, every such key named in one error. // // 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 @@ -37,7 +39,9 @@ // both zero, for no bomb rule, or both above it. An optional key, unset, takes the default the // table names: document.DefaultDPI, 150 DPI, and audio.DefaultWindowLimit, 30s; set, it is at // least 1, or for audio_limit over twice audio.DefaultOverlap, 4s, the shortest window the audio -// cutter takes. A refusal names its key and wraps [ErrRequest], as does input that isn't one JSON +// cutter takes. soffice_memory, unset, takes 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 +// stages.Options.LibreOfficeExec runs it through the exec runner. A refusal names its key and wraps [ErrRequest], as does input that isn't one JSON // object, an unknown key, and a value of the wrong JSON type; a refused value is a [KeyError]. // // [Settings.Assemble] validates the settings and assembles them into a [Run], in the shapes the diff --git a/settings/run.go b/settings/run.go index bfdc6e2..52fc368 100644 --- a/settings/run.go +++ b/settings/run.go @@ -18,8 +18,8 @@ import ( type Run struct { // Stages carry the run bounds, the inspection options, the concurrency, and the PDF, video, // ImageMagick, and audio bounds. Every option no key covers is the zero value, the host's to - // set: Exclude, Env, Inspect.Policy, Picture, and every other field of the Document, Video, - // Magick, and Audio requests. + // set: Exclude, Env, LibreOfficeExec, Inspect.Policy, Picture, and every other field of the + // Document, Video, Magick, and Audio requests. Stages stages.Options // Limits are each dispatch's caps: dispatch.Config.Limits. Limits dispatch.Limits @@ -32,8 +32,8 @@ type Run struct { } // Assemble validates s, as Validate does, and returns its Run, each optional key left unset at -// its default: PDFDPI at document.DefaultDPI, AudioLimit at audio.DefaultWindowLimit, and -// Concurrency and OutputWrites at 1. Settings Validate refuses are refused with its error, which +// its default: SofficeMemory at ToolMemory, PDFDPI at document.DefaultDPI, AudioLimit at +// audio.DefaultWindowLimit, and Concurrency and OutputWrites at 1. Settings Validate refuses are refused with its error, which // wraps ErrRequest. func (s Settings) Assemble() (Run, error) { if err := s.Validate(); err != nil { @@ -41,9 +41,10 @@ func (s Settings) Assemble() (Run, error) { } return Run{ Stages: stages.Options{ - Memory: *s.ToolMemory, - Timeout: *s.UnitTimeout, - Idle: *s.StreamIdle, + Memory: *s.ToolMemory, + LibreOfficeMemory: or(s.SofficeMemory, *s.ToolMemory), + Timeout: *s.UnitTimeout, + Idle: *s.StreamIdle, Inspect: inspect.Options{ BombRatio: *s.BombRatio, BombSize: *s.BombSize, diff --git a/settings/settings.go b/settings/settings.go index 439fef6..870a812 100644 --- a/settings/settings.go +++ b/settings/settings.go @@ -38,11 +38,14 @@ func (e *KeyError) Error() string { // Unwrap returns ErrRequest. func (e *KeyError) Unwrap() error { return ErrRequest } -// Settings are a run's settings, one key for each, nil when unset. Every key but PDFDPI, -// Concurrency, AudioLimit, and OutputWrites is required, and zero is no bound. +// Settings are a run's settings, one key for each, nil when unset. Every key but SofficeMemory, +// PDFDPI, Concurrency, AudioLimit, and OutputWrites is required, and zero is no bound. type Settings struct { // ToolMemory is every tool's memory bound in bytes, tool_memory. ToolMemory *int64 `json:"tool_memory"` + // SofficeMemory is soffice's memory bound in bytes when it runs through the exec runner, + // soffice_memory; unset, it is ToolMemory. + SofficeMemory *int64 `json:"soffice_memory"` // UnitTimeout is a unit run's bound, unit_timeout. UnitTimeout *time.Duration `json:"unit_timeout"` // StreamIdle is a stream run's idle bound, stream_idle. @@ -182,6 +185,7 @@ func (s Settings) Validate() error { } errs = append(errs, atLeast("tool_memory", s.ToolMemory, 0), + atLeast("soffice_memory", s.SofficeMemory, 0), atLeast("unit_timeout", s.UnitTimeout, 0), atLeast("stream_idle", s.StreamIdle, 0), atLeast("max_parts", s.MaxParts, 0), diff --git a/settings/test/run_test.go b/settings/test/run_test.go index 6a4753f..13e8ece 100644 --- a/settings/test/run_test.go +++ b/settings/test/run_test.go @@ -33,15 +33,16 @@ func TestAssemble(t *testing.T) { want := func(concurrency, dpi int, limit time.Duration, outputWrites int) settings.Run { return settings.Run{ Stages: stages.Options{ - Memory: 2 << 30, - Timeout: 10 * time.Minute, - Idle: 2 * time.Minute, - Inspect: inspect.Options{BombRatio: 1000, BombSize: 1 << 30, Entries: 100_000}, - Concurrency: concurrency, - Document: document.ImagesRequest{DPI: dpi, Text: true, MaxPixels: 64_000_000}, - Video: media.Request{MaxSide: 2048}, - Magick: picture.Limits{Area: 256_000_000, Memory: 1 << 30, Map: 2 << 30, Disk: 8 << 30}, - Audio: audio.Request{Limit: limit}, + Memory: 2 << 30, + LibreOfficeMemory: 2 << 30, + Timeout: 10 * time.Minute, + Idle: 2 * time.Minute, + Inspect: inspect.Options{BombRatio: 1000, BombSize: 1 << 30, Entries: 100_000}, + Concurrency: concurrency, + Document: document.ImagesRequest{DPI: dpi, Text: true, MaxPixels: 64_000_000}, + Video: media.Request{MaxSide: 2048}, + Magick: picture.Limits{Area: 256_000_000, Memory: 1 << 30, Map: 2 << 30, Disk: 8 << 30}, + Audio: audio.Request{Limit: limit}, }, Limits: dispatch.Limits{Parts: 100_000, Bytes: 32 << 30, Depth: 16}, Release: 10 * time.Second, @@ -53,23 +54,43 @@ func TestAssemble(t *testing.T) { want settings.Run }{ "every key set": { - map[string]any{"concurrency": 4, "pdf_dpi": 300, "audio_limit": "45s", "output_writes": 3}, - want(4, 300, 45*time.Second, 3), + map[string]any{"concurrency": 4, "pdf_dpi": 300, "audio_limit": "45s", "output_writes": 3, "soffice_memory": 8 << 30}, + func() settings.Run { + r := want(4, 300, 45*time.Second, 3) + r.Stages.LibreOfficeMemory = 8 << 30 + return r + }(), }, "every optional key unset": { - map[string]any{"concurrency": unset{}, "pdf_dpi": unset{}, "audio_limit": unset{}, "output_writes": unset{}}, + map[string]any{"concurrency": unset{}, "pdf_dpi": unset{}, "audio_limit": unset{}, "output_writes": unset{}, "soffice_memory": unset{}}, want(1, document.DefaultDPI, audio.DefaultWindowLimit, 1), }, "optional keys null": { - map[string]any{"concurrency": nil, "pdf_dpi": nil, "audio_limit": nil, "output_writes": nil}, + map[string]any{"concurrency": nil, "pdf_dpi": nil, "audio_limit": nil, "output_writes": nil, "soffice_memory": nil}, want(1, 150, 30*time.Second, 1), }, + "soffice_memory unset takes tool_memory": { + map[string]any{"tool_memory": 512 << 20, "soffice_memory": unset{}}, + func() settings.Run { + r := want(1, 150, 30*time.Second, 1) + r.Stages.Memory, r.Stages.LibreOfficeMemory = 512<<20, 512<<20 + return r + }(), + }, + "soffice_memory zero with tool_memory set": { + map[string]any{"soffice_memory": 0}, + func() settings.Run { + r := want(1, 150, 30*time.Second, 1) + r.Stages.LibreOfficeMemory = 0 + return r + }(), + }, "zero bounds": { map[string]any{"concurrency": 4, "pdf_dpi": 300, "audio_limit": "45s", "output_writes": 3, "tool_memory": 0, "unit_timeout": "0s", "max_bytes": 0, "bomb_ratio": 0, "bomb_size": 0, "pdf_text": false}, func() settings.Run { r := want(4, 300, 45*time.Second, 3) - r.Stages.Memory, r.Stages.Timeout, r.Limits.Bytes = 0, 0, 0 + r.Stages.Memory, r.Stages.LibreOfficeMemory, r.Stages.Timeout, r.Limits.Bytes = 0, 0, 0, 0 r.Stages.Inspect.BombRatio, r.Stages.Inspect.BombSize = 0, 0 r.Stages.Document.Text = false return r @@ -88,9 +109,10 @@ func TestAssembleRefuses(t *testing.T) { t.Fatal(err) } for name, edit := range map[string]func(*settings.Settings){ - "the zero value": func(s *settings.Settings) { *s = settings.Settings{} }, - "a required key nil": func(s *settings.Settings) { s.MagickDisk = nil }, - "output_writes zero": func(s *settings.Settings) { s.OutputWrites = new(0) }, + "the zero value": func(s *settings.Settings) { *s = settings.Settings{} }, + "a required key nil": func(s *settings.Settings) { s.MagickDisk = nil }, + "output_writes zero": func(s *settings.Settings) { s.OutputWrites = new(0) }, + "soffice_memory negative": func(s *settings.Settings) { s.SofficeMemory = new(int64(-1)) }, } { c := s edit(&c) diff --git a/settings/test/settings_test.go b/settings/test/settings_test.go index ecc8d4b..6c05339 100644 --- a/settings/test/settings_test.go +++ b/settings/test/settings_test.go @@ -108,7 +108,9 @@ func TestDecodeAccepts(t *testing.T) { "audio_limit unset": {"audio_limit": unset{}}, "concurrency unset": {"concurrency": unset{}}, "output_writes unset": {"output_writes": unset{}}, - "every optional key null": {"pdf_dpi": nil, "audio_limit": nil, "concurrency": nil, "output_writes": nil}, + "soffice_memory unset": {"soffice_memory": unset{}}, + "soffice_memory zero": {"soffice_memory": 0}, + "every optional key null": {"pdf_dpi": nil, "audio_limit": nil, "concurrency": nil, "output_writes": nil, "soffice_memory": nil}, "audio_limit just over 4s": {"audio_limit": "4001ms"}, } { s, err := settings.Decode(encode(t, edits)) @@ -166,6 +168,7 @@ func TestDecodeRefusesValues(t *testing.T) { "bomb_size below zero": {map[string]any{"bomb_size": -1}, []string{"bomb_size", "zero or more"}}, "a negative duration": {map[string]any{"unit_timeout": "-1s"}, []string{"unit_timeout", "below zero"}}, "a negative size": {map[string]any{"tool_memory": -1}, []string{"tool_memory", "below zero"}}, + "soffice_memory below zero": {map[string]any{"soffice_memory": -1}, []string{"soffice_memory", "below zero"}}, "a negative count": {map[string]any{"archive_entries": -1}, []string{"archive_entries", "below zero"}}, "a negative ratio": {map[string]any{"bomb_ratio": -0.5}, []string{"bomb_ratio"}}, "bomb_ratio alone zero": {map[string]any{"bomb_ratio": 0}, []string{"bomb_ratio and bomb_size"}}, @@ -245,11 +248,12 @@ func TestKeyError(t *testing.T) { keys []string reason string }{ - "a value below zero": {map[string]any{"max_bytes": -1}, []string{"max_bytes"}, "-1 is below zero"}, - "a value below 1": {map[string]any{"output_writes": 0}, []string{"output_writes"}, "0 is below 1"}, - "the bomb rule half off": {map[string]any{"bomb_size": 0}, []string{"bomb_ratio", "bomb_size"}, "set both above zero, or both to zero for no bomb rule"}, - "a wrong JSON type": {map[string]any{"pdf_text": "true"}, []string{"pdf_text"}, "a JSON string isn't a boolean"}, - "an unparsable duration": {map[string]any{"unit_timeout": "soon"}, []string{"unit_timeout"}, `"soon" isn't a duration, such as "90s" or "10m"`}, + "a value below zero": {map[string]any{"max_bytes": -1}, []string{"max_bytes"}, "-1 is below zero"}, + "soffice_memory below zero": {map[string]any{"soffice_memory": -1}, []string{"soffice_memory"}, "-1 is below zero"}, + "a value below 1": {map[string]any{"output_writes": 0}, []string{"output_writes"}, "0 is below 1"}, + "the bomb rule half off": {map[string]any{"bomb_size": 0}, []string{"bomb_ratio", "bomb_size"}, "set both above zero, or both to zero for no bomb rule"}, + "a wrong JSON type": {map[string]any{"pdf_text": "true"}, []string{"pdf_text"}, "a JSON string isn't a boolean"}, + "an unparsable duration": {map[string]any{"unit_timeout": "soon"}, []string{"unit_timeout"}, `"soon" isn't a duration, such as "90s" or "10m"`}, } { _, err := settings.Decode(encode(t, tc.edits)) var ke *settings.KeyError From c1ba0562b405c9ee084634d8d343e8b3330fdcb7 Mon Sep 17 00:00:00 2001 From: Jaime Still Date: Sun, 29 Nov 2026 16:30:39 -0500 Subject: [PATCH 4/6] =?UTF-8?q?tool-packaging=20=C2=B7=20docproc=20=C2=B7?= =?UTF-8?q?=20slice=204=20follow-up:=20SVG=20renders=20through=20rsvg-conv?= =?UTF-8?q?ert,=20never=20magick?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit picture renders an SVG through librsvg's own command, rsvg-convert, in place of magick's rsvg: coder, which a magick built without librsvg (Debian 13's 7.1.1-43) reads through ImageMagick's MSVG renderer, following to local files and URLs. The run is --zoom= --background-color=white --format=png --output= : zoom scales CSS pixels exactly as magick's -density did (pixel-identical on shapes.svg, and physical units stay true), the output is opaque RGB on white, and librsvg writes no time chunk, so it is reproducible with no magick step. picture.RsvgConvertSpec and RsvgConvertMinimum (2.58) declare the tool; picture.Config.RsvgConvert is required and version-checked through Tool.AtLeast in NewConverter. stages.Build builds it through the exec runner, as magick, and the office and vision-converted routes require it, their rows carrying its version line last. Decisions: - Minimum 2.58: Ubuntu 24.04 LTS's, the rule LibreOfficeMinimum follows, and after 2.56.3's fix of CVE-2023-38633 (path traversal through an SVG reference). Debian 13's 2.60.0 passes; the flags used are far older. - Config.RsvgConvert is required rather than optional, so the office route, whose converter is the same picture.Converter, requires rsvg-convert too though it hands SVGs on as stored. An optional field would have needed a refusal of its own; ErrNoReader names magick. - rsvg-convert works in the batch's picture-* directory (its HOME under the exec runner), since fontconfig writes its cache under HOME and the caller's directory must hold the PNG alone. - rsvg-convert rounds a fractional size up where magick rounded down (ink.svg 237x119, was 236x118; script-bearing.svg 625x188, was 625x187); the integration expectations follow. - magick's Limits no longer bound SVG rendering; the Tool's memory bound and timeout do, and --unlimited is never passed. TestLimitsHost now proves the width limit on a TIFF. - The office and picture stage identities change through their Version lines; the v0.12.0 CHANGELOG says so. - CI installs no magick (the tools tier runs on the developer's machine), so docs/development.md's host prerequisites gain rsvg-convert and no workflow changes. cmd/docproc's module stays on v0.11.0 and is unchanged; once it requires v0.12.0 it finds rsvg-convert through exec.LookPath as it finds magick, and docs/command.md's unit-timeout list will need it then. mise run check passes; go test -tags integration over picture, office, and stages passes, including the hostile SVG (an absolute path, a file:// URL, and an http URL render nothing and open no connection). --- CHANGELOG.md | 24 ++++- README.md | 7 ++ docs/api.md | 17 ++- docs/development.md | 4 +- docs/packages.md | 2 +- office/test/main_test.go | 18 +++- office/test/pictures_integration_test.go | 6 +- office/test/real_integration_test.go | 6 +- picture/convert.go | 101 +++++++++++------- picture/doc.go | 22 ++-- picture/exif.go | 2 +- picture/spec.go | 19 ++++ picture/test/convert_integration_test.go | 34 ++++-- picture/test/convert_test.go | 74 ++++++++----- picture/test/libreoffice_integration_test.go | 2 +- picture/test/main_test.go | 53 ++++++++- picture/test/pages_test.go | 4 +- picture/test/testdata/README.md | 3 +- stages/internal/adapter/adapter.go | 4 +- .../adapter/test/adapter_integration_test.go | 2 +- stages/internal/stagestest/doc.go | 2 +- stages/internal/stagestest/picture.go | 46 +++++++- stages/internal/stagestest/programs.go | 1 + stages/stages.go | 12 ++- stages/test/stages_test.go | 64 ++++++++++- 25 files changed, 408 insertions(+), 121 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a211d9..ba5c3a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,12 +12,23 @@ tool under `tools/` keeps its own. ## [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. The option's zero value keeps soffice in `picture.LibreOfficeImage`, so -a host that doesn't set it wires the same stages from the same tools. No stage identity changes, -`dispatch.Version` stays "1", and the run directory's schema stays "2". +office and picture routes, and renders SVG through librsvg's rsvg-convert in place of magick, so +an SVG's references to files and URLs are never followed whatever magick was built with. The +option's zero value keeps soffice in `picture.LibreOfficeImage`. The office and picture stages +require rsvg-convert, and their identities change, each `Version` carrying 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 @@ -37,6 +48,13 @@ a host that doesn't set it wires the same stages from the same tools. No stage i ### 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 diff --git a/README.md b/README.md index 6c05c33..51ac397 100644 --- a/README.md +++ b/README.md @@ -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,6 +108,12 @@ 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. +rsvg-convert renders every SVG; magick never does, since a magick built without librsvg, as +Debian 13's is, renders through its own MSVG renderer, which follows an SVG's references to files +and URLs. Its minimum, 2.58, is Ubuntu 24.04 LTS's, after 2.56.3 fixed CVE-2023-38633, a path +traversal through an SVG's reference. The office stage runs no rsvg-convert, an Office document's +SVGs being handed on as stored, but the picture package's Converter it shares requires one. + `stages.Build` runs soffice 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 diff --git a/docs/api.md b/docs/api.md index 89d0548..28fade0 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,7 +804,8 @@ 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, but diff --git a/docs/development.md b/docs/development.md index 41bb6c5..cf7bbc1 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 303bc27..f7d07b6 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -7,7 +7,7 @@ | `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. | diff --git a/office/test/main_test.go b/office/test/main_test.go index 8a4165b..da9f19c 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 6363d62..38d16a1 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 5538d1e..abc7e30 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 cad12d5..bbb1475 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,14 +79,16 @@ 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 +// 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. @@ -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,10 +177,9 @@ 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 +// 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 @@ -260,11 +270,12 @@ 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 +// 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 @@ -273,14 +284,13 @@ type Picture struct { // 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 +372,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 +385,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 +431,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 +457,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 19be3e5..a1705a0 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 b1408c7..8ef9b52 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 df0432a..46a8daf 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 efafdf6..3079b84 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 26e562d..afe927a 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 e966dd3..5fbb1bb 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 a1d1d99..c806adc 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 97fc274..04e5798 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 cbd4b03..486c0a5 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 `