From 04bb657bb3573d00d92c1748058a61c1612d48fd Mon Sep 17 00:00:00 2001 From: Sam Scholten Date: Tue, 20 Oct 2026 10:51:46 +1000 Subject: polite: fetch-light sweep (scraper off + HTTP cache honored) on every feed --- README.md | 13 +++- cmds/polite.go | 85 +++++++++++++++++++++++ cmds/polite_test.go | 161 ++++++++++++++++++++++++++++++++++++++++++++ justfile | 4 ++ main.go | 3 + miniflux/client.go | 100 ++++++++++++++++++++++++---- miniflux/client_test.go | 174 +++++++++++++++++++++++++++++++++++++++++++++--- 7 files changed, 515 insertions(+), 25 deletions(-) create mode 100644 cmds/polite.go create mode 100644 cmds/polite_test.go diff --git a/README.md b/README.md index c4d4d8c..dad3133 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ Personal Miniflux article recommender. Ranks your incoming RSS entries with a title-only classifier trained on the ones you star, and serves the top picks -as an RSS feed you subscribe to in Miniflux itself. Read-only toward Miniflux. +as an RSS feed you subscribe to in Miniflux itself. Read-only toward Miniflux +(the weekly pipeline; `polite` is the one deliberate maintenance write). No deps beyond stdlib + vendored ML core. ## Requirements @@ -21,6 +22,7 @@ fluxrec serve poll, score, RSS at /recommendations.xml (server) fluxrec retrostar model-ranked candidates to star by hand (cold start) fluxrec feeds per-feed volume + star stats (pruning aid) fluxrec compact-labels trim per-feed negative skew (one-off, re-runnable) +fluxrec polite scraper off + HTTP cache honored (maintenance write) fluxrec score debug: stdin titles → stdout scores ``` @@ -54,7 +56,14 @@ runs.jsonl server run log; doubles as the RSS render source - Serve surfaces: `GET /recommendations.xml`, `GET /api/status`, and `POST /api/poll` (out-of-schedule poll; serialized with scheduled polls, short cooldown, `curl -X POST https://server/api/poll`). -- Never writes to Miniflux. Never needs credentials in the repo. +- `polite` is the only write to Miniflux: it sets `crawler=false` and + `ignore_http_cache=false` (fetch-light, anti-blocking) on every feed, + exactly those two fields — no other setting moves. Idempotent, stops at + first failure, rerun to finish; `just polite --dry-run` previews. New + subscriptions can be added by hand with those toggles on — rerun the + sweep occasionally to sweep them in. The pipeline + (export/serve/train) never writes to Miniflux. +- Never needs credentials in the repo. - Training stays on the local PC; the server only scores (low RAM). - Deploy `serve` only after a `train` run on enough organic stars shows an honest precision@15 in report.json; tiny validation sets lie. diff --git a/cmds/polite.go b/cmds/polite.go new file mode 100644 index 0000000..2701436 --- /dev/null +++ b/cmds/polite.go @@ -0,0 +1,85 @@ +// Polite command: one-off sweep making every feed a polite fetcher. +// +// Sends PUT /v1/feeds/{id} with the two-field body {"crawler":false, +// "ignore_http_cache":false} per subscription: no original-article scraping +// and HTTP cache (conditional requests) honored. That is the strategy +// against origins blocking the polling — per poll cycle the origin sees only +// the (cheap, mostly 304) feed fetch, not a page request per new entry. +// Only those two fields are ever sent, so no other feed setting can move +// (Miniflux's update is pointer-based: omitted fields stay untouched). +// Fail-fast + idempotent: an interrupted run is resumed by simply rerunning. +// +// Side effect worth knowing: with the scraper off, future entries carry the +// feed-provided content (often an excerpt) instead of the scraped article — +// serve's RSS bodies will follow suit. Title-only scoring is unaffected. +package cmds + +import ( + "flag" + "fmt" + "io" + + "fluxrec/miniflux" +) + +type PoliteCommand struct { + DryRun bool +} + +func (c *PoliteCommand) Name() string { return "polite" } + +func (c *PoliteCommand) Init(args []string) error { + fs := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + fs.Usage = func() { + fmt.Fprint(fs.Output(), `Usage: fluxrec polite [--dry-run] + +Make every feed a polite fetcher: scraper off, HTTP cache honored. Each feed +is updated with the two-field body {"crawler":false,"ignore_http_cache":false} +— nothing else on the feed changes. Stops at the first feed that errors +(naming it and the remainder); rerun at will, the op is idempotent. +--dry-run lists the feeds without sending anything. +`) + fs.PrintDefaults() + } + fs.BoolVar(&c.DryRun, "dry-run", false, "List the feeds and exit (no PUT sent)") + if err := fs.Parse(args); err != nil { + return err + } + return nil +} + +func (c *PoliteCommand) Run(stdin io.Reader, stdout io.Writer) error { + cfg, err := miniflux.ConfigFromEnv() + if err != nil { + return err + } + client := miniflux.NewClient(cfg) + + feeds, err := client.Feeds() + if err != nil { + return err + } + + // API order, one update at a time: a subscription list is small, and + // serialized requests keep any failure's story simple. + done := 0 + for _, f := range feeds { + if c.DryRun { + fmt.Fprintf(stdout, "would %-6d %s\n", f.ID, clip(f.Title, 64)) + continue + } + if err := client.MakeFeedPolite(f.ID); err != nil { + return fmt.Errorf("updating feed %d (%s): %w; rerun polite to finish the remaining %d (idempotent)", + f.ID, f.Title, err, len(feeds)-done) + } + done++ + fmt.Fprintf(stdout, "ok %-6d %s\n", f.ID, clip(f.Title, 64)) + } + + if c.DryRun { + fmt.Fprintf(stdout, "dry-run: would set crawler=false and ignore_http_cache=false on all %d feeds; nothing was sent\n", len(feeds)) + return nil + } + fmt.Fprintf(stdout, "polite sweep: scraper off + HTTP cache honored on %d of %d feeds\n", done, len(feeds)) + return nil +} diff --git a/cmds/polite_test.go b/cmds/polite_test.go new file mode 100644 index 0000000..5af44d8 --- /dev/null +++ b/cmds/polite_test.go @@ -0,0 +1,161 @@ +// Tests for `fluxrec polite` against an httptest fake Miniflux: one GET +// plus one two-field PUT per feed in API order, dry-run sends nothing, and +// a failed PUT stops the sweep naming the feed and the remainder. +package cmds + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// politeFake serves GET /v1/feeds and records (and can fail) the per-feed +// PUTs the sweep makes, including their bodies. +type politeFake struct { + feedsJSON string + putStatus map[string]int // PUT path -> response status; 0 = 204 + calls []string // "METHOD path" per request in order (PUTs gain " body") +} + +func (f *politeFake) handler() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + call := r.Method + " " + r.URL.Path + switch { + case r.Method == http.MethodGet && r.URL.Path == "/v1/feeds": + f.calls = append(f.calls, call) + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, f.feedsJSON) + case r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/v1/feeds/"): + body, _ := io.ReadAll(r.Body) + f.calls = append(f.calls, call+" "+string(body)) + status := f.putStatus[r.URL.Path] + if status == 0 { + status = http.StatusNoContent + } + w.WriteHeader(status) + default: + http.NotFound(w, r) + } + } +} + +func newPoliteServer(t *testing.T, fake *politeFake) { + t.Helper() + srv := httptest.NewServer(fake.handler()) + t.Cleanup(srv.Close) + t.Setenv("MINIFLUX_URL", srv.URL) + t.Setenv("MINIFLUX_TOKEN", "test-token") +} + +const politeTwoFeeds = `[ + {"id": 77, "title": "Example Blog", "site_url": "https://example.com"}, + {"id": 102, "title": "Some Daily", "site_url": "https://daily.example"} +]` + +func TestPoliteSweepsAllFeeds(t *testing.T) { + fake := &politeFake{feedsJSON: politeTwoFeeds} + newPoliteServer(t, fake) + + cmd := &PoliteCommand{} + var out bytes.Buffer + if err := cmd.Run(nil, &out); err != nil { + t.Fatalf("polite: %v", err) + } + + // One list call plus one PUT per feed, in API order, each PUT carrying + // exactly the two fetch fields. + wantCalls := []string{ + "GET /v1/feeds", + `PUT /v1/feeds/77 {"crawler":false,"ignore_http_cache":false}`, + `PUT /v1/feeds/102 {"crawler":false,"ignore_http_cache":false}`, + } + if len(fake.calls) != len(wantCalls) { + t.Fatalf("API calls = %v, want %v", fake.calls, wantCalls) + } + for i, want := range wantCalls { + if fake.calls[i] != want { + t.Errorf("call[%d] = %q, want %q", i, fake.calls[i], want) + } + } + + // One ok line per feed, API order preserved. + got := out.String() + ok77 := strings.Index(got, "ok") >= 0 && strings.Contains(got, "Example Blog") + ok102 := strings.Index(got, "ok") >= 0 && strings.Contains(got, "Some Daily") + if !ok77 || !ok102 { + t.Fatalf("output missing an ok line:\n%s", got) + } + if strings.Index(got, "Example Blog") > strings.Index(got, "Some Daily") { + t.Errorf("feeds not swept in API order:\n%s", got) + } + if !strings.Contains(got, "2 of 2 feeds") { + t.Errorf("summary should count both feeds:\n%s", got) + } +} + +func TestPoliteDryRunSendsNothing(t *testing.T) { + fake := &politeFake{feedsJSON: politeTwoFeeds} + newPoliteServer(t, fake) + + cmd := &PoliteCommand{DryRun: true} + var out bytes.Buffer + if err := cmd.Run(nil, &out); err != nil { + t.Fatalf("polite dry-run: %v", err) + } + + // Only the list call happened — no PUT, so by construction nothing was + // modified. + if len(fake.calls) != 1 || fake.calls[0] != "GET /v1/feeds" { + t.Fatalf("dry-run must only list, got %v", fake.calls) + } + + got := out.String() + if !strings.Contains(got, "Example Blog") || !strings.Contains(got, "Some Daily") { + t.Errorf("dry-run should list the feeds:\n%s", got) + } + if strings.Contains(got, "\nok") { + t.Errorf("dry-run must not print ok lines:\n%s", got) + } + if !strings.Contains(got, "nothing was sent") { + t.Errorf("dry-run summary missing its nothing-was-sent promise:\n%s", got) + } +} + +func TestPoliteStopsAtFirstError(t *testing.T) { + fake := &politeFake{ + feedsJSON: politeTwoFeeds, + putStatus: map[string]int{"/v1/feeds/102": http.StatusNotFound}, + } + newPoliteServer(t, fake) + + cmd := &PoliteCommand{} + var out bytes.Buffer + err := cmd.Run(nil, &out) + if err == nil { + t.Fatal("expected error when a PUT fails, got nil") + } + + // Error names the failing feed and the idempotent-restart story. + if !strings.Contains(err.Error(), "feed 102") { + t.Errorf("error should name the failing feed: %v", err) + } + if !strings.Contains(err.Error(), "remaining 1") { + t.Errorf("error should name the remaining count: %v", err) + } + if !strings.Contains(err.Error(), "rerun polite") { + t.Errorf("error should tell the operator to rerun: %v", err) + } + + // Got as far as feed 77 (ok line printed, no summary line). + got := out.String() + if !strings.Contains(got, "Example Blog") || strings.Contains(got, "Some Daily") { + t.Errorf("output should show progress up to the failure:\n%s", got) + } + if strings.Contains(got, "of 2 feeds") { + t.Errorf("no summary after a failure:\n%s", got) + } +} diff --git a/justfile b/justfile index f2fcb92..c92278c 100644 --- a/justfile +++ b/justfile @@ -47,6 +47,10 @@ retrostar LIMIT="50": feeds DAYS="180" MIN_PER_DAY="0.05" MIN_SEEN="0": check-auth go run . feeds --days {{DAYS}} --min-per-day {{MIN_PER_DAY}} --min-seen {{MIN_SEEN}} +# Politeness sweep for feeds +polite ARGS="": check-auth + go run . polite {{ARGS}} + # export + compact + train retrain: check-auth go run . export diff --git a/main.go b/main.go index 8a7d54f..969bbd3 100644 --- a/main.go +++ b/main.go @@ -42,6 +42,8 @@ func main() { cmd = &cmds.FeedsCommand{} case "compact-labels": cmd = &cmds.CompactLabelsCommand{} + case "polite": + cmd = &cmds.PoliteCommand{} default: fmt.Fprintf(os.Stderr, "Unknown command: %s\n\n", cmdName) printHelp() @@ -75,6 +77,7 @@ Commands: retrostar Model-ranked candidates for retroactive starring (cold start) feeds Subscription audit: per-feed volume + star stats (pruning aid) compact-labels Trim per-feed negative over-representation in labels.jsonl + polite Fetch-light sweep: scraper off + HTTP cache on every feed Usage: echo "some title" | fluxrec score --model model.json diff --git a/miniflux/client.go b/miniflux/client.go index d430852..29441c4 100644 --- a/miniflux/client.go +++ b/miniflux/client.go @@ -2,12 +2,17 @@ // // Typed over exactly what fluxrec needs: GET /v1/entries with the filter // subset used by export (starred/status/changed_after) and serve -// (after_entry_id). Auth is the X-Auth-Token header; credentials come from -// the environment (MINIFLUX_* with MFLUX_* fallback, so existing mflux -// exports work). Read-only by construction: there are no mutation methods. +// (after_entry_id), GET /v1/feeds (audits, the politeness sweep), and +// exactly one write: MakeFeedPolite, whose body type carries exactly two +// fields so the request can only ever say {"crawler": false, +// "ignore_http_cache": false} and nothing else. Auth is the X-Auth-Token +// header; credentials come from the environment (MINIFLUX_* with MFLUX_* +// fallback, so existing mflux exports work). Everything else is read-only +// by construction: no entry, star, or other feed mutation exists. package miniflux import ( + "bytes" "encoding/json" "fmt" "io" @@ -54,26 +59,36 @@ func firstEnv(names [2]string) string { return "" } -// Client is a read-only Miniflux API client. +// Client talks to Miniflux: reads plus the single politeness write. +// Transport-level blips (DNS read timeouts, resets) are retried with the +// waits in retryWait. type Client struct { baseURL string token string httpClient *http.Client + retryWait []time.Duration } +// transportBackoff is the default retry spacing after a transport-level +// request failure (dial/read timeout, reset — live-observed as DNS read +// timeouts on a flaky resolver). Short enough to clear a flap without ever +// looking like extra load to the server. +var transportBackoff = []time.Duration{time.Second, 4 * time.Second} + // NewClient builds a Client with a sane default HTTP timeout. func NewClient(cfg Config) *Client { return &Client{ baseURL: cfg.BaseURL, token: cfg.Token, httpClient: &http.Client{Timeout: 60 * time.Second}, + retryWait: transportBackoff, } } // NewClientWithHTTP is NewClient with a caller-provided http.Client // (tests point it at httptest servers). func NewClientWithHTTP(cfg Config, hc *http.Client) *Client { - return &Client{baseURL: cfg.BaseURL, token: cfg.Token, httpClient: hc} + return &Client{baseURL: cfg.BaseURL, token: cfg.Token, httpClient: hc, retryWait: transportBackoff} } // Feed is the subset of a Miniflux feed fluxrec needs. @@ -164,36 +179,93 @@ func (c *Client) Feeds() ([]FeedInfo, error) { return feeds, nil } +// MakeFeedPolite sets the two per-feed fetch settings that keep polling +// light — crawler (fetch-original-content) and ignore_http_cache — both +// false, so feeds stop being scraped and conditional requests (ETag / +// If-Modified-Since) are honored again. This is the sole write fluxrec +// performs on Miniflux. The request body is a marshalled feedPatch, which +// carries exactly these two fields, so nothing else on the feed can move +// (Miniflux's update is pointer-based: omitted fields stay untouched). +// Idempotent: same input, same state. +func (c *Client) MakeFeedPolite(id int64) error { + payload, err := json.Marshal(feedPatch{}) + if err != nil { + return fmt.Errorf("encoding update request: %w", err) + } + _, err = c.sendJSON(http.MethodPut, c.baseURL+"/v1/feeds/"+strconv.FormatInt(id, 10), payload) + return err +} + +// feedPatch is the PUT /v1/feeds/{id} request body. Exactly these two +// fields, both false: the wire format is +// {"crawler":false,"ignore_http_cache":false}. +type feedPatch struct { + Crawler bool `json:"crawler"` // "Fetch original content" + IgnoreHTTPCache bool `json:"ignore_http_cache"` // "Ignore HTTP cache" +} + // fetchEntries issues the GET and returns the body on HTTP 200. func (c *Client) fetchEntries(f Filters) ([]byte, error) { return c.getJSON(entriesURL(c.baseURL, f)) } -// getJSON GETs u with the auth header and returns the body on HTTP 200; -// any other status becomes an error naming the status and a response sniff. +// getJSON GETs u with the auth header and returns the body via sendJSON. func (c *Client) getJSON(u string) ([]byte, error) { - req, err := http.NewRequest(http.MethodGet, u, nil) + return c.sendJSON(http.MethodGet, u, nil) +} + +// sendJSON issues an authenticated request to u — payload nil means no +// request body (GET), non-nil means a JSON body. Returns the response body +// on any 2xx status: Miniflux answers reads with 200 and mutations with +// 200, 201 or 204 (201 even for updates — live-observed; the 204 body is +// empty). Any other status becomes an error naming the method, URL, status +// and a response sniff. +// +// Transport-level failures are retried (up to len(retryWait) extra +// attempts) but status errors are not: a blip is transient, a server +// answer is an answer. Retrying is safe for every call this client makes +// — GETs are idempotent, and the one write (MakeFeedPolite) sets a fixed +// state. Each attempt re-arms the body from GetBody so a drained reader +// can never be re-sent empty. +func (c *Client) sendJSON(method, u string, payload []byte) ([]byte, error) { + var body io.Reader + if payload != nil { + body = bytes.NewReader(payload) + } + req, err := http.NewRequest(method, u, body) if err != nil { return nil, fmt.Errorf("building request: %w", err) } req.Header.Set("X-Auth-Token", c.token) + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } resp, err := c.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("GET %s: %w", u, err) + for attempt := 0; err != nil; attempt++ { + if attempt >= len(c.retryWait) { + return nil, fmt.Errorf("%s %s: %w", method, u, err) + } + time.Sleep(c.retryWait[attempt]) + if req.GetBody != nil { + if fresh, berr := req.GetBody(); berr == nil { + req.Body = fresh + } + } + resp, err = c.httpClient.Do(req) } defer func() { _ = resp.Body.Close() }() - if resp.StatusCode != http.StatusOK { + if resp.StatusCode < 200 || resp.StatusCode > 299 { body, _ := io.ReadAll(io.LimitReader(resp.Body, 256)) - return nil, fmt.Errorf("GET %s: status %d: %s", u, resp.StatusCode, body) + return nil, fmt.Errorf("%s %s: status %d: %s", method, u, resp.StatusCode, body) } - body, err := io.ReadAll(resp.Body) + out, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("reading response from %s: %w", u, err) } - return body, nil + return out, nil } // entriesURL builds /v1/entries?... honoring only the non-zero filters. diff --git a/miniflux/client_test.go b/miniflux/client_test.go index e3774a3..de737eb 100644 --- a/miniflux/client_test.go +++ b/miniflux/client_test.go @@ -5,10 +5,14 @@ package miniflux import ( "encoding/json" + "fmt" + "io" + "net" "net/http" "net/http/httptest" "strings" "testing" + "time" ) const entriesFixture = `{ @@ -79,26 +83,38 @@ const entriesFixture = `{ ] }` -// fakeServer records the last request's auth header and query, then replies -// with the fixture (or an error status). Accepts /v1/entries and /v1/feeds. +// fakeServer records the last request's method, path, auth header, content +// type, body and query, then replies with the fixture (or a set status). +// Accepts anything under /v1/ (entries, feeds, per-feed updates). type fakeServer struct { - t *testing.T - status int - body string - gotHeader string - gotQuery map[string]string - sawRequest bool + t *testing.T + status int + body string + gotHeader string + gotMethod string + gotPath string + gotContentType string + gotRequestBody string + gotQuery map[string]string + sawRequest bool } func (f *fakeServer) handler() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { f.sawRequest = true f.gotHeader = r.Header.Get("X-Auth-Token") + f.gotMethod = r.Method + f.gotPath = r.URL.Path + f.gotContentType = r.Header.Get("Content-Type") f.gotQuery = map[string]string{} for k, v := range r.URL.Query() { f.gotQuery[k] = v[0] } - if r.URL.Path != "/v1/entries" && r.URL.Path != "/v1/feeds" { + if r.Body != nil { + b, _ := io.ReadAll(r.Body) + f.gotRequestBody = string(b) + } + if !strings.HasPrefix(r.URL.Path, "/v1/") { f.t.Errorf("unexpected path: %s", r.URL.Path) } w.Header().Set("Content-Type", "application/json") @@ -280,6 +296,146 @@ func TestFeedsDecodesFixture(t *testing.T) { } } +// The politeness write must be a PUT to the feed's own URL, authenticated, +// JSON-typed, and whose body is exactly the two fetch fields — the property +// that keeps MakeFeedPolite from touching anything else on the feed. +func TestMakeFeedPoliteSendsOnlyTheTwoFields(t *testing.T) { + f := &fakeServer{t: t, status: http.StatusNoContent} + client := newFakeClient(t, f) + + if err := client.MakeFeedPolite(77); err != nil { + t.Fatalf("MakeFeedPolite: %v", err) + } + + if !f.sawRequest { + t.Fatal("fake server saw no request") + } + if f.gotMethod != http.MethodPut { + t.Errorf("method = %q, want PUT", f.gotMethod) + } + if f.gotPath != "/v1/feeds/77" { + t.Errorf("path = %q, want /v1/feeds/77", f.gotPath) + } + if f.gotHeader != "test-token-123" { + t.Errorf("X-Auth-Token = %q, want test-token-123", f.gotHeader) + } + if f.gotContentType != "application/json" { + t.Errorf("Content-Type = %q, want application/json", f.gotContentType) + } + wantBody := `{"crawler":false,"ignore_http_cache":false}` + if f.gotRequestBody != wantBody { + t.Errorf("request body = %q, want %q", f.gotRequestBody, wantBody) + } +} + +// All 2xx are success: reads get 200, 204 (empty body) covers some PUTs, +// and — live-observed on reader.samsci.com — Miniflux answers feed updates +// with 201 + the updated feed JSON, even though nothing was created. The +// first live polite run failed on exactly that; this test guards against +// reintroducing it. +func TestMakeFeedPoliteAcceptsAll2xx(t *testing.T) { + for _, status := range []int{http.StatusOK, http.StatusCreated, http.StatusNoContent} { + f := &fakeServer{t: t, status: status, body: `{"id":77,"crawler":false,"ignore_http_cache":false}`} + client := newFakeClient(t, f) + if err := client.MakeFeedPolite(77); err != nil { + t.Fatalf("status %d: %v", status, err) + } + } +} + +func TestMakeFeedPoliteHTTPError(t *testing.T) { + f := &fakeServer{t: t, status: http.StatusNotFound} + client := newFakeClient(t, f) + + err := client.MakeFeedPolite(999) + if err == nil { + t.Fatal("expected error on 404, got nil") + } + if !strings.Contains(err.Error(), "404") { + t.Errorf("error should name the status: %v", err) + } + if !strings.Contains(err.Error(), "/v1/feeds/999") { + t.Errorf("error should name the resource: %v", err) + } +} + +// flakyTransport fails its first `failures` RoundTrips at the transport +// level (no HTTP status — think DNS read timeouts, resets), then delegates +// to the inner transport. Counts every attempt. +type flakyTransport struct { + failures int + inner http.RoundTripper + attempts int +} + +func (f *flakyTransport) RoundTrip(req *http.Request) (*http.Response, error) { + f.attempts++ + if f.failures > 0 { + f.failures-- + return nil, &net.OpError{Op: "dial", Net: "tcp", Err: fmt.Errorf("simulated blip")} + } + return f.inner.RoundTrip(req) +} + +// installFlake wraps the client's transport with a flaky one and shrinks +// the retry waits so tests don't sleep real seconds. +func installFlake(t *testing.T, client *Client, failures int) *flakyTransport { + t.Helper() + client.retryWait = []time.Duration{time.Millisecond, time.Millisecond} + inner := client.httpClient.Transport + if inner == nil { + inner = http.DefaultTransport + } + flake := &flakyTransport{failures: failures, inner: inner} + client.httpClient.Transport = flake + return flake +} + +// Transport blips (live-observed: DNS read timeout on a flaky resolver) are +// retried, and the retried request must still carry the full body — a +// drained reader re-sent would deliver an empty PATCH. +func TestTransportBlipsRetriedWithBodyIntact(t *testing.T) { + f := &fakeServer{t: t, status: http.StatusCreated} + client := newFakeClient(t, f) + flake := installFlake(t, client, 2) + + if err := client.MakeFeedPolite(77); err != nil { + t.Fatalf("MakeFeedPolite after two blips: %v", err) + } + if flake.attempts != 3 { + t.Errorf("attempts = %d, want 3 (two blips + one success)", flake.attempts) + } + wantBody := `{"crawler":false,"ignore_http_cache":false}` + if f.gotRequestBody != wantBody { + t.Errorf("retried PUT body = %q, want %q (body must be re-armed per attempt)", f.gotRequestBody, wantBody) + } +} + +// The retry loop is not a hang: it gives up after len(retryWait) extra +// attempts and the final error still names the request. +func TestTransportFailuresGiveUp(t *testing.T) { + f := &fakeServer{t: t, status: http.StatusOK, body: `{"total":0,"entries":[]}`} + client := newFakeClient(t, f) + client.retryWait = []time.Duration{time.Millisecond} + inner := client.httpClient.Transport + if inner == nil { + inner = http.DefaultTransport + } + flake := &flakyTransport{failures: 99, inner: inner} + client.httpClient.Transport = flake + + _, err := client.Entries(Filters{}) + if err == nil { + t.Fatal("expected error after persistent blips, got nil") + } + if !strings.Contains(err.Error(), "/v1/entries") { + t.Errorf("error should name the request: %v", err) + } + if flake.attempts != 2 { + t.Errorf("attempts = %d, want 2 (one try + one retry)", flake.attempts) + } +} + func TestConfigFromEnv(t *testing.T) { t.Run("primary vars", func(t *testing.T) { t.Setenv("MINIFLUX_URL", "https://flux.example") -- cgit v1.2.3