| index e94c1ac38..f509cbddd 100644 |
| --- a/dbforward_e2e_test.go |
| +++ b/dbforward_e2e_test.go |
| @@ -33,6 +33,8 @@ import ( |
| "time" |
| |
| "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| |
| "github.com/carlosframework/platform/internal/console" |
| "github.com/carlosframework/platform/internal/dbdoor" |
| @@ -783,3 +785,185 @@ func TestDBForwardThroughTheBackhaulHop(t *testing.T) { |
| e := newDBFE2E(t, dbfE2EOptions{forward: true, serve: throughBackhaul(2*time.Second, &tap), worker: slowRestore(40 * time.Second)}) |
| checkProgressAtTheCLI(t, e, tap, 40*time.Second) |
| } |
| + |
| +func sha256File(t *testing.T, path string) string { |
| + t.Helper() |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(b) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// The pull's parity (plan 3): a forwarded pull and an in-region pull of the |
| +// same replica save byte-identical copies, for the newest copy and as of a |
| +// time, and print the same lines but for the host and the path. |
| +func TestDBForwardPullParityThroughTheCLI(t *testing.T) { |
| + e := newDBFE2E(t, dbfE2EOptions{forward: true}) |
| + for _, at := range []string{"", e.betweenTheSyncs(t)} { |
| + dir := t.TempDir() |
| + args := []string{"db", "pull", "--account", "ops", "--app", "shop"} |
| + if at != "" { |
| + args = append(args, "--at", at) |
| + } |
| + hereOut, farOut := filepath.Join(dir, "here.db"), filepath.Join(dir, "far.db") |
| + here, hereErr, err := e.run(t, append(args, "--instance", dbfE2EHere, "--out", hereOut)...) |
| + if err != nil { |
| + t.Fatalf("in region: %v\n%s", err, hereErr) |
| + } |
| + far, farErr, err := e.run(t, append(args, "--instance", dbfE2EFar, "--out", farOut)...) |
| + if err != nil { |
| + t.Fatalf("forwarded: %v\n%s", err, farErr) |
| + } |
| + if sha256File(t, hereOut) != sha256File(t, farOut) { |
| + t.Fatalf("at %q the copies differ", at) |
| + } |
| + if here == "" || strings.ReplaceAll(strings.ReplaceAll(far, dbfE2EFar, dbfE2EHere), farOut, hereOut) != here { |
| + t.Fatalf("at %q: in region %q, forwarded %q", at, here, far) |
| + } |
| + if !strings.Contains(farErr, fmt.Sprintf(dbfFetching, dbfE2EFar, "uk")) { |
| + t.Fatalf("no DBF-18: %s", farErr) |
| + } |
| + db, _ := sql.Open("sqlite", "file:"+farOut+"?mode=ro") |
| + var later int |
| + err = db.QueryRow(`SELECT count(*) FROM orders WHERE note = 'later'`).Scan(&later) |
| + db.Close() |
| + if err != nil || (at == "") != (later == 1) { |
| + t.Fatalf("at %q the copy holds %d of the second sync's rows (%v)", at, later, err) |
| + } |
| + } |
| +} |
| + |
| +// T11 for a pull: a hash mismatch saves nothing at --out. Everything else |
| +// is a pull the CLI would accept: far's real planned files, whole and |
| +// valid, a manifest that passes checkPullManifest, and a summary whose only |
| +// fault is its SHA-256 (plan review finding 32). Mutation: openDBPull skips |
| +// the hash comparison (red: the files restore and a copy is saved). |
| +func TestDBForwardPullSavesNothingForABadAnswer(t *testing.T) { |
| + e := newDBFE2E(t, dbfE2EOptions{forward: true, noBox: true}) |
| + stop := e.scriptBox(t, func(b *e2eScript) { |
| + ctx := context.Background() |
| + rd := lsfile.NewReplicaClient(filepath.Join(e.root, "instances", dbfE2EFar)) |
| + plan, err := dbdoor.PlanFrom(ctx, rd, time.Time{}) |
| + if err != nil { |
| + t.Errorf("plan far's replica: %v", err) |
| + return |
| + } |
| + var all bytes.Buffer |
| + for _, f := range plan.Planned { |
| + rc, err := rd.OpenLTXFile(ctx, f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID), 0, 0) |
| + if err != nil { |
| + t.Errorf("open %+v: %v", f, err) |
| + return |
| + } |
| + io.Copy(&all, rc) |
| + rc.Close() |
| + } |
| + b.picked(time.Now().Add(time.Minute)) |
| + sealed, _ := dbreads.SealChunk(b.pub, b.id, 1, dbreads.StreamLTX, true, all.Bytes()) |
| + b.store.Put(ctx, dbreads.ChunkKey(b.id, 1), sealed, "") |
| + wrong := sha256.Sum256([]byte("not these bytes")) |
| + summary, _ := dbreads.SealSummary(b.pub, b.id, dbreads.Summary{TXID: plan.TXID, At: plan.At, Files: plan.Planned, |
| + Bytes: int64(all.Len()), SHA256: hex.EncodeToString(wrong[:])}) |
| + r, _ := json.Marshal(dbreads.Result{State: dbreads.StateDone, LastSeq: 1, Box: "uk-1", Sealed: summary}) |
| + b.store.Put(ctx, dbreads.ResultKey(b.id), r, "") |
| + }) |
| + defer stop() |
| + out := filepath.Join(t.TempDir(), "far.db") |
| + _, stderr, err := e.run(t, "db", "pull", "--account", "ops", "--app", "shop", "--instance", dbfE2EFar, "--out", out) |
| + if err == nil || !strings.Contains(stderr, fmt.Sprintf(dbfUnchecked, "uk")) { |
| + t.Fatalf("%q %v", stderr, err) |
| + } |
| + if _, err := os.Stat(out); !os.IsNotExist(err) { |
| + t.Fatalf("something was saved at --out: %v", err) |
| + } |
| +} |
| + |
| +// Review Focus 4 and plan review finding 23, through the binary: SIGINT |
| +// while the CLI is spooling a pull prints "stopped", saves nothing at --out |
| +// and removes the pull's directory. The scripted box (a stand-in) writes two |
| +// chunks and never a result, so the CLI is mid-pull when the signal lands. |
| +// Mutation: drop dbPullForward's deferred RemoveAll (red: carlos-db-* is |
| +// left in the CLI's TMPDIR). |
| +func TestDBForwardPullInterruptedLeavesNothing(t *testing.T) { |
| + e := newDBFE2E(t, dbfE2EOptions{forward: true, noBox: true}) |
| + stop := e.scriptBox(t, func(b *e2eScript) { |
| + b.picked(time.Now().Add(time.Minute)) |
| + for seq := int64(1); seq <= 2; seq++ { |
| + sealed, _ := dbreads.SealChunk(b.pub, b.id, seq, dbreads.StreamLTX, false, bytes.Repeat([]byte{'x'}, 4096)) |
| + b.store.Put(context.Background(), dbreads.ChunkKey(b.id, seq), sealed, "") |
| + } |
| + }) |
| + defer stop() |
| + spool := t.TempDir() |
| + out := filepath.Join(t.TempDir(), "far.db") |
| + cmd := exec.Command(e.bin, "db", "pull", "--account", "ops", "--app", "shop", "--instance", dbfE2EFar, "--out", out) |
| + // The last TMPDIR wins (os/exec keeps the last of a duplicated key). |
| + cmd.Env = append(carlosTestEnv(t, append([]string{"CARLOS_CREDENTIALS=" + e.creds}, e.env...)...), "TMPDIR="+spool) |
| + cmd.Dir = t.TempDir() |
| + var stderr bytes.Buffer |
| + cmd.Stderr = &stderr |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + deadline := time.Now().Add(30 * time.Second) |
| + for { |
| + if got, _ := filepath.Glob(filepath.Join(spool, "carlos-db-*", "sealed", "2")); len(got) == 1 { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + cmd.Process.Kill() |
| + cmd.Wait() |
| + t.Fatalf("the CLI never spooled two chunks: %s", stderr.String()) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + if err := cmd.Process.Signal(os.Interrupt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cmd.Wait(); err == nil || !strings.Contains(stderr.String(), "stopped") { |
| + t.Fatalf("%v: %s", err, stderr.String()) |
| + } |
| + if _, err := os.Stat(out); !os.IsNotExist(err) { |
| + t.Fatalf("something was saved at --out: %v", err) |
| + } |
| + if left, _ := filepath.Glob(filepath.Join(spool, "carlos-db-*")); len(left) != 0 { |
| + t.Fatalf("the pull's directory is still there: %v", left) |
| + } |
| +} |
| + |
| +// A console from plan 2 forwards queries and not pulls. Its marker is |
| +// played here by a wrapper that drops "pull" from forward_ops on the way |
| +// out: the new CLI says DBF-8 and saves nothing. The wrapper buffers each |
| +// response, so it serves only where no response streams (the list door's |
| +// 409 is all this test reads). |
| +func TestDBForwardPullOnAQueryOnlyConsole(t *testing.T) { |
| + queryOnly := func(t *testing.T, h http.Handler) (string, []string) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + rec := httptest.NewRecorder() |
| + h.ServeHTTP(rec, r) |
| + body := rec.Body.Bytes() |
| + if rec.Code == http.StatusConflict { |
| + body = bytes.Replace(body, []byte(`"forward_ops":["query","pull"]`), []byte(`"forward_ops":["query"]`), 1) |
| + } |
| + for k, vs := range rec.Header() { |
| + w.Header()[k] = vs |
| + } |
| + w.Header().Del("Content-Length") |
| + w.WriteHeader(rec.Code) |
| + w.Write(body) |
| + })) |
| + t.Cleanup(ts.Close) |
| + return ts.URL, nil |
| + } |
| + e := newDBFE2E(t, dbfE2EOptions{forward: true, noBox: true, serve: queryOnly}) |
| + out := filepath.Join(t.TempDir(), "far.db") |
| + _, stderr, err := e.run(t, "db", "pull", "--account", "ops", "--app", "shop", "--instance", dbfE2EFar, "--out", out) |
| + if err == nil || !strings.Contains(stderr, fmt.Sprintf(dbfNoPull, dbfE2EFar, "uk")) { |
| + t.Fatalf("%q %v", stderr, err) |
| + } |
| + if _, err := os.Stat(out); !os.IsNotExist(err) { |
| + t.Fatalf("something was saved at --out: %v", err) |
| + } |
| +} |