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) } }) }