carlos / platform Public

scripts: G2 numbered-write fixture app with hairpin fetch (T2, T6)

claude agent, operated by paul@keymail.dev 18c5206b713b7381f1ac51525aa89c3a14fab195 parent 6e5393c
3 files changed, +632 −0
  • scripts/region-ha-g2/FIXTURES.md +71 −0
  • scripts/region-ha-g2/fixture/main.go +253 −0
  • scripts/region-ha-g2/fixture/main_test.go +308 −0

Intent

Human

<task-notification> <task-id>aaa945f69f60204ce</task-id> <tool-use-id>toolu_0128eKnmrkHquNFTh3duZ21w</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/aaa945f69f60204ce.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 4" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Fix round 1 for Task 4 (a946e618) is approved. The offline test passes (16 tests). - **Important 1, rollback hint aborts under SSM:** fixed (`chrony-fixed-box.sh:12`, `docs/region-ha-runbook.md:98`, test at `test.py:243`). - **Important 2, silent exit after a mutation:** fixed (`set -E` at :2, ERR trap at :43, `failure()` at :29-39, test at `test.py:224`). - **Important 3, no apt lock wait or update:** fixed (:77-79). - **Minors:** M1 to M8 are fixed. M9 (shellcheck) is still open because shellcheck isn't installed here. - **ERR trap risk:** I ran a probe on bash 5.2.37, the version Debian 13 ships. `x=$(cmd) || fallback` does not fire the trap, so a failed source poll can't cause a false failure exit. - **Identical-config path:** the fixed script skips only the restart. The source wait, waitsync and witness still run every time. - **New issues:** no Critical or Important ones. Three new minors: - N1 (:91-94): if chrony is installed with the same config but stopped, nothing starts it, so the run fails with the clock-source message. `systemctl enable --now` fixes it. - N2 (:76): `mutating=true` is set before `apt-get update`, so an update failure prints the rollback hint even though nothing changed. - N3: the runbook tells host-init to copy the script but not how user_data gets the file. The re-review is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-4-review.md`.</result> <usage><subagent_tokens>95832</subagent_tokens><tool_uses>5</tool_uses><duration_ms>70406</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>b67xp2r7p</task-id> <tool-use-id>toolu_01JXMXf9PsmKXnZFLxvYV85N</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/b67xp2r7p.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 5 implementer" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a05232310b616586c</task-id> <tool-use-id>toolu_011dKYuhEcbb1EVjkCmfnWQj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a05232310b616586c.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 5" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec verdict:** ❌ Issues found. The script reads the brief's "right region" filter as the AWS region, but real records carry a placement code. Everything else in the brief is present: arguments, enumeration, the four checks, the lock classes, the read-only runner, the required account, the exit codes, the named proxy, and the copy rules. The report's correction of the replica layout is right. Litestream builds keys as `&lt;HibernatePrefix&gt;/%04x/&lt;min&gt;-&lt;max&gt;.ltx` with no `ltx/`. One thing I could not check offline. aws-cli 2.36.10 does not document `--max-keys` or `--continuation-token` on `list-objects-v2`. I expect it to accept them, but someone should do one read-only smoke run against a dev bucket before the first real run. **Quality verdict:** Needs fixes. **Critical:** - **C1.** `pool-readiness.py:62`, `:259`, `:300`: one `--region` flag is used both for the AWS CLI and for the record filter. Real records hold a placement code such as `ie`, and home-region HA records hold `""` (`console/server.go:598-610`, `seedmove.go:33-37`). - With `--region eu-west-1`, every real HA record is filtered out. The tool prints `hosts: 0` and `verdict: ready`, and `--strict` exits 0. I confirmed this offline with the test's fake runner. - With `--region ie`, the AWS CLI cannot find an S3 endpoint, so every read fails. - Fix: split it into an AWS-region flag and a placement-code flag, treat `""` as the home region the way `haRegion` does, and change the fixtures to use placement codes. **Important:** - **I1.** `:363`: when no host is selected, the summary says `ready` and `--strict` exits 0. A misspelt pool or account gives a vacuous "ready". It should report `unknown` with a `no_hosts` reason, and needs a test. **Minor:** - **M1.** The replica LIST covers the whole host prefix, so a host with no replica walks every files object. Listing `&lt;prefix&gt;/&lt;host&gt;/000` keeps it to one page in practice. - **M2.** A nested key under `instances/` aborts the whole app with `read_error`. Go's `recordHosts` skips such keys. - **M3.** Stale records are not dropped the way the lifetime judge drops them. This misattributes a row but does not produce a false ready. - **M4.** Host rows have no `"type": "host"` key, and the `lock` object changes shape by state. - **M5.** `record_valid` is looser than `DecodeRecord`. Checking `schema == 1` would be cheap. - **M6.** `TEXT["read_only"]` is an internal error message that no user sees, so it does not need to go through the copy pass. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-5-review.md`.</result> <usage><subagent_tokens>128641</subagent_tokens><tool_uses>39</tool_uses><duration_ms>346082</duration_ms></usage> </task-notification>

