aboutsummaryrefslogtreecommitdiff
path: root/miniflux
diff options
context:
space:
mode:
authorSam Scholten2026-10-20 10:51:46 +1000
committerSam Scholten2026-10-20 10:51:46 +1000
commit04bb657bb3573d00d92c1748058a61c1612d48fd (patch)
tree15b2d33a7bbaa2be27aaab3fba4a3ee1eca9e618 /miniflux
parent8027bac07b61e631866f253632ce7aa4476982db (diff)
downloadfluxrec-main.tar.gz
fluxrec-main.zip
polite: fetch-light sweep (scraper off + HTTP cache honored) on every feedHEADmain
Diffstat (limited to 'miniflux')
-rw-r--r--miniflux/client.go100
-rw-r--r--miniflux/client_test.go174
2 files changed, 251 insertions, 23 deletions
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")