Files
57_WolveandClaude Opus 5.5 8b8b7da0c6 Answer a repeated ntfy message with its earlier job
Once queued jobs survive a restart, a crash in the second between
queueing an ntfy message and saving the subscription's state would
print the message twice: the replay offers it again. A card is now
submitted as unique by its message's ID. If the queue already holds
that source and reference, Submit queues nothing and returns the
earlier job, or its ID and source once its status is gone, and logs
the repeat. The queue keeps the last 512 references of each source
apart from the statuses, so queue.history = 0 cannot defeat the check,
and they come back on restore.

A replayed message that quiet hours or the paper budget would hold for
a digest never reaches Submit, so the check could not answer it, and
it would print again as a digest row. Before it holds a message, the
subscription now asks the queue through its handler whether it holds
that message's card; if so, the message counts as printed and is not
held.

Only unique jobs take part. On the HTTP routes the reference is a
request ID, which a client may set, so a check on it could answer a
new request with an old job. A unique insert is stored with a sync,
since the subscription treats the message as dealt with once it is
queued.

Part of stage 1c of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:50:09 -06:00

432 lines
15 KiB
Go

package ntfy
import (
"context"
"fmt"
"os"
"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}, skipSync); 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}, skipSync); 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}, skipSync); 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}, skipSync); 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}, skipSync); 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)
}
})
}
// A card queued just before a crash that lost the save recording it is
// offered again by the replay. Held by quiet hours, it would never reach
// the queue's own check and would print again on the morning digest, so
// the subscription asks the queue first: a card the queue holds counts as
// printed and is not held.
func TestReplayedCardTheQueueHoldsIsNotHeld(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 11, 30, 21, 0, 0, 0, loc))
f := newFakeServer()
o := testOptions(f, t.TempDir())
o.Quiet = nightly(loc)
o.MaxBacklog = 12 * time.Hour
h := &recorder{}
_, stop := start(t, o, h)
synctest.Wait()
before, err := os.ReadFile(o.StateFile)
if err != nil {
t.Fatal(err)
}
sleepUntil(time.Date(2026, 11, 30, 21, 30, 0, 0, loc))
card := f.publish(Message{Title: "backup done", RawPriority: 3})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{card.ID}) {
t.Fatalf("printed %v, want the card", got)
}
stop()
if err := os.WriteFile(o.StateFile, before, 0o600); err != nil {
t.Fatal(err)
}
sleepUntil(time.Date(2026, 11, 30, 23, 0, 0, 0, loc))
h2 := &recorder{queued: func(id string) bool { return id == card.ID }}
s, stop2 := start(t, o, h2)
defer stop2()
synctest.Wait()
if st := s.Status(); st.Held != 0 {
t.Errorf("status %+v, want the replayed card not held", st)
}
sleepUntil(time.Date(2026, 12, 1, 7, 0, 1, 0, loc))
if ds := h2.digestList(); len(ds) != 0 {
t.Errorf("digests %+v, want none: the queue holds the card", ds)
}
if got := h2.printed(); len(got) != 0 {
t.Errorf("printed %v after the restart, want nothing", got)
}
})
}