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
+159 -21

No files matched your search

+5 -3
View File
@@ -383,9 +383,11 @@ How a subscription behaves:
"skip"` it is left out. The first message of a sequence prints plain, "skip"` it is left out. The first message of a sequence prints plain,
even when its publisher named the sequence. even when its publisher named the sequence.
- **State.** The cursor, the IDs, the budget and the held messages are in - **State.** The cursor, the IDs, the budget and the held messages are in
`<state_dir>/ntfy-<name>.json`, written at most once a second and at `<state_dir>/ntfy-<name>.json`, written through a temporary file and a
shutdown, through a temporary file and a rename, so a crash leaves the rename, so a crash leaves the old file or the new one. It is written
old file or the new one. A damaged file is ignored with a warning, and within a second of a message being printed, held or left out, at most
every 10 minutes when only keepalives have moved the cursor, and at
shutdown. A damaged file is ignored with a warning, and
the subscription starts as if new. Held messages survive a restart. the subscription starts as if new. Held messages survive a restart.
- **Jobs.** Each card and digest is an ordinary job with the source - **Jobs.** Each card and digest is an ordinary job with the source
`ntfy:<name>`. Like any job, one that is still waiting when the daemon `ntfy:<name>`. Like any job, one that is still waiting when the daemon
+21 -8
View File
@@ -350,8 +350,15 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
daemon stops is lost, as any waiting job is: the queue stays in daemon stops is lost, as any waiting job is: the queue stays in
memory, because ESC/POS cannot say what printed. memory, because ESC/POS cannot say what printed.
- State is one JSON file per subscription in `ntfy.state_dir`, written - State is one JSON file per subscription in `ntfy.state_dir`, written
atomically (temporary file, fsync, rename) at most once a second and atomically (temporary file, fsync, rename), mode 0600 since held
at shutdown, mode 0600 since held messages carry titles. A damaged messages carry titles. A change a restart must see, such as a message
printed, held or left out, is written within a second, and so is the
state at shutdown. A cursor that only keepalives moved is written at
most every 10 minutes (owner, 2026-11-30): keepalives come every 45
seconds, and writing each one would mean about 1,900 synced writes a
day per subscription, which wears an SD card. A saved cursor that is
behind costs only a longer replay after a crash, and the saved IDs
drop the messages it sends again. A damaged
file means a fresh start with a warning. `state_dir` has no default, file means a fresh start with a warning. `state_dir` has no default,
since the daemon also runs on Windows; `install.sh` writes the unit's since the daemon also runs on Windows; `install.sh` writes the unit's
`StateDirectory`, `/var/lib/uberbringer`, and the image sets the same `StateDirectory`, `/var/lib/uberbringer`, and the image sets the same
@@ -430,12 +437,18 @@ come from the config (owner, 2026-11-29).
- **A persistent job store and print previews** (requested by the owner on - **A persistent job store and print previews** (requested by the owner on
2026-11-30; to be planned in full in `docs/plans/` before any of it is 2026-11-30; to be planned in full in `docs/plans/` before any of it is
built): built):
- Jobs stored with GORM on SQLite, so queued jobs, statuses and history - Jobs stored on disk, so queued jobs, statuses and history survive a
survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite restart. The owner's first choice is GORM on SQLite. Before anything
driver must be pure Go (for example `github.com/glebarez/sqlite`), and is built, the plan investigates SQLite in WAL mode, through GORM or a
the database belongs in the unit's `StateDirectory`, lighter layer (owner, 2026-11-30): its disk writes per job, what each
`/var/lib/uberbringer`, the only directory it may write. The plan must `synchronous` setting and checkpoint costs and guarantees, and whether
also say how to tell which receipts printed it can record a job as printed durably at the moment its bytes are
sent. The plan weighs it against key-value stores such as bbolt and
BadgerDB on the same terms, and the choice is recorded here. Release
builds use `CGO_ENABLED=0`, so any store must be pure Go (for SQLite,
for example `github.com/glebarez/sqlite`), and its files belong in the
unit's `StateDirectory`, `/var/lib/uberbringer`, the only directory it
may write. The plan must also say how to tell which receipts printed
before a crash, so a restart never prints a receipt twice. before a crash, so a restart never prints a receipt twice.
- A print preview as an image: a digital test print of a job that shows - A print preview as an image: a digital test print of a job that shows
what the paper would look like, without printing. Formatters phase 1 adds what the paper would look like, without printing. Formatters phase 1 adds
+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 // 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 // flush; on a disk that is slow to sync, each one costs tens of
// milliseconds. // milliseconds.
var syncFile = (*os.File).Sync 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 // 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 // hundreds of times, and on a disk that is slow to sync each flush costs
// outlast the test timeout. TestSaveStateSyncs checks the flush itself. // tens of milliseconds. TestSaveStateSyncs checks the flush itself.
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
syncFile = func(*os.File) error { return nil } syncFile = func(*os.File) error { return nil }
m.Run() m.Run()
+33 -7
View File
@@ -50,6 +50,12 @@ const (
// saveEvery is the least time between two writes of the state file. // saveEvery is the least time between two writes of the state file.
saveEvery = time.Second 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 // maxWait is the longest the loop sleeps before it looks at its
// deadlines again, so that a change to the wall clock is noticed. // deadlines again, so that a change to the wall clock is noticed.
maxWait = time.Minute maxWait = time.Minute
@@ -279,7 +285,11 @@ type run struct {
digestAt time.Time digestAt time.Time
digestDelay time.Duration digestDelay time.Duration
// 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 dirty bool
cursorMoved bool
savedAt time.Time savedAt time.Time
saveFailed bool saveFailed bool
} }
@@ -312,7 +322,7 @@ func (s *Subscriber) start(h Handler) *run {
// stop closes the connection and saves the state. // stop closes the connection and saves the state.
func (r *run) stop() { func (r *run) stop() {
r.closeConn() r.closeConn()
if r.dirty { if r.dirty || r.cursorMoved {
r.save(time.Now()) r.save(time.Now())
} }
r.s.ownedIdle() r.s.ownedIdle()
@@ -367,11 +377,22 @@ func (r *run) due(ctx context.Context, now time.Time) {
r.closeConn() r.closeConn()
r.reconnect(event{err: errStalled}, now) 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) 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. // wake returns the next time something is due after now.
func (r *run) wake(now time.Time) time.Time { func (r *run) wake(now time.Time) time.Time {
next := now.Add(maxWait) next := now.Add(maxWait)
@@ -392,8 +413,8 @@ func (r *run) wake(now time.Time) time.Time {
if at, ok := r.flushAt(now); ok { if at, ok := r.flushAt(now); ok {
earlier(at) earlier(at)
} }
if r.dirty { if at, ok := r.saveAt(); ok {
earlier(r.savedAt.Add(saveEvery)) earlier(at)
} }
return next return next
} }
@@ -546,10 +567,15 @@ func (r *run) dealt(m Message) {
r.dirty = true 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) { func (r *run) advance(t int64) {
if t > r.cursor { 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 { if r.saveFailed {
r.log.Info("ntfy state saved again") 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 // 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 // Events other than messages, and base64 bodies, print nothing but move
// the cursor. // the cursor.
func TestNonMessagesSkipped(t *testing.T) { func TestNonMessagesSkipped(t *testing.T) {