1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
package logic
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"rss_parrot/dal"
"rss_parrot/shared"
"sync"
"testing"
"time"
)
// These tests run one feed check against a real SQLite database (with every
// migration applied) and a real HTTP server, so the new columns and queries
// are exercised, not just the policy around them.
const emptyRss = `<?xml version="1.0"?>
<rss version="2.0"><channel><title>t</title><link>https://example.org</link></channel></rss>`
// These two are also in test/fakes.go. This file is in package logic, to
// reach the unexported check loop, so it cannot import package test, which
// imports logic.
type nopMetrics struct{}
func (nopMetrics) CurrentConnections(int) {}
func (nopMetrics) StartWebRequestIn(string) IRequestObserver { return nopObserver{} }
func (nopMetrics) StartApubRequestIn(string) IRequestObserver { return nopObserver{} }
func (nopMetrics) StartApubRequestOut(string) IRequestObserver { return nopObserver{} }
func (nopMetrics) FeedRequested(string) {}
func (nopMetrics) FeedUpdated() {}
func (nopMetrics) NewPostSaved() {}
func (nopMetrics) PostsDeleted(int) {}
func (nopMetrics) TotalPosts(int) {}
func (nopMetrics) FeedTootSent() {}
func (nopMetrics) ServiceStarted() {}
func (nopMetrics) TotalFollowers(int) {}
func (nopMetrics) TootQueueLength(int) {}
func (nopMetrics) CheckableFeedCount(int) {}
func (nopMetrics) DbFileSize(int64) {}
type nopObserver struct{}
func (nopObserver) Finish() {}
type nopUserAgent struct{}
func (nopUserAgent) AddUserAgent(*http.Request) {}
// feedServer is a test feed: each request is recorded and answered by respond.
type feedServer struct {
*httptest.Server
mu sync.Mutex
requests []http.Header
respond http.HandlerFunc
}
func newFeedServer(t *testing.T) *feedServer {
fs := &feedServer{}
fs.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fs.mu.Lock()
fs.requests = append(fs.requests, r.Header.Clone())
respond := fs.respond
fs.mu.Unlock()
respond(w, r)
}))
t.Cleanup(fs.Close)
return fs
}
func (fs *feedServer) lastRequest(t *testing.T) http.Header {
fs.mu.Lock()
defer fs.mu.Unlock()
if len(fs.requests) == 0 {
t.Fatal("the feed was never requested")
}
return fs.requests[len(fs.requests)-1]
}
type fetchHarness struct {
t *testing.T
repo dal.IRepo
ff *feedFollower
srv *feedServer
id int
}
const testHandle = "example.org"
// newFetchHarness sets up a database holding one followed feed account that
// points at a test server, and a feedFollower whose check loop is not running:
// tests drive it one check at a time with check().
func newFetchHarness(t *testing.T, maxRetryDelayHours int) *fetchHarness {
cfg := &shared.Config{
Host: "kakapo.example.com",
DbFile: filepath.Join(t.TempDir(), "test.db"),
MaxRetryDelayHours: maxRetryDelayHours,
UpdateSchedule: shared.UpdateSchedule{Day: 1, Week: 1, Weeks4: 1, Older: 1},
Birb: &shared.UserInfo{User: "birb", Published: time.Now()},
}
logger := shared.NewLogger(io.Discard, "Error")
repo := dal.NewRepo(cfg, logger)
repo.InitUpdateDb()
srv := newFeedServer(t)
if _, err := repo.AddAccountIfNotExist(&dal.Account{
CreatedAt: time.Now(),
Handle: testHandle,
UserUrl: "https://kakapo.example.com/u/" + testHandle,
FeedUrl: srv.URL,
}, ""); err != nil {
t.Fatal(err)
}
// A follower keeps the account alive: the loop deletes unfollowed ones.
if err := repo.AddFollower(testHandle, &dal.FollowerInfo{
UserUrl: "https://social.example/users/a", Handle: "a", Host: "social.example",
}); err != nil {
t.Fatal(err)
}
acct, err := repo.GetAccount(testHandle)
if err != nil {
t.Fatal(err)
}
return &fetchHarness{
t: t,
repo: repo,
srv: srv,
id: acct.Id,
ff: &feedFollower{
cfg: cfg,
logger: logger,
userAgent: nopUserAgent{},
repo: repo,
metrics: nopMetrics{},
},
}
}
// state reads the account's polling state back from the database, through the
// same query the check loop uses. Only valid after a check: before the first
// one the account is not due until 2100, like the birb, which a horizon of 60
// days keeps out of the result.
func (h *fetchHarness) state() *dal.Account {
acct, _, err := h.repo.GetAccountToCheck(time.Now().Add(60 * 24 * time.Hour))
if err != nil {
h.t.Fatal(err)
}
if acct == nil || acct.Id != h.id {
h.t.Fatalf("expected account %d, got %+v", h.id, acct)
}
return acct
}
// check makes the feed due and runs exactly one check of it.
func (h *fetchHarness) check(respond http.HandlerFunc) *dal.Account {
h.srv.mu.Lock()
h.srv.respond = respond
h.srv.mu.Unlock()
lastUpdated, err := h.repo.GetFeedLastUpdated(h.id)
if err != nil {
h.t.Fatal(err)
}
if err := h.repo.UpdateAccountFeedTimes(h.id, lastUpdated, time.Now().Add(-time.Minute)); err != nil {
h.t.Fatal(err)
}
h.ff.feedCheckLoopInner()
return h.state()
}
func assertDelay(t *testing.T, acct *dal.Account, lo, hi time.Duration) {
t.Helper()
d := time.Until(acct.NextCheckDue)
if d < lo || d > hi {
t.Errorf("next check in %s, want between %s and %s", d.Round(time.Minute), lo, hi)
}
}
func serve200(etag, lastModified string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("ETag", etag)
w.Header().Set("Last-Modified", lastModified)
fmt.Fprint(w, emptyRss)
}
}
func serveStatus(code int, retryAfter string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if retryAfter != "" {
w.Header().Set("Retry-After", retryAfter)
}
w.WriteHeader(code)
}
}
const lastMod = "Wed, 21 Oct 2026 07:28:00 GMT"
func TestFetchStoresValidatorsAndSendsThemBack(t *testing.T) {
h := newFetchHarness(t, 0)
acct := h.check(serve200(`"v1"`, lastMod))
if req := h.srv.lastRequest(t); req.Get("If-None-Match") != "" || req.Get("If-Modified-Since") != "" {
t.Errorf("first request should be unconditional, got %v", req)
}
if acct.FeedEtag != `"v1"` || acct.FeedLastModified != lastMod {
t.Errorf("validators not stored: etag %q, last-modified %q", acct.FeedEtag, acct.FeedLastModified)
}
acct = h.check(serveStatus(http.StatusNotModified, ""))
req := h.srv.lastRequest(t)
if req.Get("If-None-Match") != `"v1"` || req.Get("If-Modified-Since") != lastMod {
t.Errorf("validators not sent back: %v", req)
}
if acct.FeedEtag != `"v1"` || acct.FetchFailures != 0 {
t.Errorf("after 304: etag %q, failures %d", acct.FeedEtag, acct.FetchFailures)
}
// A 304 is a normal check: the 1h interval, ±20% jitter.
assertDelay(t, acct, 45*time.Minute, 75*time.Minute)
}
func TestFetchBacksOffAndRecovers(t *testing.T) {
h := newFetchHarness(t, 0)
h.check(serve200(`"v1"`, ""))
acct := h.check(serveStatus(http.StatusInternalServerError, ""))
if acct.FetchFailures != 1 {
t.Errorf("failures = %d, want 1", acct.FetchFailures)
}
if acct.FeedEtag != `"v1"` {
t.Errorf("a failed check must keep the validators, etag is %q", acct.FeedEtag)
}
assertDelay(t, acct, 90*time.Minute, 150*time.Minute) // 2 × 1h ±20%
acct = h.check(serveStatus(http.StatusInternalServerError, ""))
if acct.FetchFailures != 2 {
t.Errorf("failures = %d, want 2", acct.FetchFailures)
}
assertDelay(t, acct, 3*time.Hour, 5*time.Hour) // 4 × 1h ±20%
acct = h.check(serve200(`"v2"`, ""))
if acct.FetchFailures != 0 || acct.FeedEtag != `"v2"` {
t.Errorf("after recovery: failures %d, etag %q", acct.FetchFailures, acct.FeedEtag)
}
}
func TestFetchHonoursRetryAfter(t *testing.T) {
h := newFetchHarness(t, 0)
acct := h.check(serveStatus(http.StatusTooManyRequests, "72000")) // 20h
assertDelay(t, acct, 20*time.Hour-time.Minute, 20*time.Hour+time.Minute)
}
func TestFetchCapsAnAbsurdRetryAfter(t *testing.T) {
h := newFetchHarness(t, 0)
acct := h.check(serveStatus(http.StatusServiceUnavailable, "3024000")) // 5 weeks
assertDelay(t, acct, 24*time.Hour-time.Minute, 24*time.Hour+time.Minute)
}
func TestFetchRespectsConfiguredRetryCap(t *testing.T) {
h := newFetchHarness(t, 6)
acct := h.check(serveStatus(http.StatusServiceUnavailable, "3024000"))
assertDelay(t, acct, 6*time.Hour-time.Minute, 6*time.Hour+time.Minute)
}
|