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
|
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
// fakeForge is a stand-in for the Forgejo API.
//
// It exists because the behaviours worth testing are the awkward ones — a
// short final page, an endpoint that ignores ?since, a review that errors
// because the number is an issue — and none of them can be provoked against
// Codeberg on demand.
//
// It also reproduces Forgejo's pagination faithfully, including the trap:
// a request WITHOUT an explicit ?page returns the entire collection, ignoring
// ?limit. If getList ever stops sending ?page, the pagination tests here go
// green while the real ingest silently truncates, so the fixture models the
// bug rather than the documentation.
type fakeForge struct {
t *testing.T
repo apiRepo
labels []apiLabel
issues []apiIssue
pulls []apiPull
comments []apiComment
// Keyed by pull request number. A number absent from this map but present
// in issues is treated as an issue, and /reviews answers with the error
// object the real API returns.
reviews map[int64][]apiReview
inline map[int64][]apiReviewComment // keyed by review id
requests map[string]int // path -> count, for assertions
// Set to make /pulls ignore ?since, which is what Codeberg does.
pullsIgnoreSince bool
// When non-zero, the next /pulls/{n}/reviews request for this number is
// answered with 429 and the header Codeberg sends, then the field is
// cleared so a retry succeeds. Models hitting the git_op bucket mid-run.
rateLimitReviewsOnce int64
srv *httptest.Server
}
func newFakeForge(t *testing.T) *fakeForge {
t.Helper()
f := &fakeForge{
t: t,
repo: apiRepo{ID: 42, FullName: "acme/widget", HasIssues: true, HasPullRequests: true},
reviews: map[int64][]apiReview{},
inline: map[int64][]apiReviewComment{},
requests: map[string]int{},
pullsIgnoreSince: true,
}
f.srv = httptest.NewServer(http.HandlerFunc(f.handle))
t.Cleanup(f.srv.Close)
return f
}
// client returns a client pointed at the fake, bypassing newClient's
// https://host/api/v1 construction.
func (f *fakeForge) client() *client {
return &client{http: f.srv.Client(), baseURL: f.srv.URL + "/api/v1"}
}
func (f *fakeForge) ingester(t *testing.T, db *sql.DB) *ingester {
t.Helper()
return &ingester{db: db, c: f.client(), host: "fake.test", repoPath: "acme/widget"}
}
func (f *fakeForge) handle(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/v1/repos/acme/widget")
f.requests[path]++
q := r.URL.Query()
switch {
case path == "":
f.writeJSON(w, f.repo)
case path == "/labels":
f.page(w, q, f.labels)
case path == "/issues":
items := f.issues
if since := q.Get("since"); since != "" {
items = filterIssues(items, since)
}
// The real endpoint sorts newest-first on sort=recentupdate.
f.page(w, q, sortIssuesDesc(items))
case path == "/pulls":
if !f.repo.HasPullRequests {
// What Forgejo answers for a repo with PRs switched off: 404,
// not an empty list.
w.WriteHeader(http.StatusNotFound)
f.writeJSON(w, map[string]any{"message": "The target couldn't be found."})
return
}
items := f.pulls
// Codeberg ignores ?since here. Reproducing that is the point: the
// ingester must not depend on it.
if since := q.Get("since"); since != "" && !f.pullsIgnoreSince {
items = filterPulls(items, since)
}
f.page(w, q, sortPullsDesc(items))
case path == "/issues/comments":
items := f.comments
if since := q.Get("since"); since != "" {
items = filterComments(items, since)
}
f.page(w, q, items)
case strings.HasSuffix(path, "/reviews"):
n := numberIn(path, "/pulls/", "/reviews")
if f.rateLimitReviewsOnce == n {
f.rateLimitReviewsOnce = 0
// Both policies are sent, as Codeberg does; only git_op is
// exhausted.
w.Header().Add("RateLimit-Policy", `"git_op";q=250;w=600`)
w.Header().Add("RateLimit", `"git_op";r=0;t=600`)
w.Header().Add("RateLimit", `"baseline";r=1673;t=600`)
w.WriteHeader(http.StatusTooManyRequests)
f.writeJSON(w, map[string]any{"message": "rate limit exceeded"})
return
}
// A pull request with no reviews answers with an empty list; only a
// number that is an *issue* is an error. Conflating the two would
// let a bug through where the ingester avoids PRs it should visit.
if !f.isPull(n) {
w.WriteHeader(http.StatusNotFound)
f.writeJSON(w, map[string]any{
"message": "GetPullRequestByIndex",
"errors": []string{"pull request does not exist"},
})
return
}
f.page(w, q, f.reviews[n])
case strings.HasSuffix(path, "/comments"):
// /pulls/{n}/reviews/{id}/comments
id := numberIn(path, "/reviews/", "/comments")
f.page(w, q, f.inline[id])
default:
w.WriteHeader(http.StatusNotFound)
f.writeJSON(w, map[string]any{"message": "not found: " + path})
}
}
// page reproduces Forgejo's pagination, trap included: without an explicit
// ?page the whole collection comes back regardless of ?limit.
func (f *fakeForge) page(w http.ResponseWriter, q url.Values, items any) {
list := toSlice(items)
w.Header().Set("X-Total-Count", strconv.Itoa(len(list)))
pageStr := q.Get("page")
if pageStr == "" {
f.writeJSON(w, list)
return
}
page, _ := strconv.Atoi(pageStr)
if page < 1 {
page = 1
}
limit, _ := strconv.Atoi(q.Get("limit"))
if limit < 1 {
limit = 30 // Forgejo's default
}
if limit > pageSize {
limit = pageSize // the server clamps; asking for 200 yields 50
}
start := (page - 1) * limit
if start >= len(list) {
f.writeJSON(w, []any{})
return
}
f.writeJSON(w, list[start:min(start+limit, len(list))])
}
// isPull reports whether a number is a pull request, which is what decides
// between an empty review list and an error.
func (f *fakeForge) isPull(n int64) bool {
for _, i := range f.issues {
if i.Number == n {
return i.PullRequest != nil
}
}
return false
}
func (f *fakeForge) writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
f.t.Fatalf("encode: %v", err)
}
}
func toSlice(v any) []any {
switch xs := v.(type) {
case []apiLabel:
return anySlice(xs)
case []apiIssue:
return anySlice(xs)
case []apiPull:
return anySlice(xs)
case []apiComment:
return anySlice(xs)
case []apiReview:
return anySlice(xs)
case []apiReviewComment:
return anySlice(xs)
case []any:
return xs
}
panic(fmt.Sprintf("toSlice: unhandled %T", v))
}
func anySlice[T any](xs []T) []any {
out := make([]any, len(xs))
for i, x := range xs {
out[i] = x
}
return out
}
func numberIn(path, after, before string) int64 {
_, rest, ok := strings.Cut(path, after)
if !ok {
return 0
}
num, _, ok := strings.Cut(rest, before)
if !ok {
return 0
}
n, _ := strconv.ParseInt(num, 10, 64)
return n
}
func filterIssues(xs []apiIssue, since string) []apiIssue {
var out []apiIssue
for _, x := range xs {
if !before(x.UpdatedAt, since) {
out = append(out, x)
}
}
return out
}
func filterPulls(xs []apiPull, since string) []apiPull {
var out []apiPull
for _, x := range xs {
if !before(x.UpdatedAt, since) {
out = append(out, x)
}
}
return out
}
func filterComments(xs []apiComment, since string) []apiComment {
var out []apiComment
for _, x := range xs {
if !before(x.UpdatedAt, since) {
out = append(out, x)
}
}
return out
}
func before(a, b string) bool { return later(b, a) }
func sortIssuesDesc(xs []apiIssue) []apiIssue {
out := append([]apiIssue(nil), xs...)
for i := range out {
for j := i + 1; j < len(out); j++ {
if later(out[j].UpdatedAt, out[i].UpdatedAt) {
out[i], out[j] = out[j], out[i]
}
}
}
return out
}
func sortPullsDesc(xs []apiPull) []apiPull {
out := append([]apiPull(nil), xs...)
for i := range out {
for j := i + 1; j < len(out); j++ {
if later(out[j].UpdatedAt, out[i].UpdatedAt) {
out[i], out[j] = out[j], out[i]
}
}
}
return out
}
// testDB opens a scratch database with the real schema applied.
func testDB(t *testing.T) *sql.DB {
t.Helper()
db, err := openDB(filepath.Join(t.TempDir(), "test.db"), writeBusyTimeout)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
return db
}
// ts builds a timestamp with the offset Codeberg actually returns, so the
// daylight-saving hazard is present in the fixtures rather than assumed away.
func ts(month, day, hour int, offset string) string {
return fmt.Sprintf("2026-%02d-%02dT%02d:00:00%s", month, day, hour, offset)
}
func mustCount(t *testing.T, db *sql.DB, query string, args ...any) int64 {
t.Helper()
var n int64
if err := db.QueryRow(query, args...).Scan(&n); err != nil {
t.Fatalf("%s: %v", query, err)
}
return n
}
func mustParse(t *testing.T, s string) time.Time {
t.Helper()
v, err := time.Parse(time.RFC3339, s)
if err != nil {
t.Fatal(err)
}
return v
}
|