[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics itself and print each message as a notification card, so the phone's ntfy app is the only client. Each subscription is one ntfy.Subscriber in the daemon's errgroup: one event loop owns its state, and one goroutine per connection reads the JSON stream. internal/app hands its messages to modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name> and the message's ID as ref, so ntfy never imports modules. The cursor is ntfy server time, never an ID. ntfy sends open before the replay, so only keepalives and messages dealt with move it, and a reconnect asks for two minutes before it, since a message is dated before its attachment is stored. The IDs of the messages a replay could send again are kept, at least the last 512 and 20,000 at most, so a flood in the overlap never reprints; when the cap forgets IDs a replay could send, the floor rises past them. A saved floor bounds replays: a first start sets it to the open event's time, and max_backlog (default 1h, at most 12h), measured by the server's clock as each connection tells it (its open event, else its Date, then the monotonic clock), never the host's, so replays are requested unclamped and filtered as they arrive, raises it when it clamps, so what it left out stays out. The state, with the held messages and the receipt times, is written atomically at most once a second and at shutdown. Redirects are never followed, so credentials never go to another address or over plain http. A stalled stream reconnects after twice the keepalive plus 15 s, failures back off 5 to 120 s with jitter, a 429 waits for Retry-After, and refused credentials, checked at startup through /auth, show as unauthorized and retry every 5 minutes. A full print queue pauses reading and retries the message from 1 s to 30 s, and the cursor moves past it only once it is queued. The paper budget is a strict window: at most rate_limit receipts (5) in any rate_window (10m), digests included; the rest are held and print on one digest card once there is room, and outside quiet hours bypass_priority (5) and above print at once. Quiet hours hold everything below their min_priority for one Overnight digest when the window ends, or drop it; windows cross midnight and keep their times of day when clocks change, also where the change skips midnight or a window's end. A message whose sequence printed before, on a card or a digest row, is marked (updated), or skipped with ntfy.format.updates = "skip"; the first of a sequence its publisher named prints plain. /healthz lists the subscriptions without changing how its status code is decided, and no credential, topic or message text reaches it, the logs or a config error. Subscriptions come from the file only, with strict keys and per-entry defaults; credentials are optional, at most one kind. ntfy.state_dir is required with a subscription: the unit gains StateDirectory=uberbringer, install.sh writes the path into a new config, and the Docker image sets it for a volume and runs as the fixed user 10001. README explains how to lock a self-hosted ntfy server down so that only your publishers can print. Breaking: printer.cut_feed (default 3) feeds blank lines before every cut, so the last line no longer sits right at the cut. They count toward format.max_lines once per copy, so a job within 3 lines a copy of the limit now fails. The renderer's option is 0 unless set, so the pinned receipts keep their bytes. testing/synctest drives the subscriber on a virtual clock, including a 24-hour soak with floods, repeats, refusals, a full queue, quiet hours and a restart that fails on any leaked goroutine; it replaces a 24-hour run on hardware. Tests over real sockets cover net/http's goroutines and redirects to plain http and to another port. Checked on the TM-T88IV against a live ntfy server: a phone message, quiet hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a 30-minute outage with an update, a wrong token, and the three-line cut feed. The digest and the cut-feed card are pinned in TestPaperReceipts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
230 lines
6.6 KiB
Go
230 lines
6.6 KiB
Go
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
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}
|