diff --git a/README.md b/README.md index 38a57df..b919f24 100644 --- a/README.md +++ b/README.md @@ -383,9 +383,11 @@ How a subscription behaves: "skip"` it is left out. The first message of a sequence prints plain, even when its publisher named the sequence. - **State.** The cursor, the IDs, the budget and the held messages are in - `/ntfy-.json`, written at most once a second and at - shutdown, through a temporary file and a rename, so a crash leaves the - old file or the new one. A damaged file is ignored with a warning, and + `/ntfy-.json`, written through a temporary file and a + rename, so a crash leaves the old file or the new one. It is written + 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. - **Jobs.** Each card and digest is an ordinary job with the source `ntfy:`. Like any job, one that is still waiting when the daemon diff --git a/docs/design.md b/docs/design.md index 6e604f9..3fcee17 100644 --- a/docs/design.md +++ b/docs/design.md @@ -350,8 +350,15 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( daemon stops is lost, as any waiting job is: the queue stays in memory, because ESC/POS cannot say what printed. - State is one JSON file per subscription in `ntfy.state_dir`, written - atomically (temporary file, fsync, rename) at most once a second and - at shutdown, mode 0600 since held messages carry titles. A damaged + atomically (temporary file, fsync, rename), mode 0600 since held + 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, since the daemon also runs on Windows; `install.sh` writes the unit's `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 2026-11-30; to be planned in full in `docs/plans/` before any of it is built): - - Jobs stored with GORM on SQLite, so queued jobs, statuses and history - survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite - driver must be pure Go (for example `github.com/glebarez/sqlite`), and - the database belongs 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 + - Jobs stored on disk, so queued jobs, statuses and history survive a + restart. The owner's first choice is GORM on SQLite. Before anything + is built, the plan investigates SQLite in WAL mode, through GORM or a + lighter layer (owner, 2026-11-30): its disk writes per job, what each + `synchronous` setting and checkpoint costs and guarantees, and whether + 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. - 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 diff --git a/internal/pkg/ntfy/state.go b/internal/pkg/ntfy/state.go index 1d49ecd..8c86f2b 100644 --- a/internal/pkg/ntfy/state.go +++ b/internal/pkg/ntfy/state.go @@ -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 diff --git a/internal/pkg/ntfy/state_test.go b/internal/pkg/ntfy/state_test.go index cb4ac34..450cfd1 100644 --- a/internal/pkg/ntfy/state_test.go +++ b/internal/pkg/ntfy/state_test.go @@ -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() diff --git a/internal/pkg/ntfy/subscriber.go b/internal/pkg/ntfy/subscriber.go index 1f5c287..ee442b5 100644 --- a/internal/pkg/ntfy/subscriber.go +++ b/internal/pkg/ntfy/subscriber.go @@ -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 diff --git a/internal/pkg/ntfy/subscriber_test.go b/internal/pkg/ntfy/subscriber_test.go index c3e650c..1e10e36 100644 --- a/internal/pkg/ntfy/subscriber_test.go +++ b/internal/pkg/ntfy/subscriber_test.go @@ -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) {