oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package roster
2
3import (
4 "context"
5 "database/sql"
6 "net/http"
7 "os"
8 "path/filepath"
9 "strings"
10 "sync"
11 "testing"
12 "time"
13
14 _ "modernc.org/sqlite"
15)
16
17type sqliteEvidence struct {
18 db *sql.DB
19 mu sync.Mutex
20 entering chan struct{}
21}
22
23func (s *sqliteEvidence) Load(ctx context.Context) ([]byte, error) {
24 var b []byte
25 e := s.db.QueryRowContext(ctx, "SELECT value FROM evidence WHERE id=1").Scan(&b)
26 if e == sql.ErrNoRows {
27 return nil, ErrNoEvidence
28 }
29 return b, e
30}
31func (s *sqliteEvidence) Save(ctx context.Context, b []byte) error {
32 s.mu.Lock()
33 entered := s.entering
34 s.entering = nil
35 s.mu.Unlock()
36 if entered != nil {
37 close(entered)
38 }
39 _, e := s.db.ExecContext(ctx, "INSERT INTO evidence(id,value) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET value=excluded.value", b)
40 return e
41}
42
43func TestLeaseDoesNotWaitForSQLiteWriterPublication(t *testing.T) {
44 f := setup(t)
45 db, e := sql.Open("sqlite", filepath.Join(t.TempDir(), "roster.db"))
46 if e != nil {
47 t.Fatal(e)
48 }
49 defer db.Close()
50 db.SetMaxOpenConns(1)
51 if _, e = db.Exec("CREATE TABLE evidence(id INTEGER PRIMARY KEY,value BLOB NOT NULL)"); e != nil {
52 t.Fatal(e)
53 }
54 disk := &sqliteEvidence{db: db}
55 f.cfg.Durable = disk
56 c := f.cache()
57 d := f.check(c, 1)
58 state(t, d, Member)
59 tx, e := db.BeginTx(context.Background(), nil)
60 if e != nil {
61 t.Fatal(e)
62 }
63 defer tx.Rollback()
64 if _, e = tx.Exec("UPDATE evidence SET value=value WHERE id=1"); e != nil {
65 t.Fatal(e)
66 }
67 before := db.Stats().WaitCount
68 entered := make(chan struct{})
69 disk.mu.Lock()
70 disk.entering = entered
71 disk.mu.Unlock()
72 f.clock.step(30 * time.Second)
73 refreshed := make(chan error, 1)
74 go func() { refreshed <- c.Refresh(context.Background()) }()
75 <-entered
76 // WaitCount proves Save is waiting on the real one-connection writer pool,
77 // not merely scheduled to enter a fake callback. Publication owns Cache.mu.
78 deadline := time.Now().Add(time.Second)
79 for db.Stats().WaitCount == before && time.Now().Before(deadline) {
80 time.Sleep(time.Millisecond)
81 }
82 if db.Stats().WaitCount == before {
83 _ = tx.Rollback()
84 t.Fatal("publication never waited for writer")
85 }
86 valid := make(chan bool, 1)
87 remaining := make(chan time.Duration, 1)
88 go func() { valid <- d.Lease.Valid() }()
89 go func() { remaining <- d.Lease.Remaining() }()
90 var v bool
91 var left time.Duration
92 timedOut := false
93 select {
94 case v = <-valid:
95 case <-time.After(250 * time.Millisecond):
96 timedOut = true
97 }
98 select {
99 case left = <-remaining:
100 case <-time.After(250 * time.Millisecond):
101 timedOut = true
102 }
103 // Always release the writer before reporting a mutation failure, so neither
104 // the refresh goroutine nor the blocked accessor can leak into another test.
105 _ = tx.Rollback()
106 if e = <-refreshed; e != nil {
107 t.Fatal(e)
108 }
109 if timedOut {
110 t.Fatal("lease accessor blocked behind SQLite writer publication")
111 }
112 // The publication has not finished, so the contended answer is the
113 // state before it: the lease, 30 s into its 60, is live with 30 s left.
114 if !v || left != 30*time.Second {
115 t.Fatalf("contended lease misread during publication: valid %v, remaining %v", v, left)
116 }
117 next := f.check(c, 1)
118 state(t, next, Member)
119 if !next.Lease.Valid() {
120 t.Fatal("retry could not use published lease")
121 }
122 // The publication listed the subject with the same role, so the earlier
123 // lease survives it (#97) — on its own, earlier deadline.
124 if !d.Lease.Valid() || d.Lease.Remaining() >= next.Lease.Remaining() {
125 t.Fatal("unchanged publication ended or extended the earlier lease")
126 }
127}
128
129// contended asks Valid and Remaining from other goroutines while the caller
130// holds c.mu, as a concurrent Check or a publication does, and fails the test
131// if either waits for the lock.
132func contended(t *testing.T, c *Cache, l Lease) (bool, time.Duration) {
133 t.Helper()
134 valid := make(chan bool, 1)
135 left := make(chan time.Duration, 1)
136 go func() { valid <- l.Valid() }()
137 go func() { left <- l.Remaining() }()
138 var v bool
139 var n time.Duration
140 timedOut := false
141 select {
142 case v = <-valid:
143 case <-time.After(250 * time.Millisecond):
144 timedOut = true
145 }
146 select {
147 case n = <-left:
148 case <-time.After(250 * time.Millisecond):
149 timedOut = true
150 }
151 if timedOut {
152 c.mu.Unlock()
153 t.Fatal("contended accessor waited for the lock")
154 }
155 return v, n
156}
157
158// A live lease is still live while another goroutine holds the cache's lock
159// (Docs #175: a concurrent Check's brief hold read as an expired lease, and
160// team-mode streams closed minutes before their deadline). The contended
161// answer is the cache's last published state, never a refusal for the hold.
162func TestLeaseContentionAnswersFromPublishedState(t *testing.T) {
163 f := setup(t)
164 c := f.cache()
165 d := f.check(c, 1)
166 f.clock.step(10 * time.Second)
167 before := d.Lease.Remaining()
168 if before != 50*time.Second {
169 t.Fatalf("remaining %v before contention", before)
170 }
171 c.mu.Lock()
172 v, n := contended(t, c, d.Lease)
173 c.mu.Unlock()
174 if !v || n != before {
175 t.Fatalf("contention refused a live lease: valid %v, remaining %v, want %v", v, n, before)
176 }
177 if !d.Lease.Valid() || d.Lease.Remaining() != before {
178 t.Fatal("contention changed the snapshot or deadline")
179 }
180}
181
182// Contention never extends a lease: past its deadline the contended answer
183// refuses exactly as the locked one does.
184func TestLeaseContentionDoesNotExtendAge(t *testing.T) {
185 f := setup(t)
186 c := f.cache()
187 d := f.check(c, 1)
188 f.clock.step(MaximumAge)
189 c.mu.Lock()
190 v, n := contended(t, c, d.Lease)
191 c.mu.Unlock()
192 if v || n != 0 {
193 t.Fatal("contention extended age")
194 }
195}
196
197// A removal that has been published ends the lease for a contended reader
198// too: the published state the reader sees is the one after the removal.
199func TestLeaseContentionSeesPublishedRemoval(t *testing.T) {
200 f := setup(t)
201 c := f.cache()
202 d := f.check(c, 1)
203 f.clock.step(30 * time.Second)
204 f.refreshTo(c, 2, []MemberEntry{{person(2), "member"}})
205 c.mu.Lock()
206 v, n := contended(t, c, d.Lease)
207 c.mu.Unlock()
208 if v || n != 0 {
209 t.Fatal("contended reader missed a published removal")
210 }
211}
212
213// A record update's fence is published when UpdateRecord returns: a reader
214// that then finds the lock held must not answer from the view before it.
215func TestLeaseContentionSeesRecordFence(t *testing.T) {
216 f := setup(t)
217 c := f.cache()
218 d := f.check(c, 1)
219 n := f.record
220 n.Sequence = 2
221 n.Operation = "op2"
222 if e := c.UpdateRecord(context.Background(), f.verify(n)); e != nil {
223 t.Fatal(e)
224 }
225 c.mu.Lock()
226 v, left := contended(t, c, d.Lease)
227 c.mu.Unlock()
228 if v || left != 0 {
229 t.Fatal("contended reader revived a lease the record fence ended")
230 }
231}
232
233// A clock fence made by a lease read is published too. The wall clock steps
234// back past the tolerance (the read fences), then forward again, so the
235// contended reader's own clock check against the last published observation
236// sees no net discrepancy and only the published fence can refuse it.
237func TestLeaseContentionSeesClockFenceFromALeaseRead(t *testing.T) {
238 f := setup(t)
239 c := f.cache()
240 d := f.check(c, 1)
241 f.clock.wallStep(-ClockTolerance - time.Nanosecond)
242 if d.Lease.Valid() {
243 t.Fatal("fence missed")
244 }
245 f.clock.wallStep(ClockTolerance + time.Nanosecond)
246 c.mu.Lock()
247 v, left := contended(t, c, d.Lease)
248 c.mu.Unlock()
249 if v || left != 0 {
250 t.Fatal("contended reader revived a lease a clock fence ended")
251 }
252}
253
254// Every release of c.mu must publish the view (unlock); a bare Unlock leaves
255// contended readers on a stale view. Two sites have tests above; this keeps
256// the rest honest: the one bare Unlock in cache.go is unlock's own.
257func TestEveryLockReleasePublishes(t *testing.T) {
258 raw, e := os.ReadFile("cache.go")
259 if e != nil {
260 t.Fatal(e)
261 }
262 src := string(raw)
263 if n := strings.Count(src, "c.mu.Unlock()"); n != 1 {
264 t.Fatalf("cache.go has %d bare c.mu.Unlock() calls; release the lock with c.unlock()", n)
265 }
266 start := strings.Index(src, "func (c *Cache) unlock() {")
267 at := strings.Index(src, "c.mu.Unlock()")
268 if start < 0 || at < start || strings.Contains(src[start:at], "\n}") {
269 t.Fatal("the bare c.mu.Unlock() is not inside unlock()")
270 }
271}
272
273// The production shape of #175: many requests' Checks take the lock briefly
274// while a stream's guard asks its lease. A live lease must never read as 0.
275func TestLeaseNeverReadsZeroUnderConcurrentChecks(t *testing.T) {
276 f := setup(t)
277 c := f.cache()
278 d := f.check(c, 1)
279 state(t, d, Member)
280 const checkers, readers, rounds = 4, 4, 2000
281 var wg sync.WaitGroup
282 stop := make(chan struct{})
283 for range checkers {
284 wg.Add(1)
285 go func() {
286 defer wg.Done()
287 for {
288 select {
289 case <-stop:
290 return
291 default:
292 f.check(c, 1)
293 }
294 }
295 }()
296 }
297 var zeros, invalid sync.Map
298 var rwg sync.WaitGroup
299 for i := range readers {
300 rwg.Add(1)
301 go func() {
302 defer rwg.Done()
303 z, bad := 0, 0
304 for range rounds {
305 if d.Lease.Remaining() <= 0 {
306 z++
307 }
308 if !d.Lease.Valid() {
309 bad++
310 }
311 }
312 zeros.Store(i, z)
313 invalid.Store(i, bad)
314 }()
315 }
316 rwg.Wait()
317 close(stop)
318 wg.Wait()
319 z, bad := 0, 0
320 zeros.Range(func(_, v any) bool { z += v.(int); return true })
321 invalid.Range(func(_, v any) bool { bad += v.(int); return true })
322 if z != 0 || bad != 0 {
323 t.Fatalf("live lease read as lapsed under concurrent Checks: Remaining 0 %d/%d, Valid false %d/%d", z, readers*rounds, bad, readers*rounds)
324 }
325}
326
327func TestLeaseContentionDoesNotSkipLaterClockFence(t *testing.T) {
328 f := setup(t)
329 c := f.cache()
330 d := f.check(c, 1)
331 f.clock.wallStep(-ClockTolerance - time.Nanosecond)
332 c.mu.Lock()
333 done := make(chan bool, 1)
334 go func() { done <- d.Lease.Valid() }()
335 select {
336 case v := <-done:
337 if v {
338 c.mu.Unlock()
339 t.Fatal("contention granted")
340 }
341 case <-time.After(250 * time.Millisecond):
342 c.mu.Unlock()
343 t.Fatal("contention blocked")
344 }
345 c.mu.Unlock()
346 if d.Lease.Valid() || d.Lease.Remaining() != 0 {
347 t.Fatal("successful lock skipped backward-clock fence")
348 }
349}
350
351func TestUnknownSigningKeyRefused(t *testing.T) {
352 f := setup(t)
353 raw, e := SignProvisioning(f.op, "unprovisioned", f.record)
354 if e != nil {
355 t.Fatal(e)
356 }
357 if _, e = VerifyProvisioning(raw, []Key{{"operator", f.record.Keys[0].Public}}, f.record.Bindings); e != ErrRefused {
358 t.Fatalf("unknown operator key result %v", e)
359 }
360 keys, _ := publicKeys(f.record.Keys)
361 // A valid signature under a real key still refuses when its identifier was
362 // not provisioned. The map guard is explicit rather than verifier-dependent.
363 b, e := encode(f.key, "unprovisioned", PageContext, struct {
364 Version int `json:"version"`
365 }{1})
366 if e != nil {
367 t.Fatal(e)
368 }
369 if _, e = signedPayload(b, keys, PageContext); e != ErrRefused {
370 t.Fatalf("unknown roster key result %v", e)
371 }
372}
373
374// refreshTo publishes members at epoch after the refresh interval.
375func (f *fixture) refreshTo(c *Cache, epoch int64, members []MemberEntry) {
376 f.t.Helper()
377 f.set(func(r *http.Request) (*http.Response, error) { return f.response(r, epoch, members, true, ""), nil })
378 if e := c.Refresh(context.Background()); e != nil {
379 f.t.Fatal(e)
380 }
381}
382
383// #97: a refresh that still lists the subject with the same role keeps an
384// earlier lease, and keeps its deadline: the 60 s ceiling is measured from the
385// fetch that decided it, not from the publication that merely confirmed it.
386func TestLeaseSurvivesUnchangedPublicationOnItsOwnDeadline(t *testing.T) {
387 f := setup(t)
388 c := f.cache()
389 d := f.check(c, 1)
390 state(t, d, Member)
391 f.clock.step(30 * time.Second)
392 f.refreshTo(c, 2, []MemberEntry{{person(1), "member"}, {person(2), "member"}})
393 if !d.Lease.Valid() {
394 t.Fatal("unchanged publication ended the lease")
395 }
396 if got := d.Lease.Remaining(); got != 30*time.Second {
397 t.Fatalf("remaining %v, want the original deadline's 30s", got)
398 }
399 fresh := f.check(c, 1)
400 f.clock.step(29 * time.Second)
401 if !d.Lease.Valid() {
402 t.Fatal("early expiry")
403 }
404 f.clock.step(time.Second)
405 if d.Lease.Valid() || d.Lease.Remaining() != 0 {
406 t.Fatal("publication extended the earlier lease past its deadline")
407 }
408 if !fresh.Lease.Valid() {
409 t.Fatal("the confirming publication's own lease ended early")
410 }
411}
412
413func TestLeaseEndsOnRoleChange(t *testing.T) {
414 for _, tc := range []struct{ from, to string }{{"member", "owner"}, {"owner", "member"}} {
415 f := setup(t)
416 f.set(func(r *http.Request) (*http.Response, error) {
417 return f.response(r, 1, []MemberEntry{{person(1), tc.from}}, true, ""), nil
418 })
419 c := f.cache()
420 d := f.check(c, 1)
421 if d.State != Member || d.Role != tc.from {
422 t.Fatalf("decision %+v", d)
423 }
424 f.clock.step(30 * time.Second)
425 f.refreshTo(c, 2, []MemberEntry{{person(1), tc.to}})
426 if d.Lease.Valid() || d.Lease.Remaining() != 0 {
427 t.Fatalf("%s lease survived a change to %s", tc.from, tc.to)
428 }
429 if n := f.check(c, 1); n.Role != tc.to || !n.Lease.Valid() {
430 t.Fatal("new role not decided")
431 }
432 }
433}
434
435func TestLeaseEndsOnRemovalAndReAddDoesNotReviveIt(t *testing.T) {
436 f := setup(t)
437 c := f.cache()
438 d := f.check(c, 1)
439 other := f.check(c, 1)
440 f.clock.step(30 * time.Second)
441 f.refreshTo(c, 2, []MemberEntry{{person(2), "member"}})
442 if d.Lease.Valid() || d.Lease.Remaining() != 0 {
443 t.Fatal("lease survived removal")
444 }
445 state(t, f.check(c, 1), NotMember)
446 // A forced refresh after RetryAfter re-adds the subject inside the
447 // original 60 s: the earlier lease stays ended.
448 f.clock.step(RetryAfter)
449 f.refreshTo(c, 3, []MemberEntry{{person(1), "member"}, {person(2), "member"}})
450 if d.Lease.Valid() || other.Lease.Remaining() != 0 {
451 t.Fatal("re-add revived a lease that removal ended")
452 }
453 if !f.check(c, 1).Lease.Valid() {
454 t.Fatal("re-added member not decided afresh")
455 }
456}
457
458func TestLeaseSurvivesAnotherMembersChange(t *testing.T) {
459 f := setup(t)
460 f.set(func(r *http.Request) (*http.Response, error) {
461 return f.response(r, 1, []MemberEntry{{person(1), "owner"}, {person(2), "member"}}, true, ""), nil
462 })
463 c := f.cache()
464 d := f.check(c, 1)
465 state(t, d, Member)
466 f.clock.step(30 * time.Second)
467 f.refreshTo(c, 2, []MemberEntry{{person(1), "owner"}, {person(3), "owner"}})
468 if !d.Lease.Valid() {
469 t.Fatal("another member's change ended this lease")
470 }
471}
472
473// A waiter woken by a finished refresh finds the cache unlocked: the flight
474// releases c.mu before it closes done. The closer is parked just after the
475// close (the signalled seam), so a Lease.Valid asked by the woken waiter
476// meets the lock if, and only if, the close still happens under it, which
477// TryLock reads as contention and a valid lease as invalid (#104).
478func TestRefreshWakesItsWaiterWithTheCacheUnlocked(t *testing.T) {
479 f := setup(t)
480 c := f.cache()
481 d := f.check(c, 1)
482 state(t, d, Member)
483 parked, release := make(chan struct{}), make(chan struct{})
484 c.mu.Lock()
485 c.signalled = func() { close(parked); <-release }
486 c.mu.Unlock()
487 defer close(release)
488 f.clock.step(30 * time.Second)
489 f.refreshTo(c, 2, []MemberEntry{{person(1), "member"}})
490 <-parked
491 if !d.Lease.Valid() {
492 t.Fatal("the refresh woke its waiter with the cache still locked")
493 }
494}
495
496// A fence ends every earlier lease even when a later publication lists the
497// subject unchanged: the deadline was measured on a clock the fence distrusts.
498func TestLeaseEndedByFenceStaysEndedAfterPublication(t *testing.T) {
499 f := setup(t)
500 c := f.cache()
501 d := f.check(c, 1)
502 f.clock.wallStep(-ClockTolerance - time.Nanosecond)
503 if d.Lease.Valid() {
504 t.Fatal("fence missed")
505 }
506 f.clock.step(RetryAfter)
507 f.refreshTo(c, 2, []MemberEntry{{person(1), "member"}})
508 if d.Lease.Valid() || d.Lease.Remaining() != 0 {
509 t.Fatal("publication revived a fenced lease")
510 }
511 if !f.check(c, 1).Lease.Valid() {
512 t.Fatal("no fresh decision after the fence")
513 }
514}
515
516func TestValidSubject(t *testing.T) {
517 for s, want := range map[string]bool{person(1): true, "pr_" + "aaaaaaaaaaaaaaaaaaaaaaaaa2": true, "pr_short": false, "pr_" + "AAAAAAAAAAAAAAAAAAAAAAAAAA": false, "xx_aaaaaaaaaaaaaaaaaaaaaaaaaa": false, "pr_aaaaaaaaaaaaaaaaaaaaaaaaa1": false, "": false} {
518 if ValidSubject(s) != want {
519 t.Errorf("ValidSubject(%q) = %v", s, !want)
520 }
521 }
522}
523