P6 plan, owner review folded in: caller travels with the job, 1–2 round-robin workers, busy retry, summary reads, local-only tests, 8 tasks

Kyle: "Fold them into the plan." What changed and why is in docs/P6.md §14. In short:
- FetchFunc gets the *auth.Caller (the given api test could not compile, and a fetch with no
  caller would bypass per-caller gates, the pool limit, the cache class and redaction);
- store reads never bump the lease (task 01's rule contradicted its own test); the API Touches;
- 1-2 workers round-robin over live jobs, so a batch holds at most 2 of the 8 global slots;
  busy targets retry in the runner (bounded); batch PDFs use their own pool name; 210 s deadline;
- the api tests no longer touch the network or race the cancel; private names via fake DNS;
- failed/cancelled jobs are not reused; GET is a summary plus GET …/{idx} and ?results=1;
- the 256 KiB body cap moves into ServeHTTP; a fixed metrics label for /v1/batch/{id};
- guard.PreCheck (given verbatim) replaces guard.ParseURL at submit;
- 5 tasks became 8 (refactor, wiring, endpoints and serve/config split), each restating the
  APIs it uses; every given test compiles against a panic-only skeleton and fails on it.

P6 starts after P5c: task 04 moves v1fetch, which P5b changes. Recheck the api given tests
against post-P5c master before the run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-26 17:55:50 -07:00
co-authored by Claude Opus 5.5
parent 63e70e19fc
commit 218eaa8b53
20 changed files with 1854 additions and 617 deletions
+199 -173
View File
@@ -2,253 +2,279 @@ package api
import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.wntrmute.dev/kyle/sift/internal/auth"
"git.wntrmute.dev/kyle/sift/internal/batch"
"git.wntrmute.dev/kyle/sift/internal/dcache"
"git.wntrmute.dev/kyle/sift/internal/fetch"
"git.wntrmute.dev/kyle/sift/internal/guard"
)
// newBatchServer builds a Server with the batch runner wired over an in-memory
// dcache, exactly as serve does in production. callers are the caller names to
// provision (each with a bearer key).
func newBatchServer(t *testing.T, g *guard.Guard, callers ...string) (*Server, map[string]string) {
// Every test fetches only from local httptest servers or internal.test (fake DNS): no test
// touches the network. newBatchServer, pageServer and fakeDNS come from batchrun_test.go.
func batchReq(t *testing.T, s *Server, method, path, key string, body any) *httptest.ResponseRecorder {
t.Helper()
dir := t.TempDir()
keysPath := filepath.Join(dir, "keys.toml")
keys := map[string]string{}
for _, name := range callers {
out := filepath.Join(dir, name)
if err := auth.Add(keysPath, name, "hermes-fleet", out); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(out)
var rd io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
keys[name] = strings.TrimSpace(string(b))
rd = strings.NewReader(string(b))
}
store, err := auth.Load(keysPath)
if err != nil {
t.Fatal(err)
}
if g == nil {
g = &guard.Guard{}
}
f := &fetch.Fetcher{Guard: g, UA: "sift-test"}
s := New("test", g, f, store, slog.New(slog.NewTextHandler(io.Discard, nil)))
db, err := dcache.Open("", 1<<20, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
s.Batch = batch.New(db, s.fetchTarget, batch.Config{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
return s, keys
}
func submitBatch(t *testing.T, s *Server, key string, targets []map[string]string) *httptest.ResponseRecorder {
t.Helper()
return postJSON(t, s, "/v1/batch", key, map[string]any{"targets": targets})
}
func getBatch(t *testing.T, s *Server, key, id string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/v1/batch/"+id, nil)
req := httptest.NewRequest(method, path, rd)
req.Header.Set("Authorization", "Bearer "+key)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
rec := httptest.NewRecorder()
s.ServeHTTP(rec, req)
return rec
}
func batchStatus(t *testing.T, s *Server, key, id string) map[string]any {
func batchDecode(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
rec := getBatch(t, s, key, id)
var env map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
t.Fatalf("status decode: %v (%s)", err, rec.Body.String())
var m map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &m); err != nil {
t.Fatalf("decode: %v (%d %s)", err, rec.Code, rec.Body.String())
}
return env
return m
}
// waitBatchTerminal polls until the job reaches a terminal status.
func waitBatchTerminal(t *testing.T, s *Server, key, id string) map[string]any {
func submit(t *testing.T, s *Server, key string, targets ...map[string]any) map[string]any {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
rec := batchReq(t, s, http.MethodPost, "/v1/batch", key, map[string]any{"targets": targets})
if rec.Code != 202 {
t.Fatalf("submit: %d %s", rec.Code, rec.Body.String())
}
return batchDecode(t, rec)
}
func waitTerminal(t *testing.T, s *Server, key, id string) map[string]any {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
env := batchStatus(t, s, key, id)
if st, _ := env["status"].(string); st == "done" || st == "partial" || st == "failed" || st == "cancelled" {
env := batchDecode(t, batchReq(t, s, http.MethodGet, "/v1/batch/"+id, key, nil))
switch env["status"] {
case "done", "partial", "failed", "cancelled":
return env
}
time.Sleep(time.Millisecond)
time.Sleep(5 * time.Millisecond)
}
t.Fatal("batch never reached a terminal status")
return nil
}
func TestBatchSubmitAndCollect(t *testing.T) {
g := &guard.Guard{AllowPrefixes: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(`<html><head><title>T</title></head><body><article><p>hello batch</p></article></body></html>`))
}))
defer ts.Close()
s, keys := newBatchServer(t, g, "test")
rec := submitBatch(t, s, keys["test"], []map[string]string{{"url": ts.URL}, {"url": ts.URL + "/2"}})
if rec.Code != 202 {
t.Fatalf("submit %d %s", rec.Code, rec.Body.String())
}
var sub map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &sub); err != nil {
t.Fatal(err)
}
if sub["success"] != true {
t.Fatalf("success %v", sub["success"])
}
ts := pageServer(t, nil)
s, keys := newBatchServer(t, "test")
sub := submit(t, s, keys["test"], map[string]any{"url": ts.URL + "/one"}, map[string]any{"url": ts.URL + "/two"})
id, _ := sub["job_id"].(string)
if id == "" {
t.Fatal("missing job_id")
if sub["success"] != true || id == "" || sub["reused"] != false || sub["targets"] != float64(2) || sub["status"] != "queued" {
t.Fatalf("submit body %v", sub)
}
if reused, _ := sub["reused"].(bool); reused {
t.Fatal("first submit must not be reused")
// The status body is a summary: statuses, no results.
env := waitTerminal(t, s, keys["test"], id)
if env["status"] != "done" || env["targets_total"] != float64(2) || env["targets_done"] != float64(2) {
t.Fatalf("status %v", env)
}
env := waitBatchTerminal(t, s, keys["test"], id)
if env["status"] != "done" {
t.Fatalf("status %v", env["status"])
if _, err := time.Parse(time.RFC3339, fmt.Sprint(env["created_at"])); err != nil {
t.Fatalf("created_at %v is not RFC 3339", env["created_at"])
}
targets, _ := env["targets"].([]any)
targets := env["targets"].([]any)
if len(targets) != 2 {
t.Fatalf("targets %d", len(targets))
}
first := targets[0].(map[string]any)
if first["status"] != "done" {
t.Fatalf("target0 %v", first["status"])
for i, x := range targets {
tg := x.(map[string]any)
if tg["idx"] != float64(i) || tg["status"] != "done" {
t.Fatalf("target %d: %v", i, tg)
}
if _, has := tg["result"]; has {
t.Fatalf("summary must not carry results: target %d has one", i)
}
}
res, _ := first["result"].(map[string]any)
if res == nil || !strings.Contains(res["content"].(string), "hello batch") {
t.Fatalf("target0 result %v", res)
// One target's result: the /v1/fetch envelope.
rec := batchReq(t, s, http.MethodGet, "/v1/batch/"+id+"/1", keys["test"], nil)
if rec.Code != 200 {
t.Fatalf("GET idx: %d %s", rec.Code, rec.Body.String())
}
one := batchDecode(t, rec)
res, _ := one["result"].(map[string]any)
if one["idx"] != float64(1) || one["status"] != "done" || res == nil {
t.Fatalf("GET idx body %v", one)
}
if c, _ := res["content"].(string); !strings.Contains(c, "hello batch /two") {
t.Fatalf("result content %q", c)
}
if res["untrusted"] != true || res["mode"] != "clean" {
t.Fatalf("result is not the /v1/fetch envelope: %v", res)
}
if src, _ := res["source"].(map[string]any); src == nil || src["final_url"] != ts.URL+"/two" {
t.Fatalf("result source %v", res["source"])
}
// ?results=1 inlines every result.
full := batchDecode(t, batchReq(t, s, http.MethodGet, "/v1/batch/"+id+"?results=1", keys["test"], nil))
for i, x := range full["targets"].([]any) {
if _, has := x.(map[string]any)["result"]; !has {
t.Fatalf("results=1: target %d has no result", i)
}
}
if got := batchReq(t, s, http.MethodGet, "/v1/batch/"+id+"/2", keys["test"], nil).Code; got != 404 {
t.Fatalf("GET idx out of range: %d, want 404", got)
}
if got := batchReq(t, s, http.MethodGet, "/v1/batch/"+id+"/x", keys["test"], nil).Code; got != 404 {
t.Fatalf("GET idx not a number: %d, want 404", got)
}
}
func TestBatchIdempotentResubmit(t *testing.T) {
g := &guard.Guard{AllowPrefixes: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("ok"))
}))
defer ts.Close()
s, keys := newBatchServer(t, g, "test")
targets := []map[string]string{{"url": ts.URL}}
first := submitBatch(t, s, keys["test"], targets)
second := submitBatch(t, s, keys["test"], targets)
var a, b map[string]any
_ = json.Unmarshal(first.Body.Bytes(), &a)
_ = json.Unmarshal(second.Body.Bytes(), &b)
if a["job_id"] != b["job_id"] {
t.Fatalf("ids differ: %v vs %v", a["job_id"], b["job_id"])
}
if reused, _ := b["reused"].(bool); !reused {
t.Fatal("resubmit must be reused=true")
ts := pageServer(t, nil)
s, keys := newBatchServer(t, "test")
tg := map[string]any{"url": ts.URL, "mode": "clean"}
a := submit(t, s, keys["test"], tg)
b := submit(t, s, keys["test"], tg)
if a["job_id"] != b["job_id"] || b["reused"] != true {
t.Fatalf("resubmit: %v then %v", a, b)
}
}
func TestBatchGuardRefusedUpFront(t *testing.T) {
s, keys := newBatchServer(t, nil, "test")
rec := submitBatch(t, s, keys["test"], []map[string]string{{"url": "http://example.com:8080/"}})
if rec.Code != 422 {
t.Fatalf("want 422, got %d %s", rec.Code, rec.Body.String())
func TestBatchRefusedUpFront(t *testing.T) {
s, keys := newBatchServer(t, "test")
cases := []struct {
name string
body any
code int
want string
}{
{"guard pre-check (port)", map[string]any{"targets": []any{map[string]any{"url": "http://127.0.0.1/"}, map[string]any{"url": "http://example.com:8080/"}}}, 422, "blocked"},
{"guard pre-check (private literal)", map[string]any{"targets": []any{map[string]any{"url": "http://10.0.0.5/"}}}, 422, "blocked"},
{"no targets", map[string]any{"targets": []any{}}, 400, ""},
{"not json", "nope", 400, ""},
{"empty url", map[string]any{"targets": []any{map[string]any{"url": ""}}}, 400, ""},
{"bad mode", map[string]any{"targets": []any{map[string]any{"url": "http://127.0.0.1/", "mode": "shout"}}}, 400, ""},
}
if !strings.Contains(rec.Body.String(), "blocked") {
t.Fatalf("body %s", rec.Body.String())
for _, c := range cases {
rec := batchReq(t, s, http.MethodPost, "/v1/batch", keys["test"], c.body)
if rec.Code != c.code || !strings.Contains(rec.Body.String(), c.want) {
t.Errorf("%s: %d %s, want %d containing %q", c.name, rec.Code, rec.Body.String(), c.code, c.want)
}
}
// The guard refusal names the offending index.
rec := batchReq(t, s, http.MethodPost, "/v1/batch", keys["test"], cases[0].body)
if !strings.Contains(rec.Body.String(), "1") {
t.Errorf("guard refusal does not name target 1: %s", rec.Body.String())
}
}
func TestBatchTooManyTargets(t *testing.T) {
s, keys := newBatchServer(t, nil, "test")
var targets []map[string]string
var many []any
for i := 0; i < 33; i++ {
targets = append(targets, map[string]string{"url": "https://example.com/"})
many = append(many, map[string]any{"url": fmt.Sprintf("http://127.0.0.1/%d", i)})
}
rec := submitBatch(t, s, keys["test"], targets)
if rec.Code != 422 {
t.Fatalf("want 422, got %d %s", rec.Code, rec.Body.String())
if rec := batchReq(t, s, http.MethodPost, "/v1/batch", keys["test"], map[string]any{"targets": many}); rec.Code != 422 {
t.Errorf("33 targets: %d, want 422", rec.Code)
}
}
// 32 targets, each with a 500-rune question, fit the batch body cap even though they are well
// over the 64 KiB cap of the other endpoints.
func TestBatchBodyCap(t *testing.T) {
hold := make(chan struct{})
defer close(hold)
ts := pageServer(t, hold)
s, keys := newBatchServer(t, "test")
q := strings.Repeat("q", 500)
var many []any
for i := 0; i < 32; i++ {
many = append(many, map[string]any{"url": fmt.Sprintf("%s/%d?pad=%s", ts.URL, i, strings.Repeat("p", 1500)), "question": q})
}
if rec := batchReq(t, s, http.MethodPost, "/v1/batch", keys["test"], map[string]any{"targets": many}); rec.Code != 202 {
t.Fatalf("32 targets with questions (~%d KiB): %d %s", 32*2100/1024, rec.Code, rec.Body.String())
}
}
func TestBatchPartialFailure(t *testing.T) {
g := &guard.Guard{AllowPrefixes: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("ok"))
}))
defer ts.Close()
s, keys := newBatchServer(t, g, "test")
// target 1 is a private address: passes the submit pre-check (valid URL) but
// is blocked by the connect-time guard, surfacing as a per-target failure.
rec := submitBatch(t, s, keys["test"], []map[string]string{{"url": ts.URL}, {"url": "http://10.0.0.5/"}})
if rec.Code != 202 {
t.Fatalf("submit %d %s", rec.Code, rec.Body.String())
}
var sub map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &sub)
id := sub["job_id"].(string)
env := waitBatchTerminal(t, s, keys["test"], id)
ts := pageServer(t, nil)
s, keys := newBatchServer(t, "test")
// Target 1 is a name that resolves to a private address. Names are not resolved at submit,
// so it passes the pre-check; the fetch-time guard blocks it: a per-target failure.
sub := submit(t, s, keys["test"], map[string]any{"url": ts.URL}, map[string]any{"url": "http://internal.test/"})
env := waitTerminal(t, s, keys["test"], sub["job_id"].(string))
if env["status"] != "partial" {
t.Fatalf("status %v", env["status"])
}
targets := env["targets"].([]any)
second := targets[1].(map[string]any)
second := env["targets"].([]any)[1].(map[string]any)
if second["status"] != "failed" {
t.Fatalf("target1 status %v", second["status"])
t.Fatalf("target 1: %v", second)
}
if err, _ := second["error"].(string); !strings.Contains(err, "blocked") {
t.Fatalf("target1 error %q", err)
if e, _ := second["error"].(string); !strings.Contains(e, "blocked") {
t.Fatalf("target 1 error %q", e)
}
}
func TestBatchOwnership404(t *testing.T) {
s, keys := newBatchServer(t, nil, "test", "other")
rec := submitBatch(t, s, keys["test"], []map[string]string{{"url": "https://example.com/"}})
if rec.Code != 202 {
t.Fatalf("submit %d", rec.Code)
hold := make(chan struct{})
defer close(hold)
ts := pageServer(t, hold)
s, keys := newBatchServer(t, "test", "other")
id := submit(t, s, keys["test"], map[string]any{"url": ts.URL})["job_id"].(string)
for _, p := range []string{"/v1/batch/" + id, "/v1/batch/" + id + "/0"} {
if got := batchReq(t, s, http.MethodGet, p, keys["other"], nil).Code; got != 404 {
t.Fatalf("other caller GET %s: %d (must not reveal the job)", p, got)
}
}
var sub map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &sub)
id := sub["job_id"].(string)
if got := getBatch(t, s, keys["other"], id); got.Code != 404 {
t.Fatalf("other caller GET: %d (must not reveal the job)", got.Code)
if got := batchReq(t, s, http.MethodDelete, "/v1/batch/"+id, keys["other"], nil).Code; got != 404 {
t.Fatalf("other caller DELETE: %d", got)
}
if got := getBatch(t, s, keys["test"], id); got.Code != 200 {
t.Fatalf("owner GET: %d", got.Code)
if got := batchReq(t, s, http.MethodGet, "/v1/batch/"+id, keys["test"], nil).Code; got != 200 {
t.Fatalf("owner GET: %d", got)
}
if got := batchReq(t, s, http.MethodGet, "/v1/batch/no-such-job", keys["test"], nil).Code; got != 404 {
t.Fatalf("unknown job: %d", got)
}
if got := batchReq(t, s, http.MethodGet, "/v1/batch/"+id, "not-a-key", nil).Code; got != 401 {
t.Fatalf("bad key: %d", got)
}
}
func TestBatchCancel(t *testing.T) {
g := &guard.Guard{AllowPrefixes: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}}
s, keys := newBatchServer(t, g, "test")
rec := submitBatch(t, s, keys["test"], []map[string]string{{"url": "https://example.com/"}})
var sub map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &sub)
id := sub["job_id"].(string)
req := httptest.NewRequest(http.MethodDelete, "/v1/batch/"+id, nil)
req.Header.Set("Authorization", "Bearer "+keys["test"])
drec := httptest.NewRecorder()
s.ServeHTTP(drec, req)
if drec.Code != 200 {
t.Fatalf("cancel %d %s", drec.Code, drec.Body.String())
hold := make(chan struct{})
ts := pageServer(t, hold)
s, keys := newBatchServer(t, "test")
id := submit(t, s, keys["test"], map[string]any{"url": ts.URL + "/a"}, map[string]any{"url": ts.URL + "/b"})["job_id"].(string)
rec := batchReq(t, s, http.MethodDelete, "/v1/batch/"+id, keys["test"], nil)
if rec.Code != 200 {
t.Fatalf("cancel: %d %s", rec.Code, rec.Body.String())
}
env := waitBatchTerminal(t, s, keys["test"], id)
if b := batchDecode(t, rec); b["success"] != true || b["status"] != "cancelled" {
t.Fatalf("cancel body %v", b)
}
close(hold)
env := waitTerminal(t, s, keys["test"], id)
if env["status"] != "cancelled" {
t.Fatalf("status %v", env["status"])
}
if tg := env["targets"].([]any)[1].(map[string]any); tg["status"] != "pending" {
t.Fatalf("target 1 after cancel: %v", tg)
}
if got := batchReq(t, s, http.MethodDelete, "/v1/batch/"+id, keys["test"], nil).Code; got != 409 {
t.Fatalf("cancelling a finished job: %d, want 409", got)
}
}
// The request metrics never get a job id as a label value.
func TestBatchMetricsPathLabel(t *testing.T) {
ts := pageServer(t, nil)
s, keys := newBatchServer(t, "test")
id := submit(t, s, keys["test"], map[string]any{"url": ts.URL})["job_id"].(string)
waitTerminal(t, s, keys["test"], id)
batchReq(t, s, http.MethodGet, "/v1/batch/"+id+"/0", keys["test"], nil)
if strings.Contains(promText(t, s), id) {
t.Fatal("a job id appears in /metrics")
}
}
+202
View File
@@ -0,0 +1,202 @@
package api
// P6 task 05: the runner wired to fetchTarget and the metrics, with no HTTP yet. The helpers
// here (newBatchServer, pageServer, fakeDNS) are shared with task 06's batch_test.go.
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.wntrmute.dev/kyle/sift/internal/auth"
"git.wntrmute.dev/kyle/sift/internal/batch"
"git.wntrmute.dev/kyle/sift/internal/dcache"
"git.wntrmute.dev/kyle/sift/internal/fetch"
"git.wntrmute.dev/kyle/sift/internal/guard"
)
var loopback = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}
// fakeDNS resolves internal.test to a private address; every other name fails to resolve.
func fakeDNS(_ context.Context, host string) ([]netip.Addr, error) {
if host == "internal.test" {
return []netip.Addr{netip.MustParseAddr("10.0.0.5")}, nil
}
return nil, fmt.Errorf("no such host %s", host)
}
// newBatchServer builds a Server with the batch runner wired over an in-memory dcache through
// s.NewBatchRunner, exactly as serve does. callers are the names to provision (each gets a key).
func newBatchServer(t *testing.T, callers ...string) (*Server, map[string]string) {
t.Helper()
dir := t.TempDir()
keysPath := filepath.Join(dir, "keys.toml")
keys := map[string]string{}
for _, name := range callers {
out := filepath.Join(dir, name)
if err := auth.Add(keysPath, name, "hermes-fleet", out); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(out)
if err != nil {
t.Fatal(err)
}
keys[name] = strings.TrimSpace(string(b))
}
store, err := auth.Load(keysPath)
if err != nil {
t.Fatal(err)
}
g := &guard.Guard{AllowPrefixes: loopback, LookupIP: fakeDNS}
f := &fetch.Fetcher{Guard: g, UA: "sift-test"}
log := slog.New(slog.NewTextHandler(io.Discard, nil))
s := New("test", g, f, store, log)
db, err := dcache.Open("", 1<<20, log)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
s.Batch = s.NewBatchRunner(db, batch.Config{})
t.Cleanup(s.Batch.Close) // before db.Close
return s, keys
}
// pageServer serves a small HTML page at every path; hold, when non-nil, blocks each request
// until it is closed.
func pageServer(t *testing.T, hold chan struct{}) *httptest.Server {
t.Helper()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hold != nil {
select {
case <-hold:
case <-r.Context().Done():
return
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<html><head><title>T</title></head><body><article><p>hello batch %s</p></article></body></html>`, r.URL.Path)
}))
t.Cleanup(ts.Close)
return ts
}
func waitJob(t *testing.T, r *batch.Runner, id string) batch.Job {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
j, _, ok := r.Status(id)
if ok && (j.Status == "done" || j.Status == "partial" || j.Status == "failed" || j.Status == "cancelled") {
return j
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("job never finished")
return batch.Job{}
}
func promText(t *testing.T, s *Server) string {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
req.RemoteAddr, req.Host = "127.0.0.1:9", "127.0.0.1:8890"
rec := httptest.NewRecorder()
s.ServeHTTP(rec, req)
return rec.Body.String()
}
// The runner fetches through fetchTarget as the submitting caller; a name that resolves to a
// private address is a per-target "blocked" failure; the hooks reach the metrics.
func TestBatchRunnerWired(t *testing.T) {
ts := pageServer(t, nil)
s, _ := newBatchServer(t, "test")
c := &auth.Caller{Name: "test", Workspace: "hermes-fleet"}
id, reused, err := s.Batch.Submit(context.Background(), c, dcache.ClassFleet, []batch.Target{
{URL: ts.URL + "/one"}, {URL: "http://internal.test/"},
})
if err != nil || reused {
t.Fatalf("submit: %v %v", err, reused)
}
if j := waitJob(t, s.Batch, id); j.Status != "partial" {
t.Fatalf("job %+v", j)
}
_, ts2, _ := s.Batch.Status(id)
if ts2[0].Status != "done" || ts2[0].Result == nil || !strings.Contains(ts2[0].Result.Content, "hello batch /one") {
t.Fatalf("target 0: %+v", ts2[0])
}
if ts2[0].Result.Meta["mode"] != "clean" || ts2[0].Result.Meta["untrusted"] != true {
t.Fatalf("target 0 meta %v: not the fetchTarget envelope", ts2[0].Result.Meta)
}
if ts2[1].Status != "failed" || !strings.Contains(ts2[1].Error, "blocked") {
t.Fatalf("target 1: %+v", ts2[1])
}
out := promText(t, s)
for _, want := range []string{
`sift_batch_jobs_total{outcome="created"} 1`,
`sift_batch_jobs_total{outcome="partial"} 1`,
`sift_batch_targets_total{outcome="ok"} 1`,
`sift_batch_targets_total{outcome="blocked"} 1`,
`sift_batch_result_bytes_count 1`,
`sift_batch_queue_depth 0`,
} {
if !strings.Contains(out, want) {
t.Errorf("metrics lack %q", want)
}
}
}
// The adapter turns fetch errors into what the runner and the metrics need.
func TestBatchOutcomeClasses(t *testing.T) {
cases := []struct {
err error
want string
}{
{nil, "ok"},
{fmt.Errorf("busy: %w", batch.ErrRetryLater), "busy"},
{&batch.TargetError{Status: 403, Msg: "blocked: private address"}, "blocked"},
{&batch.TargetError{Status: 429, Msg: "busy"}, "busy"},
{&batch.TargetError{Status: 504, Msg: "timeout"}, "timeout"},
{&batch.TargetError{Status: 415, Msg: "unsupported content type"}, "unsupported"},
{&batch.TargetError{Status: 422, Msg: "document too long for question (6001 chunks); use grep or pages"}, "too_long"},
{&batch.TargetError{Status: 422, Msg: "unreadable PDF"}, "upstream_4xx"},
{&batch.TargetError{Status: 404, Msg: "not found"}, "upstream_4xx"},
{&batch.TargetError{Status: 500, Msg: "internal error"}, "upstream_5xx"},
{errors.New("something else"), "upstream_5xx"},
}
for _, c := range cases {
if got := batchOutcome(c.err); got != c.want {
t.Errorf("batchOutcome(%v) = %q, want %q", c.err, got, c.want)
}
}
}
// batchFetch maps a busy fetch to ErrRetryLater (the runner retries it) and every other
// failure to a TargetError with the /v1/fetch status.
func TestBatchFetchErrors(t *testing.T) {
s, _ := newBatchServer(t, "test")
c := &auth.Caller{Name: "test", Workspace: "hermes-fleet"}
_, err := s.batchFetch(context.Background(), c, batch.Target{URL: "http://internal.test/"})
var te *batch.TargetError
if !errors.As(err, &te) || te.Status != 403 || !strings.Contains(te.Msg, "blocked") {
t.Fatalf("private name: %v, want a TargetError 403 blocked", err)
}
// Fill the global fetch gate so the next fetch is refused busy.
for i := 0; i < 8; i++ {
if err := s.acquire(fmt.Sprintf("filler%d", i), "http://filler.test/"); err != nil {
t.Fatal(err)
}
}
ts := pageServer(t, nil)
_, err = s.batchFetch(context.Background(), c, batch.Target{URL: ts.URL})
if !errors.Is(err, batch.ErrRetryLater) {
t.Fatalf("busy gate: %v, want an error wrapping batch.ErrRetryLater", err)
}
}
@@ -0,0 +1,94 @@
package api
// P6 task 04: v1fetch's per-target pipeline is extracted into s.fetchTarget, which the batch
// runner also calls. These tests pin that the two agree; every existing v1fetch test must also
// pass unchanged.
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"testing"
"git.wntrmute.dev/kyle/sift/internal/auth"
"git.wntrmute.dev/kyle/sift/internal/batch"
"git.wntrmute.dev/kyle/sift/internal/fetch"
"git.wntrmute.dev/kyle/sift/internal/guard"
)
// newTargetServer is setupAPI with loopback allowed; its key belongs to caller "test".
func newTargetServer(t *testing.T) (*Server, string) {
t.Helper()
return setupAPI(t, &guard.Guard{AllowPrefixes: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}})
}
func TestFetchTargetMatchesV1Fetch(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(`<html><head><title>Same</title></head><body><article><h1>Same</h1><p>one pipeline, two callers</p></article></body></html>`))
}))
defer ts.Close()
s, key := newTargetServer(t)
c := &auth.Caller{Name: "test", Workspace: "hermes-fleet"}
res, err := s.fetchTarget(context.Background(), c, batch.Target{URL: ts.URL})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(res.Content, "one pipeline, two callers") {
t.Fatalf("content %q", res.Content)
}
if _, has := res.Meta["content"]; has {
t.Fatal("Meta must not repeat the content")
}
for _, k := range []string{"mode", "untrusted", "source", "warnings", "sizes", "timings"} {
if _, has := res.Meta[k]; !has {
t.Errorf("Meta lacks %q (it carries every envelope field except content)", k)
}
}
if res.Meta["mode"] != "clean" || res.Meta["untrusted"] != true {
t.Fatalf("meta %v", res.Meta)
}
// The same URL through /v1/fetch: identical content and mode, and the envelope has exactly
// the fields of Meta plus content.
rec := postJSON(t, s, "/v1/fetch", key, map[string]any{"url": ts.URL})
if rec.Code != 200 {
t.Fatalf("v1fetch %d %s", rec.Code, rec.Body.String())
}
var env map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
t.Fatal(err)
}
if env["content"] != res.Content || env["mode"] != res.Meta["mode"] {
t.Fatalf("v1fetch and fetchTarget disagree:\n%v\n%+v", env, res)
}
if len(env) != len(res.Meta)+1 {
t.Fatalf("envelope keys %d, Meta keys %d: want Meta + content", len(env), len(res.Meta))
}
}
func TestFetchTargetErrors(t *testing.T) {
s, _ := newTargetServer(t)
c := &auth.Caller{Name: "test", Workspace: "hermes-fleet"}
cases := []struct {
name string
target batch.Target
status int
msg string
}{
{"blocked", batch.Target{URL: "http://10.0.0.5/"}, 403, "blocked"},
{"bad mode", batch.Target{URL: "http://127.0.0.1/", Options: batch.Options{Mode: "shout"}}, 400, ""},
}
for _, tc := range cases {
_, err := s.fetchTarget(context.Background(), c, tc.target)
var fe *fetch.Error
if !errors.As(err, &fe) || fe.Status != tc.status || !strings.Contains(fe.Msg, tc.msg) {
t.Errorf("%s: err %v, want a *fetch.Error %d containing %q", tc.name, err, tc.status, tc.msg)
}
}
}