Save a keepalive-only cursor move at most every 10 minutes
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 2m0s

Each ntfy keepalive, every 45 seconds, moved the cursor and rewrote the
subscription's state file with a synced write: about 1,900 a day per
subscription while idle, which wears an SD card. A cursor that only
keepalives or replayed repeats moved is now written at most every 10
minutes and at shutdown. A message printed, held or left out, a floor
change, a digest, and the cursor's first move from 0 are still written
within a second. A saved cursor that is behind costs only a longer
replay after a crash, and the saved IDs drop what it sends again; a
cursor still at 0 would mean a first start, which replays nothing.

Tests check the lazy cadence and a crash that loses the later moves,
the first move from 0 with an open event that has no time, and the
write at shutdown. The soak now writes its state 325 times instead of
2,702.

design.md records the decision. Its job-store entry now treats GORM on
SQLite as the first choice and has the plan investigate SQLite in WAL
mode, against bbolt and BadgerDB, before anything is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 20:20:31 -06:00
1 parent eb0c021044
commit ee65e72c44
6 files changed
+162 -24

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@ func loadState(path string) (state, error) {
}
// syncFile flushes a file, or a directory, to disk. It is a variable so
// that tests, which write state files thousands of times, can skip the
// that tests, which write state files hundreds of times, can skip the
// flush; on a disk that is slow to sync, each one costs tens of
// milliseconds.
var syncFile = (*os.File).Sync
+2 -2
View File
@@ -10,8 +10,8 @@ import (
)
// TestMain skips flushing state files to disk. The tests write them
// thousands of times, and on a disk that is slow to sync the flushes alone
// outlast the test timeout. TestSaveStateSyncs checks the flush itself.
// hundreds of times, and on a disk that is slow to sync each flush costs
// tens of milliseconds. TestSaveStateSyncs checks the flush itself.
func TestMain(m *testing.M) {
syncFile = func(*os.File) error { return nil }
m.Run()
+36 -10
View File
@@ -50,6 +50,12 @@ const (
// saveEvery is the least time between two writes of the state file.
saveEvery = time.Second
// cursorSaveEvery is the least time between two writes when only the
// cursor has moved, as each keepalive moves it. A saved cursor that is
// behind costs only a longer replay after a crash, and the saved IDs
// drop the messages it sends again.
cursorSaveEvery = 10 * time.Minute
// 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
@@ -279,9 +285,13 @@ type run struct {
digestAt time.Time
digestDelay time.Duration
dirty bool
savedAt time.Time
saveFailed bool
// dirty means the state changed in a way a restart must see, and is
// written within saveEvery; cursorMoved means only the cursor moved,
// and is written within cursorSaveEvery.
dirty bool
cursorMoved bool
savedAt time.Time
saveFailed bool
}
// start loads the state and returns the run.
@@ -312,7 +322,7 @@ func (s *Subscriber) start(h Handler) *run {
// stop closes the connection and saves the state.
func (r *run) stop() {
r.closeConn()
if r.dirty {
if r.dirty || r.cursorMoved {
r.save(time.Now())
}
r.s.ownedIdle()
@@ -367,11 +377,22 @@ func (r *run) due(ctx context.Context, now time.Time) {
r.closeConn()
r.reconnect(event{err: errStalled}, now)
}
if r.dirty && !now.Before(r.savedAt.Add(saveEvery)) {
if at, ok := r.saveAt(); ok && !now.Before(at) {
r.save(now)
}
}
// saveAt returns when the state is next due to be written, if it changed.
func (r *run) saveAt() (time.Time, bool) {
switch {
case r.dirty:
return r.savedAt.Add(saveEvery), true
case r.cursorMoved:
return r.savedAt.Add(cursorSaveEvery), true
}
return time.Time{}, false
}
// wake returns the next time something is due after now.
func (r *run) wake(now time.Time) time.Time {
next := now.Add(maxWait)
@@ -392,8 +413,8 @@ func (r *run) wake(now time.Time) time.Time {
if at, ok := r.flushAt(now); ok {
earlier(at)
}
if r.dirty {
earlier(r.savedAt.Add(saveEvery))
if at, ok := r.saveAt(); ok {
earlier(at)
}
return next
}
@@ -546,10 +567,15 @@ func (r *run) dealt(m Message) {
r.dirty = true
}
// advance moves the cursor forward to t, a server time.
// advance moves the cursor forward to t, a server time. The first move
// from 0 is written like any change a restart must see: a saved cursor of
// 0 is a first start, which replays nothing.
func (r *run) advance(t int64) {
if t > r.cursor {
r.cursor, r.dirty = t, true
if r.cursor == 0 {
r.dirty = true
}
r.cursor, r.cursorMoved = t, true
}
}
@@ -801,7 +827,7 @@ func (r *run) save(now time.Time) {
if r.saveFailed {
r.log.Info("ntfy state saved again")
}
r.saveFailed, r.dirty = false, false
r.saveFailed, r.dirty, r.cursorMoved = false, false, false
}
// describe says what went wrong with a request, without its URL, which
+97
View File
@@ -540,6 +540,103 @@ func TestStateWritesAreThrottled(t *testing.T) {
})
}
// Keepalives move the cursor but write the state at most every
// cursorSaveEvery. A crash that loses those moves replays from the older
// cursor, and the saved IDs keep what it sends again from printing twice.
func TestKeepalivesSaveTheCursorLazily(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()
// Past the first start's floor, so that the replay's slack shows.
time.Sleep(5 * time.Minute)
a := f.publish(Message{Title: "a"})
time.Sleep(saveEvery)
synctest.Wait()
if st, _ := loadState(o.StateFile); st.Cursor != a.Time {
t.Fatalf("a second after a message, the saved cursor is %d, want %d", st.Cursor, a.Time)
}
time.Sleep(cursorSaveEvery - 2*saveEvery)
synctest.Wait()
crashed, err := os.ReadFile(o.StateFile)
if err != nil {
t.Fatal(err)
}
if st, _ := loadState(o.StateFile); st.Cursor != a.Time {
t.Errorf("keepalives wrote the cursor %d before %v had passed", st.Cursor, cursorSaveEvery)
}
time.Sleep(2 * saveEvery)
synctest.Wait()
if st, _ := loadState(o.StateFile); st.Cursor <= a.Time {
t.Errorf("after %v the saved cursor is still %d", cursorSaveEvery, st.Cursor)
}
stop()
if err := os.WriteFile(o.StateFile, crashed, 0o600); err != nil {
t.Fatal(err)
}
_, stop = start(t, o, h)
defer stop()
synctest.Wait()
time.Sleep(saveEvery)
synctest.Wait()
streams := f.streams()
if since, ok := sinceOf(t, streams[len(streams)-1]); !ok || since != a.Time-int64(cursorSlack/time.Second) {
t.Errorf("after the crash, asked since %d (%v), want the saved cursor less the slack, %d", since, ok, a.Time-int64(cursorSlack/time.Second))
}
if got := h.printed(); !slices.Equal(got, []string{a.ID}) {
t.Errorf("printed %v, want %s once", got, a.ID)
}
})
}
// The cursor's first move from 0 is written within saveEvery, like a
// message: a saved cursor of 0 is a first start, which replays nothing, so
// a crash before that write would lose what was published while the
// daemon was down. With an open event that carries no time, the first
// keepalive makes that move.
func TestFirstCursorIsSavedAtOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.openNoTime = true
o := testOptions(f, t.TempDir())
_, stop := start(t, o, &recorder{})
defer stop()
synctest.Wait()
time.Sleep(f.keepalive + saveEvery)
synctest.Wait()
if st, _ := loadState(o.StateFile); st.Cursor == 0 {
t.Error("a second after the first keepalive, the saved cursor is still 0")
}
})
}
// Stopping writes a cursor that only keepalives moved.
func TestStopSavesTheCursor(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
o := testOptions(f, t.TempDir())
_, stop := start(t, o, &recorder{})
synctest.Wait()
opened, err := loadState(o.StateFile)
if err != nil {
t.Fatal(err)
}
time.Sleep(f.keepalive + saveEvery)
synctest.Wait()
if st, _ := loadState(o.StateFile); st.Cursor != opened.Cursor {
t.Fatalf("a keepalive wrote the cursor %d at once, want it kept until later", st.Cursor)
}
stop()
if st, _ := loadState(o.StateFile); st.Cursor <= opened.Cursor {
t.Errorf("after stopping, the saved cursor is %d, want past %d", st.Cursor, opened.Cursor)
}
})
}
// Events other than messages, and base64 bodies, print nothing but move
// the cursor.
func TestNonMessagesSkipped(t *testing.T) {