package ntfy import ( "context" "fmt" "math/rand/v2" "net/http" "slices" "sync" "testing" "testing/synctest" "time" ) // soakHandler records what it prints and refuses a share of the calls, as // a full print queue does. type soakHandler struct { recorder rngMu sync.Mutex rng *rand.Rand failRate float64 digestAt []time.Time } func (h *soakHandler) refuse() bool { h.rngMu.Lock() defer h.rngMu.Unlock() return h.rng.Float64() < h.failRate } func (h *soakHandler) Message(ctx context.Context, m Message, updated bool) error { if h.refuse() { return errBusy } return h.recorder.Message(ctx, m, updated) } func (h *soakHandler) Digest(ctx context.Context, d Digest) error { if h.refuse() { return errBusy } h.mu.Lock() h.digestAt = append(h.digestAt, time.Now()) h.mu.Unlock() return h.recorder.Digest(ctx, d) } func (h *soakHandler) setFailRate(r float64) { h.rngMu.Lock() defer h.rngMu.Unlock() h.failRate = r } // TestSoak runs a subscription for 24 hours of the bubble's clock against // a server that drops, stalls, refuses and rate limits it, with floods, // repeats and updates, a handler that is sometimes full, quiet hours and a // restart halfway. Then: // - no message prints twice, on a card or a digest; // - every message the subscription may read is printed or held, none // lost; // - no more than rate_limit receipts below the bypass priority print in // any rate_window; // - in quiet hours only urgent messages print, and no digest; // - a card is marked updated exactly when its sequence printed before; // - no goroutine is left running once Run returns: synctest.Test fails // the test if one is. func TestSoak(t *testing.T) { synctest.Test(t, func(t *testing.T) { rng := rand.New(rand.NewPCG(20261130, 4)) dir := t.TempDir() f := newFakeServer() h := &soakHandler{rng: rand.New(rand.NewPCG(7, 7)), failRate: 0.05} o := testOptions(f, dir) o.MinPriority = 2 o.Quiet = &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: allDays, Location: time.UTC, MinPriority: 5} s, stop := start(t, o, h) begin := time.Now().UTC() end := begin.Add(24 * time.Hour) restarted := false var published []Message publish := func(m Message) { published = append(published, f.publish(m)) } for time.Now().Before(end) { time.Sleep(time.Duration(10+rng.IntN(590)) * time.Second) switch r := rng.IntN(100); { case r < 65: m := Message{Title: fmt.Sprintf("message %d", len(published)), RawPriority: 1 + rng.IntN(5)} if len(published) > 0 && rng.IntN(5) == 0 { m.SequenceID = published[rng.IntN(len(published))].Sequence() } publish(m) case r < 70: // A same-second repeat of the newest message. if len(published) > 0 { f.publish(published[len(published)-1]) } case r < 75: for i := range 20 { publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 2 + rng.IntN(4)}) } case r < 80: f.drop() case r < 83: f.stall() case r < 86: f.answerNext(fakeAnswer{status: http.StatusTooManyRequests, retryAfter: "30"}) f.drop() case r < 87: f.answerNext(fakeAnswer{status: http.StatusUnauthorized}) f.drop() case r < 90: f.answerNext(fakeAnswer{status: http.StatusBadGateway}, fakeAnswer{status: http.StatusServiceUnavailable}) f.drop() } if !restarted && time.Since(begin) > 13*time.Hour { restarted = true stop() time.Sleep(10 * time.Minute) s, stop = start(t, o, h) } } // Let the last digest print after the quiet hours, with a handler // that takes everything. h.setFailRate(0) sleepUntil(time.Date(end.Year(), end.Month(), end.Day(), 8, 0, 0, 0, time.UTC)) if st := s.Status(); st.Held != 0 { t.Errorf("%d messages still held at 08:00", st.Held) } stop() synctest.Wait() cards := h.cardList() digests := h.digestList() if len(cards) == 0 || len(digests) == 0 { t.Fatalf("%d cards and %d digests: the soak exercised too little", len(cards), len(digests)) } t.Logf("%d messages published, %d cards, %d digests, %d server requests", len(published), len(cards), len(digests), len(f.streams())) // Every message the subscription may read, once. want := make(map[string]Message) for _, m := range published { if m.Priority() >= o.MinPriority { want[m.ID] = m } } got := make(map[string]int) total := len(cards) for _, c := range cards { got[c.m.ID]++ } for _, d := range digests { total += d.Count for _, row := range d.Rows { got[row.ID]++ } } for id, n := range got { if n > 1 { t.Errorf("%s printed %d times", id, n) } if _, ok := want[id]; !ok { t.Errorf("%s printed, but the subscription should not have read it", id) } } if total != len(want) { t.Errorf("%d messages printed or held, want %d", total, len(want)) } // The paper budget and the quiet hours. var receipts []time.Time for _, c := range cards { _, quiet := o.Quiet.window(c.at) if c.m.Priority() < o.BypassPriority { receipts = append(receipts, c.at) if quiet { t.Errorf("%s, priority %d, printed in quiet hours at %s", c.m.ID, c.m.Priority(), c.at) } } } for _, at := range h.digestAt { if _, quiet := o.Quiet.window(at); quiet { t.Errorf("a digest printed in quiet hours at %s", at) } receipts = append(receipts, at) } slices.SortFunc(receipts, func(a, b time.Time) int { return a.Compare(b) }) for i := o.RateLimit; i < len(receipts); i++ { if receipts[i].Sub(receipts[i-o.RateLimit]) < o.RateWindow { t.Errorf("receipts %d to %d printed within %s", i-o.RateLimit, i, receipts[i].Sub(receipts[i-o.RateLimit])) } } // Updates. The server sends messages in the order they were // published, and a replay only repeats ones already dealt with, so // the subscription first meets each message in that order. While it // remembers every sequence, a message is an update exactly when an // earlier one of its sequence printed, on a card or a digest row; a // message only counted on a digest does not count. updated := make(map[string]bool) for _, c := range cards { updated[c.m.ID] = c.updated } for _, d := range digests { for _, row := range d.Rows { updated[row.ID] = row.Updated } } if len(want) < ringSize { seen := make(map[string]bool) printed := make(map[string]bool) for _, m := range published { if _, ok := want[m.ID]; !ok || seen[m.ID] { continue } seen[m.ID] = true if got, ok := updated[m.ID]; ok && got != printed[m.Sequence()] { t.Errorf("%s of sequence %s marked updated=%v, want %v", m.ID, m.Sequence(), got, printed[m.Sequence()]) } if _, ok := updated[m.ID]; ok { printed[m.Sequence()] = true } } } }) }