mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
fix(pdf): bound page selections, form fields and archive filenames by the request
This commit is contained in:
2
go.mod
2
go.mod
@@ -11,7 +11,7 @@ require (
|
||||
github.com/dlclark/regexp2/v2 v2.13.1
|
||||
github.com/gomarkdown/markdown v0.0.0-20261117205700-e8c6d33a8b6c
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gotenberg/litho v0.0.17
|
||||
github.com/gotenberg/litho v0.0.18
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8
|
||||
github.com/labstack/echo/v5 v5.4.6
|
||||
github.com/labstack/gommon v0.5.0
|
||||
|
||||
4
go.sum
4
go.sum
@@ -118,8 +118,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
||||
github.com/gotenberg/litho v0.0.17 h1:ns3VFYd8Y0Pc6HTlK2X5uLQfndjVJOSYOuLg2xox1h0=
|
||||
github.com/gotenberg/litho v0.0.17/go.mod h1:BYtOYpLnI02JzPt4FbeozPgTz1OrCPyyao5kAoEpn4Y=
|
||||
github.com/gotenberg/litho v0.0.18 h1:bvi8EQ9BUTtQYL2Tbll+1uxqQ0meSwOvltXVvH06zxk=
|
||||
github.com/gotenberg/litho v0.0.18/go.mod h1:BYtOYpLnI02JzPt4FbeozPgTz1OrCPyyao5kAoEpn4Y=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
|
||||
|
||||
@@ -54,6 +54,12 @@ func (ctx *Context) extractArchive(fh *multipart.FileHeader, cfg archiveConfig,
|
||||
allowance := &unpackAllowance{remaining: cfg.maxRatio * max(fh.Size, 1)}
|
||||
|
||||
for _, f := range r.File {
|
||||
// The request's deadline stops the unpacking between entries.
|
||||
err = ctx.Err()
|
||||
if err != nil {
|
||||
return fmt.Errorf("unpack archive: %w", err)
|
||||
}
|
||||
|
||||
if !f.Mode().IsRegular() || isMacOSMetadata(f.Name) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package api
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"maps"
|
||||
@@ -192,3 +194,43 @@ func TestNewContext_Archives(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestNewContext_ArchiveStopsWhenCancelled pins that unpacking an archive
|
||||
// stops once the request is cancelled.
|
||||
func TestNewContext_ArchiveStopsWhenCancelled(t *testing.T) {
|
||||
archive := buildZip(t, zipEntry{name: "index.html", content: []byte("<html></html>")})
|
||||
|
||||
body := new(bytes.Buffer)
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreateFormFile(ArchivesFormField, "site.zip")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = part.Write(archive)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = writer.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reqCtx, cancelReq := context.WithCancel(context.Background())
|
||||
cancelReq()
|
||||
|
||||
req := httptest.NewRequestWithContext(reqCtx, http.MethodPost, "/forms/chromium/convert/html", body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
fs := gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll))
|
||||
|
||||
ctx, cancel, err := newContext(echo.New().NewContext(req, httptest.NewRecorder()), slog.New(slog.DiscardHandler), fs, 10*time.Second, 0, downloadFromConfig{disable: true}, archiveConfig{maxEntries: 10, maxRatio: 100})
|
||||
t.Cleanup(cancel)
|
||||
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("newContext err = %v, want context.Canceled", err)
|
||||
}
|
||||
|
||||
if len(ctx.files) != 0 {
|
||||
t.Fatalf("files = %v, want none unpacked", ctx.files)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,11 @@ type Context struct {
|
||||
// twin rather than wherever its numbered name would land.
|
||||
fileBase map[string]string
|
||||
|
||||
// nextSuffix maps a filename to the number uniqueFilename tries first
|
||||
// the next time it collides, so the numbers a name already took are not
|
||||
// probed again.
|
||||
nextSuffix map[string]int
|
||||
|
||||
// fields records the value form fields the route reads, and fileFields
|
||||
// the multipart fields files arrived under, so that
|
||||
// [FormData.RejectUnknown] tells the fields the route does not know.
|
||||
@@ -1032,26 +1037,31 @@ func safeExt(filename string) string {
|
||||
}
|
||||
|
||||
// uniqueFilename returns filename, or a numbered variant of it when the
|
||||
// request already carries a file by that name.
|
||||
// request already carries a file by that name: "doc.pdf", then "doc (2).pdf",
|
||||
// "doc (3).pdf" and so on.
|
||||
//
|
||||
// Uploads are keyed by their sanitized original filename, so two files sharing
|
||||
// one name used to collide: the second overwrote the first and only one
|
||||
// reached the conversion, while both stayed on disk and counted against the
|
||||
// body limit. Sanitizing strips directories, so "a/doc.pdf" and "b/doc.pdf"
|
||||
// collide too.
|
||||
// Uploads are keyed by their sanitized original filename, and sanitizing
|
||||
// strips directories, so "a/doc.pdf" and "b/doc.pdf" share a name. Each name
|
||||
// resumes from the number it last reached, so N files of one name cost N
|
||||
// probes, not N²/2.
|
||||
func (ctx *Context) uniqueFilename(filename string) string {
|
||||
_, exists := ctx.files[filename]
|
||||
if !exists {
|
||||
return filename
|
||||
}
|
||||
|
||||
if ctx.nextSuffix == nil {
|
||||
ctx.nextSuffix = make(map[string]int)
|
||||
}
|
||||
|
||||
ext := filepath.Ext(filename)
|
||||
stem := strings.TrimSuffix(filename, ext)
|
||||
|
||||
for i := 2; ; i++ {
|
||||
for i := max(ctx.nextSuffix[filename], 2); ; i++ {
|
||||
candidate := fmt.Sprintf("%s (%d)%s", stem, i, ext)
|
||||
_, exists = ctx.files[candidate]
|
||||
if !exists {
|
||||
ctx.nextSuffix[filename] = i + 1
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
@@ -976,6 +976,63 @@ func TestNewContext_DuplicateFilenamesAreBothKept(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestContext_UniqueFilename(t *testing.T) {
|
||||
add := func(ctx *Context, name string) string {
|
||||
unique := ctx.uniqueFilename(name)
|
||||
ctx.files[unique] = "/disk/" + unique
|
||||
|
||||
return unique
|
||||
}
|
||||
|
||||
t.Run("numbers each repeat in turn", func(t *testing.T) {
|
||||
ctx := &Context{files: map[string]string{}}
|
||||
|
||||
var got []string
|
||||
for range 4 {
|
||||
got = append(got, add(ctx, "doc.pdf"))
|
||||
}
|
||||
got = append(got, add(ctx, "noext"), add(ctx, "noext"))
|
||||
|
||||
want := []string{"doc.pdf", "doc (2).pdf", "doc (3).pdf", "doc (4).pdf", "noext", "noext (2)"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("names = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("skips a number a file already carries", func(t *testing.T) {
|
||||
ctx := &Context{files: map[string]string{"doc.pdf": "/disk/1", "doc (2).pdf": "/disk/2", "doc (4).pdf": "/disk/4"}}
|
||||
|
||||
got := []string{add(ctx, "doc.pdf"), add(ctx, "doc.pdf")}
|
||||
ctx.files["doc (6).pdf"] = "/disk/6"
|
||||
got = append(got, add(ctx, "doc.pdf"))
|
||||
|
||||
want := []string{"doc (3).pdf", "doc (5).pdf", "doc (7).pdf"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("names = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("many repeats stay linear", func(t *testing.T) {
|
||||
const n = 50_000
|
||||
|
||||
ctx := &Context{files: map[string]string{}}
|
||||
|
||||
start := time.Now()
|
||||
for range n {
|
||||
add(ctx, "doc.pdf")
|
||||
}
|
||||
|
||||
if len(ctx.files) != n {
|
||||
t.Fatalf("files = %d, want %d distinct names", len(ctx.files), n)
|
||||
}
|
||||
|
||||
// Probing from 2 on every repeat takes 1.25 billion lookups.
|
||||
if elapsed := time.Since(start); elapsed > 10*time.Second {
|
||||
t.Fatalf("%d repeats took %s, want well under a second", n, elapsed)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A redirect target is filtered inside the HTTP client, so the policy verdict
|
||||
// surfaces from client.Do rather than from the pre-flight check. It used to be
|
||||
// interpolated into the response body, so a redirect described the allow-list,
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"iter"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
@@ -569,16 +570,32 @@ func (p *Processor) splitOne(ctx *api.Context, s *splitStage, d document, passwo
|
||||
return nil, fmt.Errorf("count pages: %w", err)
|
||||
}
|
||||
|
||||
groups, err := splitGroups(s, pageCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// Every range is checked before any part is written, at a cost that grows
|
||||
// with the ranges' length alone.
|
||||
for _, spec := range s.Ranges {
|
||||
err = validatePages(spec, pageCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
base := strings.TrimSuffix(d.filename, filepath.Ext(d.filename))
|
||||
parts := make([]document, 0, len(groups))
|
||||
var parts []document
|
||||
|
||||
for i, pages := range groups {
|
||||
part, err := p.write(ctx, litho.NewPipeline().Open(r).Split(pages), []string{"split"}, fmt.Sprintf("%s_%d.pdf", base, i), signatureRemoval(s)...)
|
||||
// Each group is resolved when its part is written, so a split holds one
|
||||
// group in memory at a time, and the request's deadline stops it between
|
||||
// parts.
|
||||
for pages, err := range splitGroups(s, pageCount) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = ctx.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
part, err := p.write(ctx, litho.NewPipeline().Open(r).Split(pages), []string{"split"}, fmt.Sprintf("%s_%d.pdf", base, len(parts)), signatureRemoval(s)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -589,35 +606,35 @@ func (p *Processor) splitOne(ctx *api.Context, s *splitStage, d document, passwo
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
// splitGroups returns the pages of each part a split produces.
|
||||
func splitGroups(s *splitStage, pageCount int) ([][]int, error) {
|
||||
var groups [][]int
|
||||
// splitGroups yields the pages of each part a split produces, in order,
|
||||
// resolving each group when the loop reaches it. It stops after a group that
|
||||
// fails to resolve, yielding its error.
|
||||
func splitGroups(s *splitStage, pageCount int) iter.Seq2[[]int, error] {
|
||||
return func(yield func([]int, error) bool) {
|
||||
if s.Every != nil {
|
||||
every := *s.Every
|
||||
|
||||
if s.Every != nil {
|
||||
every := *s.Every
|
||||
for start := 1; start <= pageCount; start += every {
|
||||
var pages []int
|
||||
for page := start; page < start+every && page <= pageCount; page++ {
|
||||
pages = append(pages, page)
|
||||
}
|
||||
|
||||
for start := 1; start <= pageCount; start += every {
|
||||
var pages []int
|
||||
for page := start; page < start+every && page <= pageCount; page++ {
|
||||
pages = append(pages, page)
|
||||
if !yield(pages, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
groups = append(groups, pages)
|
||||
return
|
||||
}
|
||||
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
for _, part := range s.Ranges {
|
||||
pages, err := parsePages(part, pageCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
for _, part := range s.Ranges {
|
||||
pages, err := parsePages(part, pageCount)
|
||||
if !yield(pages, err) || err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
groups = append(groups, pages)
|
||||
}
|
||||
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
// runEach runs a run of stages on every document.
|
||||
|
||||
@@ -1626,3 +1626,58 @@ func TestRunMergeFileBookmarksUnknownLabel(t *testing.T) {
|
||||
t.Fatalf("got %d %q, want 400 %q", status, message, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSplitStopsAtTheDeadline pins that a split of many parts stops between
|
||||
// parts when the request's deadline passes, rather than writing them all.
|
||||
func TestSplitStopsAtTheDeadline(t *testing.T) {
|
||||
ctx, paths := testContext(t, "pages_12.pdf")
|
||||
|
||||
deadline, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
||||
defer cancel()
|
||||
ctx.Context = deadline
|
||||
|
||||
ranges := make([]string, 50_000)
|
||||
for i := range ranges {
|
||||
ranges[i] = "1-"
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
_, err := testProcessor().splitOne(ctx, &splitStage{Ranges: ranges}, document{path: paths["pages_12.pdf"], filename: "pages_12.pdf"}, "")
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("split err = %v, want context.DeadlineExceeded", err)
|
||||
}
|
||||
|
||||
if elapsed := time.Since(start); elapsed > 10*time.Second {
|
||||
t.Fatalf("split stopped after %s, want shortly after the deadline", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSplitChecksEveryRangeFirst pins that a split with an invalid range
|
||||
// writes no part, wherever the range sits in the list.
|
||||
func TestSplitChecksEveryRangeFirst(t *testing.T) {
|
||||
ctx, paths := testContext(t, "pages_12.pdf")
|
||||
|
||||
ranges := make([]string, 1_000)
|
||||
for i := range ranges {
|
||||
ranges[i] = "1-"
|
||||
}
|
||||
ranges[len(ranges)-1] = "13"
|
||||
|
||||
before, err := os.ReadDir(ctx.DirPath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = testProcessor().splitOne(ctx, &splitStage{Ranges: ranges}, document{path: paths["pages_12.pdf"], filename: "pages_12.pdf"}, "")
|
||||
if !errors.Is(err, litho.ErrInvalidPageRange) {
|
||||
t.Fatalf("split err = %v, want litho.ErrInvalidPageRange", err)
|
||||
}
|
||||
|
||||
after, err := os.ReadDir(ctx.DirPath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(after) != len(before) {
|
||||
t.Fatalf("split wrote %d files before rejecting the last range, want none", len(after)-len(before))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +174,18 @@ func parsePages(spec string, pageCount int) ([]int, error) {
|
||||
return pages, nil
|
||||
}
|
||||
|
||||
// validatePages reports whether spec is a page range specification
|
||||
// [parsePages] accepts for a document of pageCount pages, without expanding
|
||||
// it. A specification whose parts are valid but select no page passes; only
|
||||
// [parsePages] tells it.
|
||||
func validatePages(spec string, pageCount int) error {
|
||||
if strings.EqualFold(strings.TrimSpace(spec), "all") {
|
||||
return nil
|
||||
}
|
||||
|
||||
return litho.ValidatePageRanges(spec, pageCount)
|
||||
}
|
||||
|
||||
// pdfDatePattern matches a PDF date, D:YYYYMMDDHHmmSSOHH'mm (ISO 32000-1,
|
||||
// 7.9.4): the year is mandatory and each field after it is optional, the time
|
||||
// zone included.
|
||||
|
||||
@@ -420,17 +420,24 @@ func formRoute(processor *Processor) api.Route {
|
||||
// non-empty pages, a page selection, keeps the fields with a widget on a
|
||||
// selected page.
|
||||
func readForm(ctx context.Context, r *litho.Reader, pages string) ([]formField, error) {
|
||||
var selected []int
|
||||
// selected[p] tells whether the selection holds page p; nil keeps every
|
||||
// field.
|
||||
var selected []bool
|
||||
if pages != "" {
|
||||
count, err := r.PageCount(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("count pages: %w", err)
|
||||
}
|
||||
|
||||
selected, err = parsePages(pages, count)
|
||||
list, err := parsePages(pages, count)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("form field 'pages': %w", err)
|
||||
}
|
||||
|
||||
selected = make([]bool, count+1)
|
||||
for _, p := range list {
|
||||
selected[p] = true
|
||||
}
|
||||
}
|
||||
|
||||
fields, err := r.FormFields(ctx)
|
||||
@@ -438,8 +445,20 @@ func readForm(ctx context.Context, r *litho.Reader, pages string) ([]formField,
|
||||
return nil, fmt.Errorf("read form fields: %w", err)
|
||||
}
|
||||
|
||||
return formFields(ctx, fields, selected)
|
||||
}
|
||||
|
||||
// formFields describes fields for the form route, in order. A non-nil
|
||||
// selected, indexed by page, keeps the fields with a widget on a page it
|
||||
// holds.
|
||||
func formFields(ctx context.Context, fields []models.FormField, selected []bool) ([]formField, error) {
|
||||
res := []formField{}
|
||||
for _, f := range fields {
|
||||
err := ctx.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// An XFA form names its fields in its own template, which set-form
|
||||
// does not fill. A field that states no type is malformed.
|
||||
if f.Type == models.FormFieldXFA || f.Type == "" {
|
||||
@@ -469,13 +488,14 @@ func readForm(ctx context.Context, r *litho.Reader, pages string) ([]formField,
|
||||
}
|
||||
|
||||
for _, w := range f.Widgets {
|
||||
if w.PageNumber > 0 && !slices.Contains(field.Pages, w.PageNumber) {
|
||||
if w.PageNumber > 0 {
|
||||
field.Pages = append(field.Pages, w.PageNumber)
|
||||
}
|
||||
}
|
||||
slices.Sort(field.Pages)
|
||||
field.Pages = slices.Compact(field.Pages)
|
||||
|
||||
if selected != nil && !slices.ContainsFunc(field.Pages, func(page int) bool { return slices.Contains(selected, page) }) {
|
||||
if selected != nil && !slices.ContainsFunc(field.Pages, func(page int) bool { return page < len(selected) && selected[page] }) {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package pdf
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
@@ -9,7 +11,9 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gotenberg/litho/pkg/models"
|
||||
"github.com/labstack/echo/v5"
|
||||
|
||||
"github.com/gotenberg/gotenberg/v9/pkg/modules/api"
|
||||
@@ -699,6 +703,12 @@ func TestFormRoute(t *testing.T) {
|
||||
values: map[string][]string{"pages": {"1"}},
|
||||
wantBody: `{"multi.pdf":[{"name":"total","type":"text","value":"42","pages":[1,2],"readOnly":true},{"name":"tags","type":"list","value":["a","c"],"pages":[1],"options":["a","b","c"],"multiSelect":true}]}`,
|
||||
},
|
||||
{
|
||||
name: "fields on pages a selection names several times",
|
||||
fixture: "multi.pdf",
|
||||
values: map[string][]string{"pages": {"2,2-,last,!1"}},
|
||||
wantBody: `{"multi.pdf":[{"name":"total","type":"text","value":"42","pages":[1,2],"readOnly":true},{"name":"size","type":"radio","value":"Off","pages":[2],"states":["S","M","L"],"required":true},{"name":"sig","type":"signature","value":"","pages":[2]}]}`,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, rec, err := serve(t, formRoute(testProcessor()), tc.values, tc.fixture)
|
||||
@@ -720,6 +730,52 @@ func TestFormRoute(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestFormFieldsStopsWhenCancelled pins that describing a form stops once
|
||||
// the request is cancelled.
|
||||
func TestFormFieldsStopsWhenCancelled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
fields := []models.FormField{{Name: "a", Type: models.FormFieldText}}
|
||||
got, err := formFields(ctx, fields, nil)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("formFields = %v, %v, want context.Canceled", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFormFieldsManyWidgets pins that a field's pages and the page selection
|
||||
// cost a lookup per widget, not a scan: 200,000 widgets on as many pages
|
||||
// take well under a second, a scan per widget half a minute.
|
||||
func TestFormFieldsManyWidgets(t *testing.T) {
|
||||
const n = 200_000
|
||||
|
||||
widgets := make([]models.FormWidget, 0, 2*n)
|
||||
for p := n; p >= 1; p-- {
|
||||
widgets = append(widgets, models.FormWidget{PageNumber: p}, models.FormWidget{PageNumber: p})
|
||||
}
|
||||
fields := []models.FormField{
|
||||
{Name: "a", Type: models.FormFieldText, Widgets: widgets},
|
||||
{Name: "b", Type: models.FormFieldText, Widgets: widgets[:2]},
|
||||
}
|
||||
|
||||
selected := make([]bool, n+1)
|
||||
selected[1] = true
|
||||
|
||||
start := time.Now()
|
||||
got, err := formFields(context.Background(), fields, selected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if elapsed := time.Since(start); elapsed > 10*time.Second {
|
||||
t.Fatalf("formFields took %s, want well under a second", elapsed)
|
||||
}
|
||||
|
||||
if len(got) != 1 || got[0].Name != "a" || len(got[0].Pages) != n || got[0].Pages[0] != 1 || got[0].Pages[n-1] != n {
|
||||
t.Fatalf("formFields = %d fields, want field a on pages 1 to %d once each", len(got), n)
|
||||
}
|
||||
}
|
||||
|
||||
// readFormFields answers the form route on the PDF at path.
|
||||
func readFormFields(t *testing.T, processor *Processor, path string) []formField {
|
||||
t.Helper()
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"math"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -222,8 +223,23 @@ func TestRunEnd(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// collectSplitGroups resolves every group splitGroups yields, stopping at the
|
||||
// first error.
|
||||
func collectSplitGroups(s *splitStage, pageCount int) ([][]int, error) {
|
||||
var groups [][]int
|
||||
for pages, err := range splitGroups(s, pageCount) {
|
||||
if err != nil {
|
||||
return groups, err
|
||||
}
|
||||
|
||||
groups = append(groups, pages)
|
||||
}
|
||||
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
func TestSplitGroups(t *testing.T) {
|
||||
groups, err := splitGroups(&splitStage{Every: new(2)}, 5)
|
||||
groups, err := collectSplitGroups(&splitStage{Every: new(2)}, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -231,17 +247,51 @@ func TestSplitGroups(t *testing.T) {
|
||||
t.Fatalf("every 2 of 5 = %v", groups)
|
||||
}
|
||||
|
||||
groups, err = splitGroups(&splitStage{Ranges: []string{"1-2", " 4", "last", "1,3,5"}}, 5)
|
||||
groups, err = collectSplitGroups(&splitStage{Ranges: []string{"1-2", " 4", "last", "1,3,5", "1,1,3-"}}, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(groups) != 4 || !slices.Equal(groups[0], []int{1, 2}) || !slices.Equal(groups[2], []int{5}) || !slices.Equal(groups[3], []int{1, 3, 5}) {
|
||||
if len(groups) != 5 || !slices.Equal(groups[0], []int{1, 2}) || !slices.Equal(groups[2], []int{5}) || !slices.Equal(groups[3], []int{1, 3, 5}) || !slices.Equal(groups[4], []int{1, 3, 4, 5}) {
|
||||
t.Fatalf("ranges = %v", groups)
|
||||
}
|
||||
|
||||
if _, err := splitGroups(&splitStage{Ranges: []string{"1", "9"}}, 5); err == nil {
|
||||
groups, err = collectSplitGroups(&splitStage{Ranges: []string{"1", "9", "2"}}, 5)
|
||||
if err == nil {
|
||||
t.Fatal("a range past the last page must fail")
|
||||
}
|
||||
if len(groups) != 1 {
|
||||
t.Fatalf("groups before the failing range = %v, want the one before it", groups)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSplitGroupsResolvesLazily pins that a group is resolved only when the
|
||||
// loop reaches it: stopping after the first of many open ranges on a large
|
||||
// document resolves that one alone.
|
||||
func TestSplitGroupsResolvesLazily(t *testing.T) {
|
||||
const pageCount = 5_000
|
||||
|
||||
ranges := make([]string, 200_000)
|
||||
for i := range ranges {
|
||||
ranges[i] = "1-"
|
||||
}
|
||||
s := &splitStage{Ranges: ranges}
|
||||
|
||||
var before, after runtime.MemStats
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&before)
|
||||
for pages, err := range splitGroups(s, pageCount) {
|
||||
if err != nil || len(pages) != pageCount {
|
||||
t.Fatalf("first group = %d pages, %v, want %d pages", len(pages), err, pageCount)
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
runtime.ReadMemStats(&after)
|
||||
|
||||
// Resolving every group holds 200,000 x 5,000 page numbers, about 8 GB.
|
||||
if alloc := after.TotalAlloc - before.TotalAlloc; alloc > 4<<20 {
|
||||
t.Fatalf("first group allocated %d bytes, want one group's worth", alloc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePages(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user