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

+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()