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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
|
package logic
import (
"crypto/rsa"
"fmt"
"hash/fnv"
"html"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"rss_parrot/dal"
"rss_parrot/shared"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/spaolacci/murmur3"
)
// A harness that runs the real feed follower, on a real SQLite database (with
// every migration applied), against feeds served by httptest servers, on a
// simulated clock. The clock only moves when the harness moves it, so a test
// can let weeks of polling go by in milliseconds and still assert exactly
// when each request happened.
//
// The check loop goroutine is not started: the harness plays its part,
// jumping the clock to the moment the next feed is due and running one
// iteration of the loop (feedCheckLoopInner) there.
// simStart is when every simulation begins: a Monday morning.
var simStart = time.Date(2026, 1, 5, 10, 0, 0, 0, time.UTC)
// fakeClock is a shared.Clock that only moves when told to. Sleep moves it
// too, so the loop's idle waits cost nothing.
type fakeClock struct {
mu sync.Mutex
now time.Time
}
func (c *fakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *fakeClock) Sleep(d time.Duration) { c.advance(d) }
func (c *fakeClock) advance(d time.Duration) {
c.mu.Lock()
c.now = c.now.Add(d)
c.mu.Unlock()
}
// set moves the clock to t, never backwards.
func (c *fakeClock) set(t time.Time) {
c.mu.Lock()
if t.After(c.now) {
c.now = t
}
c.mu.Unlock()
}
// These 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) {}
type notBlocked struct{}
func (notBlocked) IsBlocked(string) (bool, error) { return false, nil }
// fakeKeyStore hands out placeholder keys: generating real RSA keys is slow
// and nothing here signs anything.
type fakeKeyStore struct{}
func (fakeKeyStore) GetPrivKey(string) (*rsa.PrivateKey, error) { return nil, nil }
func (fakeKeyStore) MakeKeyPair() (string, string, error) { return "pub", "priv", nil }
// titleTexts renders a toot as just the post's title, so a test can tell
// which post a toot is about.
type titleTexts struct{}
func (titleTexts) Get(id string) string { return id }
func (titleTexts) WithVals(_ string, vals map[string]string) string { return vals["title"] }
// broadcast is one call to IMessenger.EnqueueBroadcast.
type broadcast struct {
at time.Time // simulated time of the call
user string
tootedAt time.Time
content string // the post's title, see titleTexts
}
// recordingMessenger records broadcasts instead of queueing them.
type recordingMessenger struct {
clock *fakeClock
mu sync.Mutex
sent []broadcast
}
func (m *recordingMessenger) SendMessageAsync(string, string, string, []*MsgMention, []string, []string, string) {
}
func (m *recordingMessenger) EnqueueBroadcast(user, _ string, tootedAt time.Time, msg string) error {
m.mu.Lock()
m.sent = append(m.sent, broadcast{m.clock.Now(), user, tootedAt, msg})
m.mu.Unlock()
return nil
}
func (m *recordingMessenger) broadcasts() []broadcast {
m.mu.Lock()
defer m.mu.Unlock()
return append([]broadcast(nil), m.sent...)
}
func (m *recordingMessenger) titles() []string {
var res []string
for _, b := range m.broadcasts() {
res = append(res, b.content)
}
return res
}
// simPost is a post of a simulated feed. It shows up in the feed from
// visibleFrom on, which is its publication time unless set otherwise (to
// simulate a post dated into the future).
type simPost struct {
title string
published time.Time
visibleFrom time.Time
// guid and link default to the site URL followed by the title; noGuid
// leaves the guid out, noDate the date.
guid, link string
noGuid, noDate bool
}
func (p simPost) slug() string { return strings.ReplaceAll(p.title, " ", "-") }
func (p simPost) itemGuid() string {
if p.guid != "" {
return p.guid
}
return simSiteUrl + "/" + p.slug()
}
func (p simPost) itemLink() string {
if p.link != "" {
return p.link
}
return simSiteUrl + "/" + p.slug()
}
func (p simPost) shownFrom() time.Time {
if p.visibleFrom.IsZero() {
return p.published
}
return p.visibleFrom
}
// simRequest is a request a simulated feed received.
type simRequest struct {
at time.Time // simulated time
header http.Header
status int
refused bool // answered by fail, not by the feed
}
// simFeed is an RSS feed whose posts appear as the simulated clock reaches
// them. It answers conditional requests like a well-behaved server: the ETag
// and Last-Modified change exactly when the set of visible posts does.
type simFeed struct {
*httptest.Server
clock *fakeClock
mu sync.Mutex
posts []simPost
// fail, if set and returning a non-zero status, makes the server answer
// with that status (and Retry-After, if not empty) instead of the feed.
fail func(now time.Time) (status int, retryAfter string)
// handler, if set, replaces the feed entirely.
handler http.HandlerFunc
reqs []simRequest
}
const simSiteUrl = "https://blog.example.org"
const simHandle = "blog.example.org"
func newSimFeed(t *testing.T, clock *fakeClock, posts ...simPost) *simFeed {
f := &simFeed{clock: clock, posts: posts}
f.Server = httptest.NewServer(http.HandlerFunc(f.serve))
t.Cleanup(f.Close)
return f
}
func (f *simFeed) addPost(p simPost) {
f.mu.Lock()
f.posts = append(f.posts, p)
f.mu.Unlock()
}
// editPosts changes every post of the feed, as a feed generator might.
func (f *simFeed) editPosts(edit func(p *simPost)) {
f.mu.Lock()
for i := range f.posts {
edit(&f.posts[i])
}
f.mu.Unlock()
}
func (f *simFeed) setFail(fail func(now time.Time) (int, string)) {
f.mu.Lock()
f.fail = fail
f.mu.Unlock()
}
func (f *simFeed) setHandler(h http.HandlerFunc) {
f.mu.Lock()
f.handler = h
f.mu.Unlock()
}
func (f *simFeed) requests() []simRequest {
f.mu.Lock()
defer f.mu.Unlock()
return append([]simRequest(nil), f.reqs...)
}
func (f *simFeed) lastRequest(t *testing.T) simRequest {
t.Helper()
reqs := f.requests()
if len(reqs) == 0 {
t.Fatal("the feed was never requested")
}
return reqs[len(reqs)-1]
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func (f *simFeed) serve(w http.ResponseWriter, r *http.Request) {
now := f.clock.Now()
f.mu.Lock()
handler, fail := f.handler, f.fail
posts := append([]simPost(nil), f.posts...)
f.mu.Unlock()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
refused := false
switch {
case handler != nil:
handler(rec, r)
default:
status, retryAfter := 0, ""
if fail != nil {
status, retryAfter = fail(now)
}
if status != 0 {
refused = true
if retryAfter != "" {
rec.Header().Set("Retry-After", retryAfter)
}
rec.WriteHeader(status)
} else {
serveFeed(rec, r, now, posts)
}
}
f.mu.Lock()
f.reqs = append(f.reqs, simRequest{now, r.Header.Clone(), rec.status, refused})
f.mu.Unlock()
}
func serveFeed(w http.ResponseWriter, r *http.Request, now time.Time, posts []simPost) {
var visible []simPost
lastMod := simStart.Add(-365 * 24 * time.Hour)
for _, p := range posts {
if p.shownFrom().After(now) {
continue
}
visible = append(visible, p)
if p.shownFrom().After(lastMod) {
lastMod = p.shownFrom()
}
}
sort.Slice(visible, func(i, j int) bool { return visible[i].published.After(visible[j].published) })
h := fnv.New64a()
for _, p := range visible {
fmt.Fprintf(h, "%s\t%s\t%s\t%d\t%v\n", p.title, p.itemGuid(), p.itemLink(), p.published.UnixNano(), p.noDate)
}
etag := fmt.Sprintf(`"%x"`, h.Sum64())
lastModStr := lastMod.UTC().Format(http.TimeFormat)
if inm := r.Header.Get("If-None-Match"); inm != "" {
if inm == etag {
w.WriteHeader(http.StatusNotModified)
return
}
} else if ims := r.Header.Get("If-Modified-Since"); ims != "" {
if t, err := http.ParseTime(ims); err == nil && !lastMod.Truncate(time.Second).After(t) {
w.WriteHeader(http.StatusNotModified)
return
}
}
var b strings.Builder
b.WriteString(`<?xml version="1.0"?><rss version="2.0"><channel>`)
fmt.Fprintf(&b, `<title>Sim blog</title><link>%s</link><description>A simulated blog</description>`, simSiteUrl)
for _, p := range visible {
fmt.Fprintf(&b, `<item><title>%s</title><link>%s</link>`,
html.EscapeString(p.title), html.EscapeString(p.itemLink()))
if !p.noGuid {
fmt.Fprintf(&b, `<guid>%s</guid>`, html.EscapeString(p.itemGuid()))
}
if !p.noDate {
fmt.Fprintf(&b, `<pubDate>%s</pubDate>`, p.published.UTC().Format(time.RFC1123Z))
}
b.WriteString(`</item>`)
}
b.WriteString(`</channel></rss>`)
w.Header().Set("ETag", etag)
w.Header().Set("Last-Modified", lastModStr)
w.Header().Set("Content-Type", "application/rss+xml")
_, _ = io.WriteString(w, b.String())
}
// sim is the feed follower under test with everything around it.
type sim struct {
t *testing.T
clock *fakeClock
cfg *shared.Config
repo dal.IRepo
ff *feedFollower
msgr *recordingMessenger
}
const simFollowerUrl = "https://social.example/users/a"
// newSim sets up an empty database and a feed follower on a fake clock at
// simStart. configure, if not nil, may change the config before anything
// uses it.
func newSim(t *testing.T, configure func(*shared.Config)) *sim {
clock := &fakeClock{now: simStart}
cfg := &shared.Config{
Host: "kakapo.example.com",
DbFile: filepath.Join(t.TempDir(), "test.db"),
UpdateSchedule: shared.UpdateSchedule{Day: 1, Week: 4, Weeks4: 12, Older: 24},
Birb: &shared.UserInfo{User: "birb", Published: simStart},
}
if configure != nil {
configure(cfg)
}
logger := shared.NewLogger(io.Discard, "Error")
repo := dal.NewRepo(cfg, logger)
repo.InitUpdateDb()
msgr := &recordingMessenger{clock: clock}
return &sim{
t: t,
clock: clock,
cfg: cfg,
repo: repo,
msgr: msgr,
ff: &feedFollower{
cfg: cfg,
logger: logger,
userAgent: nopUserAgent{},
repo: repo,
blockedFeeds: notBlocked{},
messenger: msgr,
txt: titleTexts{},
keyStore: fakeKeyStore{},
metrics: nopMetrics{},
clock: clock,
},
}
}
// follow subscribes to a feed the way a follow request does (through
// GetAccountForFeed), then adds an approved follower, without which the check
// loop would delete the account again.
func (s *sim) follow(feed *simFeed) *dal.Account {
s.t.Helper()
acct, status, err := s.ff.GetAccountForFeed(feed.URL)
if err != nil || status != FsNew {
s.t.Fatalf("following %s: status %d, err %v", feed.URL, status, err)
}
s.addFollower(acct.Handle)
return acct
}
func (s *sim) addFollower(handle string) {
s.t.Helper()
if err := s.repo.AddFollower(handle, &dal.FollowerInfo{
UserUrl: simFollowerUrl, Handle: "a", Host: "social.example", ApproveStatus: 1,
UserInbox: simFollowerUrl + "/inbox",
}); err != nil {
s.t.Fatal(err)
}
}
// nextDue is when the next account is due for a check.
func (s *sim) nextDue() (time.Time, bool) {
s.t.Helper()
accts, _, err := s.repo.GetAccountsPage(0, 1000)
if err != nil {
s.t.Fatal(err)
}
var next time.Time
found := false
for _, a := range accts {
if a.Handle == s.cfg.Birb.User {
continue
}
if !found || a.NextCheckDue.Before(next) {
next, found = a.NextCheckDue, true
}
}
// The real loop wakes at least every minute when idle, and toots items
// whose time has come each time; the harness wakes right when they do.
itemDue, ok, err := s.repo.GetNextItemDue()
if err != nil {
s.t.Fatal(err)
}
if ok && (!found || itemDue.Before(next)) {
next, found = itemDue, true
}
return next, found
}
// dueSlack is how far past an account's next_check_due the harness runs its
// check: the due query is strict (next_check_due < now).
const dueSlack = time.Millisecond
// step moves the clock to just after the next due check and runs that check
// (one iteration of the check loop), including the purges it starts.
// It reports false, without running anything, if nothing is due by until.
func (s *sim) step(until time.Time) bool {
s.t.Helper()
next, ok := s.nextDue()
if !ok || next.Add(dueSlack).After(until) {
return false
}
s.clock.set(next.Add(dueSlack))
s.ff.feedCheckLoopInner()
s.ff.bg.Wait()
return true
}
// runUntil runs every check that falls due before until, then leaves the
// clock at until.
func (s *sim) runUntil(until time.Time) {
s.t.Helper()
for i := 0; s.step(until); i++ {
if i > 100000 {
s.t.Fatal("runaway simulation: more than 100000 checks")
}
}
s.clock.set(until)
}
// state reads an account's polling state back through the query the check
// loop uses. Every account but the birb (due in 2100) is due before 2099.
func (s *sim) state(handle string) *dal.Account {
s.t.Helper()
acct, _, err := s.repo.GetAccountToCheck(time.Date(2099, 1, 1, 0, 0, 0, 0, time.UTC))
if err != nil {
s.t.Fatal(err)
}
if acct == nil || acct.Handle != handle {
s.t.Fatalf("expected account %s, got %+v", handle, acct)
}
return acct
}
// assertNoDuplicateBroadcasts checks that no post was tooted twice.
func (s *sim) assertNoDuplicateBroadcasts() {
s.t.Helper()
seen := map[string]bool{}
for _, b := range s.msgr.broadcasts() {
if seen[b.content] {
s.t.Errorf("post %q was broadcast more than once", b.content)
}
seen[b.content] = true
}
}
// murmurHash is getItemHash of an item's "guid\tlink".
func murmurHash(s string) uint {
h := murmur3.New32()
_, _ = h.Write([]byte(s))
return uint(h.Sum32())
}
|