diff --git a/docs/design.md b/docs/design.md index f71baa0..d3424c1 100644 --- a/docs/design.md +++ b/docs/design.md @@ -207,6 +207,14 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( traced to its request without logging what it says. The server copies both strings, since a request ID the client sent lives in a buffer that fasthttp reuses for the next request. + A card's reference, its message's ID, is unique at its subscription: a + card whose source and reference the queue holds, among the last 512 of + that source kept apart from the statuses, is not queued again, and the + queue answers with the earlier job. A message the subscription would + hold for a digest never reaches Submit, so the subscription asks the + queue first, and one whose card it holds counts as printed. So a + message offered again after a restart prints once while its job is + stored. A request ID is never checked, since a client may set it. - **The preview reads the bytes back.** `escpos.Interpret` parses the stream the renderer produced, so the preview and the tests show what the printer receives rather than what the layout meant. It simulates the printer's own diff --git a/internal/app/uberbringer/ntfy.go b/internal/app/uberbringer/ntfy.go index bac151a..fe39c29 100644 --- a/internal/app/uberbringer/ntfy.go +++ b/internal/app/uberbringer/ntfy.go @@ -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. diff --git a/internal/app/uberbringer/ntfy_test.go b/internal/app/uberbringer/ntfy_test.go index ca503a4..e48d66d 100644 --- a/internal/app/uberbringer/ntfy_test.go +++ b/internal/app/uberbringer/ntfy_test.go @@ -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) diff --git a/internal/pkg/ntfy/fake_test.go b/internal/pkg/ntfy/fake_test.go index 6d61101..6ef8191 100644 --- a/internal/pkg/ntfy/fake_test.go +++ b/internal/pkg/ntfy/fake_test.go @@ -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() diff --git a/internal/pkg/ntfy/replay_test.go b/internal/pkg/ntfy/replay_test.go index 561f7ed..5921b47 100644 --- a/internal/pkg/ntfy/replay_test.go +++ b/internal/pkg/ntfy/replay_test.go @@ -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) + } + }) +} diff --git a/internal/pkg/ntfy/subscriber.go b/internal/pkg/ntfy/subscriber.go index 525cde4..7ecaa71 100644 --- a/internal/pkg/ntfy/subscriber.go +++ b/internal/pkg/ntfy/subscriber.go @@ -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) { diff --git a/internal/pkg/printqueue/queue.go b/internal/pkg/printqueue/queue.go index 7e5ed9f..321bbc0 100644 --- a/internal/pkg/printqueue/queue.go +++ b/internal/pkg/printqueue/queue.go @@ -155,6 +155,17 @@ type Meta struct { // "/"; 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() diff --git a/internal/pkg/printqueue/unique_test.go b/internal/pkg/printqueue/unique_test.go new file mode 100644 index 0000000..0f85537 --- /dev/null +++ b/internal/pkg/printqueue/unique_test.go @@ -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") + } + } +}