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
|
package dal
import (
"context"
"io"
"path/filepath"
"rss_parrot/shared"
"slices"
"strings"
"testing"
"time"
)
const testHandle = "blog.example.org"
// newPublishRepo returns a fresh, migrated database with one feed account,
// and that account's id.
func newPublishRepo(t *testing.T) (*Repo, int) {
t.Helper()
cfg := &shared.Config{
DbFile: filepath.Join(t.TempDir(), "test.db"),
Birb: &shared.UserInfo{User: "birb"},
}
repo := NewRepo(cfg, shared.NewLogger(io.Discard, "Error")).(*Repo)
repo.InitUpdateDb()
if _, err := repo.AddAccountIfNotExist(&Account{
CreatedAt: time.Now(), Handle: testHandle, UserUrl: "https://kakapo.example.org/u/" + testHandle,
}, ""); err != nil {
t.Fatal(err)
}
acct, err := repo.GetAccount(testHandle)
if err != nil {
t.Fatal(err)
}
return repo, acct.Id
}
// addDueItem adds one item to the ledger, due for tooting.
func addDueItem(t *testing.T, repo *Repo, accountId int, guid string) *FeedItem {
t.Helper()
now := time.Now().UTC()
itm := &FeedItem{
AccountId: accountId, Guid: guid, LinkKey: "blog.example.org/" + guid,
PostTime: now, FirstSeen: now, Status: ItemDue,
Link: "https://blog.example.org/" + guid, Title: "Post " + guid, Description: "About " + guid,
}
if err := repo.AddFeedItems(accountId, []*FeedItem{itm}, true); err != nil {
t.Fatal(err)
}
return itm
}
func countRows(t *testing.T, repo *Repo, table string) int {
t.Helper()
var n int
if err := repo.db.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
func itemStatus(t *testing.T, repo *Repo, id int64) int {
t.Helper()
var status int
if err := repo.db.QueryRow(`SELECT status FROM feed_items WHERE id=?`, id).Scan(&status); err != nil {
t.Fatal(err)
}
return status
}
func testToot(id string) *Toot {
return &Toot{
TootedAt: time.Now().UTC(), Content: "toot " + id,
StatusId: "https://kakapo.example.org/u/" + testHandle + "/status/" + id,
}
}
func TestPublishItemQueuesOncePerApprovedInbox(t *testing.T) {
repo, acctId := newPublishRepo(t)
for _, f := range []*FollowerInfo{
// Two on the same instance share its inbox.
{UserUrl: "https://social.example/users/a", ApproveStatus: 1,
UserInbox: "https://social.example/users/a/inbox", SharedInbox: "https://social.example/inbox"},
{UserUrl: "https://social.example/users/b", ApproveStatus: 1,
UserInbox: "https://social.example/users/b/inbox", SharedInbox: "https://social.example/inbox"},
// One without a shared inbox gets its own.
{UserUrl: "https://lone.example/users/c", ApproveStatus: 1,
UserInbox: "https://lone.example/users/c/inbox"},
// Not approved: gets nothing.
{UserUrl: "https://other.example/users/d", ApproveStatus: 0,
UserInbox: "https://other.example/users/d/inbox", SharedInbox: "https://other.example/inbox"},
} {
if err := repo.AddFollower(testHandle, f); err != nil {
t.Fatal(err)
}
}
itm := addDueItem(t, repo, acctId, "1")
toot := testToot("1")
published, err := repo.PublishItem(itm, toot, true)
if err != nil || !published {
t.Fatalf("PublishItem = %v, %v; want true, nil", published, err)
}
queued, err := repo.GetTootQueueItems(0, 100)
if err != nil {
t.Fatal(err)
}
var inboxes []string
for _, q := range queued {
inboxes = append(inboxes, q.ToInbox)
if q.SendingUser != testHandle || q.StatusId != toot.StatusId || q.Content != toot.Content ||
!q.TootedAt.Equal(toot.TootedAt) {
t.Errorf("queued %+v, want the toot %+v sent by %s", q, toot, testHandle)
}
}
slices.Sort(inboxes)
if want := []string{"https://lone.example/users/c/inbox", "https://social.example/inbox"}; !slices.Equal(inboxes, want) {
t.Errorf("queued for %v, want %v", inboxes, want)
}
// The content is stored once, in toots; a delivery only refers to it.
var copies int
if err := repo.db.QueryRow(`SELECT COUNT(*) FROM toots WHERE content=?`, toot.Content).Scan(&copies); err != nil ||
copies != 1 {
t.Errorf("content stored %d times (%v), want once", copies, err)
}
if n := countRows(t, repo, "toot_deliveries"); n != 2 {
t.Errorf("%d deliveries, want 2", n)
}
if got, err := repo.GetToot(toot.StatusId); err != nil || got == nil || got.Content != toot.Content {
t.Errorf("GetToot = %+v, %v; want the toot", got, err)
}
posts, err := repo.GetPostsPage(acctId, 0, 10)
if err != nil {
t.Fatal(err)
}
if len(posts) != 1 || posts[0].Link != itm.Link || posts[0].Title != itm.Title {
t.Errorf("posts = %+v, want the item's", posts)
}
if s := itemStatus(t, repo, itm.Id); s != ItemPublished {
t.Errorf("item status %d, want %d (published)", s, ItemPublished)
}
}
func TestPublishItemWithoutBroadcastQueuesNothing(t *testing.T) {
repo, acctId := newPublishRepo(t)
if err := repo.AddFollower(testHandle, &FollowerInfo{
UserUrl: "https://social.example/users/a", ApproveStatus: 1, UserInbox: "https://social.example/users/a/inbox",
}); err != nil {
t.Fatal(err)
}
itm := addDueItem(t, repo, acctId, "1")
if published, err := repo.PublishItem(itm, testToot("1"), false); err != nil || !published {
t.Fatalf("PublishItem = %v, %v; want true, nil", published, err)
}
if n := countRows(t, repo, "toot_deliveries"); n != 0 {
t.Errorf("%d toots queued, want none", n)
}
if n := countRows(t, repo, "toots"); n != 1 {
t.Errorf("%d toots, want 1", n)
}
}
// Two publishers racing for the same item (the check loop and a new follow,
// or a retry after a crash) publish it once.
func TestPublishItemTwiceWritesOnce(t *testing.T) {
repo, acctId := newPublishRepo(t)
itm := addDueItem(t, repo, acctId, "1")
if published, err := repo.PublishItem(itm, testToot("1"), true); err != nil || !published {
t.Fatalf("first PublishItem = %v, %v; want true, nil", published, err)
}
if published, err := repo.PublishItem(itm, testToot("2"), true); err != nil || published {
t.Fatalf("second PublishItem = %v, %v; want false, nil", published, err)
}
if n := countRows(t, repo, "feed_posts"); n != 1 {
t.Errorf("%d posts, want 1", n)
}
if n := countRows(t, repo, "toots"); n != 1 {
t.Errorf("%d toots, want 1", n)
}
}
// A failure halfway through leaves nothing behind, and the item due.
func TestPublishItemFailureWritesNothing(t *testing.T) {
repo, acctId := newPublishRepo(t)
if err := repo.AddFollower(testHandle, &FollowerInfo{
UserUrl: "https://social.example/users/a", ApproveStatus: 1, UserInbox: "https://social.example/users/a/inbox",
}); err != nil {
t.Fatal(err)
}
first := addDueItem(t, repo, acctId, "1")
if published, err := repo.PublishItem(first, testToot("1"), true); err != nil || !published {
t.Fatalf("PublishItem = %v, %v; want true, nil", published, err)
}
posts, toots, queued := countRows(t, repo, "feed_posts"), countRows(t, repo, "toots"), countRows(t, repo, "toot_deliveries")
// The same status id again violates toots' unique index, after the item
// was marked and its post stored.
second := addDueItem(t, repo, acctId, "2")
if published, err := repo.PublishItem(second, testToot("1"), true); err == nil || published {
t.Fatalf("PublishItem = %v, %v; want false and an error", published, err)
}
if s := itemStatus(t, repo, second.Id); s != ItemDue {
t.Errorf("item status %d, want %d (still due)", s, ItemDue)
}
if n := countRows(t, repo, "feed_posts"); n != posts {
t.Errorf("%d posts, want %d", n, posts)
}
if n := countRows(t, repo, "toots"); n != toots {
t.Errorf("%d toots, want %d", n, toots)
}
if n := countRows(t, repo, "toot_deliveries"); n != queued {
t.Errorf("%d queued, want %d", n, queued)
}
}
// publishToFollower publishes one item per guid, each tooted at its time and
// broadcast to one follower, so that each queues one delivery.
func publishToFollower(t *testing.T, repo *Repo, acctId int, tootedAt map[string]time.Time) {
t.Helper()
if err := repo.AddFollower(testHandle, &FollowerInfo{
UserUrl: "https://social.example/users/a", ApproveStatus: 1, UserInbox: "https://social.example/users/a/inbox",
}); err != nil {
t.Fatal(err)
}
for guid, at := range tootedAt {
toot := testToot(guid)
toot.TootedAt = at
if published, err := repo.PublishItem(addDueItem(t, repo, acctId, guid), toot, true); err != nil || !published {
t.Fatalf("PublishItem = %v, %v; want true, nil", published, err)
}
}
}
// Purging a toot drops what was still to be delivered of it, and nothing else.
func TestPurgeDropsPendingDeliveries(t *testing.T) {
repo, acctId := newPublishRepo(t)
now := time.Now().UTC()
publishToFollower(t, repo, acctId, map[string]time.Time{"old": now.Add(-48 * time.Hour), "new": now})
if err := repo.PurgePostsAndToots(acctId, now.Add(-24*time.Hour)); err != nil {
t.Fatal(err)
}
queued, err := repo.GetTootQueueItems(0, 100)
if err != nil {
t.Fatal(err)
}
if len(queued) != 1 || queued[0].StatusId != testToot("new").StatusId {
t.Errorf("queued %+v; want only the new toot", queued)
}
}
// Deleting an account drops what was still to be delivered of its toots.
func TestDeleteAccountDropsPendingDeliveries(t *testing.T) {
repo, acctId := newPublishRepo(t)
publishToFollower(t, repo, acctId, map[string]time.Time{"1": time.Now().UTC()})
if err := repo.BruteDeleteAccount(acctId); err != nil {
t.Fatal(err)
}
if n := countRows(t, repo, "toot_deliveries"); n != 0 {
t.Errorf("%d deliveries left, want none", n)
}
}
// A database at version 10 keeps its queue through migration 11, which
// replaces the copies of the toot by references to it.
func TestMigrationKeepsTheQueue(t *testing.T) {
cfg := &shared.Config{
DbFile: filepath.Join(t.TempDir(), "test.db"),
Birb: &shared.UserInfo{User: "birb"},
}
repo := NewRepo(cfg, shared.NewLogger(io.Discard, "Error")).(*Repo)
repo.migrateTo(10)
if _, err := repo.AddAccountIfNotExist(&Account{
CreatedAt: time.Now(), Handle: testHandle, UserUrl: "https://kakapo.example.org/u/" + testHandle,
}, ""); err != nil {
t.Fatal(err)
}
acct, err := repo.GetAccount(testHandle)
if err != nil {
t.Fatal(err)
}
tootedAt := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)
statusId := "https://kakapo.example.org/u/blog.example.org/status/1"
if _, err := repo.db.Exec(`INSERT INTO toots (account_id, tooted_at, status_id, content)
VALUES (?, ?, ?, 'toot one')`, acct.Id, tootedAt, statusId); err != nil {
t.Fatal(err)
}
inboxes := []string{"https://b.example/inbox", "https://a.example/inbox"}
for _, inbox := range inboxes {
if _, err := repo.db.Exec(`INSERT INTO toot_queue (sending_user, to_inbox, tooted_at, status_id, content)
VALUES (?, ?, ?, ?, 'toot one')`, testHandle, inbox, tootedAt, statusId); err != nil {
t.Fatal(err)
}
}
repo.InitUpdateDb()
queued, err := repo.GetTootQueueItems(0, 100)
if err != nil {
t.Fatal(err)
}
if len(queued) != 2 {
t.Fatalf("queued %+v; want 2", queued)
}
for i, q := range queued {
// In the order they were queued.
if q.ToInbox != inboxes[i] || q.SendingUser != testHandle || q.StatusId != statusId ||
q.Content != "toot one" || !q.TootedAt.Equal(tootedAt) {
t.Errorf("queued[%d] = %+v, want toot one to %s", i, q, inboxes[i])
}
}
var gone int
if err := repo.db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE name='toot_queue'`).Scan(&gone); err != nil ||
gone != 0 {
t.Errorf("toot_queue still exists (%d, %v)", gone, err)
}
}
// Foreign keys are enforced: a toot cannot belong to an account that does not
// exist, on any connection of the pool.
func TestForeignKeysEnforced(t *testing.T) {
repo, acctId := newPublishRepo(t)
// Held open at once, so that each is a connection of its own.
for range 3 {
conn, err := repo.db.Conn(context.Background())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
var on int
if err := conn.QueryRowContext(context.Background(), `PRAGMA foreign_keys`).Scan(&on); err != nil || on != 1 {
t.Fatalf("foreign_keys = %d, %v; want 1", on, err)
}
}
if _, err := repo.db.Exec(`INSERT INTO toots (account_id, tooted_at, status_id, content)
VALUES (?, ?, 'https://kakapo.example.org/u/x/status/1', 'orphan')`, acctId+1, time.Now()); err == nil {
t.Error("inserted a toot for an account that does not exist")
}
}
// A database at version 9 keeps its rows through migration 10, which drops
// the hash columns.
func TestMigrationDropsTheItemHash(t *testing.T) {
cfg := &shared.Config{
DbFile: filepath.Join(t.TempDir(), "test.db"),
Birb: &shared.UserInfo{User: "birb"},
}
repo := NewRepo(cfg, shared.NewLogger(io.Discard, "Error")).(*Repo)
repo.migrateTo(9)
if _, err := repo.AddAccountIfNotExist(&Account{
CreatedAt: time.Now(), Handle: testHandle, UserUrl: "https://kakapo.example.org/u/" + testHandle,
}, ""); err != nil {
t.Fatal(err)
}
acct, err := repo.GetAccount(testHandle)
if err != nil {
t.Fatal(err)
}
postTime := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)
for _, q := range []string{
`INSERT INTO feed_posts (account_id, post_guid_hash, post_time, link, title, description)
VALUES (?1, 42, ?2, 'https://blog.example.org/1', 'One', 'About one')`,
`INSERT INTO toots (account_id, post_guid_hash, tooted_at, status_id, content)
VALUES (?1, 42, ?2, 'https://kakapo.example.org/u/blog.example.org/status/1', 'toot one')`,
`INSERT INTO feed_items (account_id, guid, link_key, post_guid_hash, post_time, first_seen, status)
VALUES (?1, 'g1', 'blog.example.org/1', 42, ?2, ?2, 1)`,
} {
if _, err := repo.db.Exec(q, acct.Id, postTime); err != nil {
t.Fatal(err)
}
}
repo.InitUpdateDb()
var ver int
if err := repo.db.QueryRow(`SELECT val FROM sys_params WHERE name='schema_ver'`).Scan(&ver); err != nil || ver != schemaVer {
t.Fatalf("schema_ver = %d, %v; want %d", ver, err, schemaVer)
}
for _, table := range []string{"feed_posts", "toots", "feed_items"} {
var n int
if err := repo.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info(?) WHERE name='post_guid_hash'`,
table).Scan(&n); err != nil || n != 0 {
t.Errorf("%s still has post_guid_hash (%d, %v)", table, n, err)
}
if c := countRows(t, repo, table); c != 1 {
t.Errorf("%s has %d rows, want 1", table, c)
}
}
posts, err := repo.GetPostsPage(acct.Id, 0, 10)
if err != nil || len(posts) != 1 || posts[0].Title != "One" || !posts[0].PostTime.Equal(postTime) {
t.Errorf("GetPostsPage = %+v, %v; want the post", posts, err)
}
if toot, err := repo.GetToot("https://kakapo.example.org/u/blog.example.org/status/1"); err != nil ||
toot == nil || toot.Content != "toot one" {
t.Errorf("GetToot = %+v, %v; want the toot", toot, err)
}
if links, err := repo.GetFeedPostLinks(acct.Id); err != nil || !slices.Equal(links, []string{"https://blog.example.org/1"}) {
t.Errorf("GetFeedPostLinks = %v, %v", links, err)
}
if byGuid, byLink, err := repo.FindSeenItem(acct.Id, "g1", "blog.example.org/1"); err != nil || !byGuid || !byLink {
t.Errorf("FindSeenItem = %v, %v, %v; want the item", byGuid, byLink, err)
}
// The posts' new index serves the web page.
var plan string
if err := repo.db.QueryRow(`EXPLAIN QUERY PLAN SELECT post_time FROM feed_posts
WHERE account_id=? ORDER BY post_time DESC`, acct.Id).Scan(new(int), new(int), new(int), &plan); err != nil {
t.Fatal(err)
}
if !strings.Contains(plan, "idx_121") {
t.Errorf("query plan %q, want it to use idx_121", plan)
}
}
|