console: fair-use limits on the PDF door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+484
−62
cmd/console/main.go+5 −0internal/console/apipdf.go+15 −42internal/console/apipdf_test.go+130 −4internal/console/claim_invariant_fixtures_test.go+1 −15internal/console/claim_invariant_probes_read_test.go+15 −0internal/console/pdflimit.go+114 −0internal/console/pdflimit_test.go+196 −0internal/console/server.go+8 −1
CI failed — run details
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 95040e3b2..76ca80e1b 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -369,6 +369,10 @@ func serve() { |
| rec := new(perf.Recorder) |
| storeProvisioner, storeDeployment := storeBackend(rec) |
| storeScanner, seedAntivirus := storeScannerFor(storeDeployment) |
| + pdfLimits, err := console.ParsePDFLimits(os.Getenv("CARLOS_PDF_LIMITS")) |
| + if err != nil { |
| + log.Fatalf("console: %v", err) |
| + } |
| pdfAddr, err := pdfEngine(os.Getenv) |
| if err != nil { |
| log.Fatalf("console: %v", err) |
| @@ -545,6 +549,7 @@ func serve() { |
| StoreProvisioner: storeProvisioner, |
| StoreScanner: storeScanner, |
| PDFEngine: pdfAddr, |
| + PDFLimits: pdfLimits, |
| ScanSeedFromDeprecatedEnv: seedAntivirus, |
| ScanBudget: envDuration("CARLOS_STORE_SCAN_BUDGET", time.Minute), |
| ScanInterval: envDuration("CARLOS_STORE_SCAN_INTERVAL", 24*time.Hour), |
diff --git a/internal/console/apipdf.go b/internal/console/apipdf.go| index bfa529847..687d5ffd7 100644 |
| --- a/internal/console/apipdf.go |
| +++ b/internal/console/apipdf.go |
| @@ -59,15 +59,7 @@ type pdfRenderRow struct { |
| At time.Time |
| } |
| -// Tasks 2 and 4 replace these admission stubs. |
| -type pdfLimiter struct{} |
| -type pdfRefusal struct { |
| - Status int |
| - RetryAfter int |
| - Msg string |
| -} |
| - |
| -func (*pdfLimiter) acquire(string, time.Time) (func(), *pdfRefusal) { return func() {}, nil } |
| +// Task 4 replaces the plan admission stub. |
| func (*Server) pdfPlanCheck(context.Context, *Account, time.Time) error { return nil } |
| func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| @@ -97,17 +89,6 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| panic(interrupted) |
| } |
| }() |
| - if err := s.pdfPlanCheck(r.Context(), acct, now); err != nil { |
| - jsonError(out, http.StatusPaymentRequired, err.Error()) |
| - return |
| - } |
| - release, refusal := s.pdfLimiter.acquire(acct.Sqid, now) |
| - if refusal != nil { |
| - out.Header().Set("Retry-After", strconv.Itoa(refusal.RetryAfter)) |
| - jsonError(out, refusal.Status, refusal.Msg) |
| - return |
| - } |
| - defer release() |
| // The mux decodes PathValue. Split the escaped path at the fixed route |
| // prefix instead, so an escaped slash can never become an allowed route. |
| @@ -136,6 +117,18 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| jsonError(out, http.StatusRequestEntityTooLarge, pdfText("pdf.too_large")) |
| return |
| } |
| + if err := s.pdfPlanCheck(r.Context(), acct, now); err != nil { |
| + jsonError(out, http.StatusPaymentRequired, err.Error()) |
| + return |
| + } |
| + release, refusal := s.pdfLimiter.acquire(acct.Sqid, now) |
| + if refusal != nil { |
| + out.Header().Set("Retry-After", strconv.Itoa(refusal.RetryAfter)) |
| + jsonError(out, refusal.Status, refusal.Msg) |
| + return |
| + } |
| + defer release() |
| + |
| engine, err := url.Parse(s.cfg.PDFEngine) |
| if err != nil || engine.Scheme != "http" || engine.Hostname() == "" { |
| log.Printf("console: invalid PDF engine address") |
| @@ -147,17 +140,14 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| if timeout <= 0 { |
| timeout = 60 * time.Second |
| } |
| - ctx, cancel := context.WithTimeout(r.Context(), timeout) |
| - defer cancel() |
| input = &pdfRequestBody{ReadCloser: http.MaxBytesReader(out, r.Body, 32<<20)} |
| - r = r.Clone(ctx) |
| + r = r.Clone(r.Context()) |
| r.Body = input |
| transport := http.DefaultTransport.(*http.Transport).Clone() |
| transport.Proxy = nil |
| transport.DisableCompression = true |
| transport.ResponseHeaderTimeout = timeout |
| defer transport.CloseIdleConnections() |
| - gateRefused := false |
| proxy := &httputil.ReverseProxy{ |
| Rewrite: func(pr *httputil.ProxyRequest) { |
| pr.Out.URL = &url.URL{Scheme: engine.Scheme, Host: engine.Host, Path: "/" + route} |
| @@ -174,21 +164,7 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| pr.Out.Close = false |
| }, |
| Transport: pdfRoundTripper(func(req *http.Request) (*http.Response, error) { |
| - var resp *http.Response |
| - var engineErr error |
| - // A render is an outbound app operation. Settle the admission after |
| - // sending; streaming the answer makes no further engine requests. |
| - gateErr := s.claimAppMutation(req.Context(), acct, app, "pdf.render", func(ctx context.Context) error { |
| - resp, engineErr = transport.RoundTrip(req.WithContext(ctx)) |
| - return nil |
| - }) |
| - if gateErr != nil { |
| - gateRefused = true |
| - if resp != nil { |
| - resp.Body.Close() |
| - } |
| - return nil, gateErr |
| - } |
| + resp, engineErr := transport.RoundTrip(req) |
| if resp != nil { |
| // Transport fills trailers on its response at EOF. Give the |
| // proxy a separate response so those headers stay private. |
| @@ -215,9 +191,6 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| case input.tooLarge.Load() || errors.As(err, &tooLarge): |
| row.Outcome = pdfRefused |
| jsonError(w, http.StatusRequestEntityTooLarge, pdfText("pdf.too_large")) |
| - case gateRefused: |
| - row.Outcome = pdfRefused |
| - jsonError(w, http.StatusBadGateway, pdfText("pdf.engine_down")) |
| case r.Context().Err() == context.Canceled: |
| row.Outcome = pdfAborted |
| case errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &network) && network.Timeout()): |
diff --git a/internal/console/apipdf_test.go b/internal/console/apipdf_test.go| index 173f265be..91a8b26ff 100644 |
| --- a/internal/console/apipdf_test.go |
| +++ b/internal/console/apipdf_test.go |
| @@ -320,7 +320,7 @@ func TestPDFDoorExactLimits(t *testing.T) { |
| } |
| } |
| -func TestPDFDoorClientGone(t *testing.T) { |
| +func TestPDFDoorReleasesOnClientGone(t *testing.T) { |
| started := make(chan struct{}) |
| fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| close(started) |
| @@ -356,6 +356,9 @@ func TestPDFDoorClientGone(t *testing.T) { |
| t.Fatal("client did not stop") |
| } |
| fx.row(t, pdfOutcome("aborted"), 0) |
| + for i := 0; i < 4; i++ { |
| + defer pdfAcquire(t, fx.srv.pdfLimiter, fx.sqid, time.Now())() |
| + } |
| } |
| func TestPDFDoorRoleGate(t *testing.T) { |
| @@ -415,10 +418,133 @@ func TestPDFDoorFiltersInformationalHeaders(t *testing.T) { |
| } |
| } |
| -func TestPDFDoorClaimGate(t *testing.T) { |
| - door := claimFixtures["route POST /api/cli/apps/{account}/{app}/pdf/{route...}"].door |
| - problems, _ := runClaimDoor(t, door) |
| +func TestPDFDoorClaimRead(t *testing.T) { |
| + key := "route POST /api/cli/apps/{account}/{app}/pdf/{route...}" |
| + if claimFixtures[key].read == "" { |
| + t.Fatal("PDF rendering must be classified as a read") |
| + } |
| + cx := newClaimCase(t) |
| + probe := claimReadProbes[key] |
| + if probe.do == nil { |
| + t.Fatal("missing PDF read probe") |
| + } |
| + problems := runClaimProbe(t, cx, key, probe) |
| for _, problem := range problems { |
| t.Error(problem) |
| } |
| + restore := cx.foreign(t, claimAppRef{Account: "bab", App: "shop"}) |
| + defer restore() |
| + probe.setup = nil |
| + for _, problem := range runClaimProbe(t, cx, key, probe) { |
| + t.Error(problem) |
| + } |
| +} |
| + |
| +func TestPDFDoorUnknownRoutesPreserveRate(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) {}) |
| + for i := 0; i < 25; i++ { |
| + pdfWantError(t, fx.request(t, "unlisted", nil, nil), 404, "pdf.unknown_route") |
| + fx.row(t, pdfRefused, 404) |
| + } |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + if resp.StatusCode != 200 { |
| + t.Fatalf("valid request status = %d", resp.StatusCode) |
| + } |
| + fx.row(t, pdfRendered, 200) |
| +} |
| + |
| +func TestPDFDoorCheapRefusalsBeforeLimiter(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, route, key string |
| + status int |
| + unconfigured, webhook, oversized bool |
| + }{ |
| + {name: "unconfigured", route: pdfHTMLRoute, key: "pdf.unconfigured", status: 503, unconfigured: true}, |
| + {name: "route", route: "unlisted", key: "pdf.unknown_route", status: 404}, |
| + {name: "webhook", route: pdfHTMLRoute, key: "pdf.webhook", status: 400, webhook: true}, |
| + {name: "length", route: pdfHTMLRoute, key: "pdf.too_large", status: 413, oversized: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var calls atomic.Int64 |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + if tc.unconfigured { |
| + fx.srv.cfg.PDFEngine = "" |
| + } |
| + fx.srv.pdfLimiter = newPDFLimiter(pdfLimits{1, 60, 1, 1}) |
| + defer pdfAcquire(t, fx.srv.pdfLimiter, fx.sqid, time.Now())() |
| + req := httptest.NewRequest(http.MethodPost, "/api/cli/apps/"+fx.sqid+"/shop/pdf/"+tc.route, nil) |
| + req.Header.Set("Authorization", "Bearer "+fx.token) |
| + if tc.webhook { |
| + req.Header.Set("Gotenberg-Webhook-Url", "https://example.com") |
| + } |
| + if tc.oversized { |
| + req.ContentLength = 33 << 20 |
| + } |
| + out := httptest.NewRecorder() |
| + fx.srv.ServeHTTP(out, req) |
| + pdfWantError(t, out.Result(), tc.status, tc.key) |
| + fx.row(t, pdfRefused, tc.status) |
| + if calls.Load() != 0 { |
| + t.Fatal("cheap refusal reached engine") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPDFDoorLimiterRefusal(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { t.Error("refusal reached engine") }) |
| + fx.srv.pdfLimiter = newPDFLimiter(pdfLimits{2, 60, 20, 3}) |
| + for i := 0; i < 2; i++ { |
| + defer pdfAcquire(t, fx.srv.pdfLimiter, fx.sqid, time.Now())() |
| + } |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + var body map[string]string |
| + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 429 || resp.Header.Get("Retry-After") != "2" || body["error"] != pdfText("pdf.busy_account", 2) { |
| + t.Fatalf("response: %d %v %v", resp.StatusCode, resp.Header, body) |
| + } |
| + fx.row(t, pdfRefused, 429) |
| +} |
| + |
| +func TestPDFDoorSlowDownload(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/pdf") |
| + io.WriteString(w, "%PDF-") |
| + w.(http.Flusher).Flush() |
| + time.Sleep(150 * time.Millisecond) |
| + io.WriteString(w, "complete") |
| + }) |
| + fx.srv.pdfTimeout = 50 * time.Millisecond |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + body, err := io.ReadAll(resp.Body) |
| + if err != nil || string(body) != "%PDF-complete" { |
| + t.Fatalf("download = %q, %v", body, err) |
| + } |
| + fx.row(t, pdfRendered, 200) |
| +} |
| + |
| +func TestPDFDoorSlowUpload(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + body, err := io.ReadAll(r.Body) |
| + if err == nil { |
| + w.Write(body) |
| + } |
| + }) |
| + fx.srv.pdfTimeout = 50 * time.Millisecond |
| + reader, writer := io.Pipe() |
| + defer reader.Close() |
| + go func() { |
| + defer writer.Close() |
| + io.WriteString(writer, "start") |
| + time.Sleep(150 * time.Millisecond) |
| + io.WriteString(writer, "finish") |
| + }() |
| + resp := fx.request(t, pdfHTMLRoute, reader, nil) |
| + body, err := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 200 || err != nil || string(body) != "startfinish" { |
| + t.Fatalf("upload response = %d %q, %v", resp.StatusCode, body, err) |
| + } |
| + fx.row(t, pdfRendered, 200) |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index aff05656e..adbfcc6e0 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -24,7 +24,6 @@ import ( |
| "errors" |
| "fmt" |
| "net/http" |
| - "net/http/httptest" |
| "net/url" |
| "strconv" |
| "strings" |
| @@ -2108,20 +2107,7 @@ var claimFixtures = map[string]claimFixture{ |
| setup: func(t *testing.T, cx *claimCase) { cx.scanGranted(t) }, |
| do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/store/scan/sweep", `{}`), |
| }}, |
| - "route POST /api/cli/apps/{account}/{app}/pdf/{route...}": {door: &claimDoor{ |
| - apps: claimRefs("bab/shop"), |
| - setup: func(t *testing.T, cx *claimCase) { |
| - cx.enroll(t, "bab", "shop") |
| - engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - cx.rec.add(claimRawEvent{Surface: "http", Method: r.Method, Key: r.URL.String(), Unscoped: true}) |
| - w.Header().Set("Content-Type", "application/pdf") |
| - _, _ = w.Write([]byte("%PDF-fixture")) |
| - })) |
| - t.Cleanup(engine.Close) |
| - cx.srv.cfg.PDFEngine = engine.URL |
| - }, |
| - do: claimAPI(http.MethodPost, "/api/cli/apps/bab/shop/pdf/forms/chromium/convert/html", "fixture"), |
| - }}, |
| + "route POST /api/cli/apps/{account}/{app}/pdf/{route...}": claimRead("renders caller-supplied content through the deployment PDF engine; changes no app state and takes no app lease"), |
| "route POST /api/cli/apps/{account}/{app}/store/scan/object": {door: &claimDoor{ |
| apps: claimRefs("bab/titogo"), |
| setup: func(t *testing.T, cx *claimCase) { cx.scanGranted(t) }, |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index f0adf4e6c..089b1dff6 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "context" |
| "encoding/json" |
| "net/http" |
| + "net/http/httptest" |
| "testing" |
| "time" |
| @@ -175,6 +176,20 @@ func claimInvitePageProbe() claimProbe { |
| } |
| var claimReadProbes = map[string]claimProbe{ |
| + "route POST /api/cli/apps/{account}/{app}/pdf/{route...}": { |
| + setup: func(t *testing.T, cx *claimCase) { |
| + cx.enroll(t, "bab", "shop") |
| + engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cx.rec.add(claimRawEvent{Surface: "http", Method: r.Method, Key: r.URL.String(), NonApp: "stateless PDF engine; no app resource is changed"}) |
| + w.Header().Set("Content-Type", "application/pdf") |
| + _, _ = w.Write([]byte("%PDF-fixture")) |
| + })) |
| + t.Cleanup(engine.Close) |
| + cx.srv.cfg.PDFEngine = engine.URL |
| + }, |
| + do: claimAPIReply(http.MethodPost, "/api/cli/apps/bab/shop/pdf/forms/chromium/convert/html", "fixture"), |
| + body: []string{"%PDF-fixture"}, |
| + }, |
| "route GET /accounts": claimPageRead(nil, "/accounts", `id="index-title">Accounts</h1>`), |
| // ---- methodless ---- |
| "route /api/economics/backhaul": claimAPIRead(nil, "/api/economics/backhaul", `"period"`, `"accounts"`), |
diff --git a/internal/console/pdflimit.go b/internal/console/pdflimit.go| new file mode 100644 |
| index 000000000..c45cb451d |
| --- /dev/null |
| +++ b/internal/console/pdflimit.go |
| @@ -0,0 +1,114 @@ |
| +package console |
| + |
| +import ( |
| + "fmt" |
| + "math" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +type pdfLimits struct { |
| + PerAccountInflight, PerMinute, Burst, TotalInflight int |
| +} |
| + |
| +// PDFLimits configures the console's PDF admission limits. |
| +type PDFLimits = pdfLimits |
| + |
| +// ParsePDFLimits parses CARLOS_PDF_LIMITS for the console entry point. |
| +func ParsePDFLimits(v string) (PDFLimits, error) { return parsePDFLimits(v) } |
| + |
| +func parsePDFLimits(v string) (pdfLimits, error) { |
| + if v == "" { |
| + return pdfLimits{4, 60, 20, 16}, nil |
| + } |
| + parts := strings.Split(v, ",") |
| + var l pdfLimits |
| + if len(parts) != 4 { |
| + return l, fmt.Errorf("CARLOS_PDF_LIMITS must contain four positive integers") |
| + } |
| + for i, field := range []*int{&l.PerAccountInflight, &l.PerMinute, &l.Burst, &l.TotalInflight} { |
| + n, err := strconv.Atoi(parts[i]) |
| + if err != nil || n <= 0 { |
| + return pdfLimits{}, fmt.Errorf("CARLOS_PDF_LIMITS must contain four positive integers") |
| + } |
| + *field = n |
| + } |
| + return l, nil |
| +} |
| + |
| +type pdfRefusal struct { |
| + Status int |
| + RetryAfter int |
| + Msg string |
| +} |
| + |
| +type pdfAccountLimit struct { |
| + inflight int |
| + tokens float64 |
| + at time.Time |
| +} |
| + |
| +type pdfLimiter struct { |
| + mu sync.Mutex |
| + limits pdfLimits |
| + accounts map[string]*pdfAccountLimit |
| + total int |
| + nextSweep time.Time |
| +} |
| + |
| +func newPDFLimiter(l pdfLimits) *pdfLimiter { |
| + return &pdfLimiter{limits: l, accounts: make(map[string]*pdfAccountLimit)} |
| +} |
| + |
| +func (l *pdfLimiter) tokens(a *pdfAccountLimit, now time.Time) float64 { |
| + elapsed := max(0, now.Sub(a.at).Seconds()) |
| + return min(float64(l.limits.Burst), a.tokens+elapsed*float64(l.limits.PerMinute)/60) |
| +} |
| + |
| +func (l *pdfLimiter) acquire(account string, now time.Time) (release func(), refusal *pdfRefusal) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + // Reclaim idle, replenished buckets on traffic, without a background worker. |
| + if !now.Before(l.nextSweep) { |
| + for key, a := range l.accounts { |
| + if a.inflight == 0 && l.tokens(a, now) >= float64(l.limits.Burst) { |
| + delete(l.accounts, key) |
| + } |
| + } |
| + l.nextSweep = now.Add(time.Minute) |
| + } |
| + if l.total >= l.limits.TotalInflight { |
| + return nil, &pdfRefusal{http.StatusServiceUnavailable, 2, pdfText("pdf.busy_engine")} |
| + } |
| + a := l.accounts[account] |
| + if a == nil { |
| + a = &pdfAccountLimit{tokens: float64(l.limits.Burst), at: now} |
| + } |
| + if a.inflight >= l.limits.PerAccountInflight { |
| + return nil, &pdfRefusal{http.StatusTooManyRequests, 2, pdfText("pdf.busy_account", l.limits.PerAccountInflight)} |
| + } |
| + tokens := l.tokens(a, now) |
| + if tokens < 1 { |
| + retry := max(1, int(math.Ceil((1-tokens)*60/float64(l.limits.PerMinute)))) |
| + return nil, &pdfRefusal{http.StatusTooManyRequests, retry, pdfText("pdf.rate", l.limits.PerMinute, retry)} |
| + } |
| + a.tokens = tokens - 1 |
| + if now.After(a.at) { |
| + a.at = now |
| + } |
| + a.inflight++ |
| + l.accounts[account] = a |
| + l.total++ |
| + var once sync.Once |
| + return func() { |
| + once.Do(func() { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + a.inflight-- |
| + l.total-- |
| + }) |
| + }, nil |
| +} |
diff --git a/internal/console/pdflimit_test.go b/internal/console/pdflimit_test.go| new file mode 100644 |
| index 000000000..eb38ae82e |
| --- /dev/null |
| +++ b/internal/console/pdflimit_test.go |
| @@ -0,0 +1,196 @@ |
| +package console |
| + |
| +import ( |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestPDFLimitsParse(t *testing.T) { |
| + for _, tc := range []struct { |
| + input string |
| + want pdfLimits |
| + bad bool |
| + }{ |
| + {"", pdfLimits{4, 60, 20, 16}, false}, {"2,10,5,8", pdfLimits{2, 10, 5, 8}, false}, |
| + {"2,10,5", pdfLimits{}, true}, {"0,1,1,1", pdfLimits{}, true}, {"a,1,1,1", pdfLimits{}, true}, |
| + {"1,2,3,4,5", pdfLimits{}, true}, {"1,-2,3,4", pdfLimits{}, true}, {"1,2,3,", pdfLimits{}, true}, |
| + {"1,2,3,999999999999999999999999", pdfLimits{}, true}, {"1,2,3,1.5", pdfLimits{}, true}, |
| + } { |
| + t.Run(tc.input, func(t *testing.T) { |
| + got, err := parsePDFLimits(tc.input) |
| + if (err != nil) != tc.bad || (!tc.bad && got != tc.want) { |
| + t.Fatalf("parse(%q) = %+v, %v; want %+v, bad=%v", tc.input, got, err, tc.want, tc.bad) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func pdfAcquire(t *testing.T, l *pdfLimiter, account string, now time.Time) func() { |
| + t.Helper() |
| + release, refusal := l.acquire(account, now) |
| + if refusal != nil || release == nil { |
| + t.Fatalf("acquire(%s): release=%v refusal=%+v", account, release != nil, refusal) |
| + } |
| + return release |
| +} |
| + |
| +func pdfWantRefusal(t *testing.T, l *pdfLimiter, account string, now time.Time, want pdfRefusal) { |
| + t.Helper() |
| + release, got := l.acquire(account, now) |
| + if release != nil || got == nil || *got != want { |
| + t.Fatalf("acquire(%s): release=%v refusal=%+v; want %+v", account, release != nil, got, want) |
| + } |
| +} |
| + |
| +func TestPDFLimiterAccountInflight(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{4, 60, 20, 16}) |
| + now := time.Now() |
| + other := pdfAcquire(t, l, "acct2", now) |
| + defer other() |
| + var releases []func() |
| + for i := 0; i < 4; i++ { |
| + releases = append(releases, pdfAcquire(t, l, "acct1", now)) |
| + } |
| + pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 2, pdfText("pdf.busy_account", 4)}) |
| + pdfAcquire(t, l, "acct2", now)() |
| + releases[0]() |
| + pdfAcquire(t, l, "acct1", now)() |
| + for _, release := range releases { |
| + release() |
| + } |
| + // The refusal spent neither a rate token nor a slot. |
| + for i := 0; i < 15; i++ { |
| + pdfAcquire(t, l, "acct1", now)() |
| + } |
| + pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60, 1)}) |
| +} |
| + |
| +func TestPDFLimiterRate(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{4, 60, 20, 16}) |
| + now := time.Now() |
| + for i := 0; i < 20; i++ { |
| + pdfAcquire(t, l, "acct1", now)() |
| + } |
| + pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60, 1)}) |
| + pdfAcquire(t, l, "acct2", now)() |
| + pdfAcquire(t, l, "acct1", now.Add(time.Second))() |
| + pdfWantRefusal(t, l, "acct1", now.Add(time.Second), pdfRefusal{429, 1, pdfText("pdf.rate", 60, 1)}) |
| +} |
| + |
| +func TestPDFLimiterRateRoundsUp(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{1, 10, 1, 2}) |
| + now := time.Now() |
| + pdfAcquire(t, l, "acct", now)() |
| + pdfWantRefusal(t, l, "acct", now.Add(100*time.Millisecond), pdfRefusal{429, 6, pdfText("pdf.rate", 10, 6)}) |
| + pdfWantRefusal(t, l, "acct", now.Add(5500*time.Millisecond), pdfRefusal{429, 1, pdfText("pdf.rate", 10, 1)}) |
| + pdfAcquire(t, l, "acct", now.Add(6*time.Second))() |
| +} |
| + |
| +func TestPDFLimiterTotal(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{4, 60, 20, 3}) |
| + now := time.Now() |
| + var releases []func() |
| + for _, account := range []string{"a", "b", "c"} { |
| + releases = append(releases, pdfAcquire(t, l, account, now)) |
| + } |
| + pdfWantRefusal(t, l, "d", now, pdfRefusal{503, 2, pdfText("pdf.busy_engine")}) |
| + releases[0]() |
| + for i := 0; i < 20; i++ { |
| + pdfAcquire(t, l, "d", now)() |
| + } |
| + for _, release := range releases { |
| + release() |
| + } |
| +} |
| + |
| +func TestPDFLimiterRefusalOrder(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{1, 60, 1, 1}) |
| + now := time.Now() |
| + release := pdfAcquire(t, l, "a", now) |
| + pdfWantRefusal(t, l, "a", now, pdfRefusal{503, 2, pdfText("pdf.busy_engine")}) |
| + release() |
| + l = newPDFLimiter(pdfLimits{1, 60, 1, 2}) |
| + release = pdfAcquire(t, l, "a", now) |
| + pdfWantRefusal(t, l, "a", now, pdfRefusal{429, 2, pdfText("pdf.busy_account", 1)}) |
| + release() |
| + pdfWantRefusal(t, l, "a", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60, 1)}) |
| +} |
| + |
| +func TestPDFLimiterReleaseIdempotent(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{2, 60, 20, 2}) |
| + now := time.Now() |
| + first := pdfAcquire(t, l, "a", now) |
| + second := pdfAcquire(t, l, "a", now) |
| + first() |
| + first() |
| + third := pdfAcquire(t, l, "a", now) |
| + pdfWantRefusal(t, l, "b", now, pdfRefusal{503, 2, pdfText("pdf.busy_engine")}) |
| + second() |
| + third() |
| +} |
| + |
| +func TestPDFLimiterConcurrent(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{4, 60, 20, 16}) |
| + now := time.Now() |
| + var wg sync.WaitGroup |
| + releases := make(chan func(), 100) |
| + for i := 0; i < 100; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + release, refusal := l.acquire("a", now) |
| + if refusal == nil { |
| + releases <- release |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + close(releases) |
| + if len(releases) != 4 { |
| + t.Fatalf("admitted %d, want 4", len(releases)) |
| + } |
| + for release := range releases { |
| + for i := 0; i < 2; i++ { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); release() }() |
| + } |
| + } |
| + wg.Wait() |
| + for i := 0; i < 4; i++ { |
| + defer pdfAcquire(t, l, "a", now)() |
| + } |
| +} |
| + |
| +func TestPDFLimiterReclaimsIdleAccounts(t *testing.T) { |
| + l := newPDFLimiter(pdfLimits{4, 60, 20, 16}) |
| + now := time.Now() |
| + pdfAcquire(t, l, "idle", now)() |
| + active := pdfAcquire(t, l, "active", now) |
| + defer active() |
| + pdfAcquire(t, l, "new", now.Add(time.Minute))() |
| + if _, ok := l.accounts["idle"]; ok { |
| + t.Fatal("idle full bucket was retained") |
| + } |
| + if _, ok := l.accounts["active"]; !ok { |
| + t.Fatal("active account was removed") |
| + } |
| + // Cleanup must retain an idle bucket that has not replenished. |
| + l = newPDFLimiter(pdfLimits{4, 1, 20, 16}) |
| + for i := 0; i < 20; i++ { |
| + pdfAcquire(t, l, "slow", now)() |
| + } |
| + pdfAcquire(t, l, "new", now.Add(time.Minute))() |
| + pdfAcquire(t, l, "slow", now.Add(time.Minute))() |
| + pdfWantRefusal(t, l, "slow", now.Add(time.Minute), pdfRefusal{429, 60, pdfText("pdf.rate", 1, 60)}) |
| +} |
| + |
| +func TestPDFLimitsServerConfig(t *testing.T) { |
| + limits := pdfLimits{2, 10, 5, 8} |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{Tweak: func(cfg *Config) { cfg.PDFLimits = limits }}) |
| + now := time.Now() |
| + for i := 0; i < 2; i++ { |
| + defer pdfAcquire(t, fx.srv.pdfLimiter, "acct", now)() |
| + } |
| + pdfWantRefusal(t, fx.srv.pdfLimiter, "acct", now, pdfRefusal{429, 2, pdfText("pdf.busy_account", 2)}) |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index a2caab8aa..eb3726790 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -779,6 +779,7 @@ type Config struct { |
| StoreScanner objstore.Scanner |
| // PDFEngine is the Gotenberg base URL; empty disables the PDF door. |
| PDFEngine string |
| + PDFLimits PDFLimits |
| // ScanSeedFromDeprecatedEnv says the retired CARLOS_STORE_SCANNER supplied |
| // this deployment's clamd address. The first scan-pass tick then seeds |
| // system/antivirus.json enabled, once, carrying forward an intent the |
| @@ -1711,6 +1712,12 @@ func normalizeDelegationZone(raw string) string { |
| // NewServer wires a server over an opened Store, loading (or minting) the |
| // console's Keymail signing key. |
| func NewServer(cfg Config, st *Store) (*Server, error) { |
| + if cfg.PDFLimits == (pdfLimits{}) { |
| + cfg.PDFLimits, _ = parsePDFLimits("") |
| + } |
| + if cfg.PDFLimits.PerAccountInflight <= 0 || cfg.PDFLimits.PerMinute <= 0 || cfg.PDFLimits.Burst <= 0 || cfg.PDFLimits.TotalInflight <= 0 { |
| + return nil, errors.New("CARLOS_PDF_LIMITS must contain four positive integers") |
| + } |
| if cfg.Billing != nil && cfg.PlanCatalog == nil { |
| return nil, errors.New("billing needs a plan catalog (CARLOS_PLAN_CATALOG)") |
| } |
| @@ -1756,7 +1763,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| km.SetSigningKey(key) |
| s := &Server{ |
| pdfTimeout: 60 * time.Second, |
| - pdfLimiter: &pdfLimiter{}, |
| + pdfLimiter: newPDFLimiter(cfg.PDFLimits), |
| recordPDF: func(context.Context, pdfRenderRow) {}, |
| purchaseWake: make(chan struct{}, 1), |