Add ntfy subscriptions with digests, quiet hours and a cut feed
[[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>
This commit is contained in:
1 parent
1335ed0687
commit
fb76284129
52 files changed
+6464
-390
No files matched your search
@@ -0,0 +1,747 @@
|
||||
package ntfy
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sinceOf returns the since parameter of a stream request, and whether it
|
||||
// has one.
|
||||
func sinceOf(t *testing.T, r *http.Request) (int64, bool) {
|
||||
t.Helper()
|
||||
s := r.URL.Query().Get("since")
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil {
|
||||
t.Fatalf("since %q: %v", s, err)
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// A first start asks for no since, so only new messages print; the
|
||||
// request names the topics and carries the token and a generic user agent.
|
||||
func TestFirstStartSendsNoSince(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
f.publish(Message{Title: "old"})
|
||||
h := &recorder{}
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.Topics = []string{"alerts", "backups"}
|
||||
s, stop := start(t, o, h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
streams := f.streams()
|
||||
if len(streams) != 1 {
|
||||
t.Fatalf("%d stream requests, want 1", len(streams))
|
||||
}
|
||||
r := streams[0]
|
||||
if r.URL.Path != "/alerts,backups/json" {
|
||||
t.Errorf("path %q, want /alerts,backups/json", r.URL.Path)
|
||||
}
|
||||
if _, ok := sinceOf(t, r); ok || r.URL.RawQuery != "" {
|
||||
t.Errorf("query %q, want none", r.URL.RawQuery)
|
||||
}
|
||||
if got := r.Header.Get("Authorization"); got != "Bearer tk_testtoken" {
|
||||
t.Errorf("Authorization %q", got)
|
||||
}
|
||||
if got := r.Header.Get("User-Agent"); got != "uberbringer" {
|
||||
t.Errorf("User-Agent %q", got)
|
||||
}
|
||||
if got := h.printed(); len(got) != 0 {
|
||||
t.Errorf("printed %v, want nothing from before the start", got)
|
||||
}
|
||||
if st := s.Status(); st.State != StateConnected || st.ConnectedSince.IsZero() || st.Name != "home" {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
|
||||
m := f.publish(Message{Title: "new", RawPriority: 4})
|
||||
synctest.Wait()
|
||||
if got := h.printed(); !slices.Equal(got, []string{m.ID}) {
|
||||
t.Errorf("printed %v, want %v", got, []string{m.ID})
|
||||
}
|
||||
if st := s.Status(); st.Printed != 1 || st.LastMessageAt.IsZero() {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBasicAuthAndPriorityFilter(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.Token, o.User, o.Password = "", "printer", "s3cret"
|
||||
o.MinPriority = 3
|
||||
_, stop := start(t, o, &recorder{})
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
r := f.streams()[0]
|
||||
if user, pass, ok := r.BasicAuth(); !ok || user != "printer" || pass != "s3cret" {
|
||||
t.Errorf("basic auth %q %q %v", user, pass, ok)
|
||||
}
|
||||
if got := r.URL.Query().Get("priority"); got != "3,4,5" {
|
||||
t.Errorf("priority %q, want 3,4,5", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// After the stream ends, the reconnect asks for the messages since the
|
||||
// cursor, less the slack, and the repeats it gets are dropped.
|
||||
func TestReconnectResumesFromCursor(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
_, stop := start(t, testOptions(f, t.TempDir()), h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
time.Sleep(10 * time.Minute)
|
||||
first := f.publish(Message{Title: "one"})
|
||||
synctest.Wait()
|
||||
f.drop()
|
||||
synctest.Wait()
|
||||
missed := f.publish(Message{Title: "missed while away"})
|
||||
|
||||
time.Sleep(7 * time.Second) // the first backoff step is 5 s ± 20%
|
||||
synctest.Wait()
|
||||
streams := f.streams()
|
||||
if len(streams) != 2 {
|
||||
t.Fatalf("%d stream requests, want 2", len(streams))
|
||||
}
|
||||
// The cursor is the first message's time: no keepalive came after it.
|
||||
since, ok := sinceOf(t, streams[1])
|
||||
if want := first.Time - int64(cursorSlack/time.Second); !ok || since != want {
|
||||
t.Errorf("since = %d, %v; want the cursor less the slack, %d", since, ok, want)
|
||||
}
|
||||
if got, want := h.printed(), []string{first.ID, missed.ID}; !slices.Equal(got, want) {
|
||||
t.Errorf("printed %v, want %v once each", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Two messages in the same second, one of them sent twice as ntfy 2.31+
|
||||
// can, and the overlap a reconnect replays, print once each, also after the
|
||||
// state is loaded from disk.
|
||||
func TestDuplicatesAreDropped(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
o := testOptions(f, dir)
|
||||
_, stop := start(t, o, h)
|
||||
synctest.Wait()
|
||||
|
||||
a := f.publish(Message{Title: "a"})
|
||||
b := f.publish(Message{Title: "b"})
|
||||
f.publish(a)
|
||||
synctest.Wait()
|
||||
if got, want := h.printed(), []string{a.ID, b.ID}; !slices.Equal(got, want) {
|
||||
t.Fatalf("printed %v, want %v", got, want)
|
||||
}
|
||||
|
||||
f.drop()
|
||||
time.Sleep(time.Minute)
|
||||
synctest.Wait()
|
||||
if got := h.printed(); len(got) != 2 {
|
||||
t.Fatalf("printed %v after the reconnect replayed the overlap", got)
|
||||
}
|
||||
stop()
|
||||
|
||||
h2 := &recorder{}
|
||||
_, stop = start(t, o, h2)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
c := f.publish(Message{Title: "c"})
|
||||
synctest.Wait()
|
||||
if got := h2.printed(); !slices.Equal(got, []string{c.ID}) {
|
||||
t.Errorf("after a restart printed %v, want only %v", got, c.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A cursor older than MaxBacklog still asks for the whole replay from the
|
||||
// cursor; only the messages older than MaxBacklog by ntfy's clock are left
|
||||
// out as they arrive.
|
||||
func TestStaleCursorReplaysUnclamped(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
f := newFakeServer()
|
||||
o := testOptions(f, dir)
|
||||
old := f.publish(Message{Title: "three hours ago"})
|
||||
if err := saveState(o.StateFile, state{Cursor: old.Time}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(3 * time.Hour)
|
||||
recent := f.publish(Message{Title: "half an hour ago"})
|
||||
time.Sleep(30 * time.Minute)
|
||||
|
||||
h := &recorder{}
|
||||
_, stop := start(t, o, h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
// The request is not clamped; the connection leaves out what is
|
||||
// older than the backlog, and the floor keeps it out.
|
||||
if since, ok := sinceOf(t, f.streams()[0]); !ok || since != old.Time-int64(cursorSlack/time.Second) {
|
||||
t.Errorf("since = %d, %v; want the cursor less the slack", since, ok)
|
||||
}
|
||||
if st, _ := loadState(o.StateFile); st.Floor != 0 && st.Floor < time.Now().Add(-o.MaxBacklog).Unix() {
|
||||
t.Errorf("floor %d below the backlog", st.Floor)
|
||||
}
|
||||
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) {
|
||||
t.Errorf("printed %v, want only %v", got, recent.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A start that leaves out messages for their age saves the floor at once,
|
||||
// so a restart soon after, before any keepalive, with a longer backlog,
|
||||
// still leaves them out.
|
||||
func TestBacklogFloorIsSaved(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.MaxBacklog = 2 * time.Minute
|
||||
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
old := f.publish(Message{Title: "published while stopped"})
|
||||
time.Sleep(3 * time.Minute)
|
||||
|
||||
h := &recorder{}
|
||||
_, stop := start(t, o, h)
|
||||
synctest.Wait()
|
||||
stop()
|
||||
if got := h.printed(); len(got) != 0 {
|
||||
t.Fatalf("printed %v, a message older than the backlog", got)
|
||||
}
|
||||
st, err := loadState(o.StateFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Floor <= old.Time {
|
||||
t.Errorf("floor %d, want it past the message left out, %d", st.Floor, old.Time)
|
||||
}
|
||||
|
||||
o.MaxBacklog = time.Hour
|
||||
h2 := &recorder{}
|
||||
_, stop2 := start(t, o, h2)
|
||||
defer stop2()
|
||||
synctest.Wait()
|
||||
if got := h2.printed(); len(got) != 0 {
|
||||
t.Errorf("after a restart with a longer backlog, printed %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A connection that sends nothing for twice the keepalive plus 15 s is
|
||||
// closed and opened again.
|
||||
func TestStallReconnects(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
time.Sleep(time.Minute) // a keepalive arrives at 45 s
|
||||
synctest.Wait()
|
||||
f.stall()
|
||||
stalledAt := time.Now()
|
||||
|
||||
// The last line was the keepalive at 45 s, so the stall is noticed
|
||||
// at 45 s + 105 s, 90 s after the stall began.
|
||||
time.Sleep(89 * time.Second)
|
||||
synctest.Wait()
|
||||
if f.open() != 1 || len(f.streams()) != 1 {
|
||||
t.Fatalf("reconnected %s after the stall, too early", time.Since(stalledAt))
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
synctest.Wait()
|
||||
if f.open() != 0 {
|
||||
t.Fatal("the stalled connection is still open")
|
||||
}
|
||||
if st := s.Status(); st.State != StateBackoff || !strings.Contains(st.LastError, "no data for 1m45s") {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
time.Sleep(7 * time.Second)
|
||||
synctest.Wait()
|
||||
if len(f.streams()) != 2 || f.open() != 1 {
|
||||
t.Errorf("%d requests, %d open; want a second connection", len(f.streams()), f.open())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Failed connections wait 5, 10, 20, 30, 60 and then 120 s, each ± 20%;
|
||||
// after a connection that lasted two minutes the next wait is 5 s again.
|
||||
func TestBackoff(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
var fails []fakeAnswer
|
||||
for range 8 {
|
||||
fails = append(fails, fakeAnswer{status: http.StatusBadGateway})
|
||||
}
|
||||
f.answerNext(fails...)
|
||||
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
|
||||
defer stop()
|
||||
|
||||
steps := []time.Duration{5, 10, 20, 30, 60, 120, 120, 120}
|
||||
for i, step := range steps {
|
||||
synctest.Wait()
|
||||
times := f.streamTimes()
|
||||
prev := times[len(times)-1]
|
||||
step *= time.Second
|
||||
low, high := step*8/10, step*12/10
|
||||
time.Sleep(time.Until(prev.Add(low - time.Millisecond)))
|
||||
synctest.Wait()
|
||||
if got := len(f.streamTimes()); got != len(times) {
|
||||
t.Fatalf("attempt %d came before %s", i+2, low)
|
||||
}
|
||||
time.Sleep(time.Until(prev.Add(high + time.Millisecond)))
|
||||
synctest.Wait()
|
||||
if got := len(f.streamTimes()); got != len(times)+1 {
|
||||
t.Fatalf("attempt %d did not come by %s", i+2, high)
|
||||
}
|
||||
}
|
||||
synctest.Wait()
|
||||
if st := s.Status(); st.State != StateConnected {
|
||||
t.Fatalf("status %+v after the failures", st)
|
||||
}
|
||||
|
||||
time.Sleep(3 * time.Minute)
|
||||
f.drop()
|
||||
synctest.Wait()
|
||||
n := len(f.streams())
|
||||
time.Sleep(6100 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
if len(f.streams()) != n+1 {
|
||||
t.Error("after a stable connection the backoff did not start again at 5 s")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A 429 waits as long as Retry-After says.
|
||||
func TestTooManyRequestsHonoursRetryAfter(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
f.answerNext(fakeAnswer{status: http.StatusTooManyRequests, retryAfter: "300"})
|
||||
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
if st := s.Status(); st.State != StateBackoff || !strings.Contains(st.LastError, "429") {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
time.Sleep(299 * time.Second)
|
||||
synctest.Wait()
|
||||
if len(f.streams()) != 1 {
|
||||
t.Fatal("reconnected before Retry-After")
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
synctest.Wait()
|
||||
if len(f.streams()) != 2 {
|
||||
t.Fatal("did not reconnect after Retry-After")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestParseRetryAfter(t *testing.T) {
|
||||
now := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
|
||||
tests := map[string]time.Duration{
|
||||
"": 0,
|
||||
"120": 2 * time.Minute,
|
||||
" 7 ": 7 * time.Second,
|
||||
"-5": 0,
|
||||
"86400": time.Hour,
|
||||
"Mon, 30 Nov 2026 12:01:30 GMT": 90 * time.Second,
|
||||
"Mon, 30 Nov 2026 11:00:00 GMT": 0,
|
||||
"soon": 0,
|
||||
}
|
||||
for h, want := range tests {
|
||||
if got := parseRetryAfter(h, now); got != want {
|
||||
t.Errorf("parseRetryAfter(%q) = %s, want %s", h, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Refused credentials show at startup through the credentials check: the
|
||||
// state is unauthorized, and the next try is five minutes later.
|
||||
func TestUnauthorized(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
f.setAuth(http.StatusUnauthorized)
|
||||
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
if st := s.Status(); st.State != StateUnauthorized || !strings.Contains(st.LastError, "HTTP 401") {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
if strings.Contains(s.Status().LastError, "tk_testtoken") {
|
||||
t.Error("the status shows the token")
|
||||
}
|
||||
if n := len(f.streams()); n != 0 {
|
||||
t.Fatalf("%d stream requests before the retry", n)
|
||||
}
|
||||
|
||||
// The stream refuses too, so the state stays unauthorized.
|
||||
f.answerNext(fakeAnswer{status: http.StatusForbidden})
|
||||
time.Sleep(5*time.Minute + time.Second)
|
||||
synctest.Wait()
|
||||
if n := len(f.streams()); n != 1 {
|
||||
t.Fatalf("%d stream requests five minutes later, want 1", n)
|
||||
}
|
||||
if st := s.Status(); st.State != StateUnauthorized || !strings.Contains(st.LastError, "403") {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
|
||||
time.Sleep(5*time.Minute + time.Second)
|
||||
synctest.Wait()
|
||||
if st := s.Status(); st.State != StateConnected || st.LastError != "" {
|
||||
t.Errorf("status %+v once the stream accepts the credentials", st)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// While the handler cannot take a message, nothing more is read and the
|
||||
// cursor stays before it; the message is offered again after 1, 2, 4 ...
|
||||
// seconds and prints once the handler takes it.
|
||||
func TestFullQueueHoldsTheCursor(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
o := testOptions(f, dir)
|
||||
_, stop := start(t, o, h)
|
||||
synctest.Wait()
|
||||
time.Sleep(10 * time.Minute)
|
||||
synctest.Wait()
|
||||
|
||||
h.failNext(4)
|
||||
a := f.publish(Message{Title: "a"})
|
||||
time.Sleep(time.Second)
|
||||
b := f.publish(Message{Title: "b"})
|
||||
synctest.Wait()
|
||||
time.Sleep(2 * time.Second) // a failed at 0 s and 1 s; next try at 3 s
|
||||
synctest.Wait()
|
||||
|
||||
st, err := loadState(o.StateFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Cursor >= a.Time {
|
||||
t.Errorf("cursor %d moved to the unprinted message's time %d", st.Cursor, a.Time)
|
||||
}
|
||||
if got := h.printed(); len(got) != 0 {
|
||||
t.Fatalf("printed %v while the queue was full", got)
|
||||
}
|
||||
|
||||
time.Sleep(12 * time.Second) // tries at 3 s and 7 s fail; 15 s takes it
|
||||
synctest.Wait()
|
||||
if got, want := h.printed(), []string{a.ID, b.ID}; !slices.Equal(got, want) {
|
||||
t.Fatalf("printed %v, want %v", got, want)
|
||||
}
|
||||
stop()
|
||||
if st, _ := loadState(o.StateFile); st.Cursor < b.Time {
|
||||
t.Errorf("cursor %d, want at least %d once both printed", st.Cursor, b.Time)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The state file survives a restart; a damaged file counts as no state,
|
||||
// with a warning.
|
||||
func TestStateFile(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
f := newFakeServer()
|
||||
o := testOptions(f, dir)
|
||||
_, stop := start(t, o, &recorder{})
|
||||
synctest.Wait()
|
||||
m := f.publish(Message{Title: "a", SequenceID: "s1"})
|
||||
synctest.Wait()
|
||||
stop()
|
||||
|
||||
st, err := loadState(o.StateFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Version != stateVersion || st.Cursor != m.Time || !slices.Contains(st.Seen, seenID{ID: m.ID, Time: m.Time}) ||
|
||||
!slices.Contains(st.Printed, "s1") || len(st.Prints) != 1 {
|
||||
t.Errorf("state %+v", st)
|
||||
}
|
||||
if info, err := os.Stat(o.StateFile); err == nil && info.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' {
|
||||
t.Errorf("state file mode %v, want owner only", info.Mode().Perm())
|
||||
}
|
||||
|
||||
for name, data := range map[string]string{
|
||||
"partial": `{"version":1,"cursor":12`,
|
||||
"not JSON": "\x00\x01",
|
||||
"other version": `{"version":2,"cursor":1}`,
|
||||
} {
|
||||
if err := os.WriteFile(o.StateFile, []byte(data), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs logBuffer
|
||||
o.Logger = debugLogger(&logs)
|
||||
f2 := newFakeServer()
|
||||
o.Transport = f2
|
||||
_, stop := start(t, o, &recorder{})
|
||||
synctest.Wait()
|
||||
stop()
|
||||
if !strings.Contains(logs.String(), "ntfy state file unreadable; starting without state") {
|
||||
t.Errorf("%s: no warning in %q", name, logs.String())
|
||||
}
|
||||
if _, ok := sinceOf(t, f2.streams()[0]); ok {
|
||||
t.Errorf("%s: asked for since, want a fresh start", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The state file is written at most once a second.
|
||||
func TestStateWritesAreThrottled(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.RateLimit = 100
|
||||
_, stop := start(t, o, &recorder{})
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
info := func() time.Time {
|
||||
fi, err := os.Stat(o.StateFile)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return fi.ModTime()
|
||||
}
|
||||
f.publish(Message{Title: "a"})
|
||||
synctest.Wait()
|
||||
st1, _ := loadState(o.StateFile)
|
||||
f.publish(Message{Title: "b"})
|
||||
synctest.Wait()
|
||||
st2, _ := loadState(o.StateFile)
|
||||
if len(st2.Seen) != len(st1.Seen) {
|
||||
t.Errorf("the state was written twice within a second: %d then %d seen", len(st1.Seen), len(st2.Seen))
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
synctest.Wait()
|
||||
if st3, _ := loadState(o.StateFile); len(st3.Seen) != 2 || info().IsZero() {
|
||||
t.Errorf("after a second the state has %d seen, want 2", len(st3.Seen))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Events other than messages, and base64 bodies, print nothing but move
|
||||
// the cursor.
|
||||
func TestNonMessagesSkipped(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
o := testOptions(f, t.TempDir())
|
||||
_, stop := start(t, o, h)
|
||||
synctest.Wait()
|
||||
f.publish(Message{Event: EventMessageDelete, SequenceID: "x"})
|
||||
f.publish(Message{Event: EventPollRequest})
|
||||
last := f.publish(Message{Message: base64.StdEncoding.EncodeToString([]byte{0, 1}), Encoding: "base64"})
|
||||
synctest.Wait()
|
||||
stop()
|
||||
if got := h.printed(); len(got) != 0 {
|
||||
t.Errorf("printed %v", got)
|
||||
}
|
||||
if st, _ := loadState(o.StateFile); st.Cursor != last.Time || len(st.Seen) != 3 {
|
||||
t.Errorf("state %+v", st)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A line longer than 1 MiB, and one that is not JSON, are skipped with a
|
||||
// warning; the stream goes on.
|
||||
func TestBadLinesSkipped(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
var logs logBuffer
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.Logger = debugLogger(&logs)
|
||||
_, stop := start(t, o, h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
f.publish(Message{Title: strings.Repeat("x", maxLine)})
|
||||
ok := f.publish(Message{Title: "fine"})
|
||||
synctest.Wait()
|
||||
if got := h.printed(); !slices.Equal(got, []string{ok.ID}) {
|
||||
t.Errorf("printed %v, want only %v", got, ok.ID)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "longer than 1 MiB") {
|
||||
t.Errorf("no warning in %q", logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Over the budget, messages are held and print on one digest when there is
|
||||
// room; priority 5 always prints.
|
||||
func TestRateLimitDigest(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
s, stop := start(t, testOptions(f, t.TempDir()), h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
var ids []string
|
||||
for i := range 8 {
|
||||
ids = append(ids, f.publish(Message{Title: fmt.Sprintf("m%d", i), RawPriority: 4}).ID)
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
urgent := f.publish(Message{Title: "urgent", RawPriority: 5})
|
||||
synctest.Wait()
|
||||
if got, want := h.printed(), append(slices.Clone(ids[:5]), urgent.ID); !slices.Equal(got, want) {
|
||||
t.Fatalf("printed %v, want the first five and the urgent one, %v", got, want)
|
||||
}
|
||||
if st := s.Status(); st.Digested != 3 || st.Held != 3 || st.Printed != 6 {
|
||||
t.Errorf("status %+v", st)
|
||||
}
|
||||
|
||||
// The first card printed at 0 s, so the window has room at 10 min.
|
||||
time.Sleep(10*time.Minute - 80*time.Second - time.Second)
|
||||
synctest.Wait()
|
||||
if len(h.digestList()) != 0 {
|
||||
t.Fatal("the digest printed before the budget had room")
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
synctest.Wait()
|
||||
ds := h.digestList()
|
||||
if len(ds) != 1 {
|
||||
t.Fatalf("%d digests, want 1", len(ds))
|
||||
}
|
||||
d := ds[0]
|
||||
if d.Overnight || d.Count != 3 || len(d.Rows) != 3 || d.Rows[0].ID != ids[5] || d.Rows[2].Title != "m7" {
|
||||
t.Errorf("digest %+v", d)
|
||||
}
|
||||
if st := s.Status(); st.Held != 0 {
|
||||
t.Errorf("status %+v after the digest", st)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A digest lists 50 messages and counts the rest.
|
||||
func TestDigestCapsRows(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.RateLimit = 1
|
||||
_, stop := start(t, o, h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
for i := range 61 {
|
||||
f.publish(Message{Message: fmt.Sprintf("line %d\nsecond line", i)})
|
||||
}
|
||||
time.Sleep(o.RateWindow)
|
||||
synctest.Wait()
|
||||
ds := h.digestList()
|
||||
if len(ds) != 1 || ds[0].Count != 60 || len(ds[0].Rows) != MaxDigestRows {
|
||||
t.Fatalf("digests %+v", ds)
|
||||
}
|
||||
if row := ds[0].Rows[0]; row.FirstLine != "line 1" || row.Title != "" {
|
||||
t.Errorf("row %+v, want the first line of a message without a title", row)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A message of a sequence printed before is handed over as an update; the
|
||||
// first message of a sequence its publisher named prints plain; with
|
||||
// SkipUpdates an update is left out.
|
||||
func TestUpdates(t *testing.T) {
|
||||
for _, skip := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("skip=%v", skip), func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
h := &recorder{}
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.SkipUpdates = skip
|
||||
_, stop := start(t, o, h)
|
||||
defer stop()
|
||||
synctest.Wait()
|
||||
|
||||
first := f.publish(Message{Title: "download"})
|
||||
update := f.publish(Message{Title: "download done", SequenceID: first.ID})
|
||||
named := f.publish(Message{Title: "backup started", SequenceID: "backup-42"})
|
||||
namedUpdate := f.publish(Message{Title: "backup done", SequenceID: "backup-42"})
|
||||
synctest.Wait()
|
||||
|
||||
want := map[string]bool{first.ID: false, update.ID: true, named.ID: false, namedUpdate.ID: true}
|
||||
var got []string
|
||||
for _, c := range h.cardList() {
|
||||
got = append(got, c.m.ID)
|
||||
if c.updated != want[c.m.ID] {
|
||||
t.Errorf("%s updated = %v", c.m.Title, c.updated)
|
||||
}
|
||||
}
|
||||
wantIDs := []string{first.ID, update.ID, named.ID, namedUpdate.ID}
|
||||
if skip {
|
||||
wantIDs = []string{first.ID, named.ID}
|
||||
}
|
||||
if !slices.Equal(got, wantIDs) {
|
||||
t.Errorf("printed %v, want %v", got, wantIDs)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// No log line carries what a message says, nor the token.
|
||||
func TestLogsCarryNoText(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
f := newFakeServer()
|
||||
var logs logBuffer
|
||||
h := &recorder{}
|
||||
o := testOptions(f, t.TempDir())
|
||||
o.Topics = []string{"secret-topic"}
|
||||
o.Logger = debugLogger(&logs)
|
||||
o.RateLimit = 1
|
||||
o.Quiet = &Quiet{Start: Clock{0, 0}, End: Clock{0, 30}, Days: allDays, Location: time.UTC, MinPriority: 5}
|
||||
_, stop := start(t, o, h)
|
||||
synctest.Wait()
|
||||
secret := []string{"SecretTitle", "SecretBody", "SecretTag", "SecretLabel", "secret-topic"}
|
||||
h.failNext(1)
|
||||
for p := 1; p <= 5; p++ {
|
||||
f.publish(Message{Topic: "secret-topic", Title: "SecretTitle", Message: "SecretBody", Tags: []string{"SecretTag"},
|
||||
RawPriority: p, Actions: []Action{{Action: "view", Label: "SecretLabel", URL: "https://x/SecretTitle"}}})
|
||||
}
|
||||
time.Sleep(time.Hour)
|
||||
f.publish(Message{Topic: "secret-topic", Title: "SecretTitle", Message: "SecretBody"})
|
||||
f.publish(Message{Topic: "secret-topic", Title: "SecretTitle", Message: "SecretBody"})
|
||||
f.answerNext(fakeAnswer{status: http.StatusBadGateway}, fakeAnswer{status: http.StatusUnauthorized})
|
||||
f.stall()
|
||||
time.Sleep(10 * time.Minute)
|
||||
synctest.Wait()
|
||||
stop()
|
||||
out := logs.String()
|
||||
for _, want := range []string{"ntfy connection lost", "ntfy credentials refused", "ntfy message held", "ntfy digest printed", "ntfy message waits to print"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("the log lacks %q, so the test did not reach it", want)
|
||||
}
|
||||
}
|
||||
if out == "" {
|
||||
t.Fatal("nothing was logged")
|
||||
}
|
||||
for _, s := range append(secret, "tk_testtoken", "SecretTitle") {
|
||||
if strings.Contains(out, s) {
|
||||
t.Errorf("the log holds %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// allDays are the seven days of the week.
|
||||
var allDays = []time.Weekday{time.Sunday, time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday, time.Saturday}
|
||||
Reference in new issue
Block a user