carlos / platform Public

carlos db query: the forwarded read, buffered and checked before anything prints (plan 2, Task 8)

The CLI rows (DBF-3 to DBF-8, DBF-11 to DBF-13, DBF-15, DBF-16, DBF-32)
are wired with the record's pending text: they are reached only after a
console with CARLOS_DB_FORWARD=1 sends the forward marker.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev dbc3bc39595158eddafe4b4e70f887aee7b2caa0 parent f4271e7
4 files changed, +565 −1
  • approved_db_forward_copy_test.go +4 −1
  • db.go +23 −0
  • dbforward.go +250 −0
  • dbforward_test.go +288 −0
diff --git a/approved_db_forward_copy_test.go b/approved_db_forward_copy_test.go
index b552abd37..a13eedb37 100644
--- a/approved_db_forward_copy_test.go
+++ b/approved_db_forward_copy_test.go
@@ -49,7 +49,10 @@ var dbForwardCopyBuilt = []string{}
// that has not turned forwarding on. The copy review moves each id from here
// to dbForwardCopyBuilt, applying Paul's edits in the same commit. Docs rows
// are public the moment the site syncs, so they are never wired.
-var dbForwardCopyWired = []string{"DBF-1", "DBF-2", "DBF-14", "DBF-9", "DBF-10", "DBF-21", "DBF-22"}
+var dbForwardCopyWired = []string{
+ "DBF-1", "DBF-2", "DBF-14", "DBF-9", "DBF-10", "DBF-21", "DBF-22", // the console
+ "DBF-3", "DBF-4", "DBF-5", "DBF-6", "DBF-7", "DBF-8", "DBF-11", "DBF-12", "DBF-13", "DBF-15", "DBF-16", "DBF-32", // the CLI
+}
func mustParseDBForwardRecord(t *testing.T) []copyRow {
t.Helper()
diff --git a/db.go b/db.go
index 155e5e3b8..0757bdde4 100644
--- a/db.go
+++ b/db.go
@@ -26,6 +26,7 @@ import (
"log"
"os"
"os/signal"
+ "slices"
"sort"
"strings"
"syscall"
@@ -33,6 +34,7 @@ import (
"github.com/carlosframework/platform/internal/dbdoor"
"github.com/carlosframework/platform/internal/dbquery"
+ "github.com/carlosframework/platform/internal/dbreads"
)
const dbUsage = `usage: carlos db <verb> --app <a> [--instance <host>] [flags]
@@ -183,9 +185,16 @@ func resolveDBInstance(ctx context.Context, sess *apiSession, acct apiAcct, app,
// dbRestore restores the target's replica into a private directory under
// the system temp dir. The caller removes Restored.Dir.
+//
+// A door refusal carrying the db region forward marker comes back as an
+// *errDBForward, so a verb can switch to the forwarded read (dbforward.go).
func dbRestore(ctx context.Context, t dbTarget) (*dbdoor.Restored, error) {
r, err := dbdoor.RestoreAsOf(ctx, t.sess.dbClient(t.acct, t.app, t.host), "", t.at)
if err != nil {
+ var door *dbdoor.DoorError
+ if errors.As(err, &door) && door.Forward != nil {
+ return nil, &errDBForward{door: door}
+ }
return nil, dbRestoreError(t.host, err)
}
return r, nil
@@ -273,6 +282,11 @@ func runDBPull(args []string) {
// every path. It returns rather than exits so that cleanup always runs.
func dbPull(ctx context.Context, t dbTarget, out string) error {
r, err := dbRestore(ctx, t)
+ var fwd *errDBForward
+ if errors.As(err, &fwd) {
+ // Phase 1 forwards queries only (db region forward spec §6): DBF-8.
+ return fmt.Errorf(dbfNoPull, t.host, fwd.door.Forward.Region)
+ }
if err != nil {
return err
}
@@ -370,6 +384,15 @@ func runDBQuery(args []string) {
func dbQuery(ctx context.Context, t dbTarget, sqlText string) error {
r, err := dbRestore(ctx, t)
+ var fwd *errDBForward
+ if errors.As(err, &fwd) {
+ // The instance is read in its own region (db region forward spec
+ // §5.5), when the console forwards queries there.
+ if !slices.Contains(fwd.door.Forward.Ops, dbreads.OpQuery) {
+ return errors.New(fwd.door.Error())
+ }
+ return dbQueryForward(ctx, t, sqlText, *fwd.door.Forward)
+ }
if err != nil {
return err
}
diff --git a/dbforward.go b/dbforward.go
new file mode 100644
index 000000000..6e2b479b3
--- /dev/null
+++ b/dbforward.go
@@ -0,0 +1,250 @@
+// dbforward.go is the CLI's half of a forwarded `carlos db query` (spec
+// docs/superpowers/specs/2026-10-22-db-region-forward-design.md §5.5): when
+// the db door answers with the forward marker, the CLI makes an ephemeral
+// key, holds one request to the console's reads route open, buffers every
+// sealed chunk, and prints nothing until a done result's summary checks out
+// against the bytes (codex 6).
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbreads"
+)
+
+// The forwarded read's CLI sentences (copy record DBF-3 to DBF-8, DBF-11 to
+// DBF-13, DBF-15, DBF-16, DBF-32). PENDING copy review: each is reached only
+// after a console with CARLOS_DB_FORWARD=1 answered the forward marker
+// (approved_db_forward_copy_test.go, dbForwardCopyWired).
+const (
+ dbfNotPicked = "no server in region %s picked up the read within 60 seconds. try again in a few minutes." // DBF-3
+ dbfTooLarge = "%s's database is %s once restored. carlos db can query at most %s in region %s." // DBF-4
+ dbfNoRoom = "the server in region %s does not have room to restore %s's database right now. try again later." // DBF-5
+ dbfOutputCap = "the result was cut off at 64 MB. narrow the query with WHERE or LIMIT and run it again." // DBF-6
+ dbfTimeout = "the query ran for 5 minutes and was stopped. narrow it and run it again." // DBF-7
+ dbfNoPull = "%s keeps its data in region %s. carlos db pull cannot fetch a copy from there yet. carlos db query can read it." // DBF-8
+ dbfReading = "reading a copy of %s's database in region %s." // DBF-11
+ dbfUnfinished = "the read of %s's database in region %s did not finish, so nothing was printed. try again." // DBF-12
+ dbfUnchecked = "the answer from region %s did not check out, so carlos db showed none of it. try again." // DBF-13
+ dbfChanged = "%s changed while the read was waiting. try again." // DBF-15
+ dbfMovingCLI = "%s is moving between regions. read its database once the move has finished." // DBF-16
+ dbfNotUTF8 = "this query cannot be sent to region %s, because it holds bytes that are not UTF-8 text or the character U+FFFD. fix the query and run it again." // DBF-32
+)
+
+// errDBForward is the db door's forward marker, handed back by dbRestore so
+// a verb can switch to the forwarded read.
+type errDBForward struct {
+ door *dbdoor.DoorError
+}
+
+func (e *errDBForward) Error() string { return e.door.Error() }
+
+type dbForwardAnswer struct {
+ rows []byte
+ summary dbreads.Summary
+ capped bool
+}
+
+// dbQueryForward is spec §5.5 steps 2 and 8 for a query.
+func dbQueryForward(ctx context.Context, t dbTarget, sqlText string, fwd dbdoor.Forward) error {
+ // json.Marshal would send U+FFFD for bytes that are not UTF-8, and the
+ // box would run SQL nobody typed; the console refuses U+FFFD for the
+ // same reason (plan review finding 36). First, so no other check can
+ // read the bytes differently.
+ if !utf8.ValidString(sqlText) || strings.ContainsRune(sqlText, utf8.RuneError) {
+ return fmt.Errorf(dbfNotUTF8, fwd.Region)
+ }
+ if err := checkQuerySQL(sqlText); err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(ctx, dbreads.CLIBound)
+ defer cancel()
+ key, err := dbreads.NewReplyKey()
+ if err != nil {
+ return err
+ }
+ at := ""
+ if !t.at.IsZero() {
+ at = t.at.UTC().Format(time.RFC3339Nano)
+ }
+ body, err := json.Marshal(dbreads.ReadBody{Op: dbreads.OpQuery, SQL: sqlText, At: at, ReplyKey: dbreads.EncodeReplyKey(key.PublicKey())})
+ if err != nil {
+ return err
+ }
+ res, err := t.sess.c.doStream(ctx, http.MethodPost, apiPath(t.acct, t.app, "/db/"+url.PathEscape(t.host)+"/reads"),
+ bytes.NewReader(body), int64(len(body)), http.Header{"Content-Type": {"application/json"}})
+ if err != nil {
+ if errors.Is(ctx.Err(), context.Canceled) {
+ return errors.New("stopped")
+ }
+ return fmt.Errorf(dbfUnfinished, t.host, fwd.Region)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ raw, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ return apiErrorFromBody(res.StatusCode, raw)
+ }
+ ans, err := readDBForward(ctx, res.Body, key, t.host, fwd.Region, os.Stderr)
+ if err != nil {
+ return err
+ }
+ fmt.Fprint(os.Stderr, dbQueryStatus(t.host, &dbdoor.Restored{TXID: ans.summary.TXID, At: ans.summary.At}, t.at))
+ if _, err := stdout.Write(ans.rows); err != nil {
+ return err
+ }
+ if ans.capped {
+ return errors.New(dbfOutputCap)
+ }
+ return nil
+}
+
+// dbfChunkBound is what a reader keeps before a result arrives (plan review
+// finding 37). Every chunk is at least a sealed empty one; only the last
+// may be empty, so nothing may follow an empty chunk; there are at most as
+// many chunks as a read can make (full ones for the payload, plus one per
+// flush interval over the owner's deadline, plus the last); and their
+// plaintext, ciphertext less each seal, stays within the payload cap.
+type dbfChunkBound struct {
+ maxBytes, maxChunks int64
+ n, plain int64
+ sawEmpty bool
+}
+
+func newDBFChunkBound(maxBytes, chunkBytes int64) *dbfChunkBound {
+ return &dbfChunkBound{maxBytes: maxBytes,
+ maxChunks: (maxBytes+chunkBytes-1)/chunkBytes + int64(dbreads.OwnerDeadline/dbreads.ChunkEvery) + 1}
+}
+
+// admit says whether a chunk may be kept; false is DBF-13.
+func (b *dbfChunkBound) admit(sealed []byte) bool {
+ size := int64(len(sealed)) - int64(dbreads.SealOverhead)
+ if size < 0 || b.sawEmpty || b.n >= b.maxChunks || b.plain+size > b.maxBytes {
+ return false
+ }
+ b.n++
+ b.plain += size
+ b.sawEmpty = size == 0
+ return true
+}
+
+// readDBForward reads the reads route's lines (spec §5.5 steps 6 to 8). It
+// says DBF-11 once admitted, buffers every chunk in sequence, and opens and
+// checks the answer only when the result arrives.
+func readDBForward(ctx context.Context, body io.Reader, key *ecdh.PrivateKey, host, region string, status io.Writer) (dbForwardAnswer, error) {
+ unchecked := fmt.Errorf(dbfUnchecked, region)
+ sc := bufio.NewScanner(body)
+ sc.Buffer(make([]byte, 64<<10), dbreads.MaxLineBytes)
+ var id, ended string
+ var sealed [][]byte
+ bound := newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes)
+ for sc.Scan() {
+ var l dbreads.Line
+ if err := json.Unmarshal(sc.Bytes(), &l); err != nil {
+ return dbForwardAnswer{}, unchecked
+ }
+ switch {
+ case l.Admitted != "":
+ if id != "" || !dbreads.ValidID(l.Admitted) {
+ return dbForwardAnswer{}, unchecked
+ }
+ id = l.Admitted
+ fmt.Fprintln(status, fmt.Sprintf(dbfReading, host, region))
+ case l.Chunk != 0:
+ if id == "" || l.Chunk != int64(len(sealed))+1 || !bound.admit(l.Data) {
+ return dbForwardAnswer{}, unchecked
+ }
+ sealed = append(sealed, l.Data)
+ case l.Result != nil:
+ if id == "" {
+ return dbForwardAnswer{}, unchecked
+ }
+ return openDBForward(id, key, sealed, *l.Result, host, region)
+ case l.Ended != "":
+ ended = l.Ended
+ }
+ }
+ if errors.Is(ctx.Err(), context.Canceled) {
+ return dbForwardAnswer{}, errors.New("stopped")
+ }
+ if ended == dbreads.EndedNotPicked {
+ return dbForwardAnswer{}, fmt.Errorf(dbfNotPicked, region)
+ }
+ return dbForwardAnswer{}, fmt.Errorf(dbfUnfinished, host, region)
+}
+
+// openDBForward opens a result: a done one's every chunk and its summary,
+// checked against each other before anything is returned; any other state
+// mapped to its sentence (spec §5.6, §10).
+func openDBForward(id string, key *ecdh.PrivateKey, sealed [][]byte, res dbreads.Result, host, region string) (dbForwardAnswer, error) {
+ unchecked := fmt.Errorf(dbfUnchecked, region)
+ if res.Valid() != nil {
+ return dbForwardAnswer{}, unchecked
+ }
+ s, err := dbreads.OpenSummary(key, id, res.Sealed)
+ if err != nil {
+ return dbForwardAnswer{}, unchecked
+ }
+ switch res.State {
+ case dbreads.StateDone:
+ if res.LastSeq != int64(len(sealed)) {
+ return dbForwardAnswer{}, unchecked
+ }
+ var rows bytes.Buffer
+ for i, c := range sealed {
+ seq := int64(i + 1)
+ plain, err := dbreads.OpenChunk(key, id, seq, dbreads.StreamRows, seq == res.LastSeq, c)
+ if err != nil {
+ return dbForwardAnswer{}, unchecked
+ }
+ rows.Write(plain)
+ }
+ sum := sha256.Sum256(rows.Bytes())
+ if int64(rows.Len()) != s.Bytes || hex.EncodeToString(sum[:]) != s.SHA256 {
+ return dbForwardAnswer{}, unchecked
+ }
+ return dbForwardAnswer{rows: rows.Bytes(), summary: s, capped: res.Code == dbreads.CodeOutputCap}, nil
+ case dbreads.StateRefused:
+ if res.Code == dbreads.CodeMoving {
+ return dbForwardAnswer{}, fmt.Errorf(dbfMovingCLI, host)
+ }
+ return dbForwardAnswer{}, fmt.Errorf(dbfChanged, host)
+ case dbreads.StateFailed:
+ switch res.Code {
+ case dbreads.CodeNothingReplicated:
+ return dbForwardAnswer{}, dbRestoreError(host, dbdoor.ErrNothingReplicated)
+ case dbreads.CodeHistoryGone:
+ if !s.Oldest.IsZero() {
+ return dbForwardAnswer{}, dbRestoreError(host, &dbdoor.BeforeHistoryError{Oldest: s.Oldest})
+ }
+ case dbreads.CodeCheckFailed:
+ return dbForwardAnswer{}, dbRestoreError(host, fmt.Errorf("%w: %s", dbdoor.ErrCheckFailed, s.Error))
+ case dbreads.CodeChangedTwice:
+ return dbForwardAnswer{}, dbRestoreError(host, os.ErrNotExist)
+ case dbreads.CodeTooLarge:
+ return dbForwardAnswer{}, fmt.Errorf(dbfTooLarge, host, humanBytes(&s.Restored), humanBytes(&s.Cap), region)
+ case dbreads.CodeNoRoom:
+ return dbForwardAnswer{}, fmt.Errorf(dbfNoRoom, region, host)
+ case dbreads.CodeSQLError:
+ return dbForwardAnswer{}, errors.New(s.Error)
+ case dbreads.CodeTimeout:
+ return dbForwardAnswer{}, errors.New(dbfTimeout)
+ }
+ }
+ return dbForwardAnswer{}, fmt.Errorf(dbfUnfinished, host, region)
+}
diff --git a/dbforward_test.go b/dbforward_test.go
new file mode 100644
index 000000000..e6710057c
--- /dev/null
+++ b/dbforward_test.go
@@ -0,0 +1,288 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/dbdoor"
+ "github.com/carlosframework/platform/internal/dbreads"
+)
+
+// These feed readDBForward crafted line streams, sealed with real keys:
+// unit tests of the CLI's half (dbforward_e2e_test.go runs the binary).
+
+const fwdID = "dbr_aaaaaaaaaaaaaaaaaaaaaaaaaa"
+
+// stream builds a reads-route body: admitted, picked, the chunks, then end.
+type stream struct {
+ t *testing.T
+ pub *ecdh.PublicKey
+ buf bytes.Buffer
+}
+
+func newStream(t *testing.T, key *ecdh.PrivateKey) *stream {
+ s := &stream{t: t, pub: key.PublicKey()}
+ s.line(dbreads.Line{Admitted: fwdID})
+ s.line(dbreads.Line{Picked: "uk-1"})
+ return s
+}
+
+func (s *stream) line(l dbreads.Line) {
+ b, _ := json.Marshal(l)
+ s.buf.Write(append(b, '\n'))
+}
+
+func (s *stream) chunk(seq int64, last bool, plain []byte) {
+ sealed, err := dbreads.SealChunk(s.pub, fwdID, seq, dbreads.StreamRows, last, plain)
+ if err != nil {
+ s.t.Fatal(err)
+ }
+ s.line(dbreads.Line{Chunk: seq, Data: sealed})
+}
+
+func (s *stream) result(state, code string, last int64, sum dbreads.Summary) {
+ sealed, _ := dbreads.SealSummary(s.pub, fwdID, sum)
+ s.line(dbreads.Line{Result: &dbreads.Result{State: state, Code: code, LastSeq: last, Sealed: sealed}})
+}
+
+func summaryOf(rows string) dbreads.Summary {
+ h := sha256.Sum256([]byte(rows))
+ return dbreads.Summary{TXID: 7, At: time.Date(2026, 10, 7, 14, 0, 0, 0, time.UTC), Bytes: int64(len(rows)), SHA256: hex.EncodeToString(h[:])}
+}
+
+func readFwd(t *testing.T, s *stream, key *ecdh.PrivateKey) (dbForwardAnswer, string, error) {
+ t.Helper()
+ var status bytes.Buffer
+ ans, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", &status)
+ return ans, status.String(), err
+}
+
+func TestForwardedQueryPrintsOnlyACheckedAnswer(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ s.chunk(1, false, []byte("n\n"))
+ s.chunk(2, true, []byte("30\n"))
+ s.result(dbreads.StateDone, "", 2, summaryOf("n\n30\n"))
+ ans, status, err := readFwd(t, s, key)
+ if err != nil || string(ans.rows) != "n\n30\n" || ans.summary.TXID != 7 {
+ t.Fatalf("%q %v", ans.rows, err)
+ }
+ if status != fmt.Sprintf(dbfReading, "shop.example.com", "uk")+"\n" {
+ t.Fatalf("status %q", status)
+ }
+}
+
+// T11's unit half (codex 6): a dropped or bad last chunk and a summary that
+// does not add up each print nothing.
+func TestForwardedQueryRefusesAnAnswerThatDoesNotCheckOut(t *testing.T) {
+ t.Parallel()
+ unchecked := fmt.Sprintf(dbfUnchecked, "uk")
+ for name, build := range map[string]func(s *stream){
+ "the last chunk dropped": func(s *stream) {
+ s.chunk(1, false, []byte("n\n"))
+ s.result(dbreads.StateDone, "", 2, summaryOf("n\n30\n"))
+ },
+ "the last chunk not sealed as last": func(s *stream) {
+ s.chunk(1, false, []byte("n\n"))
+ s.chunk(2, false, []byte("30\n"))
+ s.result(dbreads.StateDone, "", 2, summaryOf("n\n30\n"))
+ },
+ "a hash mismatch": func(s *stream) {
+ s.chunk(1, true, []byte("n\n31\n"))
+ s.result(dbreads.StateDone, "", 1, summaryOf("n\n30\n"))
+ },
+ "a chunk out of order": func(s *stream) {
+ s.chunk(2, true, []byte("30\n"))
+ s.result(dbreads.StateDone, "", 1, summaryOf("30\n"))
+ },
+ } {
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ build(s)
+ ans, _, err := readFwd(t, s, key)
+ if err == nil || err.Error() != unchecked || ans.rows != nil {
+ t.Errorf("%s: %q, %v", name, ans.rows, err)
+ }
+ }
+}
+
+func TestForwardedQueryEndsWithoutAResult(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ s.chunk(1, false, []byte("n\n"))
+ if _, _, err := readFwd(t, s, key); err == nil || err.Error() != fmt.Sprintf(dbfUnfinished, "shop.example.com", "uk") {
+ t.Fatalf("no result: %v", err)
+ }
+ key2, _ := dbreads.NewReplyKey()
+ s2 := &stream{t: t, pub: key2.PublicKey()}
+ s2.line(dbreads.Line{Admitted: fwdID})
+ s2.line(dbreads.Line{Wait: dbreads.WaitPickup})
+ s2.line(dbreads.Line{Ended: dbreads.EndedNotPicked})
+ if _, _, err := readFwd(t, s2, key2); err == nil || err.Error() != fmt.Sprintf(dbfNotPicked, "uk") {
+ t.Fatalf("not picked: %v", err)
+ }
+}
+
+func TestForwardedQueryMapsEveryCode(t *testing.T) {
+ t.Parallel()
+ host := "shop.example.com"
+ for code, want := range map[string]string{
+ dbreads.CodeTooLarge: fmt.Sprintf(dbfTooLarge, host, "3.0GB", "2.0GB", "uk"),
+ dbreads.CodeNoRoom: fmt.Sprintf(dbfNoRoom, "uk", host),
+ dbreads.CodeTimeout: dbfTimeout,
+ dbreads.CodeSQLError: "no such table: nope",
+ dbreads.CodeNothingReplicated: dbRestoreError(host, dbdoorErrNothing()).Error(),
+ dbreads.CodeChangedTwice: dbRestoreError(host, errVanished()).Error(),
+ dbreads.CodeInterrupted: fmt.Sprintf(dbfUnfinished, host, "uk"),
+ } {
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ sum := dbreads.Summary{Restored: 3 << 30, Cap: 2 << 30, Error: "no such table: nope"}
+ s.result(dbreads.StateFailed, code, 0, sum)
+ if _, _, err := readFwd(t, s, key); err == nil || err.Error() != want {
+ t.Errorf("%s: %v, want %q", code, err, want)
+ }
+ }
+ for code, want := range map[string]string{
+ dbreads.CodeRecordChanged: fmt.Sprintf(dbfChanged, host),
+ dbreads.CodeMoving: fmt.Sprintf(dbfMovingCLI, host),
+ } {
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ s.result(dbreads.StateRefused, code, 0, dbreads.Summary{})
+ if _, _, err := readFwd(t, s, key); err == nil || err.Error() != want {
+ t.Errorf("%s: %v", code, err)
+ }
+ }
+}
+
+func TestForwardedQueryOutputCapPrintsTheRows(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ s.chunk(1, true, []byte("cut"))
+ s.result(dbreads.StateDone, dbreads.CodeOutputCap, 1, summaryOf("cut"))
+ ans, _, err := readFwd(t, s, key)
+ if err != nil || !ans.capped || string(ans.rows) != "cut" {
+ t.Fatalf("%+v %v", ans, err)
+ }
+}
+
+// Review Focus 2: a full-size chunk line, about 350 KiB, is read.
+func TestForwardedQueryReadsAFullSizeChunkLine(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ rows := strings.Repeat("x", dbreads.ChunkBytes)
+ s := newStream(t, key)
+ s.chunk(1, false, []byte(rows))
+ s.chunk(2, true, nil)
+ s.result(dbreads.StateDone, "", 2, summaryOf(rows))
+ ans, _, err := readFwd(t, s, key)
+ if err != nil || len(ans.rows) != dbreads.ChunkBytes {
+ t.Fatalf("%d bytes, %v", len(ans.rows), err)
+ }
+}
+
+// Review Focus 1: Ctrl-C mid-stream is "stopped", with nothing printed.
+func TestForwardedQueryCtrlCPrintsNothing(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ s := newStream(t, key)
+ s.chunk(1, false, []byte("n\n"))
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ var status bytes.Buffer
+ ans, err := readDBForward(ctx, &cutReader{r: &s.buf}, key, "shop.example.com", "uk", &status)
+ if err == nil || err.Error() != "stopped" || ans.rows != nil {
+ t.Fatalf("%q %v", ans.rows, err)
+ }
+}
+
+// Plan review finding 37: what the CLI holds before a result is bounded by
+// count as well as bytes, and a malformed chunk is refused before it is
+// kept. Each stream is otherwise one the CLI would accept, so each case is
+// red under its own mutation of dbfChunkBound.admit: drop the size floor
+// ("a chunk shorter than its seal" then ends DBF-12, the stream having no
+// result, instead of DBF-13 at once); drop the empty-chunk rule or the
+// count bound (the stream then opens and prints).
+func TestForwardedQueryBoundsChunkCountAndSize(t *testing.T) {
+ t.Parallel()
+ key, _ := dbreads.NewReplyKey()
+ unchecked := fmt.Sprintf(dbfUnchecked, "uk")
+ many := newDBFChunkBound(dbreads.MaxOutputBytes, dbreads.ChunkBytes).maxChunks + 1
+ for name, write := range map[string]func(s *stream){
+ "a chunk shorter than its seal": func(s *stream) {
+ s.line(dbreads.Line{Chunk: 1, Data: []byte("short")})
+ },
+ "a chunk after an empty one": func(s *stream) {
+ s.chunk(1, false, nil)
+ s.chunk(2, true, []byte("n\n"))
+ s.result(dbreads.StateDone, "", 2, summaryOf("n\n"))
+ },
+ "more chunks than a read can make": func(s *stream) {
+ for seq := int64(1); seq <= many; seq++ {
+ s.chunk(seq, seq == many, []byte("x"))
+ }
+ s.result(dbreads.StateDone, "", many, summaryOf(strings.Repeat("x", int(many))))
+ },
+ } {
+ s := newStream(t, key)
+ write(s)
+ var status bytes.Buffer
+ if _, err := readDBForward(context.Background(), &s.buf, key, "shop.example.com", "uk", &status); err == nil || err.Error() != unchecked {
+ t.Errorf("%s: %v", name, err)
+ }
+ }
+}
+
+// Plan review finding 36: SQL that JSON would rewrite is refused before
+// anything is sent. Mutation: drop the check (red: the request goes out).
+func TestForwardedQueryRefusesSQLThatIsNotUTF8(t *testing.T) {
+ t.Parallel()
+ var sent atomic.Bool
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sent.Store(true)
+ http.Error(w, "no", http.StatusTeapot)
+ }))
+ defer ts.Close()
+ target := dbTarget{sess: &apiSession{c: newConsoleClient(ts.URL, "tok"), console: ts.URL}, acct: apiAcct{Seg: "acme"},
+ app: "shop", host: "shop.example.com"}
+ for _, q := range []string{"SELECT '\xff'", "SELECT '�'"} {
+ err := dbQueryForward(context.Background(), target, q, dbdoor.Forward{Region: "uk", Ops: []string{dbreads.OpQuery}})
+ if err == nil || err.Error() != fmt.Sprintf(dbfNotUTF8, "uk") {
+ t.Errorf("%q: %v", q, err)
+ }
+ }
+ if sent.Load() {
+ t.Fatal("a query JSON would rewrite was sent")
+ }
+}
+
+// cutReader ends like a connection the context closed.
+type cutReader struct{ r *bytes.Buffer }
+
+func (c *cutReader) Read(p []byte) (int, error) {
+ if c.r.Len() == 0 {
+ return 0, context.Canceled
+ }
+ return c.r.Read(p)
+}
+
+// The errors the in-region restore answers with, for the mapping test.
+func dbdoorErrNothing() error { return dbdoor.ErrNothingReplicated }
+
+func errVanished() error { return os.ErrNotExist }