Add ntfy subscriptions with digests, quiet hours and a cut feed
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s

[[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:
57_WolveandClaude Opus 5.5 committed 2026-11-30 17:50:23 -06:00
1 parent 1335ed0687
commit fb76284129
52 files changed
+6464 -390

No files matched your search

+471
View File
@@ -0,0 +1,471 @@
package ntfy
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
)
// fakeServer is an ntfy server in memory, for tests in a synctest bubble.
// It answers the stream and the credentials check through RoundTrip: an
// open event, then the stored messages since the request's since, then
// each message as it is published, with keepalives in between. Like ntfy,
// since takes messages dated at or after it.
type fakeServer struct {
keepalive time.Duration
// skew is how far the server's clock is ahead of the host's.
skew time.Duration
// authFails makes the credentials check fail as an unreachable server
// does, and authSkew puts its answer's Date this far off the server's
// clock.
authFails bool
authSkew time.Duration
// noDate leaves the Date header out of the stream's answer, and
// dateSkew puts it this far off the server's clock, as a proxy in front
// of it with a clock of its own does.
noDate bool
dateSkew time.Duration
// openNoTime leaves the open event without a time.
openNoTime bool
mu sync.Mutex
messages []Message
conns map[*fakeConn]bool
requests []*http.Request
streamAt []time.Time
answers []fakeAnswer
authStatus int
nextID int
}
// fakeAnswer is an answer other than the stream, for a request to it.
type fakeAnswer struct {
status int
retryAfter string
}
func newFakeServer() *fakeServer {
return &fakeServer{keepalive: 45 * time.Second, conns: make(map[*fakeConn]bool)}
}
func (f *fakeServer) RoundTrip(req *http.Request) (*http.Response, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.requests = append(f.requests, req)
if strings.HasSuffix(req.URL.Path, "/auth") {
if f.authFails {
return nil, errors.New("connection refused")
}
status := f.authStatus
if status == 0 {
status = http.StatusOK
}
resp := answer(req, status, "")
resp.Header.Set("Date", time.Now().Add(f.skew+f.authSkew).UTC().Format(http.TimeFormat))
return resp, nil
}
f.streamAt = append(f.streamAt, time.Now())
if len(f.answers) > 0 {
a := f.answers[0]
f.answers = f.answers[1:]
return answer(req, a.status, a.retryAfter), nil
}
if err := req.Context().Err(); err != nil {
return nil, err
}
path := strings.TrimSuffix(strings.TrimPrefix(req.URL.Path, "/"), "/json")
c := &fakeConn{
f: f,
ctx: req.Context(),
topics: strings.Split(path, ","),
wake: make(chan struct{}, 1),
closed: make(chan struct{}),
next: len(f.messages),
keepalive: time.Now().Add(f.keepalive),
}
if p := req.URL.Query().Get("priority"); p != "" {
for _, s := range strings.Split(p, ",") {
n, _ := strconv.Atoi(s)
c.priorities = append(c.priorities, n)
}
}
open := Message{ID: f.id(), Time: time.Now().Add(f.skew).Unix(), Event: EventOpen, Topic: path}
if f.openNoTime {
open.Time = 0
}
c.queue = append(c.queue, open)
if s := req.URL.Query().Get("since"); s != "" {
since, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return answer(req, http.StatusBadRequest, ""), nil
}
for _, m := range f.messages {
if m.Time >= since && c.wants(m) {
c.queue = append(c.queue, m)
}
}
}
f.conns[c] = true
h := http.Header{}
if !f.noDate {
h.Set("Date", time.Now().Add(f.skew+f.dateSkew).UTC().Format(http.TimeFormat))
}
return &http.Response{StatusCode: http.StatusOK, Header: h, Body: c, Request: req}, nil
}
func answer(req *http.Request, status int, retryAfter string) *http.Response {
h := http.Header{}
if retryAfter != "" {
h.Set("Retry-After", retryAfter)
}
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(`{"success":true}`)), Request: req}
}
// id returns a new message ID. f.mu is held.
func (f *fakeServer) id() string {
f.nextID++
return fmt.Sprintf("m%05d", f.nextID)
}
// publish stores m, dated now, and sends it to the open connections. It
// returns m as stored.
func (f *fakeServer) publish(m Message) Message {
f.mu.Lock()
defer f.mu.Unlock()
if m.ID == "" {
m.ID = f.id()
}
if m.Time == 0 {
m.Time = time.Now().Add(f.skew).Unix()
}
if m.Event == "" {
m.Event = EventMessage
}
if m.Topic == "" {
m.Topic = "alerts"
}
f.messages = append(f.messages, m)
f.wakeAll()
return m
}
// drop ends every open connection, as a server restart does.
func (f *fakeServer) drop() {
f.mu.Lock()
defer f.mu.Unlock()
for c := range f.conns {
c.ended = true
}
f.wakeAll()
}
// stall makes every open connection go silent.
func (f *fakeServer) stall() {
f.mu.Lock()
defer f.mu.Unlock()
for c := range f.conns {
c.stalled = true
}
}
// answerNext answers the next requests to the stream with as.
func (f *fakeServer) answerNext(as ...fakeAnswer) {
f.mu.Lock()
defer f.mu.Unlock()
f.answers = append(f.answers, as...)
}
// setAuth sets the status the credentials check answers with.
func (f *fakeServer) setAuth(status int) {
f.mu.Lock()
defer f.mu.Unlock()
f.authStatus = status
}
// streams returns the requests to the stream, in order.
func (f *fakeServer) streams() []*http.Request {
f.mu.Lock()
defer f.mu.Unlock()
var out []*http.Request
for _, r := range f.requests {
if strings.HasSuffix(r.URL.Path, "/json") {
out = append(out, r)
}
}
return out
}
// streamTimes returns when each request to the stream came.
func (f *fakeServer) streamTimes() []time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return slices.Clone(f.streamAt)
}
// open returns how many connections are open.
func (f *fakeServer) open() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.conns)
}
// wakeAll wakes every connection. f.mu is held.
func (f *fakeServer) wakeAll() {
for c := range f.conns {
select {
case c.wake <- struct{}{}:
default:
}
}
}
// fakeConn is one stream, read by the subscriber.
type fakeConn struct {
f *fakeServer
ctx context.Context
topics []string
priorities []int
wake chan struct{}
closed chan struct{}
closeOnce sync.Once
// Guarded by f.mu.
queue []Message
next int
ended bool
stalled bool
keepalive time.Time
buf []byte
}
// wants reports whether the connection's topics and priorities take m.
func (c *fakeConn) wants(m Message) bool {
if !slices.Contains(c.topics, m.Topic) {
return false
}
return len(c.priorities) == 0 || slices.Contains(c.priorities, m.Priority())
}
// line returns the next line to send, if one is ready, and whether the
// stream has ended.
func (c *fakeConn) line() (line []byte, ended bool, wait time.Duration) {
c.f.mu.Lock()
defer c.f.mu.Unlock()
if c.ended {
return nil, true, 0
}
if c.stalled {
return nil, false, -1
}
for len(c.queue) == 0 && c.next < len(c.f.messages) {
m := c.f.messages[c.next]
c.next++
if c.wants(m) {
c.queue = append(c.queue, m)
}
}
if len(c.queue) > 0 {
m := c.queue[0]
c.queue = c.queue[1:]
data, _ := json.Marshal(m)
return append(data, '\n'), false, 0
}
now := time.Now()
if !now.Before(c.keepalive) {
c.keepalive = now.Add(c.f.keepalive)
data, _ := json.Marshal(Message{ID: c.f.id(), Time: now.Add(c.f.skew).Unix(), Event: EventKeepalive, Topic: strings.Join(c.topics, ",")})
return append(data, '\n'), false, 0
}
return nil, false, c.keepalive.Sub(now)
}
func (c *fakeConn) Read(p []byte) (int, error) {
for len(c.buf) == 0 {
line, ended, wait := c.line()
if ended {
return 0, io.EOF
}
if line != nil {
c.buf = line
break
}
var timer <-chan time.Time
if wait >= 0 {
timer = time.After(wait)
}
select {
case <-c.wake:
case <-timer:
case <-c.ctx.Done():
return 0, c.ctx.Err()
case <-c.closed:
return 0, errors.New("read on closed body")
}
}
n := copy(p, c.buf)
c.buf = c.buf[n:]
return n, nil
}
func (c *fakeConn) Close() error {
c.closeOnce.Do(func() {
close(c.closed)
c.f.mu.Lock()
delete(c.f.conns, c)
c.f.mu.Unlock()
})
return nil
}
// errBusy stands for a full print queue.
var errBusy = errors.New("print queue is full")
// recorder is a Handler that records what it is given. fail makes the
// next calls fail with errBusy.
type recorder struct {
mu sync.Mutex
cards []card
digests []Digest
fail int
}
// card is a message the recorder printed.
type card struct {
m Message
updated bool
at time.Time
}
func (h *recorder) Message(_ context.Context, m Message, updated bool) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.fail > 0 {
h.fail--
return errBusy
}
h.cards = append(h.cards, card{m: m, updated: updated, at: time.Now()})
return nil
}
func (h *recorder) Digest(_ context.Context, d Digest) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.fail > 0 {
h.fail--
return errBusy
}
d.Rows = slices.Clone(d.Rows)
h.digests = append(h.digests, d)
return nil
}
func (h *recorder) failNext(n int) {
h.mu.Lock()
defer h.mu.Unlock()
h.fail = n
}
// printed returns the IDs of the messages printed on cards, in order.
func (h *recorder) printed() []string {
h.mu.Lock()
defer h.mu.Unlock()
var ids []string
for _, c := range h.cards {
ids = append(ids, c.m.ID)
}
return ids
}
func (h *recorder) cardList() []card {
h.mu.Lock()
defer h.mu.Unlock()
return slices.Clone(h.cards)
}
func (h *recorder) digestList() []Digest {
h.mu.Lock()
defer h.mu.Unlock()
return slices.Clone(h.digests)
}
// testOptions returns the options of a subscription to topic alerts of f,
// keeping its state in dir.
func testOptions(f *fakeServer, dir string) Options {
return Options{
Name: "home",
Server: "https://ntfy.example.com",
Topics: []string{"alerts"},
Token: "tk_testtoken",
MinPriority: 1,
MaxBacklog: time.Hour,
RateLimit: 5,
RateWindow: 10 * time.Minute,
BypassPriority: 5,
Keepalive: 45 * time.Second,
StateFile: filepath.Join(dir, "ntfy-home.json"),
Transport: f,
}
}
// start runs a subscriber with options o and handler h in the background.
// The func it returns stops it and waits for Run to return.
func start(t *testing.T, o Options, h Handler) (*Subscriber, func()) {
t.Helper()
s, err := New(o)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
if err := s.Run(ctx, h); err != nil {
t.Errorf("Run = %v, want nil", err)
}
}()
return s, func() {
cancel()
<-done
}
}
// logBuffer collects log output safely across goroutines.
type logBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *logBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *logBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// debugLogger returns a logger that writes every level to b.
func debugLogger(b *logBuffer) *slog.Logger {
return slog.New(slog.NewTextHandler(b, &slog.HandlerOptions{Level: slog.LevelDebug}))
}
+91
View File
@@ -0,0 +1,91 @@
package ntfy
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"runtime"
"runtime/pprof"
"strings"
"sync/atomic"
"testing"
"time"
)
// Reconnecting over real sockets leaves no goroutine behind. The synctest
// tests cover the subscription's own goroutines on a fake transport; this
// one covers net/http's, which a response body left open would leak. The
// server ends streams at once or after a pause, answers 502 to every third
// request, and keeps the last stream open until the client leaves.
func TestNoGoroutineLeakOverRealConnections(t *testing.T) {
const cycles = 30
before := runtime.NumGoroutine()
var requests atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/auth") {
fmt.Fprint(w, `{"success":true}`)
return
}
n := requests.Add(1)
if n%3 == 0 && n < cycles {
http.Error(w, "bad gateway", http.StatusBadGateway)
return
}
now := time.Now().Unix()
fmt.Fprintf(w, "{\"id\":\"o%d\",\"time\":%d,\"event\":\"open\",\"topic\":\"alerts\"}\n", n, now)
fmt.Fprintf(w, "{\"id\":\"m%d\",\"time\":%d,\"event\":\"message\",\"topic\":\"alerts\",\"title\":\"t\"}\n", n, now)
w.(http.Flusher).Flush()
switch {
case n >= cycles:
<-r.Context().Done()
case n%2 == 0:
// The client is reading when the stream ends.
time.Sleep(5 * time.Millisecond)
}
}))
o := Options{
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, MinPriority: 1,
MaxBacklog: time.Hour, RateLimit: 1000, RateWindow: time.Minute, BypassPriority: 5,
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json",
}
s, err := New(o)
if err != nil {
t.Fatal(err)
}
s.backoff = []time.Duration{10 * time.Millisecond}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
h := &recorder{}
go func() {
defer close(done)
_ = s.Run(ctx, h)
}()
deadline := time.Now().Add(20 * time.Second)
for requests.Load() < cycles && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if requests.Load() < cycles {
t.Fatalf("only %d requests in 20 s", requests.Load())
}
time.Sleep(50 * time.Millisecond) // the last stream is open and read
cancel()
<-done
srv.Close()
if got := len(h.printed()); got < cycles/2 {
t.Errorf("printed %d messages, want the %d or so the streams carried", got, cycles*2/3)
}
deadline = time.Now().Add(5 * time.Second)
for runtime.NumGoroutine() > before && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if after := runtime.NumGoroutine(); after > before {
var buf bytes.Buffer
_ = pprof.Lookup("goroutine").WriteTo(&buf, 1)
t.Errorf("%d goroutines before, %d after:\n%s", before, after, buf.String())
}
}
+24 -1
View File
@@ -1,8 +1,12 @@
// Package ntfy holds the wire types of ntfy (https://ntfy.sh), the
// notification service: the message objects its subscribe API streams, one
// JSON object per line.
// JSON object per line. Its Subscriber reads that stream from a server and
// hands each message to be printed, keeping to a paper budget and to quiet
// hours.
package ntfy
import "strings"
// Event types of a Message.
const (
EventOpen = "open"
@@ -74,6 +78,25 @@ func (m Message) Priority() int {
return m.RawPriority
}
// Printable reports whether m carries a notification with a text body: an
// event message, or a message without an event, that is not base64.
func (m Message) Printable() bool {
switch m.Event {
case "", EventMessage:
return !strings.EqualFold(m.Encoding, EncodingBase64)
}
return false
}
// Sequence names the notification m belongs to: its SequenceID, or its ID
// when it has none. Messages of one sequence update one notification.
func (m Message) Sequence() string {
if m.SequenceID != "" {
return m.SequenceID
}
return m.ID
}
// Action is a button on a notification. View actions open URL; http
// actions send a request with Method, Headers and Body; broadcast actions
// send an Android intent with Extras; copy actions copy Value to the
+99
View File
@@ -0,0 +1,99 @@
package ntfy
import (
"slices"
"time"
)
// Clock is a time of day.
type Clock struct {
Hour, Minute int
}
// Quiet are quiet hours: a window each day in which messages below
// MinPriority are held for a digest, or dropped.
type Quiet struct {
// Start and End are the window's times of day in Location. An End
// at or before Start ends the window on the next day.
Start, End Clock
// Days are the days a window starts on.
Days []time.Weekday
// Location is the zone of Start and End; nil means local time.
Location *time.Location
// MinPriority is the lowest priority that prints during the window.
MinPriority int
// Drop leaves out the messages held back, which otherwise print on
// one digest when the window ends.
Drop bool
}
// window returns the end of the quiet window t falls in, and whether it
// falls in one. The window's bounds are the instants the zone's clocks
// show its times of day (wallTime), so a window that crosses midnight or
// a change of clocks keeps them: 22:00 to 07:00 is nine hours on most
// nights, eight on the night clocks go forward. A bound the clocks skip is
// the first instant after the gap.
func (q *Quiet) window(t time.Time) (end time.Time, in bool) {
if q == nil {
return time.Time{}, false
}
loc := q.Location
if loc == nil {
loc = time.Local
}
t = t.In(loc)
// A window that holds t started on t's day or on the day before. The
// day is taken at noon: in a zone whose clocks go forward at midnight,
// midnight does not exist, and time.Date moves it by the gap, which
// can put it on the day before.
for back := 0; back <= 1; back++ {
day := time.Date(t.Year(), t.Month(), t.Day()-back, 12, 0, 0, 0, loc)
if !slices.Contains(q.Days, day.Weekday()) {
continue
}
start, end := q.bounds(day, loc)
if !t.Before(start) && t.Before(end) {
return end, true
}
}
return time.Time{}, false
}
// bounds returns the start and end of the window that starts on day.
func (q *Quiet) bounds(day time.Time, loc *time.Location) (start, end time.Time) {
y, m, d := day.Date()
start = wallTime(y, m, d, q.Start, loc)
endDay := d
if q.End.Hour*60+q.End.Minute <= q.Start.Hour*60+q.Start.Minute {
endDay++
}
return start, wallTime(y, m, endDay, q.End, loc)
}
// wallTime returns the instant the clocks in loc show c on the given day,
// which may be one past the end of a month. A time the clocks skip, when
// they go forward, is the first instant after the gap; time.Date moves it
// by the gap's length, to before the gap or after it depending on the
// zone (west of UTC, a skipped midnight lands on the evening before). A
// time the clocks show twice is the one time.Date gives.
func wallTime(y int, m time.Month, d int, c Clock, loc *time.Location) time.Time {
y, m, d = time.Date(y, m, d, 12, 0, 0, 0, loc).Date()
t := time.Date(y, m, d, c.Hour, c.Minute, 0, 0, loc)
asked := time.Date(y, m, d, c.Hour, c.Minute, 0, 0, time.UTC)
shown := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, time.UTC)
start, end := t.ZoneBounds()
switch {
case shown.Equal(asked):
return t
case shown.Before(asked):
// t is before the gap: the gap ends where t's zone period ends.
return end
default:
// t is after the gap: the gap ends where t's zone period starts.
return start
}
}
+286
View File
@@ -0,0 +1,286 @@
package ntfy
import (
"slices"
"testing"
"testing/synctest"
"time"
// Embeds the zone database, so that IANA names load on any host.
_ "time/tzdata"
)
func london(t *testing.T) *time.Location {
t.Helper()
loc, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
return loc
}
// nightly is 22:00 to 07:00 every day in loc.
func nightly(loc *time.Location) *Quiet {
return &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: allDays, Location: loc, MinPriority: 5}
}
func TestQuietWindow(t *testing.T) {
loc := london(t)
at := func(y int, m time.Month, d, hh, mm int) time.Time { return time.Date(y, m, d, hh, mm, 0, 0, loc) }
tests := []struct {
name string
q *Quiet
t time.Time
in bool
wantEnd time.Time
}{
{"evening before", nightly(loc), at(2026, 11, 30, 21, 59), false, time.Time{}},
{"start", nightly(loc), at(2026, 11, 30, 22, 0), true, at(2026, 12, 1, 7, 0)},
{"after midnight", nightly(loc), at(2026, 12, 1, 3, 0), true, at(2026, 12, 1, 7, 0)},
{"end", nightly(loc), at(2026, 12, 1, 7, 0), false, time.Time{}},
{"daytime window", &Quiet{Start: Clock{13, 0}, End: Clock{14, 30}, Days: allDays, Location: loc}, at(2026, 12, 1, 14, 0), true, at(2026, 12, 1, 14, 30)},
{"daytime window over", &Quiet{Start: Clock{13, 0}, End: Clock{14, 30}, Days: allDays, Location: loc}, at(2026, 12, 1, 14, 30), false, time.Time{}},
// Friday's window runs into Saturday morning; Saturday's does not
// start.
{"friday night", &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: []time.Weekday{time.Friday}, Location: loc}, at(2026, 12, 5, 3, 0), true, at(2026, 12, 5, 7, 0)},
{"saturday night", &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: []time.Weekday{time.Friday}, Location: loc}, at(2026, 12, 5, 23, 0), false, time.Time{}},
{"no quiet hours", nil, at(2026, 12, 1, 3, 0), false, time.Time{}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
end, in := tt.q.window(tt.t)
if in != tt.in || !end.Equal(tt.wantEnd) {
t.Errorf("window(%s) = %s, %v; want %s, %v", tt.t, end, in, tt.wantEnd, tt.in)
}
})
}
}
// On the nights the clocks change, the window keeps its times of day: it
// lasts eight hours when they go forward and ten when they go back.
func TestQuietWindowAcrossClockChanges(t *testing.T) {
loc := london(t)
q := nightly(loc)
for _, tt := range []struct {
night time.Time
hours time.Duration
}{
{time.Date(2026, 3, 28, 23, 0, 0, 0, loc), 8},
{time.Date(2026, 10, 24, 23, 0, 0, 0, loc), 10},
} {
end, in := q.window(tt.night)
if !in {
t.Fatalf("%s is not in the window", tt.night)
}
start := time.Date(tt.night.Year(), tt.night.Month(), tt.night.Day(), 22, 0, 0, 0, loc)
if got := end.Sub(start); got != tt.hours*time.Hour || end.In(loc).Hour() != 7 {
t.Errorf("night of %s: window %s to %s, %s long; want %dh ending 07:00", tt.night.Format("2 Jan"), start, end, got, tt.hours)
}
// Just after 07:00 local time is outside the window.
if _, in := q.window(end.Add(time.Second)); in {
t.Errorf("%s is still in the window", end.Add(time.Second))
}
if _, in := q.window(end.Add(-time.Second)); !in {
t.Errorf("%s is not in the window", end.Add(-time.Second))
}
}
}
// In zones whose clocks go forward at midnight, the evening of that day
// still has its window.
func TestQuietWindowWhenMidnightIsSkipped(t *testing.T) {
for _, tt := range []struct {
zone string
y int
m time.Month
d int
}{
{"America/Santiago", 2026, time.September, 6},
{"America/Havana", 2026, time.March, 8},
} {
t.Run(tt.zone, func(t *testing.T) {
loc, err := time.LoadLocation(tt.zone)
if err != nil {
t.Fatal(err)
}
if mid := time.Date(tt.y, tt.m, tt.d, 0, 0, 0, 0, loc); mid.Day() == tt.d && mid.Hour() == 0 {
t.Skipf("midnight of %d-%02d-%02d exists in this zone database", tt.y, tt.m, tt.d)
}
q := nightly(loc)
evening := time.Date(tt.y, tt.m, tt.d, 23, 0, 0, 0, loc)
end, in := q.window(evening)
if want := time.Date(tt.y, tt.m, tt.d+1, 7, 0, 0, 0, loc); !in || !end.Equal(want) {
t.Errorf("window(%s) = %s, %v; want the window ending %s", evening, end, in, want)
}
// The night before, which runs into the gap, is in its window too.
early := time.Date(tt.y, tt.m, tt.d, 3, 0, 0, 0, loc)
if _, in := q.window(early); !in {
t.Errorf("%s is not in the window", early)
}
// A window ending at the skipped midnight ends when the clocks
// show 01:00, the first instant after the gap, not at 23:00
// the evening before; one starting then starts at 01:00.
toMidnight := &Quiet{Start: Clock{22, 0}, End: Clock{0, 0}, Days: allDays, Location: loc}
lateEvening := time.Date(tt.y, tt.m, tt.d-1, 23, 30, 0, 0, loc)
end, in = toMidnight.window(lateEvening)
if want := time.Date(tt.y, tt.m, tt.d, 1, 0, 0, 0, loc); !in || !end.Equal(want) {
t.Errorf("window(%s) = %s, %v; want the window ending %s", lateEvening, end, in, want)
}
fromMidnight := &Quiet{Start: Clock{0, 0}, End: Clock{6, 0}, Days: allDays, Location: loc}
gapEnd := time.Date(tt.y, tt.m, tt.d, 1, 0, 0, 0, loc)
if _, in := fromMidnight.window(gapEnd.Add(-time.Second)); in {
t.Errorf("%s, before the gap ends, is in a window starting at the skipped midnight", gapEnd.Add(-time.Second))
}
if _, in := fromMidnight.window(gapEnd); !in {
t.Errorf("%s is not in a window starting at the skipped midnight", gapEnd)
}
})
}
}
func TestWallTime(t *testing.T) {
loc := london(t)
tests := []struct {
y int
m time.Month
d int
c Clock
want time.Time
}{
{2026, time.November, 30, Clock{22, 0}, time.Date(2026, 11, 30, 22, 0, 0, 0, loc)},
{2026, time.November, 31, Clock{7, 0}, time.Date(2026, 12, 1, 7, 0, 0, 0, loc)},
// 01:30 on the night clocks go forward does not exist in London.
{2026, time.March, 29, Clock{1, 30}, time.Date(2026, 3, 29, 1, 0, 0, 0, time.UTC)},
// 01:30 on the night they go back exists twice; time.Date's
// choice, the second, stands.
{2026, time.October, 25, Clock{1, 30}, time.Date(2026, 10, 25, 1, 30, 0, 0, time.UTC)},
}
for _, tt := range tests {
if got := wallTime(tt.y, tt.m, tt.d, tt.c, loc); !got.Equal(tt.want) {
t.Errorf("wallTime(%d-%02d-%02d %02d:%02d) = %s, want %s", tt.y, tt.m, tt.d, tt.c.Hour, tt.c.Minute, got, tt.want)
}
}
}
// sleepUntil advances the bubble's clock to t.
func sleepUntil(t time.Time) {
time.Sleep(time.Until(t))
synctest.Wait()
}
// During quiet hours a priority 3 message is held, a priority 5 message
// prints at once, and the held one prints on an overnight digest when the
// window ends, on the night the clocks go forward too.
func TestQuietHoursHoldForTheMorning(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 3, 28, 21, 0, 0, 0, loc))
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.Quiet = nightly(loc)
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
sleepUntil(time.Date(2026, 3, 28, 23, 0, 0, 0, loc))
held := f.publish(Message{Title: "backup finished", RawPriority: 3})
sleepUntil(time.Date(2026, 3, 28, 23, 30, 0, 0, loc))
urgent := f.publish(Message{Title: "grafana is DOWN", RawPriority: 5})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{urgent.ID}) {
t.Fatalf("printed %v during quiet hours, want only the urgent %v", got, urgent.ID)
}
if st := s.Status(); st.Held != 1 || st.Digested != 1 {
t.Errorf("status %+v", st)
}
// 07:00 BST is 06:00 UTC.
end := time.Date(2026, 3, 29, 7, 0, 0, 0, loc)
sleepUntil(end.Add(-time.Second))
if len(h.digestList()) != 0 {
t.Fatal("the digest printed before the window ended")
}
sleepUntil(end.Add(time.Second))
ds := h.digestList()
if len(ds) != 1 {
t.Fatalf("%d digests at the end of the window, want 1", len(ds))
}
if d := ds[0]; !d.Overnight || d.Count != 1 || d.Rows[0].ID != held.ID {
t.Errorf("digest %+v", d)
}
after := f.publish(Message{Title: "morning", RawPriority: 3})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{urgent.ID, after.ID}) {
t.Errorf("printed %v after the window", got)
}
})
}
// With action drop, messages below the window's priority are left out.
func TestQuietHoursDrop(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 11, 30, 23, 0, 0, 0, loc))
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.Quiet = nightly(loc)
o.Quiet.Drop = true
o.Quiet.MinPriority = 4
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
f.publish(Message{Title: "dropped", RawPriority: 3})
high := f.publish(Message{Title: "high", RawPriority: 4})
sleepUntil(time.Date(2026, 12, 1, 8, 0, 0, 0, loc))
if got := h.printed(); !slices.Equal(got, []string{high.ID}) {
t.Errorf("printed %v, want only %v", got, high.ID)
}
if ds := h.digestList(); len(ds) != 0 {
t.Errorf("digests %+v, want none", ds)
}
if st := s.Status(); st.Held != 0 || st.Digested != 0 {
t.Errorf("status %+v", st)
}
})
}
// Messages held overnight are saved with the state, so a restart during
// the night still prints them in the morning.
func TestQuietHoursHeldSurviveRestart(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 11, 30, 23, 0, 0, 0, loc))
dir := t.TempDir()
f := newFakeServer()
o := testOptions(f, dir)
o.Quiet = nightly(loc)
_, stop := start(t, o, &recorder{})
synctest.Wait()
held := f.publish(Message{Title: "held", RawPriority: 2, SequenceID: "nightly-backup"})
synctest.Wait()
stop()
sleepUntil(time.Date(2026, 12, 1, 2, 0, 0, 0, loc))
h := &recorder{}
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
if st := s.Status(); st.Held != 1 {
t.Errorf("status %+v after the restart", st)
}
update := f.publish(Message{Title: "held again", RawPriority: 2, SequenceID: "nightly-backup"})
sleepUntil(time.Date(2026, 12, 1, 7, 0, 1, 0, loc))
ds := h.digestList()
if len(ds) != 1 || ds[0].Count != 2 || ds[0].Rows[0].ID != held.ID || ds[0].Rows[1].ID != update.ID {
t.Fatalf("digests %+v", ds)
}
if ds[0].Rows[0].Updated || !ds[0].Rows[1].Updated {
t.Errorf("rows %+v: want the second marked as an update", ds[0].Rows)
}
})
}
+172
View File
@@ -0,0 +1,172 @@
package ntfy
import (
"strings"
"time"
"unicode/utf8"
)
// MaxDigestRows is how many held messages a digest lists; it counts the
// rest.
const MaxDigestRows = 50
// maxRowText is the most bytes of a title or a first line a digest row
// keeps.
const maxRowText = 256
// budget is the paper budget: at most limit receipts in any window. It
// keeps the times of the last limit receipts.
type budget struct {
limit int
window time.Duration
prints []time.Time
}
// room reports whether a receipt may print at now.
func (b *budget) room(now time.Time) bool {
b.forget(now)
return len(b.prints) < b.limit
}
// next returns when the budget next has room, or now if it has.
func (b *budget) next(now time.Time) time.Time {
if b.room(now) {
return now
}
return b.prints[0].Add(b.window)
}
// spend records a receipt printed at now.
func (b *budget) spend(now time.Time) {
b.forget(now)
b.prints = append(b.prints, now)
if extra := len(b.prints) - b.limit; extra > 0 {
b.prints = b.prints[extra:]
}
}
// forget drops the receipts older than the window. A receipt dated after
// now, as after the clock was set back, counts as printed now.
func (b *budget) forget(now time.Time) {
i := 0
for i < len(b.prints) && !now.Before(b.prints[i].Add(b.window)) {
i++
}
b.prints = b.prints[i:]
for j, t := range b.prints {
if t.After(now) {
b.prints[j] = now
}
}
}
// DigestRow is a held message, as a digest lists it.
type DigestRow struct {
ID string `json:"id"`
// Time is when the message was published, in Unix seconds.
Time int64 `json:"time"`
Topic string `json:"topic,omitempty"`
Title string `json:"title,omitempty"`
Tags []string `json:"tags,omitempty"`
// FirstLine is the first line of the message's text, kept when it has
// no title, and Markdown is set when that text is markdown.
FirstLine string `json:"first_line,omitempty"`
Markdown bool `json:"markdown,omitempty"`
Priority int `json:"priority,omitempty"`
// Updated is set when the message replaces one printed before.
Updated bool `json:"updated,omitempty"`
}
// Digest is the messages held back, printed on one receipt.
type Digest struct {
// Overnight is set when quiet hours held any of the messages.
Overnight bool
// Rows are the first MaxDigestRows messages held, in the order they
// arrived.
Rows []DigestRow
// Count is how many messages were held, the rows included.
Count int
// Since is when the first message was held, and Until when the digest
// was made.
Since, Until time.Time
}
// held are the messages held for the next digest. It is saved with the
// subscription's state.
type held struct {
Rows []DigestRow `json:"rows"`
Count int `json:"count"`
Overnight bool `json:"overnight,omitempty"`
// Since is when the first message was held, in Unix seconds.
Since int64 `json:"since"`
}
// add holds m, and reports whether it got a row; overnight says that
// quiet hours held it.
func (h *held) add(m Message, updated, overnight bool, now time.Time) bool {
if h.Count == 0 {
h.Since = now.Unix()
}
h.Count++
h.Overnight = h.Overnight || overnight
if len(h.Rows) >= MaxDigestRows {
return false
}
row := DigestRow{
ID: m.ID,
Time: m.Time,
Topic: m.Topic,
Title: cutText(m.Title),
Tags: m.Tags,
Priority: m.Priority(),
Updated: updated,
}
if strings.TrimSpace(row.Title) == "" {
row.FirstLine = cutText(firstLine(m.Message))
row.Markdown = strings.EqualFold(m.ContentType, ContentTypeMarkdown)
}
h.Rows = append(h.Rows, row)
return true
}
// digest returns the held messages as a digest made at now.
func (h *held) digest(now time.Time) Digest {
return Digest{
Overnight: h.Overnight,
Rows: h.Rows,
Count: h.Count,
Since: time.Unix(h.Since, 0),
Until: now,
}
}
// firstLine returns the first line of s that is not blank.
func firstLine(s string) string {
for line := range strings.Lines(s) {
if line = strings.TrimSpace(line); line != "" {
return line
}
}
return ""
}
// cutText returns s cut to maxRowText bytes, on a whole character.
func cutText(s string) string {
if len(s) <= maxRowText {
return s
}
end := maxRowText
for end > 0 && !utf8.RuneStart(s[end]) {
end--
}
return s[:end]
}
+88
View File
@@ -0,0 +1,88 @@
package ntfy
import (
"fmt"
"strings"
"testing"
"time"
)
// The budget allows limit receipts in any window, not limit per refill: a
// sixth receipt waits until the first is a whole window old.
func TestBudget(t *testing.T) {
t0 := time.Date(2026, 11, 30, 21, 0, 0, 0, time.UTC)
b := budget{limit: 5, window: 10 * time.Minute}
for i := range 5 {
now := t0.Add(time.Duration(i) * time.Minute)
if !b.room(now) {
t.Fatalf("no room for receipt %d", i+1)
}
b.spend(now)
}
at := t0.Add(5 * time.Minute)
if b.room(at) {
t.Fatal("room for a sixth receipt within the window")
}
if next := b.next(at); !next.Equal(t0.Add(10 * time.Minute)) {
t.Errorf("next = %s, want when the first receipt is 10 minutes old", next)
}
if !b.room(t0.Add(10 * time.Minute)) {
t.Error("no room once the first receipt left the window")
}
// A receipt dated in the future, as after the clock went back, counts
// as printed now rather than blocking for longer than a window.
b = budget{limit: 1, window: time.Minute, prints: []time.Time{t0.Add(time.Hour)}}
if b.room(t0) {
t.Error("room with a receipt just counted")
}
if !b.room(t0.Add(time.Minute)) {
t.Error("a receipt dated in the future blocked for more than a window")
}
}
func TestRing(t *testing.T) {
var items []string
for i := range ringSize + 10 {
items = append(items, fmt.Sprint(i))
}
r := newRing(items)
if r.has("9") || !r.has("10") || !r.has(fmt.Sprint(ringSize+9)) {
t.Error("the ring kept the wrong items")
}
if got := r.list(); len(got) != ringSize || got[0] != "10" {
t.Errorf("list has %d items from %q", len(got), got[0])
}
// An item added twice stays until both copies are forgotten.
r = newRing([]string{"a", "a"})
for i := range ringSize - 1 {
r.add(fmt.Sprint(i))
}
if !r.has("a") {
t.Error("forgot a while one copy is left")
}
r.add("x")
if r.has("a") {
t.Error("remembers a after both copies left")
}
}
func TestHeldRows(t *testing.T) {
now := time.Date(2026, 11, 30, 21, 5, 0, 0, time.UTC)
var h held
h.add(Message{ID: "a", Time: now.Unix(), Title: strings.Repeat("é", 200), Tags: []string{"warning"}, RawPriority: 4}, false, false, now)
h.add(Message{ID: "b", Message: "\n \nfirst line\nsecond"}, true, true, now.Add(time.Minute))
if h.Count != 2 || !h.Overnight || h.Since != now.Unix() {
t.Errorf("held %+v", h)
}
if row := h.Rows[0]; len(row.Title) > maxRowText || !strings.HasPrefix(row.Title, "é") || row.FirstLine != "" || row.Priority != 4 {
t.Errorf("row %+v", row)
}
if row := h.Rows[1]; row.FirstLine != "first line" || !row.Updated || row.Priority != 3 {
t.Errorf("row %+v", row)
}
d := h.digest(now.Add(9 * time.Minute))
if d.Count != 2 || !d.Since.Equal(now) || !d.Until.Equal(now.Add(9*time.Minute)) || len(d.Rows) != 2 {
t.Errorf("digest %+v", d)
}
}
+76
View File
@@ -0,0 +1,76 @@
package ntfy
import (
"context"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// A redirect is never followed: not to plain http, which would send the
// token in the clear, and not to another host or port, such as the
// printer's raw port, which would print the request. The connection fails
// with an error that says so.
func TestRedirectsAreNotFollowed(t *testing.T) {
// The raw listener stands for any other address, the printer's port
// 9100 among them; it counts the connections it gets.
raw, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer raw.Close()
var dialed atomic.Int64
go func() {
for {
c, err := raw.Accept()
if err != nil {
return
}
dialed.Add(1)
_ = c.Close()
}
}()
for _, target := range []string{"http://" + raw.Addr().String() + "/x", "https://" + raw.Addr().String() + "/x"} {
t.Run(strings.SplitN(target, ":", 2)[0], func(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target, http.StatusFound)
}))
defer srv.Close()
o := Options{
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, Token: "tk_secret",
MinPriority: 1, MaxBacklog: time.Hour, RateLimit: 5, RateWindow: time.Minute, BypassPriority: 5,
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json",
Transport: srv.Client().Transport,
}
s, err := New(o)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = s.Run(ctx, &recorder{})
}()
deadline := time.Now().Add(10 * time.Second)
for s.Status().LastError == "" && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
cancel()
<-done
if st := s.Status(); st.State != StateBackoff || !strings.Contains(st.LastError, "HTTP 302: the server redirects") {
t.Errorf("status %+v, want a backoff after the 302", st)
}
if n := dialed.Load(); n != 0 {
t.Errorf("the redirect target got %d connections", n)
}
})
}
}
+381
View File
@@ -0,0 +1,381 @@
package ntfy
import (
"context"
"fmt"
"slices"
"testing"
"testing/synctest"
"time"
)
// A flood larger than the 512 IDs kept at least, inside the overlap a
// reconnect replays, still prints once: every message a replay can send
// again is remembered. Once the cursor has moved on, the state keeps the
// last 512 only.
func TestFloodInTheOverlapPrintsOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
for i := range 600 {
f.publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 5})
}
synctest.Wait()
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
if n := len(f.streams()); n != 2 {
t.Fatalf("%d stream requests, want a reconnect", n)
}
ids := h.printed()
slices.Sort(ids)
if len(ids) != 600 || len(slices.Compact(slices.Clone(ids))) != 600 {
t.Errorf("%d cards for 600 messages", len(ids))
}
if st := s.Status(); st.Printed != 600 {
t.Errorf("status %+v", st)
}
time.Sleep(10 * time.Minute)
synctest.Wait()
if st, err := loadState(o.StateFile); err != nil || len(st.Seen) != ringSize {
t.Errorf("state keeps %d IDs once the flood is out of reach, want %d (%v)", len(st.Seen), ringSize, err)
}
})
}
// A flood larger than the IDs the subscription keeps still prints once:
// when it forgets IDs a replay could send again, the next replay starts
// after them.
func TestFloodPastTheLimitPrintsOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
s, err := New(o)
if err != nil {
t.Fatal(err)
}
s.seenLimit = 600
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { defer close(done); _ = s.Run(ctx, h) }()
defer func() { cancel(); <-done }()
synctest.Wait()
for i := range 700 {
f.publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 5})
}
synctest.Wait()
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
if n := len(f.streams()); n != 2 {
t.Fatalf("%d stream requests, want a reconnect", n)
}
if got := h.printed(); len(got) != 700 {
t.Errorf("%d cards for 700 messages", len(got))
}
after := f.publish(Message{Title: "after the flood", RawPriority: 5})
synctest.Wait()
if got := h.printed(); len(got) != 701 || got[700] != after.ID {
t.Errorf("%d cards; the message after the flood did not print once", len(got))
}
})
}
// After a first start, a reconnect does not reach back before it: a
// message published shortly before the start never prints.
func TestFirstStartFloor(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
before := f.publish(Message{Title: "a minute before the start"})
time.Sleep(time.Minute)
h := &recorder{}
o := testOptions(f, t.TempDir())
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
started := time.Now().Unix()
time.Sleep(20 * time.Second)
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
streams := f.streams()
if since, ok := sinceOf(t, streams[len(streams)-1]); !ok || since != started {
t.Errorf("since = %d, %v; want the start, %d", since, ok, started)
}
if got := h.printed(); slices.Contains(got, before.ID) {
t.Errorf("printed %v, a message from before the first start", got)
}
})
}
// max_backlog is measured by the server's clock: with the host's clock ten
// hours behind it, a ten-hour outage still replays only the last hour.
func TestBacklogUsesTheServerClock(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew = 10 * time.Hour
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
// The subscription last ran ten hours ago by the server's clock.
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// max_backlog follows the stream's clock, the open event's time or else
// the answer's Date: with the host's clock hours ahead of or behind the
// server's, the host's clock never decides what a replay leaves out, and
// the floor never lands in the server's future. The credentials check
// fails here, which changes nothing, since it never tells the clock.
func TestBacklogFollowsTheStreamClock(t *testing.T) {
for _, tt := range []struct {
name string
skew time.Duration
noDate bool
}{
{"host 3 hours ahead", -3 * time.Hour, false},
{"host 10 hours behind", 10 * time.Hour, false},
{"host 10 hours behind, no Date", 10 * time.Hour, true},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew, f.authFails, f.noDate = tt.skew, true, tt.noDate
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
if err := saveState(o.StateFile, state{Cursor: serverNow() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: serverNow() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the message published during the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > serverNow() {
t.Errorf("floor %d is in the server's future, now %d (%v)", st.Floor, serverNow(), err)
}
})
})
}
}
// A keepalive's time is not taken for the server's clock: it may have
// waited in the connection while the subscription paused.
func TestKeepaliveDoesNotSetTheClock(t *testing.T) {
f := newFakeServer()
s, err := New(testOptions(f, t.TempDir()))
if err != nil {
t.Fatal(err)
}
r := s.start(&recorder{})
r.conn = &conn{since: true}
now := time.Now()
r.message(context.Background(), Message{ID: "k", Event: EventKeepalive, Time: now.Unix() - 7200}, now, now)
if r.conn.clockKnown || r.conn.checked {
t.Errorf("a keepalive set the clock: %+v", r.conn)
}
r.message(context.Background(), Message{ID: "o", Event: EventOpen, Time: now.Unix() + 60}, now, now)
if !r.conn.clockKnown || r.conn.serverTime != now.Unix()+60 || !r.conn.checked {
t.Errorf("the open event did not set the clock: %+v", r.conn)
}
}
// MaxBacklog is measured from the connection's own clock and the time
// passed since it read it, never from a clock learned before: a stale one,
// as after the host's clock was stepped, neither loses messages nor
// prints old ones. The credentials check's Date here disagrees with the
// stream by hours.
func TestBacklogIgnoresAnEarlierClock(t *testing.T) {
for _, tt := range []struct {
name string
authSkew time.Duration
}{
{"earlier clock ahead", 9 * time.Hour},
{"earlier clock behind", -3 * time.Hour},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.authSkew = tt.authSkew
o := testOptions(f, t.TempDir())
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: time.Now().Unix() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if since, ok := sinceOf(t, f.streams()[0]); !ok || since != time.Now().Unix()-2*3600-120 {
t.Errorf("since = %d, %v; want the cursor less the slack, unclamped", since, ok)
}
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the message published during the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > time.Now().Unix() {
t.Errorf("floor %d is in the server's future (%v)", st.Floor, err)
}
})
})
}
}
// ntfy's open event tells the clock, not the answer's Date, which a proxy
// in front of ntfy may write from a clock of its own: with the proxy hours
// off, the backlog is still exact, nothing new is left out and the floor
// is never in ntfy's future.
func TestBacklogPrefersTheOpenEvent(t *testing.T) {
for _, tt := range []struct {
name string
dateSkew time.Duration
}{
{"proxy 2 hours ahead", 2 * time.Hour},
{"proxy 3 hours behind", -3 * time.Hour},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.dateSkew = tt.dateSkew
o := testOptions(f, t.TempDir())
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: time.Now().Unix() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
live := f.publish(Message{Title: "live"})
synctest.Wait()
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, live.ID) || !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the live message and the one from the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > time.Now().Unix() {
t.Errorf("floor %d is in ntfy's future (%v)", st.Floor, err)
}
})
})
}
}
// The stream answer's Date alone tells the clock when the open event
// carries no time.
func TestBacklogFromTheDate(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew, f.openNoTime = 10*time.Hour, true
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// Only a message that got a row on a digest counts as printed: one held
// past the 50 rows is only counted, so a later message of its sequence is
// not marked as an update.
func TestHeldPastTheRowsIsNotPrinted(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()
f.publish(Message{Title: "takes the budget"})
for i := range MaxDigestRows + 1 {
f.publish(Message{Title: fmt.Sprintf("held %d", i), SequenceID: fmt.Sprintf("seq-%d", i)})
}
time.Sleep(o.RateWindow + time.Second)
synctest.Wait()
if ds := h.digestList(); len(ds) != 1 || ds[0].Count != MaxDigestRows+1 {
t.Fatalf("digests %+v", ds)
}
time.Sleep(o.RateWindow)
f.publish(Message{Title: "update of a row", SequenceID: "seq-0"})
time.Sleep(o.RateWindow)
f.publish(Message{Title: "update of a counted one", SequenceID: fmt.Sprintf("seq-%d", MaxDigestRows)})
synctest.Wait()
cards := h.cardList()
if len(cards) != 3 {
t.Fatalf("%d cards, want 3", len(cards))
}
if !cards[1].updated || cards[2].updated {
t.Errorf("updated = %v and %v; want only the update of a row marked", cards[1].updated, cards[2].updated)
}
})
}
+229
View File
@@ -0,0 +1,229 @@
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
}
}
}
})
}
+262
View File
@@ -0,0 +1,262 @@
package ntfy
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"time"
)
// ringSize is how many printed sequences a subscription remembers, and how
// many message IDs it keeps at least.
const ringSize = 512
// maxSeen caps the message IDs a subscription keeps, so that a flood
// cannot grow its state without bound.
const maxSeen = 20000
// stateVersion is the version of the state file's format.
const stateVersion = 1
// state is what a subscription keeps across restarts.
type state struct {
Version int `json:"version"`
// Cursor is the newest ntfy server time the subscription has dealt
// with, in Unix seconds; 0 when it has none.
Cursor int64 `json:"cursor"`
// Floor is the earliest server time a replay may start at, in Unix
// seconds: where a first start began, or where max_backlog last cut a
// replay short.
Floor int64 `json:"floor,omitempty"`
// Seen are the messages dealt with that a replay could send again,
// and at least the last ringSize, oldest first.
Seen []seenID `json:"seen"`
// Printed are the sequences of the last messages printed, on a card or
// a digest, oldest first.
Printed []string `json:"printed"`
// Prints are the times of the receipts in the paper budget, in Unix
// seconds.
Prints []int64 `json:"prints,omitempty"`
// Held are the messages waiting for the next digest.
Held *held `json:"held,omitempty"`
}
// loadState reads the state file at path. A file that does not exist
// gives an empty state. A file that cannot be read or parsed also gives an
// empty state, with the error saying why, for the caller to warn about.
func loadState(path string) (state, error) {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return state{}, nil
}
if err != nil {
return state{}, err
}
var st state
if err := json.Unmarshal(data, &st); err != nil {
return state{}, fmt.Errorf("parsing %s: %w", path, err)
}
if st.Version != stateVersion {
return state{}, fmt.Errorf("%s has version %d, want %d", path, st.Version, stateVersion)
}
if st.Held != nil && len(st.Held.Rows) > MaxDigestRows {
st.Held.Rows = st.Held.Rows[:MaxDigestRows]
}
return st, nil
}
// saveState writes st to path atomically: to a temporary file in the same
// directory, synced to disk, then renamed over path. A crash leaves the
// old file or the new one, never part of either.
func saveState(path string, st state) error {
st.Version = stateVersion
data, err := json.Marshal(st)
if err != nil {
return err
}
dir := filepath.Dir(path)
// CreateTemp makes the file readable by its owner only: held messages
// carry titles.
f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
tmp := f.Name()
_, err = f.Write(data)
if err == nil {
err = f.Sync()
}
if closeErr := f.Close(); err == nil {
err = closeErr
}
if err == nil {
err = os.Rename(tmp, path)
}
if err != nil {
_ = os.Remove(tmp)
return err
}
syncDir(dir)
return nil
}
// syncDir makes a rename in dir durable. Windows cannot open a directory
// to sync it, and its renames need no such step.
func syncDir(dir string) {
if runtime.GOOS == "windows" {
return
}
d, err := os.Open(dir)
if err != nil {
return
}
_ = d.Sync()
_ = d.Close()
}
// seenID is a message dealt with: its ID and its server time.
type seenID struct {
ID string `json:"id"`
Time int64 `json:"time"`
}
// seenSet holds the IDs of the messages dealt with, so that a message a
// replay sends again is dropped. It keeps the messages a replay could
// send, those dated at or after where a replay can start, and at least
// the last ringSize, up to limit in all.
type seenSet struct {
items []seenID
counts map[string]int
limit int
}
// newSeenSet returns a set of at most limit items holding items, oldest
// first.
func newSeenSet(items []seenID, limit int) *seenSet {
s := &seenSet{counts: make(map[string]int), limit: limit}
for _, it := range items {
s.add(it.ID, it.Time)
}
return s
}
// add records the message id of server time t. When the set is full, it
// forgets the oldest, and returns the latest server time among them, for
// the caller to keep a replay from sending them again; otherwise 0.
func (s *seenSet) add(id string, t int64) int64 {
s.items = append(s.items, seenID{ID: id, Time: t})
s.counts[id]++
extra := len(s.items) - s.limit
if extra <= 0 {
return 0
}
var latest int64
for _, it := range s.items[:extra] {
latest = max(latest, it.Time)
}
s.drop(s.items[:extra])
s.items = s.items[extra:]
return latest
}
// has reports whether id was dealt with.
func (s *seenSet) has(id string) bool {
return s.counts[id] > 0
}
// prune forgets the messages dated before start, the earliest time a
// replay can start at, apart from the last ringSize.
func (s *seenSet) prune(start int64) {
keepFrom := len(s.items) - ringSize
kept := s.items[:0]
for i, it := range s.items {
if i >= keepFrom || it.Time >= start {
kept = append(kept, it)
continue
}
s.drop([]seenID{it})
}
clear(s.items[len(kept):])
s.items = kept
}
func (s *seenSet) drop(items []seenID) {
for _, it := range items {
if s.counts[it.ID]--; s.counts[it.ID] <= 0 {
delete(s.counts, it.ID)
}
}
}
// list returns the items, oldest first.
func (s *seenSet) list() []seenID {
return append([]seenID(nil), s.items...)
}
// ring remembers the last ringSize strings added to it.
type ring struct {
items []string
counts map[string]int
}
// newRing returns a ring holding items, oldest first; only the last
// ringSize are kept.
func newRing(items []string) *ring {
r := &ring{counts: make(map[string]int)}
for _, s := range items {
r.add(s)
}
return r
}
// add remembers s, forgetting the oldest item when the ring is full. An
// item may be added more than once.
func (r *ring) add(s string) {
if len(r.items) == ringSize {
oldest := r.items[0]
r.items = r.items[1:]
if r.counts[oldest]--; r.counts[oldest] == 0 {
delete(r.counts, oldest)
}
}
r.items = append(r.items, s)
r.counts[s]++
}
// has reports whether s is remembered.
func (r *ring) has(s string) bool {
return r.counts[s] > 0
}
// list returns the items, oldest first.
func (r *ring) list() []string {
return append([]string(nil), r.items...)
}
// unixTimes returns ts in Unix seconds.
func unixTimes(ts []time.Time) []int64 {
out := make([]int64, len(ts))
for i, t := range ts {
out[i] = t.Unix()
}
return out
}
// fromUnix returns ts, in Unix seconds, as times.
func fromUnix(ts []int64) []time.Time {
out := make([]time.Time, len(ts))
for i, t := range ts {
out[i] = time.Unix(t, 0)
}
return out
}
+63
View File
@@ -0,0 +1,63 @@
package ntfy
import (
"sync"
"time"
)
// States of a subscription, as Status reports them.
const (
// StateConnecting is a subscription opening its connection.
StateConnecting = "connecting"
// StateConnected is a subscription reading its stream.
StateConnected = "connected"
// StateBackoff is a subscription waiting to reconnect after a failure.
StateBackoff = "backoff"
// StateUnauthorized is a subscription whose credentials the server
// refused; it tries again every five minutes.
StateUnauthorized = "unauthorized"
)
// Status is a snapshot of a subscription, for health checks. It holds no
// credentials and nothing a message says.
type Status struct {
Name string
State string
// ConnectedSince is when the current connection opened; zero when
// there is none.
ConnectedSince time.Time
// LastMessageAt is when the last message arrived; zero when none has.
LastMessageAt time.Time
// Printed is how many messages printed on their own card, Digested how
// many were held for a digest, and Held how many wait for the next one.
Printed int
Digested int
Held int
// LastError says why the last connection failed; "" once one opens.
LastError string
}
// status is a Status shared between the subscription and its readers.
type status struct {
mu sync.Mutex
s Status
}
func (st *status) get() Status {
st.mu.Lock()
defer st.mu.Unlock()
return st.s
}
func (st *status) update(fn func(*Status)) {
st.mu.Lock()
defer st.mu.Unlock()
fn(&st.s)
}
+970
View File
@@ -0,0 +1,970 @@
package ntfy
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math/rand/v2"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// Timing of a subscription.
const (
// stallGrace is added to twice the keepalive interval to give the time
// a connection may stay silent before it counts as stalled.
stallGrace = 15 * time.Second
// stableAfter is how long a connection must have lasted for the next
// reconnect to start the backoff from its first step.
stableAfter = 2 * time.Minute
// unauthorizedRetry is how often a subscription whose credentials were
// refused tries again.
unauthorizedRetry = 5 * time.Minute
// cursorSlack is how far before its cursor a subscription asks the
// server to start. ntfy dates a message when it arrives, before an
// attachment is stored, so a message can reach subscribers after
// others dated later; the slack catches it after a reconnect, and the
// seen IDs drop the repeats.
cursorSlack = 2 * time.Minute
// maxRetryAfter caps the wait a 429 answer asks for.
maxRetryAfter = time.Hour
// firstPrintRetry and maxPrintRetry bound the wait before a message,
// or a digest, the handler could not take is offered again.
firstPrintRetry = time.Second
maxPrintRetry = 30 * time.Second
// saveEvery is the least time between two writes of the state file.
saveEvery = time.Second
// maxWait is the longest the loop sleeps before it looks at its
// deadlines again, so that a change to the wall clock is noticed.
maxWait = time.Minute
// authTimeout bounds the credentials check at startup.
authTimeout = 30 * time.Second
)
// Limits of the stream.
const (
// maxLine is the longest line read from the stream; a longer one is
// skipped.
maxLine = 1 << 20
// userAgent is sent with every request.
userAgent = "uberbringer"
)
// defaultBackoff are the waits before successive reconnects, each with
// ±20% jitter; the last one repeats.
var defaultBackoff = []time.Duration{
5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second, time.Minute, 2 * time.Minute,
}
// errStalled ends a connection that sent nothing for too long.
var errStalled = errors.New("stalled")
// Options configure a Subscriber.
type Options struct {
// Name names the subscription in its status and its log lines.
Name string
// Server is the ntfy server's base URL, e.g. https://ntfy.sh.
Server string
// Topics are the topics read, on one connection.
Topics []string
// Token is an access token, sent as a bearer token. User and Password
// are sent with basic authentication instead. With neither, requests
// carry no credentials.
Token string
User, Password string
// MinPriority is the lowest priority read, 1-5; the server filters by
// it.
MinPriority int
// MaxBacklog is how old, by the server's clock, a missed message may
// be and still print after a restart or an outage. The replay is asked
// for in full; its older messages are left out as they arrive, once the
// connection tells the server's clock: the open event's time, or else
// the answer's Date.
MaxBacklog time.Duration
// RateLimit receipts print per RateWindow at most. Messages over it
// are held and print on one digest once there is room.
RateLimit int
RateWindow time.Duration
// BypassPriority is the lowest priority that prints at once, outside
// the rate limit.
BypassPriority int
// Keepalive is the server's keepalive interval.
Keepalive time.Duration
// Quiet are the quiet hours; nil means none.
Quiet *Quiet
// SkipUpdates leaves out a message that replaces one printed before,
// which is otherwise handed over marked as an update.
SkipUpdates bool
// StateFile is where the subscription keeps its state.
StateFile string
// Transport sends the requests. Nil means a transport with dial, TLS
// handshake and response header timeouts and no overall timeout,
// since the response is a stream.
Transport http.RoundTripper
// Logger logs the subscription's events, never what a message says.
Logger *slog.Logger
// Report receives faults that need attention, such as a state file
// that cannot be written, once each.
Report func(error)
}
// Handler prints what a subscription delivers. It is called from the
// subscription's own goroutine, one call at a time.
type Handler interface {
// Message prints m. updated is set when an earlier message of its
// sequence printed. An error means it was not printed: the subscription
// stops reading and offers it again, after 1 second, then after twice
// as long each time, up to 30 seconds.
Message(ctx context.Context, m Message, updated bool) error
// Digest prints the messages held back on one receipt. An error is
// retried as for Message, while the subscription goes on reading.
Digest(ctx context.Context, d Digest) error
}
// Subscriber reads the messages of an ntfy server's topics as they are
// published and hands them to a Handler. It reconnects after failures,
// resumes from where it stopped, drops repeats, keeps to a paper budget and
// holds messages during quiet hours.
type Subscriber struct {
o Options
streamURL string
authURL string
client *http.Client
ownedIdle func()
backoff []time.Duration
seenLimit int
logger *slog.Logger
status status
}
// New returns a subscriber with options o.
func New(o Options) (*Subscriber, error) {
u, err := url.Parse(o.Server)
switch {
case o.Name == "":
return nil, errors.New("ntfy: a subscription needs a name")
case err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https"):
return nil, fmt.Errorf("ntfy %s: the server is not an http or https URL", o.Name)
case len(o.Topics) == 0:
return nil, fmt.Errorf("ntfy %s: no topics", o.Name)
case o.RateLimit < 1 || o.RateWindow <= 0 || o.Keepalive <= 0 || o.MaxBacklog <= 0:
return nil, fmt.Errorf("ntfy %s: rate limit, rate window, keepalive and backlog must be positive", o.Name)
case o.StateFile == "":
return nil, fmt.Errorf("ntfy %s: no state file", o.Name)
}
if o.Logger == nil {
o.Logger = slog.New(slog.DiscardHandler)
}
if o.Report == nil {
o.Report = func(error) {}
}
base := strings.TrimRight(u.String(), "/") + "/" + strings.Join(o.Topics, ",")
s := &Subscriber{
o: o,
streamURL: base + "/json",
authURL: base + "/auth",
backoff: defaultBackoff,
seenLimit: maxSeen,
logger: o.Logger.With("subscription", o.Name),
ownedIdle: func() {},
}
transport := o.Transport
if transport == nil {
t := newTransport()
transport, s.ownedIdle = t, t.CloseIdleConnections
}
s.client = &http.Client{Transport: transport, CheckRedirect: refuseRedirect}
s.status.s = Status{Name: o.Name, State: StateConnecting}
return s, nil
}
// refuseRedirect makes the client return a redirect as the answer instead
// of following it. A redirect would carry the credentials to wherever it
// points, over plain http or to another host or port, and the stream read
// there would print; a 3xx is a failed connection instead.
func refuseRedirect(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
// newTransport returns a transport whose connection and header waits are
// bounded and whose body reads are not, for a stream that stays open.
func newTransport() *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
IdleConnTimeout: 90 * time.Second,
MaxIdleConns: 2,
}
}
// Status returns a snapshot of the subscription.
func (s *Subscriber) Status() Status {
return s.status.get()
}
// Run reads the subscription until ctx is cancelled, then saves its state
// and returns nil. Failures to connect or to print are retried, never
// returned.
func (s *Subscriber) Run(ctx context.Context, h Handler) error {
r := s.start(h)
defer r.stop()
r.checkAuth(ctx)
r.loop(ctx)
return nil
}
// run is one Run of a subscriber: its state and its connection. Only the
// goroutine that called Run uses it.
type run struct {
s *Subscriber
h Handler
o *Options
log *slog.Logger
cursor int64
floor int64
seen *seenSet
printed *ring
budget budget
held held
conn *conn
connectedAt time.Time
attempt int
reconnectAt time.Time
stallAt time.Time
// pending is the message the handler did not take, offered again at
// retryAt; nothing more is read until it is taken.
pending *Message
retryAt time.Time
retryDelay time.Duration
// digestAt is when a digest the handler did not take is offered again.
digestAt time.Time
digestDelay time.Duration
dirty bool
savedAt time.Time
saveFailed bool
}
// start loads the state and returns the run.
func (s *Subscriber) start(h Handler) *run {
st, err := loadState(s.o.StateFile)
if err != nil {
s.logger.Warn("ntfy state file unreadable; starting without state", "err", err)
st = state{}
}
r := &run{
s: s,
h: h,
o: &s.o,
log: s.logger,
cursor: st.Cursor,
floor: st.Floor,
seen: newSeenSet(st.Seen, s.seenLimit),
printed: newRing(st.Printed),
budget: budget{limit: s.o.RateLimit, window: s.o.RateWindow, prints: fromUnix(st.Prints)},
}
if st.Held != nil {
r.held = *st.Held
}
s.status.update(func(st *Status) { st.Held = r.held.Count })
return r
}
// stop closes the connection and saves the state.
func (r *run) stop() {
r.closeConn()
if r.dirty {
r.save(time.Now())
}
r.s.ownedIdle()
}
// loop runs the subscription until ctx is cancelled: it reads the stream,
// connects and reconnects, retries prints, prints digests and saves the
// state, each when it is due.
func (r *run) loop(ctx context.Context) {
timer := time.NewTimer(maxWait)
defer timer.Stop()
for {
now := time.Now()
r.due(ctx, now)
if ctx.Err() != nil {
return
}
timer.Reset(min(max(r.wake(now).Sub(now), 0), maxWait))
var events <-chan event
if r.conn != nil && r.pending == nil {
events = r.conn.events
}
select {
case <-ctx.Done():
return
case ev := <-events:
r.event(ctx, ev, time.Now())
case <-timer.C:
}
}
}
// due does what is due at now.
func (r *run) due(ctx context.Context, now time.Time) {
if r.pending != nil && !now.Before(r.retryAt) {
m := *r.pending
if !r.deliver(ctx, m, now) {
r.wait(m, now)
} else {
r.dealt(m)
r.pending = nil
if r.conn != nil {
r.stallAt = now.Add(r.stall())
}
}
}
r.flush(ctx, now)
if r.conn == nil && !now.Before(r.reconnectAt) && ctx.Err() == nil {
r.connect(ctx, now)
}
if r.conn != nil && r.pending == nil && !now.Before(r.stallAt) {
r.closeConn()
r.reconnect(event{err: errStalled}, now)
}
if r.dirty && !now.Before(r.savedAt.Add(saveEvery)) {
r.save(now)
}
}
// wake returns the next time something is due after now.
func (r *run) wake(now time.Time) time.Time {
next := now.Add(maxWait)
earlier := func(t time.Time) {
if t.Before(next) {
next = t
}
}
switch {
case r.pending != nil:
earlier(r.retryAt)
case r.conn != nil:
earlier(r.stallAt)
}
if r.conn == nil {
earlier(r.reconnectAt)
}
if at, ok := r.flushAt(now); ok {
earlier(at)
}
if r.dirty {
earlier(r.savedAt.Add(saveEvery))
}
return next
}
// stall is how long a connection may stay silent.
func (r *run) stall() time.Duration {
return 2*r.o.Keepalive + stallGrace
}
// event acts on what the connection's reader sent.
func (r *run) event(ctx context.Context, ev event, now time.Time) {
r.stallAt = now.Add(r.stall())
switch {
case ev.opened:
r.connectedAt = now
r.s.status.update(func(st *Status) {
st.State, st.ConnectedSince, st.LastError = StateConnected, now, ""
})
r.log.Info("ntfy connected")
// The answer's Date may come from a proxy in front of ntfy, whose
// clock is not the one ntfy dates messages by; it stands in only
// when the stream's first line does not tell ntfy's own.
r.conn.date, r.conn.dateRead = ev.date, ev.at
case ev.skipped != "":
r.log.Warn("ntfy line skipped", "reason", ev.skipped)
case ev.msg != nil:
r.message(ctx, *ev.msg, ev.at, now)
case ev.end:
r.closeConn()
r.reconnect(ev, now)
}
}
// message deals with one object of the stream, which its reader read at
// readAt.
func (r *run) message(ctx context.Context, m Message, readAt, now time.Time) {
switch m.Event {
case EventOpen:
// The open event comes first, as soon as the stream opens, so its
// time is ntfy's clock, read live; a keepalive may have waited in
// the connection while the subscription paused, so its time is not.
if !r.conn.clockKnown && m.Time > 0 {
r.conn.setClock(m.Time, readAt)
}
r.learnClock(now)
// Without since, the server replays nothing, so the time it opened
// at is where a reconnect resumes, and no replay may reach before
// it. With since, the replay follows the open event, so its time
// says nothing yet.
if !r.conn.since && r.cursor == 0 && m.Time > 0 {
r.cursor, r.floor, r.dirty = m.Time, m.Time, true
}
return
case EventKeepalive:
r.advance(m.Time)
return
}
r.learnClock(now)
if m.Time > 0 && m.Time < r.conn.oldest {
r.log.Debug("ntfy message older than max_backlog skipped", "ntfy_id", m.ID)
return
}
if m.ID != "" && r.seen.has(m.ID) {
r.log.Debug("ntfy message repeated", "ntfy_id", m.ID)
r.advance(m.Time)
return
}
if m.Printable() {
r.s.status.update(func(st *Status) { st.LastMessageAt = now })
}
if !r.deliver(ctx, m, now) {
r.wait(m, now)
return
}
r.dealt(m)
}
// deliver prints m, holds it for a digest or leaves it out, and reports
// whether it is dealt with: false when the handler did not take it.
func (r *run) deliver(ctx context.Context, m Message, now time.Time) bool {
priority := m.Priority()
if !m.Printable() || priority < r.o.MinPriority {
r.log.Debug("ntfy event skipped", "ntfy_id", m.ID, "event", m.Event)
return true
}
sequence := m.Sequence()
updated := r.printed.has(sequence)
if updated && r.o.SkipUpdates {
r.log.Debug("ntfy update skipped", "ntfy_id", m.ID)
return true
}
_, quiet := r.o.Quiet.window(now)
if quiet && priority < r.o.Quiet.MinPriority {
if r.o.Quiet.Drop {
r.log.Debug("ntfy message dropped in quiet hours", "ntfy_id", m.ID)
return true
}
r.hold(m, updated, true, now)
return true
}
if priority < r.o.BypassPriority && (!r.budget.room(now) || (r.held.Count > 0 && !quiet)) {
r.hold(m, updated, false, now)
return true
}
if err := r.h.Message(ctx, m, updated); err != nil {
if r.pending == nil {
r.log.Warn("ntfy message waits to print", "ntfy_id", m.ID, "err", err)
}
return false
}
if priority < r.o.BypassPriority {
r.budget.spend(now)
}
r.printed.add(sequence)
r.s.status.update(func(st *Status) { st.Printed++ })
return true
}
// hold keeps m for the next digest. Only a message that gets a row counts
// as printed; one past the rows is only counted on the digest.
func (r *run) hold(m Message, updated, overnight bool, now time.Time) {
if r.held.add(m, updated, overnight, now) {
r.printed.add(m.Sequence())
}
r.log.Debug("ntfy message held", "ntfy_id", m.ID, "quiet_hours", overnight)
r.s.status.update(func(st *Status) { st.Digested++; st.Held = r.held.Count })
}
// wait keeps m to offer it again later, waiting longer each time.
func (r *run) wait(m Message, now time.Time) {
if r.pending == nil {
r.retryDelay = firstPrintRetry
} else {
r.retryDelay = min(2*r.retryDelay, maxPrintRetry)
}
r.pending = &m
r.retryAt = now.Add(r.retryDelay)
}
// dealt records m as dealt with, so that it is never handled again. When
// the seen IDs are full and forget messages a replay could still send,
// the floor rises past them, so that no replay sends them again.
func (r *run) dealt(m Message) {
if m.ID != "" {
if forgot := r.seen.add(m.ID, m.Time); forgot > 0 && forgot >= r.replayStart() {
r.floor = max(r.floor, forgot+1)
}
}
r.advance(m.Time)
r.dirty = true
}
// advance moves the cursor forward to t, a server time.
func (r *run) advance(t int64) {
if t > r.cursor {
r.cursor, r.dirty = t, true
}
}
// learnClock settles the connection's clock once a line has come: ntfy's
// own, from the open event, or else the answer's Date, and applies
// MaxBacklog with it.
func (r *run) learnClock(now time.Time) {
c := r.conn
if !c.clockKnown && !c.date.IsZero() {
c.setClock(c.date.Unix(), c.dateRead)
}
r.checkBacklog(now)
}
// checkBacklog applies MaxBacklog to the connection once it has told the
// server's clock: the replay's messages older than MaxBacklog are left out
// as they arrive, and the floor rises to that time, so that they stay out.
func (r *run) checkBacklog(now time.Time) {
c := r.conn
if c == nil || c.checked || !c.clockKnown {
return
}
// The time since the server's clock was read comes from the
// monotonic clock, so a step of the host's clock cannot move it.
serverNow := c.serverTime + int64(now.Sub(c.serverRead)/time.Second)
c.checked, c.oldest = true, serverNow-int64(r.o.MaxBacklog/time.Second)
if c.oldest > r.floor {
r.floor, r.dirty = c.oldest, true
}
}
// replayStart is the earliest server time a replay can start at.
func (r *run) replayStart() int64 {
return max(r.cursor-int64(cursorSlack/time.Second), r.floor)
}
// flushAt returns when the held messages may print, if any are held.
func (r *run) flushAt(now time.Time) (time.Time, bool) {
if r.held.Count == 0 || r.pending != nil {
return time.Time{}, false
}
at := r.budget.next(now)
if end, quiet := r.o.Quiet.window(now); quiet {
at = end
}
if at.Before(r.digestAt) {
at = r.digestAt
}
return at, true
}
// flush prints the held messages on one digest when they may print.
func (r *run) flush(ctx context.Context, now time.Time) {
at, ok := r.flushAt(now)
if !ok || now.Before(at) {
return
}
if _, quiet := r.o.Quiet.window(now); quiet || !r.budget.room(now) {
return
}
if err := r.h.Digest(ctx, r.held.digest(now)); err != nil {
if r.digestAt.IsZero() {
r.digestDelay = firstPrintRetry
r.log.Warn("ntfy digest waits to print", "held", r.held.Count, "err", err)
} else {
r.digestDelay = min(2*r.digestDelay, maxPrintRetry)
}
r.digestAt = now.Add(r.digestDelay)
return
}
r.log.Debug("ntfy digest printed", "held", r.held.Count, "overnight", r.held.Overnight)
r.budget.spend(now)
r.held, r.digestAt, r.dirty = held{}, time.Time{}, true
r.s.status.update(func(st *Status) { st.Held = 0 })
}
// since returns the since parameter of the next connection: the cursor
// less the slack, but not before the floor. With no cursor there is none,
// so that only new messages are read. MaxBacklog is not applied here: the
// host's clock may be off, or may have been stepped since the server last
// told its own, so the connection applies it from the server's clock as
// it tells it (checkBacklog).
func (r *run) since() (int64, bool) {
if r.cursor == 0 {
return 0, false
}
return r.replayStart(), true
}
// request returns a GET request for rawURL with the subscription's
// credentials.
func (r *run) request(ctx context.Context, rawURL string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
switch {
case r.o.Token != "":
req.Header.Set("Authorization", "Bearer "+r.o.Token)
case r.o.User != "":
req.SetBasicAuth(r.o.User, r.o.Password)
}
return req, nil
}
// checkAuth asks the server whether the credentials may read the topics,
// so that refused credentials show at startup. Only a refusal counts:
// anything else is left to the connection to find out.
func (r *run) checkAuth(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, authTimeout)
defer cancel()
req, err := r.request(ctx, r.s.authURL)
if err != nil {
return
}
resp, err := r.s.client.Do(req)
if err != nil {
r.log.Debug("ntfy credentials check failed", "err", describe(err))
return
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
r.reconnect(event{end: true, status: resp.StatusCode}, time.Now())
}
}
// connect opens a connection, read by its own goroutine.
func (r *run) connect(ctx context.Context, now time.Time) {
query := url.Values{}
since, hasSince := r.since()
if hasSince {
query.Set("since", strconv.FormatInt(since, 10))
}
if r.o.MinPriority > 1 {
var ps []string
for p := r.o.MinPriority; p <= PriorityMax; p++ {
ps = append(ps, strconv.Itoa(p))
}
query.Set("priority", strings.Join(ps, ","))
}
rawURL := r.s.streamURL
if len(query) > 0 {
rawURL += "?" + query.Encode()
}
cctx, cancel := context.WithCancel(ctx)
req, err := r.request(cctx, rawURL)
if err != nil {
cancel()
r.reconnect(event{end: true, err: err}, now)
return
}
c := &conn{cancel: cancel, events: make(chan event), done: make(chan struct{}), since: hasSince}
go c.read(cctx, r.s.client, req)
r.conn = c
r.stallAt = now.Add(r.stall())
r.s.status.update(func(st *Status) { st.State = StateConnecting })
}
// closeConn closes the connection, if there is one, and waits for its
// reader to stop.
func (r *run) closeConn() {
if r.conn == nil {
return
}
r.conn.cancel()
<-r.conn.done
r.conn = nil
}
// reconnect sets when to connect again after the connection ended as ev
// says: Retry-After for a 429, every five minutes for refused credentials,
// and the backoff otherwise, from its first step after a stable
// connection.
func (r *run) reconnect(ev event, now time.Time) {
if !r.connectedAt.IsZero() && now.Sub(r.connectedAt) >= stableAfter {
r.attempt = 0
}
r.connectedAt = time.Time{}
state, why := StateBackoff, ""
var wait time.Duration
switch {
case ev.status == http.StatusUnauthorized || ev.status == http.StatusForbidden:
state, wait = StateUnauthorized, unauthorizedRetry
why = fmt.Sprintf("HTTP %d: the server refused the credentials", ev.status)
if ev.status == http.StatusForbidden {
why = "HTTP 403: the credentials may not read the topics"
}
case ev.status == http.StatusTooManyRequests:
why, wait = "HTTP 429: too many requests", r.nextBackoff()
if ev.retryAfter > 0 {
wait = ev.retryAfter
}
case ev.status >= 300 && ev.status < 400:
why = fmt.Sprintf("HTTP %d: the server redirects, and redirects are not followed; set server to the address it redirects to", ev.status)
wait = r.nextBackoff()
case ev.status != 0:
why, wait = fmt.Sprintf("HTTP %d", ev.status), r.nextBackoff()
case errors.Is(ev.err, errStalled):
why, wait = fmt.Sprintf("no data for %s", r.stall()), r.nextBackoff()
case ev.err != nil && !errors.Is(ev.err, io.EOF):
why, wait = describe(ev.err), r.nextBackoff()
default:
why, wait = "the server closed the stream", r.nextBackoff()
}
r.reconnectAt = now.Add(wait)
r.s.status.update(func(st *Status) {
st.State, st.ConnectedSince, st.LastError = state, time.Time{}, why
})
if state == StateUnauthorized {
r.log.Warn("ntfy credentials refused", "err", why, "retry_in", wait)
return
}
r.log.Warn("ntfy connection lost", "err", why, "retry_in", wait.Round(time.Millisecond))
}
// nextBackoff returns the wait before the next reconnect, with jitter.
func (r *run) nextBackoff() time.Duration {
d := r.s.backoff[min(r.attempt, len(r.s.backoff)-1)]
r.attempt++
return time.Duration(float64(d) * (0.8 + 0.4*rand.Float64()))
}
// save writes the state. The first failure is logged and reported; later
// ones are retried quietly until a write succeeds.
func (r *run) save(now time.Time) {
r.seen.prune(r.replayStart())
st := state{
Cursor: r.cursor,
Floor: r.floor,
Seen: r.seen.list(),
Printed: r.printed.list(),
Prints: unixTimes(r.budget.prints),
}
if r.held.Count > 0 {
h := r.held
st.Held = &h
}
r.savedAt = now
if err := saveState(r.o.StateFile, st); err != nil {
if !r.saveFailed {
r.log.Error("ntfy state not saved", "err", err)
r.o.Report(fmt.Errorf("saving state: %w", err))
}
r.saveFailed = true
return
}
if r.saveFailed {
r.log.Info("ntfy state saved again")
}
r.saveFailed, r.dirty = false, false
}
// describe says what went wrong with a request, without its URL, which
// names the topics.
func describe(err error) string {
var urlErr *url.Error
if errors.As(err, &urlErr) {
err = urlErr.Err
}
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return "the connection closed"
}
return err.Error()
}
// parseRetryAfter reads a Retry-After header, seconds or an HTTP date, as
// a wait from now, capped at maxRetryAfter; 0 when there is none.
func parseRetryAfter(h string, now time.Time) time.Duration {
h = strings.TrimSpace(h)
if h == "" {
return 0
}
var d time.Duration
if secs, err := strconv.Atoi(h); err == nil {
d = time.Duration(secs) * time.Second
} else if t, err := http.ParseTime(h); err == nil {
d = t.Sub(now)
}
return min(max(d, 0), maxRetryAfter)
}
// event is what a connection's reader sends the loop.
type event struct {
// opened is set when the server answered 200, and date is the
// answer's Date, if it had one.
opened bool
date time.Time
// at is when the reader got the answer or read the line, which can be
// well before the loop takes it.
at time.Time
// msg is an object read from the stream.
msg *Message
// skipped says why a line was skipped.
skipped string
// end is set when the connection ended: with the answer's status and
// Retry-After when it was not 200, or with err.
end bool
status int
retryAfter time.Duration
err error
}
// conn is one connection to the stream.
type conn struct {
cancel context.CancelFunc
events chan event
done chan struct{}
// since is set when the request asked for messages since a time.
since bool
// serverTime is the server's clock, in Unix seconds, as the connection
// told it, read at serverRead; clockKnown is set once it has. Each
// connection learns it afresh, so the host's clock never stands in
// for it.
serverTime int64
serverRead time.Time
clockKnown bool
// date is the answer's Date, read at dateRead, which tells the clock
// only when the stream does not.
date time.Time
dateRead time.Time
// checked is set once MaxBacklog applies to the connection, and oldest
// is then the earliest server time of a message it lets through.
checked bool
oldest int64
}
// setClock records the server's clock, serverTime, read at readAt.
func (c *conn) setClock(serverTime int64, readAt time.Time) {
if serverTime > 0 {
c.serverTime, c.serverRead, c.clockKnown = serverTime, readAt, true
}
}
// read sends the request and the stream's lines to the loop as events,
// until the stream ends or ctx is cancelled.
func (c *conn) read(ctx context.Context, client *http.Client, req *http.Request) {
defer close(c.done)
resp, err := client.Do(req)
if err != nil {
c.send(ctx, event{end: true, err: err})
return
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
c.send(ctx, event{end: true, status: resp.StatusCode,
retryAfter: parseRetryAfter(resp.Header.Get("Retry-After"), time.Now())})
return
}
opened := event{opened: true, at: time.Now()}
if date, err := http.ParseTime(resp.Header.Get("Date")); err == nil {
opened.date = date
}
if !c.send(ctx, opened) {
return
}
br := bufio.NewReaderSize(resp.Body, 64<<10)
for {
line, tooLong, err := readLine(br)
switch {
case tooLong:
if !c.send(ctx, event{skipped: "longer than 1 MiB"}) {
return
}
case len(bytes.TrimSpace(line)) > 0:
var m Message
ev := event{msg: &m, at: time.Now()}
if jsonErr := json.Unmarshal(line, &m); jsonErr != nil {
ev = event{skipped: "not a JSON message"}
}
if !c.send(ctx, ev) {
return
}
}
if err != nil {
c.send(ctx, event{end: true, err: err})
return
}
}
}
// send hands ev to the loop, unless ctx is cancelled first.
func (c *conn) send(ctx context.Context, ev event) bool {
select {
case c.events <- ev:
return true
case <-ctx.Done():
return false
}
}
// readLine reads one line. A line longer than maxLine is read to its end
// and dropped, and reported as too long.
func readLine(br *bufio.Reader) (line []byte, tooLong bool, err error) {
for {
chunk, err := br.ReadSlice('\n')
if !tooLong {
if len(line)+len(chunk) > maxLine {
tooLong, line = true, nil
} else {
line = append(line, chunk...)
}
}
if !errors.Is(err, bufio.ErrBufferFull) {
return line, tooLong, err
}
}
}
+747
View File
@@ -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}