mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
fix(images): give async image tasks their own body memory reservation
Async tasks inherited the ingress reservation through context.WithoutCancel, but RequestBodyLimit releases and closes it when Submit returns. The task's request body was a plain reader, so the gateway's read reserved against the closed reservation and every task failed with a 503 budget error. - Add httputil.DetachRequestBodyMemory: a reservation on the same budget that the handler's release does not close. It takes over the retained body's existing charge from the request and reserves only the remainder, so the body is never counted twice; the caller releases it when the work ends. - Submit reserves the retained body before creating the task, returning 503 with Retry-After on exhaustion instead of accepting a task that cannot run; the task releases it when execution finishes. - Back the task request with PrereadBody so the body is not buffered again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
957a83f32e
commit
0853d16036
4 files changed
+293
-7
No files matched your search
@@ -103,7 +103,13 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
taskCtx, recorder, cancel := newAsyncImageContext(c, body, h.tasks.ExecutionTimeout())
|
||||
taskCtx, recorder, cancel, err := newAsyncImageContext(c, body, h.tasks.ExecutionTimeout())
|
||||
if err != nil {
|
||||
if !middleware2.RejectRequestBodyMemoryOverload(c, err) {
|
||||
imageTaskError(c, service.ErrImageTaskUnavailable)
|
||||
}
|
||||
return
|
||||
}
|
||||
task, err := h.tasks.Create(c.Request.Context(), service.ImageTaskOwner{UserID: apiKey.UserID, APIKeyID: apiKey.ID})
|
||||
if err != nil {
|
||||
cancel()
|
||||
@@ -261,13 +267,23 @@ func (h *AsyncImageHandler) failTask(taskID string, statusCode int, taskErr json
|
||||
}
|
||||
}
|
||||
|
||||
func newAsyncImageContext(c *gin.Context, body []byte, timeoutDuration time.Duration) (*gin.Context, *httptest.ResponseRecorder, context.CancelFunc) {
|
||||
base := context.WithoutCancel(c.Request.Context())
|
||||
executionCtx, cancel := context.WithTimeout(base, timeoutDuration)
|
||||
func newAsyncImageContext(c *gin.Context, body []byte, timeoutDuration time.Duration) (*gin.Context, *httptest.ResponseRecorder, context.CancelFunc, error) {
|
||||
// The task keeps body after Submit returns and the ingress reservation is
|
||||
// released, so it holds the body, and whatever it buffers, on its own one.
|
||||
retained, releaseBody, err := pkghttputil.DetachRequestBodyMemory(c.Request.Context(), int64(len(body)))
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
base := context.WithoutCancel(retained)
|
||||
executionCtx, cancelExecution := context.WithTimeout(base, timeoutDuration)
|
||||
cancel := func() {
|
||||
cancelExecution()
|
||||
releaseBody()
|
||||
}
|
||||
request := c.Request.Clone(executionCtx)
|
||||
request.Body = io.NopCloser(bytes.NewReader(body))
|
||||
request.Body = pkghttputil.NewPrereadBody(body)
|
||||
request.GetBody = func() (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(body)), nil
|
||||
return pkghttputil.NewPrereadBody(body), nil
|
||||
}
|
||||
request.ContentLength = int64(len(body))
|
||||
request.URL.Path = strings.TrimSuffix(request.URL.Path, "/async")
|
||||
@@ -277,7 +293,7 @@ func newAsyncImageContext(c *gin.Context, body []byte, timeoutDuration time.Dura
|
||||
recorderCtx, _ := gin.CreateTestContext(recorder)
|
||||
taskCtx.Writer = recorderCtx.Writer
|
||||
taskCtx.Request = request
|
||||
return taskCtx, recorder, cancel
|
||||
return taskCtx, recorder, cancel, nil
|
||||
}
|
||||
|
||||
func asyncImageRequestStreams(contentType string, body []byte) bool {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -106,6 +107,150 @@ func TestAsyncImageHandlerSubmitAndPoll(t *testing.T) {
|
||||
require.Contains(t, pollWriter.Body.String(), "https://example.test/image.png")
|
||||
}
|
||||
|
||||
// The background task runs after Submit has released the ingress reservation;
|
||||
// it must still read its body and buffer under the shared budget, then return
|
||||
// every byte it held.
|
||||
func TestAsyncImageHandlerTaskUsesOwnBodyReservation(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const budgetLimit = 1 << 20
|
||||
budget := pkghttputil.NewBodyMemoryBudget(budgetLimit)
|
||||
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
|
||||
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
|
||||
requestBody := `{"model":"gpt-image-1","prompt":"cat"}`
|
||||
submitted := make(chan struct{})
|
||||
h := &AsyncImageHandler{tasks: tasks}
|
||||
h.execute = func(_ string, c *gin.Context) {
|
||||
<-submitted
|
||||
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
|
||||
if err != nil || string(body) != requestBody {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{"message": "read body failed"}})
|
||||
return
|
||||
}
|
||||
if err := pkghttputil.ReserveRequestBodyMemory(c.Request.Context(), 4096); err != nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{"message": err.Error()}})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"created": 123, "data": []gin.H{{"url": "https://example.test/image.png"}}})
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
router.Use(middleware2.RequestBodyLimit(1<<20, budget))
|
||||
router.Use(func(c *gin.Context) {
|
||||
groupID := int64(3)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 9,
|
||||
UserID: 7,
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, AllowImageGeneration: true},
|
||||
})
|
||||
c.Next()
|
||||
})
|
||||
router.POST("/v1/images/generations/async", h.Submit)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations/async", strings.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusAccepted, w.Code)
|
||||
var accepted struct {
|
||||
TaskID string `json:"task_id"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &accepted))
|
||||
close(submitted) // Submit and its ingress release have completed.
|
||||
|
||||
owner := service.ImageTaskOwner{UserID: 7, APIKeyID: 9}
|
||||
require.Eventually(t, func() bool {
|
||||
got, err := tasks.Get(context.Background(), owner, accepted.TaskID)
|
||||
return err == nil && got.Status != service.ImageTaskStatusProcessing
|
||||
}, time.Second, 10*time.Millisecond)
|
||||
got, err := tasks.Get(context.Background(), owner, accepted.TaskID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, service.ImageTaskStatusCompleted, got.Status, "task error: %s", string(got.Error))
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
ctx, release := pkghttputil.WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
defer release()
|
||||
return pkghttputil.ReserveRequestBodyMemory(ctx, budgetLimit) == nil
|
||||
}, time.Second, 10*time.Millisecond, "task must release its reservation")
|
||||
}
|
||||
|
||||
// The retained body is charged before a task is created, so exhaustion is
|
||||
// reported as retryable overload instead of an accepted task that cannot run.
|
||||
// A body the request already holds moves to the task instead of being charged
|
||||
// twice.
|
||||
func TestAsyncImageHandlerSubmitRejectsWhenBodyCannotBeRetained(t *testing.T) {
|
||||
requestBody := `{"model":"gpt-image-1","prompt":"cat"}`
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
chargeRequest bool
|
||||
want int
|
||||
}{
|
||||
{name: "budget held by other requests", want: http.StatusServiceUnavailable},
|
||||
{name: "body already charged to the request", chargeRequest: true, want: http.StatusAccepted},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
|
||||
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
|
||||
h := &AsyncImageHandler{tasks: tasks}
|
||||
ran := make(chan struct{})
|
||||
h.execute = func(_ string, c *gin.Context) {
|
||||
if !tt.chargeRequest {
|
||||
t.Error("task must not run")
|
||||
}
|
||||
close(ran)
|
||||
}
|
||||
|
||||
budget := pkghttputil.NewBodyMemoryBudget(int64(len(requestBody)))
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
groupID := int64(3)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
ID: 9,
|
||||
UserID: 7,
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, AllowImageGeneration: true},
|
||||
})
|
||||
ctx, release := pkghttputil.WithRequestBodyMemoryBudget(c.Request.Context(), budget)
|
||||
defer release()
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Request.Body = pkghttputil.NewPrereadBody([]byte(requestBody))
|
||||
if tt.chargeRequest {
|
||||
require.NoError(t, pkghttputil.ReserveRequestBodyMemory(ctx, int64(len(requestBody))))
|
||||
} else {
|
||||
// Another in-flight request holds all remaining capacity.
|
||||
other, releaseOther := pkghttputil.WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
defer releaseOther()
|
||||
require.NoError(t, pkghttputil.ReserveRequestBodyMemory(other, int64(len(requestBody))))
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
router.POST("/v1/images/generations/async", h.Submit)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations/async", strings.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, tt.want, w.Code)
|
||||
if !tt.chargeRequest {
|
||||
require.Equal(t, "1", w.Header().Get("Retry-After"))
|
||||
require.Empty(t, store.tasks)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ran:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("accepted task did not run")
|
||||
}
|
||||
require.Eventually(t, func() bool {
|
||||
ctx, release := pkghttputil.WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
defer release()
|
||||
return pkghttputil.ReserveRequestBodyMemory(ctx, int64(len(requestBody))) == nil
|
||||
}, time.Second, 10*time.Millisecond, "task must release the body it took over")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// When object storage is not configured the feature is fully disabled: the
|
||||
// endpoints must return 404 without creating a task or writing to Redis.
|
||||
func TestAsyncImageHandlerDisabledReturns404(t *testing.T) {
|
||||
|
||||
@@ -61,6 +61,50 @@ func WithRequestBodyMemoryScope(ctx context.Context) (context.Context, func()) {
|
||||
return context.WithValue(ctx, bodyMemoryReservationKey{}, r), r.release
|
||||
}
|
||||
|
||||
// DetachRequestBodyMemory opens a reservation on the request's budget for work
|
||||
// that keeps request-derived buffers after the handler returns, such as an
|
||||
// accepted asynchronous task. It takes over up to n bytes the request already
|
||||
// holds for the retained body and reserves only the remainder, so the body is
|
||||
// never charged twice; reservations made through the returned ctx accumulate on
|
||||
// it. The handler's release does not affect it, so the caller owns release and
|
||||
// must call it when the work ends. Without a request budget in ctx it is a no-op.
|
||||
func DetachRequestBodyMemory(ctx context.Context, n int64) (context.Context, func(), error) {
|
||||
parent, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation)
|
||||
if parent == nil {
|
||||
return ctx, func() {}, nil
|
||||
}
|
||||
detached, release := WithRequestBodyMemoryScope(ctx)
|
||||
r, _ := detached.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation)
|
||||
parent.mu.Lock()
|
||||
moved := int64(0)
|
||||
if !parent.closed && !r.closed {
|
||||
moved = min(max(n, 0), parent.bytes)
|
||||
parent.bytes -= moved
|
||||
}
|
||||
parent.mu.Unlock()
|
||||
r.mu.Lock()
|
||||
r.bytes += moved
|
||||
r.mu.Unlock()
|
||||
if err := reserveRequestBodyMemory(detached, n-moved); err != nil {
|
||||
// Hand the body back: the handler still owns it until it returns.
|
||||
r.mu.Lock()
|
||||
r.bytes -= moved
|
||||
r.mu.Unlock()
|
||||
parent.mu.Lock()
|
||||
if parent.closed {
|
||||
parent.budget.mu.Lock()
|
||||
parent.budget.used -= moved
|
||||
parent.budget.mu.Unlock()
|
||||
} else {
|
||||
parent.bytes += moved
|
||||
}
|
||||
parent.mu.Unlock()
|
||||
release()
|
||||
return ctx, func() {}, err
|
||||
}
|
||||
return detached, release, nil
|
||||
}
|
||||
|
||||
func (r *bodyMemoryReservation) release() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
@@ -481,3 +481,84 @@ func TestReleaseRequestBodyMemoryCapsAtOwnReservation(t *testing.T) {
|
||||
t.Fatalf("release after close changed the budget: used=%d", budget.used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetachRequestBodyMemoryOutlivesHandlerRelease(t *testing.T) {
|
||||
budget := NewBodyMemoryBudget(100)
|
||||
ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
detached, releaseDetached, err := DetachRequestBodyMemory(ctx, 40)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release() // The handler returns while the detached work still runs.
|
||||
if budget.used != 40 {
|
||||
t.Fatalf("detached body must stay reserved: %d", budget.used)
|
||||
}
|
||||
if err := ReserveRequestBodyMemory(detached, 30); err != nil {
|
||||
t.Fatalf("detached work must keep reserving after handler release: %v", err)
|
||||
}
|
||||
if err := ReserveRequestBodyMemory(detached, 31); !errors.Is(err, ErrRequestBodyMemoryBudget) {
|
||||
t.Fatalf("detached reservations still share the budget: %v", err)
|
||||
}
|
||||
releaseDetached()
|
||||
releaseDetached()
|
||||
if budget.used != 0 {
|
||||
t.Fatalf("leaked reservations: %d", budget.used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetachRequestBodyMemoryTakesOverTheRequestCharge(t *testing.T) {
|
||||
budget := NewBodyMemoryBudget(100)
|
||||
ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
if err := ReserveRequestBodyMemory(ctx, 70); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The retained body is already charged to the request, so detaching it must
|
||||
// not need a second copy's worth of capacity.
|
||||
_, releaseDetached, err := DetachRequestBodyMemory(ctx, 60)
|
||||
if err != nil {
|
||||
t.Fatalf("detach charged the body twice: %v", err)
|
||||
}
|
||||
if budget.used != 70 {
|
||||
t.Fatalf("detach changed the shared usage: %d", budget.used)
|
||||
}
|
||||
release()
|
||||
if budget.used != 60 {
|
||||
t.Fatalf("handler release must leave only the detached body: %d", budget.used)
|
||||
}
|
||||
releaseDetached()
|
||||
if budget.used != 0 {
|
||||
t.Fatalf("leaked reservations: %d", budget.used)
|
||||
}
|
||||
|
||||
ctx, release = WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
if err := ReserveRequestBodyMemory(ctx, 50); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := DetachRequestBodyMemory(ctx, 101); !errors.Is(err, ErrRequestBodyMemoryBudget) {
|
||||
t.Fatalf("want capacity error, got %v", err)
|
||||
}
|
||||
if budget.used != 50 {
|
||||
t.Fatalf("failed detach must return the body to the request: %d", budget.used)
|
||||
}
|
||||
release()
|
||||
if budget.used != 0 {
|
||||
t.Fatalf("failed detach leaked reservations: %d", budget.used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetachRequestBodyMemoryRejectsWhenBudgetExhausted(t *testing.T) {
|
||||
budget := NewBodyMemoryBudget(100)
|
||||
ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget)
|
||||
defer release()
|
||||
if _, _, err := DetachRequestBodyMemory(ctx, 101); !errors.Is(err, ErrRequestBodyMemoryBudget) {
|
||||
t.Fatalf("want capacity error, got %v", err)
|
||||
}
|
||||
if budget.used != 0 {
|
||||
t.Fatalf("failed detach consumed budget: %d", budget.used)
|
||||
}
|
||||
if got, releaseNoop, err := DetachRequestBodyMemory(context.Background(), 101); err != nil || got == nil {
|
||||
t.Fatalf("without a budget detach is a no-op: %v", err)
|
||||
} else {
|
||||
releaseNoop()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user