package ntfy import ( "context" "encoding/json" "errors" "os" "slices" "strings" "sync" "sync/atomic" "testing" "testing/synctest" "time" ) // crashingRecorder is a recorder that also copies the state file each time // a digest is offered: the state a crash right after the handler took the // digest leaves behind, before the subscription saved that it did. type crashingRecorder struct { recorder path string mu sync.Mutex states [][]byte } func (h *crashingRecorder) Digest(ctx context.Context, d Digest) error { data, err := os.ReadFile(h.path) if err != nil { return err } h.mu.Lock() h.states = append(h.states, data) h.mu.Unlock() return h.recorder.Digest(ctx, d) } // state returns the state file as it was when digest i was offered. func (h *crashingRecorder) state(t *testing.T, i int) (state, []byte) { t.Helper() h.mu.Lock() defer h.mu.Unlock() if i >= len(h.states) { t.Fatalf("no state for digest %d", i) } var st state if err := json.Unmarshal(h.states[i], &st); err != nil { t.Fatal(err) } return st, h.states[i] } // rowIDs returns the IDs of d's rows. func rowIDs(d Digest) []string { var ids []string for _, row := range d.Rows { ids = append(ids, row.ID) } return ids } // A digest is saved with its reference before it is offered. If the // daemon dies before the handler's success is saved, the restart offers // the same digest, rows and reference, before any later one; a message // held after it goes on the next digest under a new reference. func TestDigestIsSavedBeforeItIsOffered(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := newFakeServer() o := testOptions(f, t.TempDir()) o.RateLimit = 1 h := &crashingRecorder{path: o.StateFile} _, stop := start(t, o, h) synctest.Wait() f.publish(Message{Title: "card", RawPriority: 3}) a := f.publish(Message{Title: "a", RawPriority: 3}) b := f.publish(Message{Title: "b", RawPriority: 3}) synctest.Wait() time.Sleep(o.RateWindow) synctest.Wait() ds := h.digestList() if len(ds) != 1 || !strings.HasPrefix(ds[0].Ref, "digest_") || !slices.Equal(rowIDs(ds[0]), []string{a.ID, b.ID}) { t.Fatalf("digests %+v, want one of a and b with a reference", ds) } saved, crashState := h.state(t, 0) if saved.Digest == nil || saved.Digest.Ref != ds[0].Ref || saved.Digest.Count != 2 || saved.Held != nil { t.Fatalf("state when offered: digest %+v, held %+v; want the digest saved apart", saved.Digest, saved.Held) } stop() if after, err := loadState(o.StateFile); err != nil || after.Digest != nil { t.Errorf("state after the handler took it: %+v, %v; want no digest", after.Digest, err) } if err := os.WriteFile(o.StateFile, crashState, 0o600); err != nil { t.Fatal(err) } h2 := &recorder{} s, stop2 := start(t, o, h2) defer stop2() synctest.Wait() later := f.publish(Message{Title: "later", RawPriority: 3}) synctest.Wait() ds2 := h2.digestList() if len(ds2) != 1 || ds2[0].Ref != ds[0].Ref || !slices.Equal(rowIDs(ds2[0]), []string{a.ID, b.ID}) { t.Fatalf("digests after the restart %+v, want the same digest again", ds2) } if got := h2.printed(); len(got) != 0 { t.Errorf("printed %v after the restart, want the later message held", got) } if st := s.Status(); st.Held != 1 { t.Errorf("status %+v, want the later message held", st) } time.Sleep(o.RateWindow) synctest.Wait() ds2 = h2.digestList() if len(ds2) != 2 || ds2[1].Ref == ds[0].Ref || !strings.HasPrefix(ds2[1].Ref, "digest_") || !slices.Equal(rowIDs(ds2[1]), []string{later.ID}) { t.Errorf("digests %+v, want the later message on a digest of its own reference", ds2) } }) } // Quiet hours delay a saved digest offered again after a restart, and the // messages held meanwhile go on the next digest, under a new reference. func TestSavedDigestWaitsForQuietHours(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.RateLimit = 1 o.Quiet = nightly(loc) h := &crashingRecorder{path: o.StateFile} _, stop := start(t, o, h) synctest.Wait() f.publish(Message{Title: "card", RawPriority: 3}) a := f.publish(Message{Title: "a", RawPriority: 3}) synctest.Wait() sleepUntil(time.Date(2026, 11, 30, 21, 10, 1, 0, loc)) ds := h.digestList() if len(ds) != 1 { t.Fatalf("%d digests by 21:10, want 1", len(ds)) } _, crashState := h.state(t, 0) stop() if err := os.WriteFile(o.StateFile, crashState, 0o600); err != nil { t.Fatal(err) } sleepUntil(time.Date(2026, 11, 30, 23, 30, 0, 0, loc)) h2 := &recorder{} _, stop2 := start(t, o, h2) defer stop2() synctest.Wait() night := f.publish(Message{Title: "night", RawPriority: 3}) sleepUntil(time.Date(2026, 12, 1, 6, 59, 0, 0, loc)) if got := h2.digestList(); len(got) != 0 { t.Fatalf("digests %+v during quiet hours", got) } sleepUntil(time.Date(2026, 12, 1, 7, 0, 1, 0, loc)) ds2 := h2.digestList() if len(ds2) != 1 || ds2[0].Ref != ds[0].Ref || !slices.Equal(rowIDs(ds2[0]), []string{a.ID}) || ds2[0].Overnight { t.Fatalf("digests at 07:00 %+v, want the saved digest again", ds2) } sleepUntil(time.Date(2026, 12, 1, 7, 10, 1, 0, loc)) ds2 = h2.digestList() if len(ds2) != 2 || ds2[1].Ref == ds[0].Ref || !ds2[1].Overnight || !slices.Equal(rowIDs(ds2[1]), []string{night.ID}) { t.Errorf("digests %+v, want the night's message on an overnight digest of its own reference", ds2) } }) } // Each digest gets a reference of its own. func TestEachDigestHasItsOwnRef(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := newFakeServer() o := testOptions(f, t.TempDir()) o.RateLimit = 1 h := &recorder{} _, stop := start(t, o, h) defer stop() synctest.Wait() for range 3 { f.publish(Message{Title: "m", RawPriority: 3}) } synctest.Wait() time.Sleep(o.RateWindow) synctest.Wait() f.publish(Message{Title: "m", RawPriority: 3}) time.Sleep(o.RateWindow) synctest.Wait() ds := h.digestList() if len(ds) != 2 || ds[0].Ref == "" || ds[0].Ref == ds[1].Ref { t.Errorf("digests %+v, want two with references of their own", ds) } }) } // A new digest is not offered while the state holding it cannot be // saved; once a save succeeds it is offered, under the reference it was // made with. func TestUnsavedDigestIsNotOffered(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := newFakeServer() o := testOptions(f, t.TempDir()) o.RateLimit = 1 var broken atomic.Bool o.Sync = func(*os.File) error { if broken.Load() { return errors.New("I/O error") } return nil } h := &recorder{} _, stop := start(t, o, h) defer stop() synctest.Wait() f.publish(Message{Title: "card", RawPriority: 3}) a := f.publish(Message{Title: "a", RawPriority: 3}) synctest.Wait() time.Sleep(time.Second) synctest.Wait() broken.Store(true) time.Sleep(o.RateWindow) synctest.Wait() if ds := h.digestList(); len(ds) != 0 { t.Fatalf("digests %+v offered although the state was not saved", ds) } broken.Store(false) time.Sleep(maxPrintRetry) synctest.Wait() ds := h.digestList() if len(ds) != 1 || !slices.Equal(rowIDs(ds[0]), []string{a.ID}) { t.Fatalf("digests %+v once the state saved, want the held message's", ds) } saved, err := loadState(o.StateFile) if err != nil || saved.Digest != nil || saved.Held != nil { t.Errorf("state %+v, %v; want nothing waiting", saved, err) } }) }