diff options
Diffstat (limited to 'cmds')
| -rw-r--r-- | cmds/polite.go | 85 | ||||
| -rw-r--r-- | cmds/polite_test.go | 161 |
2 files changed, 246 insertions, 0 deletions
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) + } +} |
