console: idle deadlines on the PDF door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+394
−19
internal/console/apipdf.go+178 −6internal/console/apipdf_test.go+195 −0internal/console/pdf_copy.go+1 −1internal/console/pdflimit.go+1 −1internal/console/pdflimit_test.go+14 −7internal/console/server.go+5 −4
CI failed — run details
diff --git a/internal/console/apipdf.go b/internal/console/apipdf.go| index 687d5ffd7..caf8d8546 100644 |
| --- a/internal/console/apipdf.go |
| +++ b/internal/console/apipdf.go |
| @@ -11,6 +11,7 @@ import ( |
| "net/url" |
| "strconv" |
| "strings" |
| + "sync" |
| "sync/atomic" |
| "time" |
| ) |
| @@ -73,11 +74,17 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| row := pdfRenderRow{Account: acct.Sqid, App: app, Credential: principal.Name, Route: r.PathValue("route"), Outcome: pdfRefused, At: now} |
| out := &pdfResponseWriter{ResponseWriter: w} |
| var input *pdfRequestBody |
| + var watchdog *pdfIdleWatchdog |
| defer func() { |
| interrupted := recover() |
| if interrupted != nil || clientCtx.Err() != nil { |
| row.Outcome = pdfAborted |
| } |
| + if watchdog != nil { |
| + if outcome := watchdog.stop(); outcome != "" { |
| + row.Outcome = outcome |
| + } |
| + } |
| row.Status, row.BytesOut = out.status, out.bytes |
| if input != nil { |
| row.BytesIn = input.bytes.Load() |
| @@ -140,8 +147,23 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| if timeout <= 0 { |
| timeout = 60 * time.Second |
| } |
| - input = &pdfRequestBody{ReadCloser: http.MaxBytesReader(out, r.Body, 32<<20)} |
| - r = r.Clone(r.Context()) |
| + idle := s.pdfIdleTimeout |
| + if idle <= 0 { |
| + idle = 60 * time.Second |
| + } |
| + rc := http.NewResponseController(w) |
| + ctx, cancel := context.WithCancel(clientCtx) |
| + defer cancel() |
| + watchdog = newPDFIdleWatchdog(idle, func() { |
| + cancel() |
| + // Transport closes the request body on cancellation. Wake any |
| + // pending read (including Close's drain) before it can hold a slot. |
| + _ = rc.SetReadDeadline(time.Now()) |
| + }) |
| + defer watchdog.stop() |
| + out.rc, out.watchdog = rc, watchdog |
| + input = &pdfRequestBody{ReadCloser: http.MaxBytesReader(out, r.Body, 32<<20), rc: rc, watchdog: watchdog} |
| + r = r.Clone(ctx) |
| r.Body = input |
| transport := http.DefaultTransport.(*http.Transport).Clone() |
| transport.Proxy = nil |
| @@ -177,7 +199,8 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| ModifyResponse: func(resp *http.Response) error { |
| pdfFilterResponseHeaders(resp.Header) |
| resp.Trailer = nil |
| - resp.Body = &pdfResponseBody{ReadCloser: resp.Body, remaining: 64 << 20} |
| + watchdog.progress() |
| + resp.Body = &pdfResponseBody{ReadCloser: resp.Body, remaining: 64 << 20, watchdog: watchdog} |
| row.Outcome = pdfEngineError |
| if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| row.Outcome = pdfRendered |
| @@ -191,7 +214,10 @@ 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 r.Context().Err() == context.Canceled: |
| + case watchdog.outcome() == pdfFailed: |
| + row.Outcome = pdfFailed |
| + jsonError(w, http.StatusGatewayTimeout, pdfText("pdf.engine_timeout")) |
| + case input.aborted.Load() || clientCtx.Err() == context.Canceled || watchdog.outcome() == pdfAborted: |
| row.Outcome = pdfAborted |
| case errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &network) && network.Timeout()): |
| row.Outcome = pdfFailed |
| @@ -203,6 +229,15 @@ func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| }, |
| } |
| proxy.ServeHTTP(out, r) |
| + if row.Outcome == pdfAborted { |
| + panic(http.ErrAbortHandler) |
| + } |
| + // Flush buffered bytes before releasing the slot or counting a render. |
| + // Keep the deadline for net/http's final chunked terminator too. |
| + if err := out.FlushError(); err != nil { |
| + row.Outcome = pdfAborted |
| + panic(http.ErrAbortHandler) |
| + } |
| } |
| type pdfRoundTripper func(*http.Request) (*http.Response, error) |
| @@ -213,10 +248,27 @@ type pdfRequestBody struct { |
| io.ReadCloser |
| bytes atomic.Int64 |
| tooLarge atomic.Bool |
| + aborted atomic.Bool |
| + rc *http.ResponseController |
| + watchdog *pdfIdleWatchdog |
| } |
| func (b *pdfRequestBody) Read(p []byte) (int, error) { |
| + b.watchdog.clientIO(1) |
| + defer b.watchdog.clientIO(-1) |
| + if err := b.watchdog.readDeadline(b.rc, time.Now().Add(b.watchdog.idle)); err != nil { |
| + b.aborted.Store(true) |
| + return 0, err |
| + } |
| n, err := b.ReadCloser.Read(p) |
| + if n > 0 { |
| + b.watchdog.progress() |
| + } |
| + if err == io.EOF { |
| + _ = b.watchdog.readDeadline(b.rc, time.Time{}) |
| + } else if err != nil { |
| + b.aborted.Store(true) |
| + } |
| b.bytes.Add(int64(n)) |
| var limit *http.MaxBytesError |
| if errors.As(err, &limit) { |
| @@ -228,6 +280,7 @@ func (b *pdfRequestBody) Read(p []byte) (int, error) { |
| type pdfResponseBody struct { |
| io.ReadCloser |
| remaining int64 |
| + watchdog *pdfIdleWatchdog |
| } |
| func (b *pdfResponseBody) Read(p []byte) (int, error) { |
| @@ -247,13 +300,18 @@ func (b *pdfResponseBody) Read(p []byte) (int, error) { |
| } |
| n, err := b.ReadCloser.Read(p) |
| b.remaining -= int64(n) |
| + if n > 0 { |
| + b.watchdog.progress() |
| + } |
| return n, err |
| } |
| type pdfResponseWriter struct { |
| http.ResponseWriter |
| - status int |
| - bytes int64 |
| + status int |
| + bytes int64 |
| + rc *http.ResponseController |
| + watchdog *pdfIdleWatchdog |
| } |
| func (w *pdfResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| @@ -268,14 +326,128 @@ func (w *pdfResponseWriter) WriteHeader(status int) { |
| w.ResponseWriter.WriteHeader(status) |
| } |
| func (w *pdfResponseWriter) Write(p []byte) (int, error) { |
| + if w.watchdog != nil { |
| + w.watchdog.clientIO(1) |
| + defer w.watchdog.clientIO(-1) |
| + if err := w.writeDeadline(); err != nil { |
| + return 0, err |
| + } |
| + } |
| if w.status == 0 { |
| w.WriteHeader(http.StatusOK) |
| } |
| n, err := w.ResponseWriter.Write(p) |
| w.bytes += int64(n) |
| + if n > 0 && w.watchdog != nil { |
| + w.watchdog.progress() |
| + } |
| return n, err |
| } |
| +func (w *pdfResponseWriter) writeDeadline() error { |
| + err := w.rc.SetWriteDeadline(time.Now().Add(w.watchdog.idle)) |
| + if errors.Is(err, http.ErrNotSupported) { |
| + return nil |
| + } |
| + return err |
| +} |
| + |
| +func (w *pdfResponseWriter) FlushError() error { |
| + w.watchdog.clientIO(1) |
| + defer w.watchdog.clientIO(-1) |
| + if err := w.writeDeadline(); err != nil { |
| + return err |
| + } |
| + err := w.rc.Flush() |
| + if errors.Is(err, http.ErrNotSupported) { |
| + return nil |
| + } |
| + return err |
| +} |
| + |
| +// The timer spans engine writes, response headers and response reads. Client |
| +// reads and writes have socket deadlines too; tracking them attributes a stall |
| +// to the client even if the watchdog fires before the socket timeout does. |
| +type pdfIdleWatchdog struct { |
| + mu sync.Mutex |
| + idle time.Duration |
| + deadline time.Time |
| + timer *time.Timer |
| + cancel func() |
| + clients int |
| + expired pdfOutcome |
| + stopped bool |
| +} |
| + |
| +func newPDFIdleWatchdog(idle time.Duration, cancel func()) *pdfIdleWatchdog { |
| + w := &pdfIdleWatchdog{idle: idle, deadline: time.Now().Add(idle), cancel: cancel} |
| + w.timer = time.AfterFunc(idle, w.expire) |
| + return w |
| +} |
| + |
| +func (w *pdfIdleWatchdog) expire() { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if w.stopped || w.expired != "" { |
| + return |
| + } |
| + // Reset can race an already dispatched callback. Recheck progress |
| + // under the same lock before cancelling a transfer. |
| + if left := time.Until(w.deadline); left > 0 { |
| + w.timer.Reset(left) |
| + return |
| + } |
| + w.expired = pdfFailed |
| + if w.clients > 0 { |
| + w.expired = pdfAborted |
| + } |
| + w.cancel() |
| +} |
| + |
| +// Serialize renewal with expiry so a late upload read cannot undo the |
| +// deadline that wakes Transport's cancelled request-body reader. |
| +func (w *pdfIdleWatchdog) readDeadline(rc *http.ResponseController, deadline time.Time) error { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if w.expired != "" || w.stopped { |
| + return context.Canceled |
| + } |
| + err := rc.SetReadDeadline(deadline) |
| + if errors.Is(err, http.ErrNotSupported) { |
| + return nil |
| + } |
| + return err |
| +} |
| + |
| +func (w *pdfIdleWatchdog) progress() { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if !w.stopped && w.expired == "" { |
| + w.deadline = time.Now().Add(w.idle) |
| + w.timer.Reset(w.idle) |
| + } |
| +} |
| + |
| +func (w *pdfIdleWatchdog) clientIO(delta int) { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + w.clients += delta |
| +} |
| + |
| +func (w *pdfIdleWatchdog) outcome() pdfOutcome { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + return w.expired |
| +} |
| + |
| +func (w *pdfIdleWatchdog) stop() pdfOutcome { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + w.stopped = true |
| + w.timer.Stop() |
| + return w.expired |
| +} |
| + |
| func pdfFilterResponseHeaders(header http.Header) { |
| for key := range header { |
| switch http.CanonicalHeaderKey(key) { |
diff --git a/internal/console/apipdf_test.go b/internal/console/apipdf_test.go| index 91a8b26ff..2d10be788 100644 |
| --- a/internal/console/apipdf_test.go |
| +++ b/internal/console/apipdf_test.go |
| @@ -1,11 +1,15 @@ |
| package console |
| import ( |
| + "bufio" |
| "bytes" |
| "context" |
| "encoding/json" |
| + "errors" |
| + "fmt" |
| "io" |
| "mime/multipart" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "net/http/httptrace" |
| @@ -266,6 +270,7 @@ func TestPDFDoorResponseLimit(t *testing.T) { |
| t.Fatalf("output = %d bytes, err %v; want 64 MiB then abort", n, err) |
| } |
| row := fx.row(t, pdfOutcome("aborted"), 200) |
| + fx.wantSlotsFree(t) |
| if row.BytesOut != n { |
| t.Fatalf("row bytes = %d, sent %d", row.BytesOut, n) |
| } |
| @@ -548,3 +553,193 @@ func TestPDFDoorSlowUpload(t *testing.T) { |
| } |
| fx.row(t, pdfRendered, 200) |
| } |
| + |
| +func (fx *pdfDoorFixture) wantSlotsFree(t *testing.T) { |
| + t.Helper() |
| + for i := 0; i < 4; i++ { |
| + defer pdfAcquire(t, fx.srv.pdfLimiter, fx.sqid, time.Now())() |
| + } |
| +} |
| + |
| +func (fx *pdfDoorFixture) rawRequest(t *testing.T, size int) *net.TCPConn { |
| + t.Helper() |
| + conn, err := net.Dial("tcp", strings.TrimPrefix(fx.ts.URL, "http://")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tcp := conn.(*net.TCPConn) |
| + t.Cleanup(func() { tcp.Close() }) |
| + if err := tcp.SetReadBuffer(1024); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tcp.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = fmt.Fprintf(tcp, "POST /api/cli/apps/%s/shop/pdf/%s HTTP/1.1\r\nHost: console\r\nAuthorization: Bearer %s\r\nContent-Length: %d\r\n\r\n", fx.sqid, pdfHTMLRoute, fx.token, size) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return tcp |
| +} |
| + |
| +func TestPDFDoorIdleClientUpload(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) }) |
| + fx.srv.pdfIdleTimeout = 100 * time.Millisecond |
| + conn := fx.rawRequest(t, 100) |
| + if _, err := conn.Write([]byte("start")); err != nil { |
| + t.Fatal(err) |
| + } |
| + row := fx.row(t, pdfAborted, 0) |
| + if row.BytesIn != 5 { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + fx.wantSlotsFree(t) |
| +} |
| + |
| +func TestPDFDoorIdleClientDownload(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/pdf") |
| + io.CopyN(w, pdfGeneratedBytes{}, 32<<20) |
| + }) |
| + fx.srv.pdfIdleTimeout = 100 * time.Millisecond |
| + conn := fx.rawRequest(t, 0) |
| + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 200 { |
| + t.Fatalf("status = %d", resp.StatusCode) |
| + } |
| + // Leave the body unread and the socket open until the slot is free. |
| + row := fx.row(t, pdfAborted, 200) |
| + if row.BytesOut == 0 || row.BytesOut >= 32<<20 { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + fx.wantSlotsFree(t) |
| +} |
| + |
| +func TestPDFDoorIdleEngineUpload(t *testing.T) { |
| + stop := make(chan struct{}) |
| + started := make(chan struct{}) |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + close(started) |
| + <-stop |
| + }) |
| + t.Cleanup(func() { close(stop) }) |
| + fx.srv.pdfIdleTimeout = 100 * time.Millisecond |
| + conn := fx.rawRequest(t, 32<<20) |
| + done := make(chan struct{}) |
| + go func() { defer close(done); io.CopyN(conn, pdfGeneratedBytes{}, 32<<20) }() |
| + t.Cleanup(func() { conn.Close(); <-done }) |
| + select { |
| + case <-started: |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("engine never started") |
| + } |
| + row := fx.row(t, pdfFailed, 504) |
| + if row.BytesIn == 0 || row.BytesIn >= 32<<20 { |
| + t.Fatalf("engine did not stall mid-upload: %+v", row) |
| + } |
| + fx.wantSlotsFree(t) |
| +} |
| + |
| +func TestPDFDoorIdleEngineDownload(t *testing.T) { |
| + stop := make(chan struct{}) |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + io.Copy(io.Discard, r.Body) |
| + w.Header().Set("Content-Type", "application/pdf") |
| + io.WriteString(w, "%PDF-start") |
| + w.(http.Flusher).Flush() |
| + <-stop |
| + }) |
| + t.Cleanup(func() { close(stop) }) |
| + fx.srv.pdfIdleTimeout = 100 * time.Millisecond |
| + resp := fx.request(t, pdfHTMLRoute, strings.NewReader("input"), nil) |
| + row := fx.row(t, pdfFailed, 200) |
| + fx.wantSlotsFree(t) |
| + body, err := io.ReadAll(resp.Body) |
| + if err == nil || string(body) != "%PDF-start" || row.BytesOut != int64(len(body)) { |
| + t.Fatalf("body = %q, err = %v, row = %+v", body, err, row) |
| + } |
| +} |
| + |
| +func TestPDFDoorIdleProgress(t *testing.T) { |
| + for _, direction := range []string{"upload", "download"} { |
| + t.Run(direction, func(t *testing.T) { |
| + const chunks = 12 |
| + const gap = 30 * time.Millisecond |
| + const idle = 200 * time.Millisecond |
| + want := strings.Repeat("progress", chunks) |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + data, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + return |
| + } |
| + if direction == "upload" { |
| + w.Write(data) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/pdf") |
| + for i := 0; i < chunks; i++ { |
| + if _, err := io.WriteString(w, "progress"); err != nil { |
| + return |
| + } |
| + w.(http.Flusher).Flush() |
| + time.Sleep(gap) |
| + } |
| + }) |
| + fx.srv.pdfIdleTimeout = idle |
| + // A stale server-wide read deadline must not cap an active upload. |
| + fx.ts.Close() |
| + fx.ts = httptest.NewUnstartedServer(fx.srv) |
| + fx.ts.Config = NewHTTPServer(fx.srv) |
| + fx.ts.Config.ReadTimeout = idle |
| + fx.ts.Start() |
| + t.Cleanup(fx.ts.Close) |
| + var input io.Reader |
| + if direction == "upload" { |
| + reader, writer := io.Pipe() |
| + done := make(chan struct{}) |
| + defer func() { reader.Close(); <-done }() |
| + go func() { |
| + defer close(done) |
| + defer writer.Close() |
| + for i := 0; i < chunks; i++ { |
| + if _, err := io.WriteString(writer, "progress"); err != nil { |
| + return |
| + } |
| + time.Sleep(gap) |
| + } |
| + }() |
| + input = reader |
| + } |
| + resp := fx.request(t, pdfHTMLRoute, input, nil) |
| + body, err := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 200 || err != nil || string(body) != want { |
| + t.Fatalf("response = %d %q, %v", resp.StatusCode, body, err) |
| + } |
| + fx.row(t, pdfRendered, 200) |
| + fx.wantSlotsFree(t) |
| + }) |
| + } |
| +} |
| + |
| +func TestPDFDoorExpiredUploadDoesNotResume(t *testing.T) { |
| + expired := make(chan struct{}) |
| + watchdog := newPDFIdleWatchdog(time.Millisecond, func() { close(expired) }) |
| + defer watchdog.stop() |
| + select { |
| + case <-expired: |
| + case <-time.After(time.Second): |
| + t.Fatal("watchdog did not expire") |
| + } |
| + body := &pdfRequestBody{ |
| + ReadCloser: io.NopCloser(strings.NewReader("late bytes")), |
| + rc: http.NewResponseController(httptest.NewRecorder()), |
| + watchdog: watchdog, |
| + } |
| + var buf [32]byte |
| + if n, err := body.Read(buf[:]); n != 0 || !errors.Is(err, context.Canceled) { |
| + t.Fatalf("expired upload resumed: %d bytes, %v", n, err) |
| + } |
| +} |
diff --git a/internal/console/pdf_copy.go b/internal/console/pdf_copy.go| index fdc091612..726f17186 100644 |
| --- a/internal/console/pdf_copy.go |
| +++ b/internal/console/pdf_copy.go |
| @@ -9,7 +9,7 @@ var pdfCopy = map[string]string{ |
| "pdf.webhook": "webhooks are not available here. send the PDF request without a webhook header", |
| "pdf.too_large": "the request is over 32 MiB. send a smaller request", |
| "pdf.busy_account": "this account already has %d PDFs rendering. wait for one to finish and try again", |
| - "pdf.rate": "this account has asked for more than %d PDFs in a minute. try again in %d seconds", |
| + "pdf.rate": "this account has asked for more than %d PDFs in a minute. try again in a moment", |
| "pdf.busy_engine": "the PDF engine is busy. try again in a few seconds", |
| "pdf.engine_down": "the PDF engine did not answer. try again shortly", |
| "pdf.engine_timeout": "the PDF engine took more than 60 seconds and was stopped. try again", |
diff --git a/internal/console/pdflimit.go b/internal/console/pdflimit.go| index c45cb451d..53766ca65 100644 |
| --- a/internal/console/pdflimit.go |
| +++ b/internal/console/pdflimit.go |
| @@ -93,7 +93,7 @@ func (l *pdfLimiter) acquire(account string, now time.Time) (release func(), ref |
| 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)} |
| + return nil, &pdfRefusal{http.StatusTooManyRequests, retry, pdfText("pdf.rate", l.limits.PerMinute)} |
| } |
| a.tokens = tokens - 1 |
| if now.After(a.at) { |
diff --git a/internal/console/pdflimit_test.go b/internal/console/pdflimit_test.go| index eb38ae82e..8a2be1023 100644 |
| --- a/internal/console/pdflimit_test.go |
| +++ b/internal/console/pdflimit_test.go |
| @@ -63,7 +63,7 @@ func TestPDFLimiterAccountInflight(t *testing.T) { |
| for i := 0; i < 15; i++ { |
| pdfAcquire(t, l, "acct1", now)() |
| } |
| - pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60, 1)}) |
| + pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60)}) |
| } |
| func TestPDFLimiterRate(t *testing.T) { |
| @@ -72,18 +72,18 @@ func TestPDFLimiterRate(t *testing.T) { |
| for i := 0; i < 20; i++ { |
| pdfAcquire(t, l, "acct1", now)() |
| } |
| - pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60, 1)}) |
| + pdfWantRefusal(t, l, "acct1", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60)}) |
| 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)}) |
| + pdfWantRefusal(t, l, "acct1", now.Add(time.Second), pdfRefusal{429, 1, pdfText("pdf.rate", 60)}) |
| } |
| 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)}) |
| + pdfWantRefusal(t, l, "acct", now.Add(100*time.Millisecond), pdfRefusal{429, 6, pdfText("pdf.rate", 10)}) |
| + pdfWantRefusal(t, l, "acct", now.Add(5500*time.Millisecond), pdfRefusal{429, 1, pdfText("pdf.rate", 10)}) |
| pdfAcquire(t, l, "acct", now.Add(6*time.Second))() |
| } |
| @@ -114,7 +114,7 @@ func TestPDFLimiterRefusalOrder(t *testing.T) { |
| 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)}) |
| + pdfWantRefusal(t, l, "a", now, pdfRefusal{429, 1, pdfText("pdf.rate", 60)}) |
| } |
| func TestPDFLimiterReleaseIdempotent(t *testing.T) { |
| @@ -182,7 +182,7 @@ func TestPDFLimiterReclaimsIdleAccounts(t *testing.T) { |
| } |
| 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)}) |
| + pdfWantRefusal(t, l, "slow", now.Add(time.Minute), pdfRefusal{429, 60, pdfText("pdf.rate", 1)}) |
| } |
| func TestPDFLimitsServerConfig(t *testing.T) { |
| @@ -194,3 +194,10 @@ func TestPDFLimitsServerConfig(t *testing.T) { |
| } |
| pdfWantRefusal(t, fx.srv.pdfLimiter, "acct", now, pdfRefusal{429, 2, pdfText("pdf.busy_account", 2)}) |
| } |
| + |
| +func TestPDFRateCopy(t *testing.T) { |
| + want := "this account has asked for more than 60 PDFs in a minute. try again in a moment" |
| + if got := pdfText("pdf.rate", 60); got != want { |
| + t.Fatalf("rate copy = %q, want %q", got, want) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index eb3726790..f4d0d8a43 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -983,10 +983,11 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| - pdfTimeout time.Duration |
| - pdfLimiter *pdfLimiter |
| - recordPDF func(context.Context, pdfRenderRow) |
| - purchaseWake chan struct{} |
| + pdfTimeout time.Duration |
| + pdfIdleTimeout time.Duration |
| + pdfLimiter *pdfLimiter |
| + recordPDF func(context.Context, pdfRenderRow) |
| + purchaseWake chan struct{} |
| // manifestSeen is the sqids whose accounts/<sqid>/account.json this |
| // process has seen exist (read, or written by the backfill), so an app |