mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
fix(api): keep a handler past its hard timeout away from the pooled request context
This commit is contained in:
@@ -117,14 +117,20 @@ type Route struct {
|
||||
// Optional.
|
||||
DisableTelemetry bool
|
||||
|
||||
// AnswersDirectly tells that a multipart route writes its response
|
||||
// itself, such as JSON, rather than producing output files. Middlewares
|
||||
// that deliver output files elsewhere, such as the webhook, read it with
|
||||
// [RouteAnswersDirectly] to refuse the request before it runs.
|
||||
// AnswersDirectly tells that a multipart route answers with a value it
|
||||
// sets with [Context.SetAnswer], sent as JSON, rather than producing
|
||||
// output files. Middlewares that deliver output files elsewhere, such as
|
||||
// the webhook, read it with [RouteAnswersDirectly] to refuse the request
|
||||
// before it runs.
|
||||
// Optional.
|
||||
AnswersDirectly bool
|
||||
|
||||
// Handler is the function that handles the request.
|
||||
// Handler is the function that handles the request. The handler of a
|
||||
// multipart route never writes the response: it registers output files
|
||||
// with [Context.AddOutputPaths], or sets an answer with
|
||||
// [Context.SetAnswer], and the API sends them. It runs under a hard
|
||||
// timeout, on an [echo.Context] whose response is discarded. The handler
|
||||
// of any other route writes its response itself.
|
||||
// Required.
|
||||
Handler echo.HandlerFunc
|
||||
}
|
||||
@@ -710,9 +716,9 @@ func (a *Api) Start() error {
|
||||
for _, externalMultipartMiddleware := range externalMultipartMiddlewares {
|
||||
middlewares = append(middlewares, externalMultipartMiddleware.Handler)
|
||||
}
|
||||
}
|
||||
|
||||
middlewares = append(middlewares, hardTimeoutMiddleware(hardTimeout))
|
||||
middlewares = append(middlewares, hardTimeoutMiddleware(hardTimeout))
|
||||
}
|
||||
|
||||
a.srv.Add(
|
||||
route.Method,
|
||||
@@ -747,22 +753,14 @@ func (a *Api) Start() error {
|
||||
copy(checks, a.healthChecks)
|
||||
checks = append(checks, health.WithTimeout(a.timeout))
|
||||
checker := health.NewChecker(checks...)
|
||||
healthCheckHandler := health.NewHandler(checker)
|
||||
// The health handler writes its own response, so the hard timeout is
|
||||
// [http.TimeoutHandler]'s: it buffers what the handler writes and drops it
|
||||
// once the time is up, rather than let a late answer reach the response.
|
||||
_, hardTimeoutMessage := ParseError(context.DeadlineExceeded)
|
||||
healthCheckHandler := echo.WrapHandler(http.TimeoutHandler(health.NewHandler(checker), hardTimeout, hardTimeoutMessage))
|
||||
|
||||
a.srv.GET(
|
||||
fmt.Sprintf("%s%s", a.rootPath, "health"),
|
||||
func() echo.HandlerFunc {
|
||||
return echo.WrapHandler(healthCheckHandler)
|
||||
}(),
|
||||
hardTimeoutMiddleware(hardTimeout),
|
||||
)
|
||||
a.srv.HEAD(
|
||||
fmt.Sprintf("%s%s", a.rootPath, "health"),
|
||||
func() echo.HandlerFunc {
|
||||
return echo.WrapHandler(healthCheckHandler)
|
||||
}(),
|
||||
hardTimeoutMiddleware(hardTimeout),
|
||||
)
|
||||
a.srv.GET(fmt.Sprintf("%s%s", a.rootPath, "health"), healthCheckHandler)
|
||||
a.srv.HEAD(fmt.Sprintf("%s%s", a.rootPath, "health"), healthCheckHandler)
|
||||
|
||||
// ...the version route.
|
||||
a.srv.GET(
|
||||
|
||||
@@ -58,6 +58,7 @@ type Context struct {
|
||||
diskToOriginalMu sync.RWMutex
|
||||
outputPaths []string
|
||||
outputHeaders map[string]string
|
||||
answer any
|
||||
cancelled bool
|
||||
|
||||
// fileOrder records the order files were received in, keyed by disk path.
|
||||
@@ -88,8 +89,12 @@ type Context struct {
|
||||
// yields whichever request happens to own it by then.
|
||||
outputFilename string
|
||||
|
||||
// correlationIdHeader and correlationId are snapshotted for the same
|
||||
// reason, and downloads forward them.
|
||||
correlationIdHeader string
|
||||
correlationId string
|
||||
|
||||
logger *slog.Logger
|
||||
echoCtx *echo.Context
|
||||
mkdirAll gotenberg.MkdirAll
|
||||
pathRename gotenberg.PathRename
|
||||
context.Context
|
||||
@@ -203,17 +208,20 @@ func newContext(echoCtx *echo.Context, logger *slog.Logger, fs *gotenberg.FileSy
|
||||
|
||||
// Snapshot now, while echoCtx still belongs to this request.
|
||||
outputFilename, _ := echoCtx.Get("outputFilename").(string)
|
||||
correlationIdHeader, _ := echoCtx.Get("correlationIdHeader").(string)
|
||||
correlationId, _ := echoCtx.Get("correlationId").(string)
|
||||
|
||||
ctx := &Context{
|
||||
outputPaths: make([]string, 0),
|
||||
cancelled: false,
|
||||
outputFilename: outputFilename,
|
||||
timeout: timeout,
|
||||
logger: logger,
|
||||
echoCtx: echoCtx,
|
||||
mkdirAll: new(gotenberg.OsMkdirAll),
|
||||
pathRename: new(gotenberg.OsPathRename),
|
||||
Context: processCtx,
|
||||
outputPaths: make([]string, 0),
|
||||
cancelled: false,
|
||||
outputFilename: outputFilename,
|
||||
correlationIdHeader: correlationIdHeader,
|
||||
correlationId: correlationId,
|
||||
timeout: timeout,
|
||||
logger: logger,
|
||||
mkdirAll: new(gotenberg.OsMkdirAll),
|
||||
pathRename: new(gotenberg.OsPathRename),
|
||||
Context: processCtx,
|
||||
}
|
||||
|
||||
// A custom cancel function which removes the context's working directory
|
||||
@@ -522,10 +530,8 @@ func (ctx *Context) downloadOne(groupCtx context.Context, i int, dl downloadFrom
|
||||
}
|
||||
|
||||
// Propagate correlation ID header.
|
||||
if correlationIdHeader, ok := ctx.echoCtx.Get("correlationIdHeader").(string); ok {
|
||||
if correlationId, ok := ctx.echoCtx.Get("correlationId").(string); ok {
|
||||
req.Header.Set(correlationIdHeader, correlationId)
|
||||
}
|
||||
if ctx.correlationIdHeader != "" && ctx.correlationId != "" {
|
||||
req.Header.Set(ctx.correlationIdHeader, ctx.correlationId)
|
||||
}
|
||||
|
||||
// Entries are serialized by the concurrency limit, so a late one can start
|
||||
@@ -753,11 +759,6 @@ func (ctx *Context) Timeout() time.Duration {
|
||||
return ctx.timeout
|
||||
}
|
||||
|
||||
// Request returns the [http.Request].
|
||||
func (ctx *Context) Request() *http.Request {
|
||||
return ctx.echoCtx.Request()
|
||||
}
|
||||
|
||||
// FormData return a [FormData]. Every [FormData] of a request records the
|
||||
// fields it reads in the same set, which [FormData.RejectUnknown] checks.
|
||||
func (ctx *Context) FormData() *FormData {
|
||||
@@ -876,6 +877,15 @@ func (ctx *Context) AddOutputPaths(paths ...string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetAnswer sets the value the API answers with, as JSON with a 200 status,
|
||||
// instead of output files. A route that reads rather than writes PDFs, such
|
||||
// as one returning metadata, sets it. The API, not the route, writes the
|
||||
// response, and only when the route returns in time. Like
|
||||
// [Context.AddOutputPaths], it is not safe for concurrent use.
|
||||
func (ctx *Context) SetAnswer(answer any) {
|
||||
ctx.answer = answer
|
||||
}
|
||||
|
||||
// SetOutputHeader sets a header that describes the output, such as the
|
||||
// outcome of a remediation. It goes with the output file, on the response or
|
||||
// on the webhook request. Like [Context.AddOutputPaths], it is not safe for
|
||||
|
||||
@@ -258,6 +258,57 @@ func TestNewContext_DownloadFromConcurrentMapWrites(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A download carries the request's correlation ID, the one the client sent
|
||||
// included, even over a downloadFrom entry's own header of the same name.
|
||||
func TestNewContext_DownloadFromForwardsCorrelationId(t *testing.T) {
|
||||
var got atomic.Value
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got.Store(r.Header.Get("Gotenberg-Trace"))
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="download.txt"`)
|
||||
_, _ = w.Write([]byte("downloaded"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
payload, err := json.Marshal([]downloadFrom{{
|
||||
Url: server.URL,
|
||||
ExtraHttpHeaders: map[string]string{"Gotenberg-Trace": "entry"},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal downloadFrom payload: %v", err)
|
||||
}
|
||||
|
||||
body := new(bytes.Buffer)
|
||||
writer := multipart.NewWriter(body)
|
||||
err = writer.WriteField("downloadFrom", string(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("write downloadFrom field: %v", err)
|
||||
}
|
||||
err = writer.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("close multipart writer: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/forms/libreoffice/convert", body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
echoCtx := echo.New().NewContext(req, httptest.NewRecorder())
|
||||
echoCtx.Set("correlationIdHeader", "Gotenberg-Trace")
|
||||
echoCtx.Set("correlationId", "client")
|
||||
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
fs := gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll))
|
||||
|
||||
_, cancel, err := newContext(echoCtx, logger, fs, 10*time.Second, 0, downloadFromConfig{}, archiveConfig{})
|
||||
if err != nil {
|
||||
t.Fatalf("newContext returned error: %v", err)
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
if got, _ := got.Load().(string); got != "client" {
|
||||
t.Fatalf("Gotenberg-Trace = %q, want %q", got, "client")
|
||||
}
|
||||
}
|
||||
|
||||
// A failed download cancels the ones still in flight instead of letting them
|
||||
// run to --api-timeout (env API_TIMEOUT).
|
||||
func TestNewContext_DownloadFromFailureCancelsSiblings(t *testing.T) {
|
||||
|
||||
57
pkg/modules/api/detached_context.go
Normal file
57
pkg/modules/api/detached_context.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
// NewDetachedContext returns an [echo.Context] carrying a snapshot of the
|
||||
// given keys, of the matched route and of its path values, detached from
|
||||
// Echo's context pool and from the client's response.
|
||||
//
|
||||
// Echo returns an [echo.Context] to its sync.Pool as soon as the middleware
|
||||
// chain returns, and hands it to the next request, whose c.Reset() swaps the
|
||||
// request, the response and the store. Code that keeps running past that
|
||||
// point, such as a webhook goroutine or a handler that outlives its hard
|
||||
// timeout, must not hold the pooled context: it would read another request's
|
||||
// values and write into another client's response.
|
||||
//
|
||||
// [echo.NewContext] allocates outside the pool, so recycling cannot reach the
|
||||
// returned context. It shares the [http.Request] of c, so the request
|
||||
// headers, form values and path parameters still read as they do on c. Keys
|
||||
// absent from c are omitted; the returned context still returns nil for them,
|
||||
// matching [echo.Context.Get] behavior.
|
||||
//
|
||||
// The response is not the client's: whatever the code writes to the returned
|
||||
// context lands in a discarding writer. The client only ever gets what the
|
||||
// owner of c writes.
|
||||
//
|
||||
// Call it on the goroutine that owns c, before handing the returned context
|
||||
// to another one.
|
||||
func NewDetachedContext(c *echo.Context, keys ...string) *echo.Context {
|
||||
detached := echo.NewContext(c.Request(), &discardResponseWriter{header: make(http.Header)}, c.Echo())
|
||||
|
||||
route := c.RouteInfo()
|
||||
pathValues := c.PathValues()
|
||||
detached.InitializeRoute(&route, &pathValues)
|
||||
|
||||
for _, key := range keys {
|
||||
if v := c.Get(key); v != nil {
|
||||
detached.Set(key, v)
|
||||
}
|
||||
}
|
||||
|
||||
return detached
|
||||
}
|
||||
|
||||
// discardResponseWriter is an [http.ResponseWriter] that drops everything.
|
||||
type discardResponseWriter struct {
|
||||
header http.Header
|
||||
}
|
||||
|
||||
func (w *discardResponseWriter) Header() http.Header { return w.header }
|
||||
|
||||
func (w *discardResponseWriter) Write(p []byte) (int, error) { return len(p), nil }
|
||||
|
||||
func (w *discardResponseWriter) WriteHeader(int) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
package webhook
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
@@ -19,7 +19,7 @@ func TestNewDetachedContext_SurvivesUnderlyingReset(t *testing.T) {
|
||||
c.Set("logger", logger)
|
||||
c.Set("correlationId", "abc-123")
|
||||
|
||||
detached := newDetachedContext(c, "logger", "correlationId", "missing")
|
||||
detached := NewDetachedContext(c, "logger", "correlationId", "missing")
|
||||
|
||||
// Simulate Echo recycling c for a concurrent request. Reset clears the
|
||||
// pooled store, which is exactly the crash scenario the detached context
|
||||
@@ -48,7 +48,7 @@ func TestNewDetachedContext_SetDoesNotTouchUnderlying(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(req, rec)
|
||||
|
||||
detached := newDetachedContext(c)
|
||||
detached := NewDetachedContext(c)
|
||||
detached.Set("foo", "bar")
|
||||
|
||||
if got, _ := detached.Get("foo").(string); got != "bar" {
|
||||
@@ -64,7 +64,7 @@ func TestNewDetachedContext_DiscardsWrites(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
|
||||
|
||||
detached := newDetachedContext(c)
|
||||
detached := NewDetachedContext(c)
|
||||
|
||||
err := detached.JSON(http.StatusOK, map[string]string{"foo": "bar"})
|
||||
if err != nil {
|
||||
@@ -74,3 +74,30 @@ func TestNewDetachedContext_DiscardsWrites(t *testing.T) {
|
||||
t.Fatalf("detached write reached the client's response: %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDetachedContext_KeepsRouteAndPathValues(t *testing.T) {
|
||||
e := echo.New()
|
||||
e.POST("/forms/:name/*", func(c *echo.Context) error {
|
||||
detached := NewDetachedContext(c)
|
||||
|
||||
// Simulate Echo recycling c for a concurrent request.
|
||||
c.Reset(httptest.NewRequest(http.MethodGet, "/", nil), httptest.NewRecorder())
|
||||
|
||||
if got := detached.Param("name"); got != "pdf" {
|
||||
t.Errorf("Param(name) = %q, want %q", got, "pdf")
|
||||
}
|
||||
if got := detached.Param("*"); got != "merge" {
|
||||
t.Errorf("Param(*) = %q, want %q", got, "merge")
|
||||
}
|
||||
if got := detached.Path(); got != "/forms/:name/*" {
|
||||
t.Errorf("Path = %q, want %q", got, "/forms/:name/*")
|
||||
}
|
||||
if got := detached.Request().URL.Path; got != "/forms/pdf/merge" {
|
||||
t.Errorf("request path = %q, want %q", got, "/forms/pdf/merge")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/forms/pdf/merge", nil))
|
||||
}
|
||||
@@ -31,8 +31,8 @@ var (
|
||||
// in an asynchronous fashion.
|
||||
ErrAsyncProcess = errors.New("async process")
|
||||
|
||||
// ErrNoOutputFile happens when a handler or middleware has already written
|
||||
// the response itself, so no output file must be sent.
|
||||
// ErrNoOutputFile happens when a middleware has already written the
|
||||
// response itself, so neither an answer nor an output file must be sent.
|
||||
ErrNoOutputFile = errors.New("no output file")
|
||||
)
|
||||
|
||||
@@ -146,8 +146,8 @@ func answersDirectlyMiddleware() echo.MiddlewareFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// RouteAnswersDirectly reports whether the route of c writes its response
|
||||
// itself rather than producing output files. See [Route.AnswersDirectly].
|
||||
// RouteAnswersDirectly reports whether the route of c answers with a value
|
||||
// rather than producing output files. See [Route.AnswersDirectly].
|
||||
func RouteAnswersDirectly(c *echo.Context) bool {
|
||||
answers, _ := c.Get(AnswersDirectlyKey).(bool)
|
||||
return answers
|
||||
@@ -516,17 +516,15 @@ func oidcAuthMiddleware(verifier *oidc.IDTokenVerifier) echo.MiddlewareFunc {
|
||||
// contextMiddleware, middleware for "multipart/form-data" requests, sets the
|
||||
// [Context] and related context.CancelFunc in the [echo.Context] under
|
||||
// "context" and "cancel". If the process is synchronous, it also handles the
|
||||
// result of a "multipart/form-data" request.
|
||||
// result of a "multipart/form-data" request: the answer the handler set with
|
||||
// [Context.SetAnswer], or else its output files.
|
||||
//
|
||||
// ctx := c.Get("context").(*api.Context)
|
||||
// cancel := c.Get("cancel").(context.CancelFunc)
|
||||
func contextMiddleware(fs *gotenberg.FileSystem, timeout time.Duration, bodyLimit int64, downloadFromCfg downloadFromConfig, archiveCfg archiveConfig) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c *echo.Context) error {
|
||||
logger, _ := c.Get("logger").(*slog.Logger)
|
||||
if logger == nil {
|
||||
return errors.New("no logger in context (possible pool reuse)")
|
||||
}
|
||||
logger := c.Get("logger").(*slog.Logger)
|
||||
|
||||
// We create a context with a timeout so that underlying processes are
|
||||
// able to stop early and correctly handle a timeout scenario.
|
||||
@@ -552,14 +550,27 @@ func contextMiddleware(fs *gotenberg.FileSystem, timeout time.Duration, bodyLimi
|
||||
defer cancel()
|
||||
|
||||
if errors.Is(err, ErrNoOutputFile) {
|
||||
// A middleware/handler already wrote the response.
|
||||
// A middleware already wrote the response.
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// The handler may still be running after a hard timeout, so
|
||||
// its answer and output files are left alone.
|
||||
return err
|
||||
}
|
||||
|
||||
// This goroutine owns the response: the handler only sets what to
|
||||
// send. See hardTimeoutMiddleware.
|
||||
if ctx.answer != nil {
|
||||
err = c.JSON(http.StatusOK, ctx.answer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send response: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// No error, let's build the output file.
|
||||
outputPath, err := ctx.BuildOutputFile()
|
||||
if err != nil {
|
||||
@@ -582,19 +593,34 @@ func contextMiddleware(fs *gotenberg.FileSystem, timeout time.Duration, bodyLimi
|
||||
}
|
||||
}
|
||||
|
||||
// contextKeys are the [echo.Context] keys the API's middlewares set for the
|
||||
// middlewares and handlers after them.
|
||||
var contextKeys = []string{
|
||||
"logger",
|
||||
"rootPath",
|
||||
"startTime",
|
||||
"outputFilename",
|
||||
"correlationIdHeader",
|
||||
"correlationId",
|
||||
"context",
|
||||
"cancel",
|
||||
AnswersDirectlyKey,
|
||||
}
|
||||
|
||||
// hardTimeoutMiddleware manages hard timeout scenarios, i.e., when a route
|
||||
// handler fails to timeout as expected.
|
||||
//
|
||||
// The handler runs on its own goroutine, which outlives the request after a
|
||||
// hard timeout. It gets a context from [NewDetachedContext] rather than the
|
||||
// pooled c, which Echo recycles for another request once this middleware
|
||||
// returns: whatever the handler writes is dropped, and the response belongs to
|
||||
// the request goroutine alone. A multipart handler sets its answer with
|
||||
// [Context.SetAnswer] or registers output files, and contextMiddleware sends
|
||||
// them when the handler returns in time.
|
||||
func hardTimeoutMiddleware(hardTimeout time.Duration) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c *echo.Context) error {
|
||||
// Guard the type assertion so a pooled [echo.Context] whose
|
||||
// store has been recycled under us does not crash the process.
|
||||
// See the webhook async handler for the race this protects
|
||||
// against.
|
||||
logger, _ := c.Get("logger").(*slog.Logger)
|
||||
if logger == nil {
|
||||
return errors.New("no logger in context (possible pool reuse)")
|
||||
}
|
||||
logger := c.Get("logger").(*slog.Logger)
|
||||
|
||||
// Define a hard timeout if the route handler fails to timeout as
|
||||
// expected.
|
||||
@@ -604,14 +630,13 @@ func hardTimeoutMiddleware(hardTimeout time.Duration) echo.MiddlewareFunc {
|
||||
)
|
||||
defer hardTimeoutCancel()
|
||||
|
||||
detached := NewDetachedContext(c, contextKeys...)
|
||||
errChan := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
// A panic either comes from the handler itself or, after a hard
|
||||
// timeout, from c being recycled under this goroutine. In the
|
||||
// first case the client gets a 500 right away; in the second
|
||||
// nobody reads errChan anymore, and its buffer keeps the send
|
||||
// from blocking.
|
||||
// A handler panic reaches the client as a 500 right away. After
|
||||
// a hard timeout, nobody reads errChan anymore, and its buffer
|
||||
// keeps the send from blocking.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.ErrorContext(hardTimeoutCtx, fmt.Sprintf("recover from handler panic: %v\n%s", r, debug.Stack()))
|
||||
@@ -620,7 +645,7 @@ func hardTimeoutMiddleware(hardTimeout time.Duration) echo.MiddlewareFunc {
|
||||
}()
|
||||
|
||||
// Call the next middleware in the chain.
|
||||
errChan <- next(c)
|
||||
errChan <- next(detached)
|
||||
}()
|
||||
|
||||
select {
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"crypto/rsa"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -367,31 +369,169 @@ func TestTelemetryMiddleware_Route(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHardTimeoutMiddleware_MissingLoggerReturnsErrorInsteadOfPanicking(t *testing.T) {
|
||||
mw := hardTimeoutMiddleware(100 * time.Millisecond)
|
||||
handler := mw(func(c *echo.Context) error { return nil })
|
||||
// newMultipartServer returns a server whose route /forms/test runs handler as
|
||||
// the API runs a multipart route, under the given hard timeout, and whose route
|
||||
// /other answers "other" after a while, to keep a request on a recycled
|
||||
// [echo.Context] busy.
|
||||
func newMultipartServer(t *testing.T, hardTimeout time.Duration, handler echo.HandlerFunc) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
e := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(req, rec)
|
||||
srv := newEchoServer()
|
||||
srv.Pre(
|
||||
latencyMiddleware(),
|
||||
rootPathMiddleware("/"),
|
||||
outputFilenameMiddleware(),
|
||||
telemetryMiddleware(slog.New(slog.DiscardHandler), "", ":3000", "Gotenberg-Trace", nil),
|
||||
versionHeaderMiddleware(),
|
||||
)
|
||||
|
||||
// c has no "logger" key, mimicking a pooled context whose store was
|
||||
// recycled under a concurrently running webhook goroutine. The
|
||||
// middleware must surface an error instead of panicking on the
|
||||
// unchecked type assertion the pre-fix code relied on.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("hardTimeoutMiddleware panicked: %v", r)
|
||||
}
|
||||
}()
|
||||
fs := gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll))
|
||||
srv.POST(
|
||||
"/forms/test",
|
||||
handler,
|
||||
contextMiddleware(fs, time.Minute, 0, downloadFromConfig{disable: true}, archiveConfig{}),
|
||||
hardTimeoutMiddleware(hardTimeout),
|
||||
)
|
||||
srv.POST("/other", func(c *echo.Context) error {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
return c.String(http.StatusOK, "other")
|
||||
})
|
||||
|
||||
err := handler(c)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for missing logger, got nil")
|
||||
ts := httptest.NewServer(srv)
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
return ts
|
||||
}
|
||||
|
||||
// postMultipart posts a multipart form with one field to url.
|
||||
func postMultipart(t *testing.T, url string) *http.Response {
|
||||
t.Helper()
|
||||
|
||||
var body bytes.Buffer
|
||||
form := multipart.NewWriter(&body)
|
||||
err := form.WriteField("foo", "bar")
|
||||
if err != nil {
|
||||
t.Fatalf("write field: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "logger") {
|
||||
t.Fatalf("error = %q, want a message mentioning logger", err)
|
||||
err = form.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("close form: %v", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, url, &body)
|
||||
if err != nil {
|
||||
t.Fatalf("new request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", form.FormDataContentType())
|
||||
req.Header.Set("Gotenberg-Trace", "my-trace")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("post %s: %v", url, err)
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
// A handler that outlives its hard timeout keeps running while Echo hands its
|
||||
// pooled [echo.Context] to the next request. Whatever it does then, the next
|
||||
// request gets its own answer only.
|
||||
func TestHardTimeoutMiddleware_LateHandlerReachesNoOtherRequest(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
late func(c *echo.Context)
|
||||
}{
|
||||
{
|
||||
name: "writes the response",
|
||||
late: func(c *echo.Context) {
|
||||
_ = c.JSON(http.StatusOK, map[string]string{"secret": "late"})
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sets an answer",
|
||||
late: func(c *echo.Context) {
|
||||
c.Get("context").(*Context).SetAnswer(map[string]string{"secret": "late"})
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
ts := newMultipartServer(t, 50*time.Millisecond, func(c *echo.Context) error {
|
||||
defer func() { done <- struct{}{} }()
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
tc.late(c)
|
||||
return nil
|
||||
})
|
||||
|
||||
// Echo's pool may hand the next request another context, and
|
||||
// sync.Pool drops items at random under -race: a few rounds make
|
||||
// the reuse all but certain.
|
||||
for range 3 {
|
||||
resp := postMultipart(t, ts.URL+"/forms/test")
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusServiceUnavailable {
|
||||
t.Fatalf("late request: status %d, want %d", resp.StatusCode, http.StatusServiceUnavailable)
|
||||
}
|
||||
|
||||
resp, err := http.Post(ts.URL+"/other", "text/plain", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("post /other: %v", err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
|
||||
<-done
|
||||
|
||||
if resp.StatusCode != http.StatusOK || string(body) != "other" {
|
||||
t.Fatalf("other request: got %d %q, want %d %q", resp.StatusCode, body, http.StatusOK, "other")
|
||||
}
|
||||
if got := resp.Header.Get(echo.HeaderContentType); got != echo.MIMETextPlainCharsetUTF8 {
|
||||
t.Fatalf("other request: Content-Type %q, want %q", got, echo.MIMETextPlainCharsetUTF8)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The API, not the handler, sends the answer a handler sets in time, with the
|
||||
// headers of any other response.
|
||||
func TestContextMiddleware_SendsAnswer(t *testing.T) {
|
||||
ts := newMultipartServer(t, time.Minute, func(c *echo.Context) error {
|
||||
ctx := c.Get("context").(*Context)
|
||||
|
||||
var foo string
|
||||
err := ctx.FormData().String("foo", &foo).Validate()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx.SetAnswer(map[string]string{"foo": foo})
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
resp := postMultipart(t, ts.URL+"/forms/test")
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d: %s", resp.StatusCode, http.StatusOK, body)
|
||||
}
|
||||
if got := string(body); got != "{\"foo\":\"bar\"}\n" {
|
||||
t.Errorf("body = %q, want the answer as JSON", got)
|
||||
}
|
||||
if got := resp.Header.Get(echo.HeaderContentType); got != echo.MIMEApplicationJSON {
|
||||
t.Errorf("Content-Type = %q, want %q", got, echo.MIMEApplicationJSON)
|
||||
}
|
||||
if got := resp.Header.Get("Gotenberg-Trace"); got != "my-trace" {
|
||||
t.Errorf("Gotenberg-Trace = %q, want %q", got, "my-trace")
|
||||
}
|
||||
if got := resp.Header.Get("Gotenberg-Version"); got == "" {
|
||||
t.Error("Gotenberg-Version missing")
|
||||
}
|
||||
if got := resp.Header.Get(echo.HeaderContentDisposition); got != "" {
|
||||
t.Errorf("Content-Disposition = %q, want none on an answer", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/alexliesenfeld/health"
|
||||
"github.com/labstack/echo/v5"
|
||||
|
||||
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
|
||||
)
|
||||
@@ -84,6 +83,14 @@ func (ctx *ContextMock) OutputPaths() []string {
|
||||
return ctx.outputPaths
|
||||
}
|
||||
|
||||
// Answer returns the answer [Context.SetAnswer] set.
|
||||
//
|
||||
// ctx := &api.ContextMock{Context: &api.Context{}}
|
||||
// answer := ctx.Answer()
|
||||
func (ctx *ContextMock) Answer() any {
|
||||
return ctx.answer
|
||||
}
|
||||
|
||||
// SetTimeout sets the time limit of the request.
|
||||
//
|
||||
// ctx := &api.ContextMock{Context: &api.Context{}}
|
||||
@@ -100,14 +107,6 @@ func (ctx *ContextMock) SetLogger(logger *slog.Logger) {
|
||||
ctx.logger = logger
|
||||
}
|
||||
|
||||
// SetEchoContext sets the [echo.Context].
|
||||
//
|
||||
// ctx := &api.ContextMock{Context: &api.Context{}}
|
||||
// ctx.setEchoContext(c)
|
||||
func (ctx *ContextMock) SetEchoContext(c *echo.Context) {
|
||||
ctx.echoCtx = c
|
||||
}
|
||||
|
||||
// SetMkdirAll sets the [gotenberg.MkdirAll].
|
||||
//
|
||||
// ctx := &api.ContextMock{Context: &api.Context{}}
|
||||
|
||||
@@ -156,12 +156,9 @@ func readRoute(processor *Processor, name string, newRead func(form *api.FormDat
|
||||
res[ctx.OriginalFilename(inputPath)] = collected[i]
|
||||
}
|
||||
|
||||
err = c.JSON(http.StatusOK, res)
|
||||
if err != nil {
|
||||
return fmt.Errorf("return JSON response: %w", err)
|
||||
}
|
||||
ctx.SetAnswer(res)
|
||||
|
||||
return api.ErrNoOutputFile
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,11 +24,34 @@ func serve(t *testing.T, route api.Route, values map[string][]string, fixtures .
|
||||
mock := &api.ContextMock{Context: ctx}
|
||||
mock.SetValues(values)
|
||||
|
||||
rec, err := handle(t, route, ctx)
|
||||
|
||||
return ctx, rec, err
|
||||
}
|
||||
|
||||
// handle runs the handler of route on ctx, then writes the answer it set as
|
||||
// the API does. The handler itself must not write the response.
|
||||
func handle(t *testing.T, route api.Route, ctx *api.Context) (*httptest.ResponseRecorder, error) {
|
||||
t.Helper()
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c := echo.New().NewContext(httptest.NewRequest(http.MethodPost, route.Path, nil), rec)
|
||||
c.Set("context", ctx)
|
||||
|
||||
return ctx, rec, route.Handler(c)
|
||||
err := route.Handler(c)
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Fatalf("handler wrote %q, want it to set an answer instead", rec.Body.String())
|
||||
}
|
||||
|
||||
answer := (&api.ContextMock{Context: ctx}).Answer()
|
||||
if err == nil && answer != nil {
|
||||
jsonErr := c.JSON(http.StatusOK, answer)
|
||||
if jsonErr != nil {
|
||||
t.Fatalf("write answer: %v", jsonErr)
|
||||
}
|
||||
}
|
||||
|
||||
return rec, err
|
||||
}
|
||||
|
||||
func TestStageRoute(t *testing.T) {
|
||||
@@ -248,8 +271,8 @@ func TestPipeRoute(t *testing.T) {
|
||||
func TestReadRoutes(t *testing.T) {
|
||||
// pages_12.pdf carries neither an /Info dictionary nor an XMP packet.
|
||||
_, rec, err := serve(t, metadataRoute(testProcessor()), nil, "pages_12.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
t.Fatalf("handler: %v, want ErrNoOutputFile after writing JSON", err)
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
if got := strings.TrimSpace(rec.Body.String()); got != `{"pages_12.pdf":{}}` {
|
||||
@@ -257,8 +280,8 @@ func TestReadRoutes(t *testing.T) {
|
||||
}
|
||||
|
||||
_, rec, err = serve(t, infoRoute(testProcessor()), nil, "pages_12.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
t.Fatalf("handler: %v, want ErrNoOutputFile after writing JSON", err)
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
var info map[string]documentInfo
|
||||
@@ -277,7 +300,7 @@ func TestReadRoutes(t *testing.T) {
|
||||
}
|
||||
|
||||
_, rec, err = serve(t, validateRoute(testProcessor()), map[string][]string{"profile": {"PDF/A-2b"}}, "page_1.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
@@ -290,7 +313,7 @@ func TestReadRoutes(t *testing.T) {
|
||||
t.Fatalf("a plain PDF reported as PDF/A-2b compliant: %+v", got)
|
||||
}
|
||||
_, rec, err = serve(t, validateRoute(testProcessor()), map[string][]string{"profile": {"Factur-X"}}, "page_1.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
@@ -318,7 +341,7 @@ func TestReadRoutes(t *testing.T) {
|
||||
// 400 with the pairs.
|
||||
func TestValidateRoutePair(t *testing.T) {
|
||||
_, rec, err := serve(t, validateRoute(testProcessor()), map[string][]string{"profile": {"PDF/A-2b", "PDF/UA-1"}}, "page_1.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
@@ -347,7 +370,7 @@ func TestValidateRoutePair(t *testing.T) {
|
||||
}
|
||||
|
||||
_, rec, err = serve(t, validateRoute(testProcessor()), map[string][]string{"profile": {"PDF/UA-1"}}, "page_1.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
@@ -396,13 +419,9 @@ func readMetadata(t *testing.T, processor *Processor, path string) documentMetad
|
||||
ctx, _ := testContext(t)
|
||||
(&api.ContextMock{Context: ctx}).SetFiles(map[string]string{"doc.pdf": path})
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c := echo.New().NewContext(httptest.NewRequest(http.MethodPost, "/forms/pdf/metadata", nil), rec)
|
||||
c.Set("context", ctx)
|
||||
|
||||
err := metadataRoute(processor).Handler(c)
|
||||
if err != api.ErrNoOutputFile {
|
||||
t.Fatalf("handler: %v, want ErrNoOutputFile after writing JSON", err)
|
||||
rec, err := handle(t, metadataRoute(processor), ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
var answer map[string]documentMetadata
|
||||
@@ -578,7 +597,7 @@ func TestUnknownFields(t *testing.T) {
|
||||
// The fields a route reads are not unknown: password on a read route,
|
||||
// profile on the validate route, the stage's options on a stage route.
|
||||
_, _, err := serve(t, validateRoute(testProcessor()), map[string][]string{"profile": {"PDF/A-2b"}, "password": {""}}, "page_1.pdf")
|
||||
if err != api.ErrNoOutputFile {
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
|
||||
@@ -683,8 +702,8 @@ func TestFormRoute(t *testing.T) {
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, rec, err := serve(t, formRoute(testProcessor()), tc.values, tc.fixture)
|
||||
if err != api.ErrNoOutputFile {
|
||||
t.Fatalf("handler: %v, want ErrNoOutputFile after writing JSON", err)
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
if got := strings.TrimSpace(rec.Body.String()); got != tc.wantBody {
|
||||
@@ -708,13 +727,9 @@ func readFormFields(t *testing.T, processor *Processor, path string) []formField
|
||||
ctx, _ := testContext(t)
|
||||
(&api.ContextMock{Context: ctx}).SetFiles(map[string]string{"doc.pdf": path})
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c := echo.New().NewContext(httptest.NewRequest(http.MethodPost, "/forms/pdf/form", nil), rec)
|
||||
c.Set("context", ctx)
|
||||
|
||||
err := formRoute(processor).Handler(c)
|
||||
if err != api.ErrNoOutputFile {
|
||||
t.Fatalf("handler: %v, want ErrNoOutputFile after writing JSON", err)
|
||||
rec, err := handle(t, formRoute(processor), ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("handler: %v", err)
|
||||
}
|
||||
|
||||
var answer map[string][]formField
|
||||
|
||||
@@ -270,8 +270,8 @@ func webhookMiddleware(w *Webhook) api.Middleware {
|
||||
|
||||
// The downstream chain writes into a detached response, never
|
||||
// the client's: the client only ever gets the 204 below, and the
|
||||
// outcome goes to the webhook URLs. See newDetachedContext.
|
||||
detached := newDetachedContext(c, "logger", "context", "correlationId", "correlationIdHeader", "startTime")
|
||||
// outcome goes to the webhook URLs. See api.NewDetachedContext.
|
||||
detached := api.NewDetachedContext(c, "logger", "context", "correlationId", "correlationIdHeader", "startTime")
|
||||
|
||||
process := func() {
|
||||
err := next(detached)
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestWebhookMiddleware_SyncModeAnswersOnce(t *testing.T) {
|
||||
expectEventStatus: http.StatusInternalServerError,
|
||||
},
|
||||
{
|
||||
scenario: "route that writes its own response",
|
||||
scenario: "chain that answers itself",
|
||||
next: func(c *echo.Context) error {
|
||||
err := c.JSON(http.StatusOK, map[string]string{"foo": "bar"})
|
||||
if err != nil {
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
// newDetachedContext returns an [echo.Context] carrying a snapshot of the given
|
||||
// keys, detached from Echo's context pool and from the client's response.
|
||||
//
|
||||
// Echo returns an [echo.Context] to its sync.Pool as soon as the synchronous
|
||||
// handler returns, including when the webhook middleware returns
|
||||
// [api.ErrAsyncProcess]. A concurrent request can then claim the recycled
|
||||
// context and c.Reset() wipes the shared store out from under the webhook
|
||||
// goroutine, which causes any `c.Get("logger").(*slog.Logger)`-style assertion
|
||||
// further down the chain to panic on a nil value.
|
||||
//
|
||||
// [echo.NewContext] allocates outside the pool, so recycling cannot reach the
|
||||
// returned context. Keys absent from c are omitted; the returned context still
|
||||
// returns nil for them, matching [echo.Context.Get] behavior.
|
||||
//
|
||||
// The response is pooled too, and the client must only ever get the webhook
|
||||
// middleware's 204. Whatever the downstream chain writes, such as a route
|
||||
// answering with JSON, lands in a discarding writer instead.
|
||||
func newDetachedContext(c *echo.Context, keys ...string) *echo.Context {
|
||||
detached := echo.NewContext(c.Request(), &discardResponseWriter{header: make(http.Header)}, c.Echo())
|
||||
|
||||
for _, key := range keys {
|
||||
if v := c.Get(key); v != nil {
|
||||
detached.Set(key, v)
|
||||
}
|
||||
}
|
||||
|
||||
return detached
|
||||
}
|
||||
|
||||
// discardResponseWriter is an [http.ResponseWriter] that drops everything.
|
||||
type discardResponseWriter struct {
|
||||
header http.Header
|
||||
}
|
||||
|
||||
func (w *discardResponseWriter) Header() http.Header { return w.header }
|
||||
|
||||
func (w *discardResponseWriter) Write(p []byte) (int, error) { return len(p), nil }
|
||||
|
||||
func (w *discardResponseWriter) WriteHeader(int) {}
|
||||
Reference in New Issue
Block a user