Answer a repeated ntfy message with its earlier job

Once queued jobs survive a restart, a crash in the second between
queueing an ntfy message and saving the subscription's state would
print the message twice: the replay offers it again. A card is now
submitted as unique by its message's ID. If the queue already holds
that source and reference, Submit queues nothing and returns the
earlier job, or its ID and source once its status is gone, and logs
the repeat. The queue keeps the last 512 references of each source
apart from the statuses, so queue.history = 0 cannot defeat the check,
and they come back on restore.

A replayed message that quiet hours or the paper budget would hold for
a digest never reaches Submit, so the check could not answer it, and
it would print again as a digest row. Before it holds a message, the
subscription now asks the queue through its handler whether it holds
that message's card; if so, the message counts as printed and is not
held.

Only unique jobs take part. On the HTTP routes the reference is a
request ID, which a client may set, so a check on it could answer a
new request with an old job. A unique insert is stored with a sync,
since the subscription treats the message as dealt with once it is
queued.

Part of 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:09 -06:00
1 parent 792ee26af5
commit 8b8b7da0c6
8 files changed
+336 -17

No files matched your search

+11 -2
View File
@@ -147,6 +147,7 @@ func quietHours(q config.NtfyQuiet, formatZone string) (*ntfy.Quiet, error) {
// ntfySubmitter is the print queue as a subscription uses it.
type ntfySubmitter interface {
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
Holds(source, ref string) bool
}
// ntfyPrinter prints what a subscription delivers: each message as a
@@ -163,7 +164,9 @@ type ntfyPrinter struct {
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.
// 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
// the queue already holds, is not queued twice.
func (p *ntfyPrinter) Message(_ context.Context, m ntfy.Message, updated bool) error {
n, err := modules.FromNtfy(m)
if err != nil {
@@ -174,7 +177,13 @@ func (p *ntfyPrinter) Message(_ context.Context, m ntfy.Message, updated bool) e
env := p.env()
job, err := modules.Card(n, env.Card, env)
p.reportFallback(m.ID, err)
return p.submit(job, printqueue.Meta{Ref: m.ID, Sequence: m.Notification()})
return p.submit(job, printqueue.Meta{Ref: m.ID, Sequence: m.Notification(), Unique: true})
}
// Queued reports whether the queue holds the card of m, which a message
// offered again after a restart may already have.
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.
+15 -1
View File
@@ -218,6 +218,16 @@ func (q *fakeQueue) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.St
return printqueue.Status{}, nil
}
// Holds reports whether a unique job of source and ref was submitted.
func (q *fakeQueue) Holds(source, ref string) bool {
for _, m := range q.metas {
if m.Unique && m.Source == source && m.Ref == ref {
return true
}
}
return false
}
func testEnv() modules.Env {
return modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
}
@@ -244,7 +254,7 @@ func TestNtfyPrinter(t *testing.T) {
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"}) ||
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"}) {
t.Errorf("metas %+v", q.metas)
}
@@ -257,6 +267,10 @@ func TestNtfyPrinter(t *testing.T) {
t.Errorf("metas %+v, %v; want a card of a named sequence to carry its notification", q.metas, err)
}
if !p.Queued(m) || p.Queued(ntfy.Message{ID: "other"}) {
t.Error("Queued does not answer by the card's message ID")
}
q.err = printqueue.ErrQueueFull
if err := p.Message(ctx, m, false); !errors.Is(err, printqueue.ErrQueueFull) {
t.Errorf("err = %v, want the full queue back", err)
+7
View File
@@ -345,6 +345,9 @@ type recorder struct {
cards []card
digests []Digest
fail int
// queued, if set, answers Queued for a message's ID.
queued func(id string) bool
}
// card is a message the recorder printed.
@@ -377,6 +380,10 @@ func (h *recorder) Digest(_ context.Context, d Digest) error {
return nil
}
func (h *recorder) Queued(m Message) bool {
return h.queued != nil && h.queued(m.ID)
}
func (h *recorder) failNext(n int) {
h.mu.Lock()
defer h.mu.Unlock()
+50
View File
@@ -3,6 +3,7 @@ package ntfy
import (
"context"
"fmt"
"os"
"slices"
"testing"
"testing/synctest"
@@ -379,3 +380,52 @@ func TestHeldPastTheRowsIsNotPrinted(t *testing.T) {
}
})
}
// A card queued just before a crash that lost the save recording it is
// offered again by the replay. Held by quiet hours, it would never reach
// the queue's own check and would print again on the morning digest, so
// the subscription asks the queue first: a card the queue holds counts as
// printed and is not held.
func TestReplayedCardTheQueueHoldsIsNotHeld(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.Quiet = nightly(loc)
o.MaxBacklog = 12 * time.Hour
h := &recorder{}
_, stop := start(t, o, h)
synctest.Wait()
before, err := os.ReadFile(o.StateFile)
if err != nil {
t.Fatal(err)
}
sleepUntil(time.Date(2026, 11, 30, 21, 30, 0, 0, loc))
card := f.publish(Message{Title: "backup done", RawPriority: 3})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{card.ID}) {
t.Fatalf("printed %v, want the card", got)
}
stop()
if err := os.WriteFile(o.StateFile, before, 0o600); err != nil {
t.Fatal(err)
}
sleepUntil(time.Date(2026, 11, 30, 23, 0, 0, 0, loc))
h2 := &recorder{queued: func(id string) bool { return id == card.ID }}
s, stop2 := start(t, o, h2)
defer stop2()
synctest.Wait()
if st := s.Status(); st.Held != 0 {
t.Errorf("status %+v, want the replayed card not held", st)
}
sleepUntil(time.Date(2026, 12, 1, 7, 0, 1, 0, loc))
if ds := h2.digestList(); len(ds) != 0 {
t.Errorf("digests %+v, want none: the queue holds the card", ds)
}
if got := h2.printed(); len(got) != 0 {
t.Errorf("printed %v after the restart, want nothing", got)
}
})
}
+25 -2
View File
@@ -163,6 +163,12 @@ type Handler interface {
// Digest prints the messages held back on one receipt. An error is
// retried as for Message, while the subscription goes on reading.
Digest(ctx context.Context, d Digest) error
// Queued reports whether the print queue already holds the card of m:
// one queued before a restart that lost the subscription's record of
// it. Such a message is not held for a digest, where it would print
// again.
Queued(m Message) bool
}
// Subscriber reads the messages of an ntfy server's topics as they are
@@ -520,11 +526,15 @@ func (r *run) deliver(ctx context.Context, m Message, now time.Time) bool {
r.log.Debug("ntfy message dropped in quiet hours", "ntfy_id", m.ID)
return true
}
r.hold(m, updated, true, now)
if !r.queued(m) {
r.hold(m, updated, true, now)
}
return true
}
if priority < r.o.BypassPriority && (!r.budget.room(now) || (r.held.Count > 0 && !quiet)) {
r.hold(m, updated, false, now)
if !r.queued(m) {
r.hold(m, updated, false, now)
}
return true
}
if err := r.h.Message(ctx, m, updated); err != nil {
@@ -541,6 +551,19 @@ func (r *run) deliver(ctx context.Context, m Message, now time.Time) bool {
return true
}
// queued reports whether the print queue already holds m's card, queued
// before a restart that lost the save of m. m then counts as printed and
// is not held, since a digest row would print it again; a message that is
// not held reaches the queue, whose own check answers it.
func (r *run) queued(m Message) bool {
if m.ID == "" || !r.h.Queued(m) {
return false
}
r.printed.add(m.Sequence())
r.log.Debug("ntfy message already queued", "ntfy_id", m.ID)
return true
}
// hold keeps m for the next digest. Only a message that gets a row counts
// as printed; one past the rows is only counted on the digest.
func (r *run) hold(m Message, updated, overnight bool, now time.Time) {
+76 -12
View File
@@ -155,6 +155,17 @@ type Meta struct {
// "<topic>/<sequence>"; empty for other jobs. It is stored with the
// job.
Sequence string
// Unique marks Ref as unique at Source, as an ntfy message's ID is: a
// job whose source and reference the queue already holds is not
// queued again. A unique job is stored with a sync. A client's request
// ID is never unique, since a client may reuse one.
Unique bool
}
// refKey is a unique job's source and reference.
type refKey struct {
source, ref string
}
// entry is a job the queue keeps.
@@ -206,6 +217,11 @@ type Queue struct {
closed bool
failure error // the store error that stopped the queue
// refs are the kept references of unique jobs, KeptRefs per source,
// apart from the statuses; refOrder lists each source's oldest first.
refs map[refKey]JobID
refOrder map[string][]string
// wake tells the worker that a delivery is waiting or the queue
// stopped.
wake chan struct{}
@@ -237,6 +253,8 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
logger: logger,
options: options,
jobs: make(map[JobID]*entry),
refs: make(map[refKey]JobID),
refOrder: make(map[string][]string),
wake: make(chan struct{}, 1),
halted: halted,
halt: halt,
@@ -247,7 +265,9 @@ func New(renderer Renderer, sender Sender, store Store, logger *slog.Logger, opt
// validated so callers can report problems synchronously; it is validated
// again when rendered. The job is stored before Submit returns, whatever
// happens to the caller meanwhile. A store error stops the queue and is
// returned, marked as ErrStoreFailed.
// returned, marked as ErrStoreFailed. A unique job whose source and
// reference the queue already holds is not queued: Submit returns the
// earlier job's status, or only its ID and source once its status is gone.
func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
id, err := typeid.New[JobID]()
if err != nil {
@@ -257,12 +277,19 @@ func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
if err != nil {
return Status{}, fmt.Errorf("encoding job %s: %w", id, err)
}
unique := meta.Unique && meta.Ref != ""
q.submitMu.Lock()
defer q.submitMu.Unlock()
if err := q.admit(); err != nil {
earlier, repeated, err := q.admit(meta, unique)
if err != nil {
return Status{}, err
}
if repeated {
q.logger.Info("job already queued from this source and reference; not queued again",
"job_id", earlier.ID.String(), "source", meta.Source, "ref", meta.Ref)
return earlier, nil
}
q.nextJob++
q.nextDelivery++
rec := Record{
@@ -271,18 +298,22 @@ func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
Source: meta.Source,
Ref: meta.Ref,
Sequence: meta.Sequence,
Unique: unique,
CreatedAt: time.Now().UTC(),
Deliveries: []Delivery{
{Seq: q.nextDelivery, Printer: DefaultPrinter, State: StoredQueued},
},
}
if err := q.store.Add(context.Background(), rec, content, false); err != nil {
if err := q.store.Add(context.Background(), rec, content, unique); err != nil {
return Status{}, q.stop(fmt.Errorf("storing job %s: %w", id, err))
}
rec.Size = int64(len(content))
q.mu.Lock()
e := q.keep(rec)
if unique {
q.keepRef(meta.Source, meta.Ref, id)
}
q.waiting = append(q.waiting, e.deliveries...)
status := e.status()
q.mu.Unlock()
@@ -290,17 +321,46 @@ func (q *Queue) Submit(job receipt.Job, meta Meta) (Status, error) {
return status, nil
}
// admit refuses a new job once the queue is closed or full.
func (q *Queue) admit() error {
// admit refuses a new job once the queue is closed or full. For a unique
// job whose source and reference it holds, it returns the earlier job's
// status instead, and true.
func (q *Queue) admit(meta Meta, unique bool) (Status, bool, error) {
q.mu.Lock()
defer q.mu.Unlock()
switch {
case q.closed:
return ErrClosed
case len(q.waiting) >= q.options.Size:
return ErrQueueFull
if q.closed {
return Status{}, false, ErrClosed
}
return nil
if id, ok := q.refs[refKey{meta.Source, meta.Ref}]; unique && ok {
if e, ok := q.jobs[id]; ok {
return e.status(), true, nil
}
return Status{ID: id, Source: meta.Source}, true, nil
}
if len(q.waiting) >= q.options.Size {
return Status{}, false, ErrQueueFull
}
return Status{}, false, nil
}
// Holds reports whether the queue holds a unique job of source and ref,
// among the references it keeps.
func (q *Queue) Holds(source, ref string) bool {
q.mu.Lock()
defer q.mu.Unlock()
_, ok := q.refs[refKey{source, ref}]
return ok
}
// keepRef records the reference of a unique job, and forgets the oldest of
// its source beyond KeptRefs. The caller holds q.mu.
func (q *Queue) keepRef(source, ref string, id JobID) {
q.refs[refKey{source, ref}] = id
order := append(q.refOrder[source], ref)
if len(order) > KeptRefs {
delete(q.refs, refKey{source, order[0]})
order = slices.Delete(order, 0, 1)
}
q.refOrder[source] = order
}
// keep makes r a job the queue keeps and returns it. The caller holds
@@ -337,7 +397,8 @@ func (q *Queue) Pending() int {
// Submit. Their queued deliveries wait again, in submission order and
// ahead of any new job, even beyond Size, and their statuses answer at
// once. Each delivery the load turned uncertain is logged at WARN by its
// job's ID, source and reference; it is never sent again.
// job's ID, source and reference; it is never sent again. The kept
// references of unique jobs come back too, for the duplicate check.
func (q *Queue) Restore(ctx context.Context) error {
q.submitMu.Lock()
defer q.submitMu.Unlock()
@@ -380,6 +441,9 @@ func (q *Queue) Restore(ctx context.Context) error {
q.finished = append(q.finished, e)
}
}
for _, r := range loaded.Refs {
q.keepRef(r.Source, r.Ref, r.ID)
}
waiting := len(q.waiting)
q.mu.Unlock()
+144
View File
@@ -0,0 +1,144 @@
package printqueue_test
import (
"context"
"fmt"
"slices"
"strings"
"testing"
"uberbringer/internal/pkg/printqueue"
)
// A unique job submitted twice is queued once: the second Submit answers
// with the first job, also once its status is gone. The same reference on
// a job that is not unique, or from another source, is queued again.
func TestUniqueJobQueuedOnce(t *testing.T) {
var logs lockedBuffer
store := newTestStore(printqueue.NewMemoryStore())
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, slogTo(&logs), printqueue.Options{})
meta := printqueue.Meta{Source: "ntfy:home", Ref: "msg1", Unique: true}
first, err := q.Submit(job("card"), meta)
if err != nil {
t.Fatal(err)
}
again, err := q.Submit(job("card"), meta)
if err != nil || again.ID != first.ID || again.State != printqueue.StateQueued {
t.Errorf("second Submit = %+v, %v; want the first job", again, err)
}
if q.Pending() != 1 {
t.Errorf("Pending = %d, want 1", q.Pending())
}
if !strings.Contains(logs.String(), "job_id="+first.ID.String()) || !strings.Contains(logs.String(), "not queued again") {
t.Errorf("log %q, want the repeat logged with the earlier job", logs.String())
}
plain, _ := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Ref: "msg1"})
other, _ := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:work", Ref: "msg1", Unique: true})
noRef, _ := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Unique: true})
noRefAgain, _ := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Unique: true})
ids := []printqueue.JobID{first.ID, plain.ID, other.ID, noRef.ID, noRefAgain.ID}
slices.SortFunc(ids, func(a, b printqueue.JobID) int { return strings.Compare(a.String(), b.String()) })
if len(slices.Compact(ids)) != 5 || q.Pending() != 5 {
t.Errorf("Pending = %d; want a job each for the plain, the other source and the two without a reference", q.Pending())
}
want := []commit{
{op: "add", seq: 1, state: printqueue.StoredQueued, synced: true},
{op: "add", seq: 2, state: printqueue.StoredQueued},
{op: "add", seq: 3, state: printqueue.StoredQueued, synced: true},
{op: "add", seq: 4, state: printqueue.StoredQueued},
{op: "add", seq: 5, state: printqueue.StoredQueued},
}
if got := store.Commits(); !slices.Equal(got, want) {
t.Errorf("commits %+v, want %+v: unique inserts synced", got, want)
}
}
// The duplicate check outlives the status: with History 0 the first job's
// status goes once it prints, and a repeat still gets its ID.
func TestUniqueJobAfterItsStatusIsGone(t *testing.T) {
sender := &fakeSender{}
q := printqueue.New(fakeRenderer{}, sender, printqueue.NewMemoryStore(), discardLogger(), printqueue.Options{Size: 10, History: 0})
startQueue(t, q)
meta := printqueue.Meta{Source: "ntfy:home", Ref: "msg1", Unique: true}
first, _ := q.Submit(job("card"), meta)
waitFor(t, func() bool { return len(sender.Sent()) == 1 })
waitFor(t, func() bool { _, err := q.Status(first.ID); return err != nil })
again, err := q.Submit(job("card"), meta)
if err != nil || again != (printqueue.Status{ID: first.ID, Source: "ntfy:home"}) {
t.Errorf("Submit after the status went = %+v, %v; want only the first job's ID and source", again, err)
}
if q.Pending() != 0 || len(sender.Sent()) != 1 {
t.Errorf("pending %d, sent %v; want nothing more", q.Pending(), sender.Sent())
}
}
// The references are kept KeptRefs per source: the oldest is forgotten.
func TestUniqueRefsKeptPerSource(t *testing.T) {
q := newQueueOn(printqueue.NewMemoryStore(), fakeRenderer{}, &fakeSender{}, discardLogger(),
printqueue.Options{Size: 2 * printqueue.KeptRefs})
var ids []printqueue.JobID
for i := range printqueue.KeptRefs + 1 {
st, err := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Ref: fmt.Sprint(i), Unique: true})
if err != nil {
t.Fatal(err)
}
ids = append(ids, st.ID)
}
if st, _ := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Ref: "1", Unique: true}); st.ID != ids[1] {
t.Errorf("reference 1 gave %s, want the job it named, %s", st.ID, ids[1])
}
if st, _ := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Ref: "0", Unique: true}); st.ID == ids[0] {
t.Error("the oldest reference was still kept")
}
}
// A unique job queued before a restart is found after it, so an ntfy
// message replayed after a crash prints once.
func TestUniqueJobAcrossARestart(t *testing.T) {
store := printqueue.NewDurableMemoryStore()
meta := printqueue.Meta{Source: "ntfy:home", Ref: "msg1", Unique: true}
before := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
first, _ := before.Submit(job("card"), meta)
sender := &fakeSender{}
q := newQueueOn(store, fakeRenderer{}, sender, discardLogger(), printqueue.Options{})
if err := q.Restore(context.Background()); err != nil {
t.Fatal(err)
}
again, err := q.Submit(job("card"), meta)
if err != nil || again.ID != first.ID {
t.Errorf("Submit after the restart = %+v, %v; want the job queued before it", again, err)
}
startQueue(t, q)
waitForState(t, q, first.ID, printqueue.StateDone)
if sent := sender.Sent(); !slices.Equal(sent, []string{"card"}) {
t.Errorf("sent %v, want the card once", sent)
}
}
// Holds answers for the kept references of unique jobs, also after a
// restart, and for nothing else.
func TestHolds(t *testing.T) {
store := printqueue.NewDurableMemoryStore()
q := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
if _, err := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Ref: "msg1", Unique: true}); err != nil {
t.Fatal(err)
}
if _, err := q.Submit(job("card"), printqueue.Meta{Source: "ntfy:home", Ref: "req1"}); err != nil {
t.Fatal(err)
}
after := newQueueOn(store, fakeRenderer{}, &fakeSender{}, discardLogger(), printqueue.Options{})
if err := after.Restore(context.Background()); err != nil {
t.Fatal(err)
}
for _, queue := range []*printqueue.Queue{q, after} {
if !queue.Holds("ntfy:home", "msg1") || queue.Holds("ntfy:home", "req1") ||
queue.Holds("ntfy:work", "msg1") || queue.Holds("ntfy:home", "msg2") {
t.Error("Holds answers other than for the unique job's source and reference")
}
}
}