Attributed to this commit: 9.57 g CO₂e (1,227,001 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/scripts/region-ha-g2/FIXTURES.md b/scripts/region-ha-g2/FIXTURES.md
new file mode 100644
index 000000000..2678b5722
--- /dev/null
+++ b/scripts/region-ha-g2/FIXTURES.md
@@ -0,0 +1,71 @@
+# G2 fixtures.
+
+## Frozen body and log formats.
+
+Tasks 6 and 8 parse these formats. The exported constants in `fixture/main.go` define the bytes. Every HTTP body ends with one LF. `LogFormat` has no LF; the stdout logger appends it without a timestamp or prefix, after writing the response.
+
+| Constant | Body or log line, before the final LF. |
+| --- | --- |
+| `ResponseFormat` | `g2fixture box=<hostname> hits=<count> max=<max n> rid=<X-Request-Id or ->` |
+| `RangesFormat` | Comma-separated inclusive ranges, such as `1-120,125-300`. A single number has no hyphen. An empty database gives only LF. |
+| `FetchFormat` | `fetch status=<code> ms=<n>` |
+| `FetchErrorFormat` | `fetch error=<class>` |
+| `HairpinNotConfigured` | `hairpin address not configured.` |
+| `LogFormat` | `g2fixture status=<code> host=<r.Host> path=<path> rid=<rid>` |
+| `InvalidNumberBody` | `n must be a positive integer.` |
+| `DatabaseErrorBody` | `database error.` |
+| `NotFoundBody` | `not found.` |
+| `MethodNotAllowedBody` | `method not allowed.` |
+
+`POST /write?n=<int>` inserts a positive decimal integer of at most 9223372036854775807. A duplicate is ignored. A 200 response follows a successful commit. `GET /` reports the same database count and maximum without writing. An empty database reports `hits=0 max=0`. `box` is the operating system hostname, and `rid` echoes `X-Request-Id`, or `-` when absent. Invalid numbers return 400. Database failures return 500 without `hits=`. `GET /ranges` reports the stored numbers in ascending order. Responses use `Cache-Control: no-store`.
+
+`GET /fetch` makes an HTTPS GET of `/` on the incoming Host, with that hostname as TLS Server Name Indication (SNI). A Host port is retained in the URL and removed from SNI. The connection goes only to `G2_HAIRPIN_ADDR`, with no proxy or redirect following and a five-second timeout. TLS certificates must validate against the system trust store. The outer response is 200 when an HTTP response arrives, including a redirect; `status` is that response's code and `ms` is elapsed whole milliseconds. An unset address returns 503. A request failure returns 502 with class `timeout`, `tls`, `connect` or `request`. `request` means the URL could not be built; other transport failures use `connect`. No error body contains raw network errors.
+
+## Create the window fixtures.
+
+These commands are for the approved drill window. The build task does not run them. Replace all angle-bracket placeholders. Use the window's console and account, configured so new instances land in `<pool>` in `<region>`. Signed-in `instances enable` cannot set the pool. Confirm that placement before creating fixtures.
+
+Build the binary from the repository root. The activator supplies `--socket <socket>` and `--db <database>` when it starts the app. The database uses SQLite WAL and a 5000 ms busy timeout.
+
+```sh
+GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o <binary> ./scripts/region-ha-g2/fixture
+```
+
+Create a separate app for each label below. Set `<app>` to the chosen app identifier and `<label>` to its fixture label. Create fresh instances without copying or importing an existing database.
+
+| Fixture label. | Replication class. |
+| --- | --- |
+| `g2-stream` | `stream` |
+| `g2-batched` | `batched` |
+| `g2-daily` | `daily` |
+| `g2-hairpin` | `stream` |
+
+```sh
+carlos apps create --app <app> --region <region>
+carlos instances enable --app <app> --channel edge
+carlos deploy --app <app> --version <v> --channel edge <binary>
+carlos instances create --app <app> --host <label>.<domain> --channel edge
+carlos instances list --app <app>
+```
+
+Read back each persisted instance record using the window's operator credentials. Save it with the drill evidence. Check `ha: true`, `pool: <pool>` and `region: <region>` before sending numbered writes. The formatted `instances list` output does not prove these fields.
+
+```sh
+aws --profile <profile> --region <aws-region> s3 cp s3://<control-bucket>/apps/<account-id>/<app>/instances/<label>.<domain>.json <record.json>
+```
+
+For the hairpin app, set the selected Network Load Balancer (NLB) address and restart the instance so it receives the environment value. If its egress policy restricts private addresses, the window must already allow this destination.
+
+```sh
+carlos env set --app <app> G2_HAIRPIN_ADDR=<nlb-ip>:443
+carlos restart --app <app>
+```
+
+On every serving box, open the window's approved Systems Manager (SSM) session and run the following commands with `<h>` set to the fixture's full hostname. Set `<class>` from the table. Read the class back in the replication column of `carlos instances` on that box. The current CLI labels it `REPL`; the drill brief calls it `REPLICATION`.
+
+```sh
+carlos route --host <h> --replication <class>
+carlos instances
+```
+
+Repeat this on every replacement before each drill. `carlos route --replication` edits only the box where it runs. Instance records do not carry the class, so setting it on one box does not configure the others. Save each readback with the evidence and stop the drill if any serving box has the wrong class.
diff --git a/scripts/region-ha-g2/fixture/main.go b/scripts/region-ha-g2/fixture/main.go
new file mode 100644
index 000000000..cc025f5a8
--- /dev/null
+++ b/scripts/region-ha-g2/fixture/main.go
@@ -0,0 +1,253 @@
+package main
+
+import (
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "database/sql"
+ "errors"
+ "flag"
+ "fmt"
+ "log"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ _ "modernc.org/sqlite"
+)
+
+// These formats are shared with the G2 evidence collectors. Bodies end in LF;
+// the logger supplies the log line's LF without a timestamp or prefix.
+const (
+ ResponseFormat = "g2fixture box=%s hits=%d max=%d rid=%s\n"
+ RangesFormat = "%s\n"
+ FetchFormat = "fetch status=%d ms=%d\n"
+ FetchErrorFormat = "fetch error=%s\n"
+ HairpinNotConfigured = "hairpin address not configured.\n"
+ LogFormat = "g2fixture status=%d host=%s path=%s rid=%s"
+ InvalidNumberBody = "n must be a positive integer.\n"
+ DatabaseErrorBody = "database error.\n"
+ NotFoundBody = "not found.\n"
+ MethodNotAllowedBody = "method not allowed.\n"
+)
+
+type fixture struct {
+ db *sql.DB
+ box string
+ logger *log.Logger
+ roots *x509.CertPool
+}
+
+func openDB(path string) (*sql.DB, error) {
+ u := &url.URL{Scheme: "file", Path: path}
+ q := u.Query()
+ // DSN pragmas apply again if database/sql replaces a connection.
+ q.Add("_pragma", "journal_mode(WAL)")
+ q.Add("_pragma", "busy_timeout(5000)")
+ u.RawQuery = q.Encode()
+ db, err := sql.Open("sqlite", u.String())
+ if err != nil {
+ return nil, err
+ }
+ db.SetMaxOpenConns(1)
+ if _, err := db.Exec("CREATE TABLE IF NOT EXISTS w(n INTEGER PRIMARY KEY, box TEXT, at TEXT)"); err != nil {
+ db.Close()
+ return nil, err
+ }
+ return db, nil
+}
+
+func (f *fixture) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ rid := r.Header.Get("X-Request-Id")
+ if rid == "" {
+ rid = "-"
+ }
+ status, body := f.response(r, rid)
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ fmt.Fprint(w, body)
+ f.logger.Printf(LogFormat, status, r.Host, r.URL.Path, rid)
+}
+
+func (f *fixture) response(r *http.Request, rid string) (int, string) {
+ method := "GET"
+ switch r.URL.Path {
+ case "/write":
+ method = "POST"
+ case "/", "/ranges", "/fetch":
+ default:
+ return 404, NotFoundBody
+ }
+ if r.Method != method {
+ return 405, MethodNotAllowedBody
+ }
+ switch r.URL.Path {
+ case "/write":
+ values, err := url.ParseQuery(r.URL.RawQuery)
+ numbers := values["n"]
+ if err != nil || len(numbers) != 1 || numbers[0] == "" || strings.IndexFunc(numbers[0], func(c rune) bool { return c < '0' || c > '9' }) >= 0 {
+ return 400, InvalidNumberBody
+ }
+ n, err := strconv.ParseInt(numbers[0], 10, 64)
+ if err != nil || n <= 0 {
+ return 400, InvalidNumberBody
+ }
+ if err := f.write(r.Context(), n); err != nil {
+ return 500, DatabaseErrorBody
+ }
+ case "/ranges":
+ body, err := f.ranges(r.Context())
+ if err != nil {
+ return 500, DatabaseErrorBody
+ }
+ return 200, fmt.Sprintf(RangesFormat, body)
+ case "/fetch":
+ return f.fetch(r)
+ }
+ return f.report(r.Context(), rid)
+}
+
+func (f *fixture) write(ctx context.Context, n int64) error {
+ tx, err := f.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if _, err := tx.ExecContext(ctx, "INSERT OR IGNORE INTO w(n, box, at) VALUES (?, ?, ?)", n, f.box, time.Now().UTC().Format(time.RFC3339Nano)); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+func (f *fixture) report(ctx context.Context, rid string) (int, string) {
+ var hits, max int64
+ if err := f.db.QueryRowContext(ctx, "SELECT count(*), coalesce(max(n), 0) FROM w").Scan(&hits, &max); err != nil {
+ return 500, DatabaseErrorBody
+ }
+ return 200, fmt.Sprintf(ResponseFormat, f.box, hits, max, rid)
+}
+
+func (f *fixture) ranges(ctx context.Context) (string, error) {
+ rows, err := f.db.QueryContext(ctx, "SELECT n FROM w ORDER BY n")
+ if err != nil {
+ return "", err
+ }
+ defer rows.Close()
+ var parts []string
+ var start, end int64
+ have := false
+ flush := func() {
+ if start == end {
+ parts = append(parts, strconv.FormatInt(start, 10))
+ } else {
+ parts = append(parts, fmt.Sprintf("%d-%d", start, end))
+ }
+ }
+ for rows.Next() {
+ var n int64
+ if err := rows.Scan(&n); err != nil {
+ return "", err
+ }
+ if have && n-end == 1 {
+ end = n
+ continue
+ }
+ if have {
+ flush()
+ }
+ start, end, have = n, n, true
+ }
+ if err := rows.Err(); err != nil {
+ return "", err
+ }
+ if have {
+ flush()
+ }
+ return strings.Join(parts, ","), nil
+}
+
+func fetchClient(addr, host string, roots *x509.CertPool) *http.Client {
+ if name, _, err := net.SplitHostPort(host); err == nil {
+ host = name
+ }
+ dialer := &net.Dialer{Timeout: 5 * time.Second}
+ return &http.Client{
+ Timeout: 5 * time.Second,
+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse },
+ Transport: &http.Transport{
+ // No proxy and no hostname lookup from the request: only addr is dialled.
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, network, addr)
+ },
+ TLSClientConfig: &tls.Config{ServerName: host, RootCAs: roots, MinVersion: tls.VersionTLS12},
+ DisableKeepAlives: true,
+ },
+ }
+}
+
+func (f *fixture) fetch(r *http.Request) (int, string) {
+ addr := os.Getenv("G2_HAIRPIN_ADDR")
+ if addr == "" {
+ return 503, HairpinNotConfigured
+ }
+ u := &url.URL{Scheme: "https", Host: r.Host, Path: "/"}
+ req, err := http.NewRequestWithContext(r.Context(), "GET", u.String(), nil)
+ if err != nil {
+ return 502, fmt.Sprintf(FetchErrorFormat, "request")
+ }
+ client := fetchClient(addr, r.Host, f.roots)
+ defer client.CloseIdleConnections()
+ start := time.Now()
+ resp, err := client.Do(req)
+ if err != nil {
+ return 502, fmt.Sprintf(FetchErrorFormat, fetchError(err))
+ }
+ resp.Body.Close()
+ return 200, fmt.Sprintf(FetchFormat, resp.StatusCode, time.Since(start).Milliseconds())
+}
+
+func fetchError(err error) string {
+ var netErr net.Error
+ var certErr *tls.CertificateVerificationError
+ var recordErr tls.RecordHeaderError
+ switch {
+ case errors.As(err, &netErr) && netErr.Timeout():
+ return "timeout"
+ case errors.As(err, &certErr), errors.As(err, &recordErr):
+ return "tls"
+ default:
+ return "connect"
+ }
+}
+
+func main() {
+ logger := log.New(os.Stdout, "", 0)
+ socket := flag.String("socket", "", "unix socket")
+ path := flag.String("db", "g2fixture.db", "database")
+ flag.Parse()
+ db, err := openDB(*path)
+ if err != nil {
+ logger.Fatal(err)
+ }
+ defer db.Close()
+ box, err := os.Hostname()
+ if err != nil {
+ logger.Fatal(err)
+ }
+ network, addr := "tcp", "127.0.0.1:8098"
+ if *socket != "" {
+ network, addr = "unix", *socket
+ }
+ ln, err := net.Listen(network, addr)
+ if err != nil {
+ logger.Fatal(err)
+ }
+ defer ln.Close()
+ server := &http.Server{Handler: &fixture{db: db, box: box, logger: logger}, ReadHeaderTimeout: 5 * time.Second}
+ logger.Fatal(server.Serve(ln))
+}
diff --git a/scripts/region-ha-g2/fixture/main_test.go b/scripts/region-ha-g2/fixture/main_test.go
new file mode 100644
index 000000000..5bf22c0ed
--- /dev/null
+++ b/scripts/region-ha-g2/fixture/main_test.go
@@ -0,0 +1,308 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func testFixture(t *testing.T) (*fixture, *bytes.Buffer) {
+ t.Helper()
+ db, err := openDB(filepath.Join(t.TempDir(), "fixture.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ logs := new(bytes.Buffer)
+ return &fixture{db: db, box: "test-box", logger: log.New(logs, "", 0)}, logs
+}
+
+func request(f *fixture, method, target, rid string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, target, nil)
+ r.Host = "fixture.invalid"
+ r.Header.Set("X-Request-Id", rid)
+ w := httptest.NewRecorder()
+ f.ServeHTTP(w, r)
+ return w
+}
+
+func TestFixtureWriteReadDuplicate(t *testing.T) {
+ f, _ := testFixture(t)
+ for _, tc := range []struct{ method, path, body string }{
+ {"GET", "/", "g2fixture box=test-box hits=0 max=0 rid=request-1\n"},
+ {"POST", "/write?n=7", "g2fixture box=test-box hits=1 max=7 rid=request-1\n"},
+ {"POST", "/write?n=7", "g2fixture box=test-box hits=1 max=7 rid=request-1\n"},
+ {"POST", "/write?n=2", "g2fixture box=test-box hits=2 max=7 rid=request-1\n"},
+ {"GET", "/", "g2fixture box=test-box hits=2 max=7 rid=request-1\n"},
+ } {
+ w := request(f, tc.method, tc.path, "request-1")
+ if w.Code != 200 || w.Body.String() != tc.body {
+ t.Fatalf("%s %s: status=%d body=%q", tc.method, tc.path, w.Code, w.Body.String())
+ }
+ if w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatal("fixture evidence must not be cached")
+ }
+ }
+ var box, at, mode string
+ var timeout int
+ if err := f.db.QueryRow("SELECT box, at FROM w WHERE n=7").Scan(&box, &at); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := time.Parse(time.RFC3339Nano, at); err != nil || box != f.box {
+ t.Fatalf("stored box=%q at=%q: %v", box, at, err)
+ }
+ if err := f.db.QueryRow("PRAGMA journal_mode").Scan(&mode); err != nil || mode != "wal" {
+ t.Fatalf("journal mode=%q: %v", mode, err)
+ }
+ if err := f.db.QueryRow("PRAGMA busy_timeout").Scan(&timeout); err != nil || timeout != 5000 {
+ t.Fatalf("busy timeout=%d: %v", timeout, err)
+ }
+}
+
+func TestFixtureInvalidNumber(t *testing.T) {
+ f, _ := testFixture(t)
+ for _, n := range []string{"", "0", "-1", "1.2", "x", "%2B1", "1%20", "9223372036854775808", "1&n=2"} {
+ t.Run(n, func(t *testing.T) {
+ w := request(f, "POST", "/write?n="+n, "")
+ if w.Code != 400 || strings.Contains(w.Body.String(), "hits=") {
+ t.Fatalf("invalid number acknowledged: status=%d body=%q", w.Code, w.Body.String())
+ }
+ })
+ }
+ if got := request(f, "GET", "/", "").Body.String(); got != "g2fixture box=test-box hits=0 max=0 rid=-\n" {
+ t.Fatal(got)
+ }
+}
+
+func TestFixtureRanges(t *testing.T) {
+ f, _ := testFixture(t)
+ if got := request(f, "GET", "/ranges", "").Body.String(); got != "\n" {
+ t.Fatalf("empty ranges=%q", got)
+ }
+ for _, n := range []int64{300, 125, 126, 1, 2, 3, 8, 9223372036854775806, 9223372036854775807} {
+ if w := request(f, "POST", fmt.Sprintf("/write?n=%d", n), ""); w.Code != 200 {
+ t.Fatal(w.Body.String())
+ }
+ }
+ w := request(f, "GET", "/ranges", "")
+ if w.Code != 200 || w.Body.String() != "1-3,8,125-126,300,9223372036854775806-9223372036854775807\n" {
+ t.Fatalf("status=%d ranges=%q", w.Code, w.Body.String())
+ }
+}
+
+func TestFixtureWriteFailureNoAcknowledgement(t *testing.T) {
+ for _, failure := range []string{"closed database", "insert", "commit"} {
+ t.Run(failure, func(t *testing.T) {
+ f, logs := testFixture(t)
+ switch failure {
+ case "closed database":
+ f.db.Close()
+ case "insert":
+ if _, err := f.db.Exec("DROP TABLE w"); err != nil {
+ t.Fatal(err)
+ }
+ case "commit":
+ // The insert succeeds; only COMMIT checks the deferred foreign key.
+ for _, q := range []string{
+ "PRAGMA foreign_keys=ON",
+ "CREATE TABLE parent (n INTEGER PRIMARY KEY)",
+ "CREATE TABLE child (n INTEGER REFERENCES parent(n) DEFERRABLE INITIALLY DEFERRED)",
+ "CREATE TRIGGER reject_commit AFTER INSERT ON w BEGIN INSERT INTO child VALUES (NEW.n); END",
+ } {
+ if _, err := f.db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ w := request(f, "POST", "/write?n=1", "failed-write")
+ if w.Code != 500 || strings.Contains(w.Body.String(), "hits=") {
+ t.Fatalf("failed write acknowledged: status=%d body=%q", w.Code, w.Body.String())
+ }
+ if got := logs.String(); got != "g2fixture status=500 host=fixture.invalid path=/write rid=failed-write\n" {
+ t.Fatal(got)
+ }
+ })
+ }
+}
+
+func TestFixtureReadFailure(t *testing.T) {
+ f, _ := testFixture(t)
+ f.db.Close()
+ for _, path := range []string{"/", "/ranges"} {
+ if w := request(f, "GET", path, ""); w.Code != 500 || strings.Contains(w.Body.String(), "hits=") {
+ t.Fatalf("%s: status=%d body=%q", path, w.Code, w.Body.String())
+ }
+ }
+}
+
+func TestFixtureFetch(t *testing.T) {
+ f, _ := testFixture(t)
+ var hits atomic.Int32
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ if r.TLS.ServerName != "example.com" || r.Host != "example.com" || r.URL.Path != "/" || r.Method != "GET" {
+ t.Errorf("hairpin request: SNI=%q host=%q path=%q method=%q", r.TLS.ServerName, r.Host, r.URL.Path, r.Method)
+ }
+ w.WriteHeader(204)
+ }))
+ t.Cleanup(server.Close)
+ f.roots = x509.NewCertPool()
+ f.roots.AddCert(server.Certificate())
+ t.Setenv("G2_HAIRPIN_ADDR", server.Listener.Addr().String())
+ // A proxy must never become a second dial destination.
+ t.Setenv("HTTPS_PROXY", "http://127.0.0.1:1")
+ r := httptest.NewRequest("GET", "https://example.com/fetch", nil)
+ w := httptest.NewRecorder()
+ f.ServeHTTP(w, r)
+ if w.Code != 200 || !strings.HasPrefix(w.Body.String(), "fetch status=204 ms=") || hits.Load() != 1 {
+ t.Fatalf("status=%d body=%q hits=%d", w.Code, w.Body.String(), hits.Load())
+ }
+ client := fetchClient(server.Listener.Addr().String(), r.Host, f.roots)
+ if client.Timeout != 5*time.Second {
+ t.Fatalf("timeout=%s", client.Timeout)
+ }
+}
+
+func TestFixtureFetchRedirectRefused(t *testing.T) {
+ f, _ := testFixture(t)
+ var hits, escaped atomic.Int32
+ other := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { escaped.Add(1) }))
+ t.Cleanup(other.Close)
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ http.Redirect(w, r, other.URL, http.StatusFound)
+ }))
+ t.Cleanup(server.Close)
+ f.roots = x509.NewCertPool()
+ f.roots.AddCert(server.Certificate())
+ t.Setenv("G2_HAIRPIN_ADDR", server.Listener.Addr().String())
+ w := httptest.NewRecorder()
+ f.ServeHTTP(w, httptest.NewRequest("GET", "https://example.com/fetch", nil))
+ if w.Code != 200 || !strings.HasPrefix(w.Body.String(), "fetch status=302 ms=") || hits.Load() != 1 || escaped.Load() != 0 {
+ t.Fatalf("redirect followed: status=%d body=%q hits=%d escaped=%d", w.Code, w.Body.String(), hits.Load(), escaped.Load())
+ }
+}
+
+func TestFixtureFetchFixedDestination(t *testing.T) {
+ f, _ := testFixture(t)
+ var allowed, escaped atomic.Int32
+ target := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ allowed.Add(1)
+ w.WriteHeader(204)
+ }))
+ t.Cleanup(target.Close)
+ other := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { escaped.Add(1) }))
+ t.Cleanup(other.Close)
+ f.roots = x509.NewCertPool()
+ f.roots.AddCert(target.Certificate())
+ t.Setenv("G2_HAIRPIN_ADDR", target.Listener.Addr().String())
+ w := httptest.NewRecorder()
+ f.ServeHTTP(w, httptest.NewRequest("GET", other.URL+"/fetch", nil))
+ if w.Code != 200 || !strings.HasPrefix(w.Body.String(), "fetch status=204 ms=") || allowed.Load() != 1 || escaped.Load() != 0 {
+ t.Fatalf("wrong dial destination: status=%d body=%q allowed=%d escaped=%d", w.Code, w.Body.String(), allowed.Load(), escaped.Load())
+ }
+}
+
+func TestFixtureFetchTimeout(t *testing.T) {
+ f, _ := testFixture(t)
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-r.Context().Done():
+ case <-time.After(8 * time.Second):
+ }
+ }))
+ t.Cleanup(server.Close)
+ f.roots = x509.NewCertPool()
+ f.roots.AddCert(server.Certificate())
+ t.Setenv("G2_HAIRPIN_ADDR", server.Listener.Addr().String())
+ w := httptest.NewRecorder()
+ start := time.Now()
+ f.ServeHTTP(w, httptest.NewRequest("GET", "https://example.com/fetch", nil))
+ if elapsed := time.Since(start); w.Code != 502 || w.Body.String() != "fetch error=timeout\n" || elapsed > 7*time.Second {
+ t.Fatalf("status=%d body=%q elapsed=%s", w.Code, w.Body.String(), elapsed)
+ }
+}
+
+func TestFixtureFetchErrors(t *testing.T) {
+ f, _ := testFixture(t)
+ t.Setenv("G2_HAIRPIN_ADDR", "")
+ w := request(f, "GET", "/fetch", "")
+ if w.Code != 503 || w.Body.String() != "hairpin address not configured.\n" {
+ t.Fatalf("status=%d body=%q", w.Code, w.Body.String())
+ }
+ t.Setenv("G2_HAIRPIN_ADDR", "invalid-address")
+ w = request(f, "GET", "/fetch", "")
+ if w.Code != 502 || w.Body.String() != "fetch error=connect\n" {
+ t.Fatalf("status=%d body=%q", w.Code, w.Body.String())
+ }
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Error("untrusted TLS reached handler") }))
+ t.Cleanup(server.Close)
+ t.Setenv("G2_HAIRPIN_ADDR", server.Listener.Addr().String())
+ w = request(f, "GET", "/fetch", "")
+ if w.Code != 502 || w.Body.String() != "fetch error=tls\n" {
+ t.Fatalf("status=%d body=%q", w.Code, w.Body.String())
+ }
+ if got := fetchError(context.DeadlineExceeded); got != "timeout" {
+ t.Fatalf("deadline classified as %q", got)
+ }
+ if got := fetchError(&tls.CertificateVerificationError{Err: x509.UnknownAuthorityError{}}); got != "tls" {
+ t.Fatalf("TLS classified as %q", got)
+ }
+}
+
+func TestFixtureMethodsAndLogContract(t *testing.T) {
+ if ResponseFormat != "g2fixture box=%s hits=%d max=%d rid=%s\n" || FetchFormat != "fetch status=%d ms=%d\n" || FetchErrorFormat != "fetch error=%s\n" || HairpinNotConfigured != "hairpin address not configured.\n" || LogFormat != "g2fixture status=%d host=%s path=%s rid=%s" {
+ t.Fatal("frozen contract changed")
+ }
+ if RangesFormat != "%s\n" || InvalidNumberBody != "n must be a positive integer.\n" || DatabaseErrorBody != "database error.\n" || NotFoundBody != "not found.\n" || MethodNotAllowedBody != "method not allowed.\n" {
+ t.Fatal("body contract changed")
+ }
+ f, logs := testFixture(t)
+ for _, tc := range []struct {
+ method, path string
+ status int
+ }{
+ {"GET", "/", 200}, {"POST", "/write?n=1", 200}, {"GET", "/ranges", 200},
+ {"GET", "/write?n=2", 405}, {"POST", "/", 405}, {"POST", "/fetch", 405}, {"POST", "/ranges", 405}, {"GET", "/missing", 404},
+ } {
+ logs.Reset()
+ w := request(f, tc.method, tc.path, "")
+ path, _, _ := strings.Cut(tc.path, "?")
+ want := fmt.Sprintf(LogFormat+"\n", tc.status, "fixture.invalid", path, "-")
+ if w.Code != tc.status || logs.String() != want {
+ t.Fatalf("%s %s: status=%d log=%q want=%q", tc.method, tc.path, w.Code, logs.String(), want)
+ }
+ }
+}
+
+type logOrderWriter struct {
+ *httptest.ResponseRecorder
+ logs *bytes.Buffer
+ t *testing.T
+}
+
+func (w logOrderWriter) Write(body []byte) (int, error) {
+ if w.logs.Len() != 0 {
+ w.t.Error("response logged before its body was written")
+ }
+ return w.ResponseRecorder.Write(body)
+}
+
+func TestFixtureLogAfterResponse(t *testing.T) {
+ f, logs := testFixture(t)
+ w := logOrderWriter{httptest.NewRecorder(), logs, t}
+ f.ServeHTTP(w, httptest.NewRequest("GET", "https://fixture.invalid/", nil))
+ if logs.String() != "g2fixture status=200 host=fixture.invalid path=/ rid=-\n" || w.Body.Len() == 0 {
+ t.Fatalf("body=%q log=%q", w.Body.String(), logs.String())
+ }
+}