db forward: Astra round 1: the reads route reads its body to EOF under the admission deadline; the serial bump writes nothing once its caller has ended
P1: readJSONLimit decoded one value and left any tail unread, which net/http drained at the first flush under the extended 23-minute read deadline. readDBReadBody reads the whole body under the admission deadline and requires exactly one JSON value. P2: BumpSerial checks its context before every Put, retries included (DirStore ignores its context), and admission re-checks after the bump, writing cancel for a request that ended.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+180
−26
internal/console/apidbforward.go+39 −1internal/console/apidbforward_test.go+80 −25internal/release/serial.go+7 −0internal/release/serial_test.go+54 −0
diff --git a/internal/console/apidbforward.go b/internal/console/apidbforward.go| index 7b5b74e2d..2f06f0246 100644 |
| --- a/internal/console/apidbforward.go |
| +++ b/internal/console/apidbforward.go |
| @@ -13,6 +13,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "log" |
| "net/http" |
| "os" |
| @@ -203,6 +204,37 @@ func (s *Server) handleAPIDBRead(w http.ResponseWriter, r *http.Request) { |
| s.streamDBRead(w, r, rc, a) |
| } |
| +// readDBReadBody reads the whole body, to EOF, under the admission read |
| +// deadline handleAPIDBRead set, and requires it to be exactly one JSON value |
| +// (Astra round 1, P1). readJSONLimit decodes one value and leaves any tail |
| +// unread; net/http would drain that tail when the response is first |
| +// flushed, under the read deadline the stream extends to the read's bound, |
| +// so a withheld tail could hold a request and its admission slot. The |
| +// refusals are readJSONLimit's own sentences. |
| +func readDBReadBody(w http.ResponseWriter, r *http.Request, out *dbreads.ReadBody) bool { |
| + ct, _, _ := strings.Cut(r.Header.Get("Content-Type"), ";") |
| + if strings.TrimSpace(strings.ToLower(ct)) != "application/json" { |
| + jsonError(w, http.StatusUnsupportedMediaType, "send a JSON body with Content-Type: application/json") |
| + return false |
| + } |
| + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, dbreads.MaxSQLBytes+8<<10)) |
| + if err != nil { |
| + var tooLarge *http.MaxBytesError |
| + if errors.As(err, &tooLarge) { |
| + jsonError(w, http.StatusRequestEntityTooLarge, "request body too large") |
| + return false |
| + } |
| + jsonError(w, http.StatusBadRequest, "malformed JSON body") |
| + return false |
| + } |
| + // json.Unmarshal refuses anything but whitespace after the one value. |
| + if json.Unmarshal(raw, out) != nil { |
| + jsonError(w, http.StatusBadRequest, "malformed JSON body") |
| + return false |
| + } |
| + return true |
| +} |
| + |
| // cancelDBRead is the one write J1 allows after a read's request ends |
| // without a result: best effort, so the owner stops early and a box that |
| // has not picked it skips it. |
| @@ -254,7 +286,7 @@ func (s *Server) admitDBRead(w http.ResponseWriter, r *http.Request) (dbReadAdmi |
| return none, "", false |
| } |
| var body dbreads.ReadBody |
| - if !readJSONLimit(w, r, &body, dbreads.MaxSQLBytes+8<<10) { |
| + if !readDBReadBody(w, r, &body) { |
| return none, "", false |
| } |
| host := r.PathValue("host") |
| @@ -426,6 +458,12 @@ func (s *Server) admitDBRead(w http.ResponseWriter, r *http.Request) (dbReadAdmi |
| // The bump runs on the request's context, not bumpSerial's detached one, |
| // so a request that ends while it runs does not announce (finding 33). |
| s.announceDBRead(ctx) |
| + // The request may have ended during the bump (Astra round 1, P2): the |
| + // read is published, so it gets its cancel, and the caller no 200. |
| + if ctx.Err() != nil { |
| + s.cancelDBRead(id) |
| + return none, "", false |
| + } |
| admitted = true |
| return dbReadAdmitted{id: id, region: rec.Region, issued: issued}, actor, true |
| } |
diff --git a/internal/console/apidbforward_test.go b/internal/console/apidbforward_test.go| index 71a7eb8af..07c395eb5 100644 |
| --- a/internal/console/apidbforward_test.go |
| +++ b/internal/console/apidbforward_test.go |
| @@ -468,29 +468,6 @@ func dbfBucket(t *testing.T, s release.Store) (requests, queued, cancels int) { |
| return |
| } |
| -// dbfCtxStore refuses a write whose context has ended, as the S3 store |
| -// does and DirStore does not, and runs onGet once on a read of key. |
| -type dbfCtxStore struct { |
| - release.Store |
| - key string |
| - onGet func() |
| - once sync.Once |
| -} |
| - |
| -func (c *dbfCtxStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| - if key == c.key { |
| - c.once.Do(c.onGet) |
| - } |
| - return c.Store.Get(ctx, key) |
| -} |
| - |
| -func (c *dbfCtxStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| - if err := ctx.Err(); err != nil { |
| - return "", err |
| - } |
| - return c.Store.Put(ctx, key, body, ifMatch) |
| -} |
| - |
| // Plan review findings 11, 28 and 33 (J1, spec §5.5 step 3 and §9.3 rev 6): |
| // the request's context is checked immediately before every write of |
| // admission. Ended before the audit row: nothing at all. Before |
| @@ -555,19 +532,46 @@ func TestDBReadEndedDuringAdmissionWritesOnlyTheCancel(t *testing.T) { |
| } |
| }) |
| } |
| + // Over the real DirStore, whose Put ignores its context (Astra round 1, |
| + // P2): only the read of the serial is hooked, so nothing but the bump's |
| + // own check can stop the write. The request is then re-checked after the |
| + // bump: the read was published, so it gets its cancel and no 200. |
| t.Run("ended during the serial read", func(t *testing.T) { |
| fx := newDBFFixture(t, true) |
| _, serialBefore, _ := fx.rel.Get(context.Background(), release.SerialKey) |
| ctx, cancel := context.WithCancel(context.Background()) |
| defer cancel() |
| - fx.srv.cfg.Releases = &dbfCtxStore{Store: fx.rel, key: release.SerialKey, onGet: cancel} |
| - fx.dbfServe(t, ctx, "SELECT 1") |
| + fx.srv.cfg.Releases = &dbfGetHook{Store: fx.rel, key: release.SerialKey, onGet: cancel} |
| + rec := fx.dbfServe(t, ctx, "SELECT 1") |
| if _, serialAfter, _ := fx.rel.Get(context.Background(), release.SerialKey); serialAfter != serialBefore { |
| t.Fatal("the serial was written after the request ended during the bump") |
| } |
| + if strings.Contains(rec.Body.String(), "admitted") { |
| + t.Fatalf("a request that ended during the bump was admitted: %s", rec.Body) |
| + } |
| + if requests, queued, cancels := dbfBucket(t, fx.rel); requests != 1 || queued != 1 || cancels != 1 { |
| + t.Fatalf("requests %d, queue entries %d, cancels %d", requests, queued, cancels) |
| + } |
| }) |
| } |
| +// dbfGetHook runs onGet once on a read of key and is otherwise the store |
| +// beneath it, its context handling included: a DirStore's Put ignores its |
| +// context, as CARLOS_DEPLOYMENT_DIR's store does in production. |
| +type dbfGetHook struct { |
| + release.Store |
| + key string |
| + onGet func() |
| + once sync.Once |
| +} |
| + |
| +func (h *dbfGetHook) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == h.key { |
| + h.once.Do(h.onGet) |
| + } |
| + return h.Store.Get(ctx, key) |
| +} |
| + |
| // Plan review finding 13: a body delivered slowly is cut at s.dbf.preHeader, |
| // well inside backhaul's 30 s header wait, and admits nothing. |
| // Mutation: drop the preHeader read deadline, keeping only the bound's (red: |
| @@ -1338,6 +1342,57 @@ func (c dbfDeadlineConn) SetReadDeadline(t time.Time) error { |
| return c.Conn.SetReadDeadline(t) |
| } |
| +// Astra round 1, P1: complete query JSON followed by padding, with the rest |
| +// of the declared body withheld. A decoder that stops after one JSON value |
| +// would admit the read, and the server would later drain the tail under the |
| +// extended read deadline. The whole body is read under s.dbf.preHeader |
| +// instead, so the request is cut there and nothing is published. |
| +// Mutation: decode one value without reading to EOF (red: the read is |
| +// queued and the connection is still held at 3 s). |
| +func TestDBReadWithheldBodyTailIsCutAtThePreHeaderBound(t *testing.T) { |
| + fx := newDBFFixture(t, true) |
| + fx.srv.dbf.preHeader = 300 * time.Millisecond |
| + body, _ := queryBody(t, "SELECT 1") |
| + raw, _ := json.Marshal(body) |
| + conn, err := net.Dial("tcp", strings.TrimPrefix(fx.ts.URL, "http://")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + path := strings.TrimPrefix(fx.readURL(dbfHost), fx.ts.URL) |
| + fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: console\r\nAuthorization: Bearer %s\r\n"+ |
| + "Content-Type: application/json\r\nContent-Length: 16384\r\n\r\n%s%s", path, fx.member, raw, strings.Repeat(" ", 64)) |
| + conn.SetReadDeadline(time.Now().Add(3 * time.Second)) |
| + start := time.Now() |
| + _, err = io.ReadAll(conn) |
| + if ne, ok := err.(net.Error); ok && ne.Timeout() { |
| + t.Fatalf("the withheld body tail still held the request after %s", time.Since(start)) |
| + } |
| + if keys, _ := fx.rel.List(context.Background(), dbreads.Prefix); len(keys) != 0 { |
| + t.Fatalf("a request with a withheld body tail wrote %v", keys) |
| + } |
| +} |
| + |
| +// A body holding more than one JSON value is refused, not half-read. |
| +func TestDBReadRefusesTrailingJSON(t *testing.T) { |
| + fx := newDBFFixture(t, true) |
| + body, _ := queryBody(t, "SELECT 1") |
| + raw, _ := json.Marshal(body) |
| + req, _ := http.NewRequest(http.MethodPost, fx.readURL(dbfHost), strings.NewReader(string(raw)+`{"op":"query"}`)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Authorization", "Bearer "+fx.member) |
| + res, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, out := refusal(t, res); status != http.StatusBadRequest { |
| + t.Fatalf("%d %s", status, out) |
| + } |
| + if keys, _ := fx.rel.List(context.Background(), dbreads.Prefix); len(keys) != 0 { |
| + t.Fatalf("a body with trailing JSON wrote %v", keys) |
| + } |
| +} |
| + |
| // Plan review findings 13 and 38: admission reads under s.dbf.preHeader, |
| // and once admitted the read deadline moves out to the read's bound plus a |
| // minute. Observed on the connection itself: once a body has been read to |
diff --git a/internal/release/serial.go b/internal/release/serial.go| index 7c315b788..e0f50486d 100644 |
| --- a/internal/release/serial.go |
| +++ b/internal/release/serial.go |
| @@ -60,6 +60,13 @@ func BumpSerial(ctx context.Context, s Store, now time.Time) error { |
| if err != nil { |
| return err |
| } |
| + // A caller whose context ended stops here, before the write, every |
| + // attempt: a store may ignore the context (DirStore does), and a |
| + // request that has ended must announce nothing (db region forward, |
| + // Astra round 1, P2). |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| if _, err = s.Put(ctx, SerialKey, body, etag); err == nil { |
| return nil |
| } else if errors.Is(err, ErrCASConflict) { |
diff --git a/internal/release/serial_test.go b/internal/release/serial_test.go| index 8499a07cd..833211a33 100644 |
| --- a/internal/release/serial_test.go |
| +++ b/internal/release/serial_test.go |
| @@ -2,6 +2,7 @@ package release |
| import ( |
| "context" |
| + "errors" |
| "testing" |
| "time" |
| ) |
| @@ -54,3 +55,56 @@ func TestSerialGarbageObjectStillBumps(t *testing.T) { |
| t.Fatalf("recovery bump: %+v %v", doc, err) |
| } |
| } |
| + |
| +// serialCancelStore cancels a context at a chosen point and is otherwise the |
| +// DirStore beneath it, whose Put ignores its context. |
| +type serialCancelStore struct { |
| + Store |
| + onGet, onPut func() |
| + puts int |
| +} |
| + |
| +func (s *serialCancelStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if s.onGet != nil { |
| + s.onGet() |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func (s *serialCancelStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + s.puts++ |
| + if s.onPut != nil { |
| + s.onPut() |
| + return "", ErrCASConflict // a race lost, so BumpSerial retries |
| + } |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// A caller whose context ended while BumpSerial read the serial gets no |
| +// write, even from a store that ignores its context (db region forward, |
| +// Astra round 1, P2). |
| +func TestSerialBumpDoesNotWriteAfterItsContextEnds(t *testing.T) { |
| + dir := NewDirStore(t.TempDir()) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + s := &serialCancelStore{Store: dir, onGet: cancel} |
| + if err := BumpSerial(ctx, s, time.Now()); !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err %v, want the context's", err) |
| + } |
| + if doc, etag, _ := ReadSerial(context.Background(), dir); doc.Serial != 0 || etag != "" || s.puts != 0 { |
| + t.Fatalf("the serial was written after its context ended: %+v, %d puts", doc, s.puts) |
| + } |
| +} |
| + |
| +// The same check holds before a retry's write. |
| +func TestSerialBumpRetryDoesNotWriteAfterItsContextEnds(t *testing.T) { |
| + dir := NewDirStore(t.TempDir()) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + s := &serialCancelStore{Store: dir} |
| + s.onPut = func() { cancel(); s.onPut = nil } |
| + if err := BumpSerial(ctx, s, time.Now()); !errors.Is(err, context.Canceled) { |
| + t.Fatalf("err %v, want the context's", err) |
| + } |
| + if doc, _, _ := ReadSerial(context.Background(), dir); doc.Serial != 0 || s.puts != 1 { |
| + t.Fatalf("a retry wrote the serial after its context ended: %+v, %d puts", doc, s.puts) |
| + } |
| +} |