Give each ntfy digest a reference of its own
Security / Vulnerability check (push) Successful in 47s
Test / Lint and test (push) Successful in 2m6s

Every digest went to the print queue under the fixed reference
"digest", so after a crash the queue could not tell a digest it had
queued from a new one. Once queued jobs survive a restart, a crash in
the second between queueing a digest and saving the subscription's
state would print it twice; the same window exists today for a digest
that printed in that second.

A digest now gets a reference of its own when it is made, "digest_"
and a TypeID, and is saved with it in the subscription's state, apart
from the held messages. It is offered to the queue only once that save
has succeeded, and dropped once the queue takes it; while the state
file cannot be written, digests wait. A restart with a saved digest
offers that digest again first, with the same rows and reference, and
the queue's duplicate check answers with the earlier job while it holds
it. Messages held after a digest is made wait for the next one, also
while quiet hours delay the saved digest after a restart: added to a
digest the queue already holds, they would never print. The digest is
submitted as unique, like a card.

A digest can cost one more state save, two fsyncs. The reference shows
in the log lines and Sentry reports where "digest" did.

This completes stage 1c of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 13:50:57 -06:00
1 parent 8b8b7da0c6
commit 64a72903d8
12 files changed
+431 -58

No files matched your search

+6 -7
View File
@@ -152,7 +152,7 @@ type ntfySubmitter interface {
// ntfyPrinter prints what a subscription delivers: each message as a
// card, and held messages as a digest, through the print queue. Jobs carry
// the source ntfy:<name> and the message's ID, or "digest".
// the source ntfy:<name> and the message's ID, or the digest's reference.
type ntfyPrinter struct {
name string
jobs ntfySubmitter
@@ -160,9 +160,6 @@ type ntfyPrinter struct {
logger *slog.Logger
}
// digestRef is the reference of a digest's job.
const digestRef = "digest"
// Message prints m as a card, marked "(updated)" when updated. A full
// queue is returned, for the subscription to offer m again. The card is
// unique by m's ID, so a message offered again after a crash, whose card
@@ -186,12 +183,14 @@ func (p *ntfyPrinter) Queued(m ntfy.Message) bool {
return p.jobs.Holds("ntfy:"+p.name, m.ID)
}
// Digest prints the held messages on one receipt.
// Digest prints the held messages on one receipt. It is unique by the
// digest's reference, so a digest offered again after a crash, whose job
// the queue already holds, is not queued twice.
func (p *ntfyPrinter) Digest(_ context.Context, d ntfy.Digest) error {
env := p.env()
job, err := modules.DigestCard(d, env.Card, env)
p.reportFallback(digestRef, err)
return p.submit(job, printqueue.Meta{Ref: digestRef})
p.reportFallback(d.Ref, err)
return p.submit(job, printqueue.Meta{Ref: d.Ref, Unique: true})
}
// submit validates job and queues it with meta, from the subscription.
+3 -2
View File
@@ -248,14 +248,15 @@ func TestNtfyPrinter(t *testing.T) {
if err := p.Message(ctx, ntfy.Message{ID: "b64", Event: "message", Message: "AAE=", Encoding: "base64"}, false); err != nil {
t.Fatal(err)
}
if err := p.Digest(ctx, ntfy.Digest{Rows: []ntfy.DigestRow{{ID: "x", Title: "SecretRow"}}, Count: 1, Until: testEnv().Now}); err != nil {
digest := ntfy.Digest{Rows: []ntfy.DigestRow{{ID: "x", Title: "SecretRow"}}, Count: 1, Until: testEnv().Now, Ref: "digest_01kbx4n6m3ex8tq0wq3r5vrzq1"}
if err := p.Digest(ctx, digest); err != nil {
t.Fatal(err)
}
if len(q.jobs) != 2 {
t.Fatalf("%d jobs, want the card and the digest", len(q.jobs))
}
if q.metas[0] != (printqueue.Meta{Source: "ntfy:home", Ref: "msg1", Sequence: "alerts/msg1", Unique: true}) ||
q.metas[1] != (printqueue.Meta{Source: "ntfy:home", Ref: "digest"}) {
q.metas[1] != (printqueue.Meta{Source: "ntfy:home", Ref: digest.Ref, Unique: true}) {
t.Errorf("metas %+v", q.metas)
}
if title := q.jobs[0].Elements[0].Title; title != "Disk almost full (updated)" {
+244
View File
@@ -0,0 +1,244 @@
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)
}
})
}
+46 -7
View File
@@ -1,9 +1,12 @@
package ntfy
import (
"strconv"
"strings"
"time"
"unicode/utf8"
"go.jetify.com/typeid"
)
// MaxDigestRows is how many held messages a digest lists; it counts the
@@ -97,6 +100,11 @@ type Digest struct {
// Since is when the first message was held, and Until when the digest
// was made.
Since, Until time.Time
// Ref identifies the digest: a TypeID with the prefix digest, minted
// when the digest is made. A digest offered again, also after a
// restart, keeps it, so that the print queue can tell it was queued.
Ref string
}
// held are the messages held for the next digest. It is saved with the
@@ -138,17 +146,48 @@ func (h *held) add(m Message, updated, overnight bool, now time.Time) bool {
return true
}
// digest returns the held messages as a digest made at now.
func (h *held) digest(now time.Time) Digest {
// madeDigest is a digest made from held messages that the handler has not
// yet taken. It is saved with the subscription's state apart from the
// messages held after it, so that a restart offers it again as it was,
// under the same reference, and the later messages go on the next one.
type madeDigest struct {
held
// Until is when the digest was made, in Unix seconds.
Until int64 `json:"until"`
Ref string `json:"ref"`
}
// makeDigest returns the held messages as a digest made at now, under a
// new reference.
func (h *held) makeDigest(now time.Time) madeDigest {
return madeDigest{held: *h, Until: now.Unix(), Ref: newDigestRef(now)}
}
// digest returns d as the handler takes it.
func (d *madeDigest) digest() Digest {
return Digest{
Overnight: h.Overnight,
Rows: h.Rows,
Count: h.Count,
Since: time.Unix(h.Since, 0),
Until: now,
Overnight: d.Overnight,
Rows: d.Rows,
Count: d.Count,
Since: time.Unix(d.Since, 0),
Until: time.Unix(d.Until, 0),
Ref: d.Ref,
}
}
// newDigestRef mints a digest's reference, a TypeID with the prefix
// digest. Should the system's random source fail, the time made at stands
// in, which a later digest cannot share.
func newDigestRef(now time.Time) string {
id, err := typeid.WithPrefix("digest")
if err != nil {
return "digest_" + strconv.FormatInt(now.UnixNano(), 36)
}
return id.String()
}
// firstLine returns the first line of s that is not blank.
func firstLine(s string) string {
for line := range strings.Lines(s) {
+7 -2
View File
@@ -81,8 +81,13 @@ func TestHeldRows(t *testing.T) {
if row := h.Rows[1]; row.FirstLine != "first line" || !row.Updated || row.Priority != 3 {
t.Errorf("row %+v", row)
}
d := h.digest(now.Add(9 * time.Minute))
if d.Count != 2 || !d.Since.Equal(now) || !d.Until.Equal(now.Add(9*time.Minute)) || len(d.Rows) != 2 {
made := h.makeDigest(now.Add(9 * time.Minute))
d := made.digest()
if d.Count != 2 || !d.Since.Equal(now) || !d.Until.Equal(now.Add(9*time.Minute)) || len(d.Rows) != 2 ||
!strings.HasPrefix(d.Ref, "digest_") {
t.Errorf("digest %+v", d)
}
if other := h.makeDigest(now.Add(9 * time.Minute)); other.Ref == made.Ref {
t.Error("two digests got the same reference")
}
}
+7
View File
@@ -49,6 +49,10 @@ type state struct {
// Held are the messages waiting for the next digest.
Held *held `json:"held,omitempty"`
// Digest is the digest made and not yet taken by the handler, kept
// apart from the messages held after it.
Digest *madeDigest `json:"digest,omitempty"`
}
// loadState reads the state file at path. A file that does not exist
@@ -72,6 +76,9 @@ func loadState(path string) (state, error) {
if st.Held != nil && len(st.Held.Rows) > MaxDigestRows {
st.Held.Rows = st.Held.Rows[:MaxDigestRows]
}
if st.Digest != nil && len(st.Digest.Rows) > MaxDigestRows {
st.Digest.Rows = st.Digest.Rows[:MaxDigestRows]
}
return st, nil
}
+64 -16
View File
@@ -84,6 +84,9 @@ var defaultBackoff = []time.Duration{
// errStalled ends a connection that sent nothing for too long.
var errStalled = errors.New("stalled")
// errStateNotSaved holds back a digest whose state could not be saved.
var errStateNotSaved = errors.New("the subscription's state could not be saved")
// Options configure a Subscriber.
type Options struct {
// Name names the subscription in its status and its log lines.
@@ -283,6 +286,13 @@ type run struct {
budget budget
held held
// digest is the digest made from held messages that the handler has
// not taken yet; messages held meanwhile wait for the next one.
// digestUnsaved is set until the state holding it has been saved, and
// it is not offered before.
digest *madeDigest
digestUnsaved bool
conn *conn
connectedAt time.Time
attempt int
@@ -329,7 +339,8 @@ func (s *Subscriber) start(h Handler) *run {
if st.Held != nil {
r.held = *st.Held
}
s.status.update(func(st *Status) { st.Held = r.held.Count })
r.digest = st.Digest
s.status.update(func(st *Status) { st.Held = r.waiting() })
return r
}
@@ -531,7 +542,7 @@ func (r *run) deliver(ctx context.Context, m Message, now time.Time) bool {
}
return true
}
if priority < r.o.BypassPriority && (!r.budget.room(now) || (r.held.Count > 0 && !quiet)) {
if priority < r.o.BypassPriority && (!r.budget.room(now) || (r.waiting() > 0 && !quiet)) {
if !r.queued(m) {
r.hold(m, updated, false, now)
}
@@ -571,7 +582,17 @@ func (r *run) hold(m Message, updated, overnight bool, now time.Time) {
r.printed.add(m.Sequence())
}
r.log.Debug("ntfy message held", "ntfy_id", m.ID, "quiet_hours", overnight)
r.s.status.update(func(st *Status) { st.Digested++; st.Held = r.held.Count })
r.s.status.update(func(st *Status) { st.Digested++; st.Held = r.waiting() })
}
// waiting returns how many held messages wait to print: those of the
// digest made and those held after it.
func (r *run) waiting() int {
n := r.held.Count
if r.digest != nil {
n += r.digest.Count
}
return n
}
// wait keeps m to offer it again later, waiting longer each time.
@@ -643,9 +664,9 @@ func (r *run) replayStart() int64 {
return max(r.cursor-int64(cursorSlack/time.Second), r.floor)
}
// flushAt returns when the held messages may print, if any are held.
// flushAt returns when the held messages may print, if any wait.
func (r *run) flushAt(now time.Time) (time.Time, bool) {
if r.held.Count == 0 || r.pending != nil {
if r.waiting() == 0 || r.pending != nil {
return time.Time{}, false
}
at := r.budget.next(now)
@@ -658,7 +679,12 @@ func (r *run) flushAt(now time.Time) (time.Time, bool) {
return at, true
}
// flush prints the held messages on one digest when they may print.
// flush prints the held messages on one digest when they may print. A
// digest offered again keeps its rows and reference. A new one is made
// from the messages held, under a new reference, and offered only once it
// is saved: should the daemon stop before the handler's success is saved,
// the next start offers the same digest again, which the print queue
// knows by its reference if it holds the job.
func (r *run) flush(ctx context.Context, now time.Time) {
at, ok := r.flushAt(now)
if !ok || now.Before(at) {
@@ -667,20 +693,38 @@ func (r *run) flush(ctx context.Context, now time.Time) {
if _, quiet := r.o.Quiet.window(now); quiet || !r.budget.room(now) {
return
}
if err := r.h.Digest(ctx, r.held.digest(now)); err != nil {
if r.digestAt.IsZero() {
r.digestDelay = firstPrintRetry
r.log.Warn("ntfy digest waits to print", "held", r.held.Count, "err", err)
} else {
r.digestDelay = min(2*r.digestDelay, maxPrintRetry)
if r.digest == nil {
d := r.held.makeDigest(now)
r.digest, r.held, r.digestUnsaved = &d, held{}, true
}
d := r.digest
if r.digestUnsaved {
if r.save(now); r.saveFailed {
r.digestWaits(now, errStateNotSaved)
return
}
r.digestAt = now.Add(r.digestDelay)
r.digestUnsaved = false
}
if err := r.h.Digest(ctx, d.digest()); err != nil {
r.digestWaits(now, err)
return
}
r.log.Debug("ntfy digest printed", "held", r.held.Count, "overnight", r.held.Overnight)
r.log.Debug("ntfy digest printed", "ref", d.Ref, "held", d.Count, "overnight", d.Overnight)
r.budget.spend(now)
r.held, r.digestAt, r.dirty = held{}, time.Time{}, true
r.s.status.update(func(st *Status) { st.Held = 0 })
r.digest, r.digestAt, r.dirty = nil, time.Time{}, true
r.s.status.update(func(st *Status) { st.Held = r.waiting() })
}
// digestWaits offers the digest again later, after 1 second, then after
// twice as long each time, up to 30 seconds.
func (r *run) digestWaits(now time.Time, err error) {
if r.digestAt.IsZero() {
r.digestDelay = firstPrintRetry
r.log.Warn("ntfy digest waits to print", "ref", r.digest.Ref, "held", r.digest.Count, "err", err)
} else {
r.digestDelay = min(2*r.digestDelay, maxPrintRetry)
}
r.digestAt = now.Add(r.digestDelay)
}
// since returns the since parameter of the next connection: the cursor
@@ -846,6 +890,10 @@ func (r *run) save(now time.Time) {
h := r.held
st.Held = &h
}
if r.digest != nil {
d := *r.digest
st.Digest = &d
}
r.savedAt = now
if err := saveState(r.o.StateFile, st, r.o.Sync); err != nil {
if !r.saveFailed {