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

+5
View File
@@ -104,6 +104,11 @@ version may break callers; such changes are listed under **Breaking**.
### Changed
- A digest of an ntfy subscription has a reference of its own, `digest_`
and a TypeID, in its job's log lines and Sentry reports, in place of
`digest`. It is saved with the digest before the digest is queued, so a
restart queues the same digest again, and messages held after it wait
for the next one.
- A QR code that could be wider than the paper prints with smaller modules
instead of running off its edge. Its width is worked out as if its data
were bytes, so a code of digits or capitals may shrink before it
+2 -1
View File
@@ -220,7 +220,8 @@ Request bodies and the `Authorization` header are never sent to Sentry.
or the token.
- The worker logs each job with its `job_id`, its `source` (`print`,
`module:<name>` or `ntfy:<name>`) and its `ref`, the ID of the request or
ntfy message that sent it, never with what it prints.
ntfy message that sent it, or a digest's own reference, never with what
it prints.
- Each [ntfy subscription](ntfy.md) logs with its `subscription` name,
never with what a message says or its topic. It logs at WARN when its
connection is lost, when its credentials are refused and while the queue
+18 -11
View File
@@ -201,20 +201,22 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
match. A malformed scope can therefore never widen access.
- **Jobs remember their source.** `Submit` takes a `Meta`: the source
(`print`, `module:<name>` or `ntfy:<subscription>`) and a reference, the
request ID on the HTTP routes and the message's ID, or `digest`, for a
subscription. Job status shows the source and every
request ID on the HTTP routes and the message's ID, or the digest's own
reference, for a subscription. Job status shows the source and every
worker log line of the job carries both, so a printed receipt can be
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.
A subscription's references are unique at it: a card's is its message's
ID, and a digest's is a TypeID with the prefix `digest`, minted when the
digest is made. A job 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 or a digest 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
@@ -417,7 +419,12 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
during them, `quiet.min_priority` decides first. The receipt times are
saved, so a restart cannot reset the budget. A digest lists 50
messages and counts the rest; only those with a row count as printed
for updates.
for updates. Once made, a digest gets its reference and is saved with
it, apart from the messages held, and is submitted only once that save
has succeeded; messages held after that wait for the next digest. A
restart before the queue's answer is saved submits the same digest
again under the same reference, ahead of the later messages, so the
queue's duplicate check finds it while its job is stored.
- **Quiet hours print a morning digest (owner, 2026-11-30).** During a
subscription's daily window only `quiet.min_priority` (5) and above
print; the rest are held in the same digest buffer and print as one
+9 -3
View File
@@ -91,10 +91,16 @@ a volume for the state and the token file next to the config, as
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.
starts as if new. Held messages survive a restart, and so does a digest
made and not yet queued: it is saved before it is queued, and a restart
queues it again, unchanged. While the file cannot be written, digests
wait.
- **Jobs.** Each card and digest is an ordinary job with the source
`ntfy:<name>`. Like any job, one that is still waiting when the daemon
shuts down is marked failed, and is not printed after the restart.
`ntfy:<name>` and a reference: a card's is its message's ID, and a
digest's is its own, `digest_` and a TypeID. A card or digest whose
source and reference the queue already holds is not queued again. Like
any job, one that is still waiting when the daemon shuts down is marked
failed, and is not printed after the restart.
## Securing the topics
+20 -9
View File
@@ -1,6 +1,6 @@
# Plan: persistent job store and image previews
Status: **in progress; stage 1a's measurements are done (Investigation findings), and so is stage 1b's `[state] dir`. The store itself is not built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 1 records them. Each stage runs in its own session, briefed from its section: stage 1a follows decisions 1-3, stage 1b decision 4, stage 1c decisions 5-12, stage 1d decisions 13-15, phase 2 decision 16, phase 2b decisions 17 and 18, phase 3 decision 19 and phase 4 decision 20; phase 5 holds decisions 21-23. Phases 3a-3c need nothing from phases 1 and 2, so they can come first if the owner wants previews sooner. Phase 2b needs phase 1 but not phase 2, so it can come before phase 2. Every check on the live printer needs the owner's OK.
Status: **in progress; stage 1a's measurements are done (Investigation findings), and so are stage 1b's `[state] dir` and stage 1c's state machine on the memory store. The store on disk is not built.** The owner accepted every proposed default on 2026-12-01 (Decisions), and design.md's Planned next item 1 records them. Each stage runs in its own session, briefed from its section: stage 1a follows decisions 1-3, stage 1b decision 4, stage 1c decisions 5-12, stage 1d decisions 13-15, phase 2 decision 16, phase 2b decisions 17 and 18, phase 3 decision 19 and phase 4 decision 20; phase 5 holds decisions 21-23. Phases 3a-3c need nothing from phases 1 and 2, so they can come first if the owner wants previews sooner. Phase 2b needs phase 1 but not phase 2, so it can come before phase 2. Every check on the live printer needs the owner's OK.
## Decisions (owner, 2026-11-30)
@@ -389,7 +389,7 @@ ACKNOWLEDGEMENT, WHERE THE PRINTER HAS IT (phase 5, decision 21)
- Holding the connection until the receipt prints would make `/healthz` time out (3 s) during long prints. While a job holds the connection, `/healthz` reports the status that connection last polled, with its age.
THE STORE INTERFACE (printqueue)
printqueue defines the interface and an in-memory implementation and imports no database. A new package, `internal/pkg/jobstore`, implements it on disk, and internal/app wires it in. The engine can change without touching the queue. A sketch; stage 1c settles the names:
printqueue defines the interface and an in-memory implementation and imports no database. A new package, `internal/pkg/jobstore`, implements it on disk, and internal/app wires it in. The engine can change without touching the queue. Stage 1c settled it as below; `printqueue/store.go` has the full doc comments:
```go
// Record is one job as the store keeps it, with its deliveries.
@@ -424,6 +424,14 @@ type Loaded struct {
Uncertain []uint64 // the deliveries this Load turned from sending into uncertain
}
// Prune names what Finish drops in its commit, by Seq. A job that goes is
// listed with each of its deliveries and with its content, if it still has it.
type Prune struct {
Jobs []uint64
Deliveries []uint64
Content []uint64
}
// Store keeps jobs across restarts.
type Store interface {
// Durable reports whether records outlive the process.
@@ -435,12 +443,13 @@ type Store interface {
// Add stores a new job, its queued deliveries and its content. With
// sync, the commit is durable when Add returns.
Add(ctx context.Context, r Record, job []byte, sync bool) error
// Sending records attempt n of a delivery on the printer it uses and
// returns once that is durable.
Sending(ctx context.Context, delivery uint64, printer string, attempt int, at time.Time) error
// Finish records a delivery's final state and drops the given jobs,
// deliveries and contents, in one commit; sync as for Add.
Finish(ctx context.Context, d Delivery, dropJobs, dropDeliveries, dropContent []uint64, sync bool) error
// Sending records d, an attempt about to write to its printer, in
// sending: its printer, attempts, StartedAt and SentAt. It returns once
// that is durable.
Sending(ctx context.Context, d Delivery) error
// Finish records d in its final state and drops what p names, in one
// commit; sync as for Add.
Finish(ctx context.Context, d Delivery, p Prune, sync bool) error
// Job returns a stored job's content, or ErrContentGone.
Job(ctx context.Context, seq uint64) ([]byte, error)
// Idle is called when the queue has nothing to do.
@@ -658,6 +667,8 @@ Docs
### Stage 1c: The state machine, without a database
Done on 2026-12-01.
**Goal.** The queue runs on the `Store` interface, with the memory store only: jobs with deliveries, the state machine, `sent_at` and `uncertain`, restoring at start, the shutdown rules, store failures, the duplicate check and digest references, and retention by content bytes. No new dependency. With the memory store the daemon behaves as today, apart from what the API and the logs add, the duplicate check on ntfy jobs, and a digest kept apart from later held messages once it is made.
**Work.**
@@ -858,7 +869,7 @@ internal/pkg/printqueue
- A store error stops the queue (decision 11).
- If docs/plans/printers.md stage 3 has shipped, a delivery with any `sending` mark is not cancellable, even while it waits on the next printer of an anycast list, and a move takes the delivery lock (its decision 26).
- A cancelled job counts as finished for retention. An ntfy job keeps its reference (decision 10), so a replay after a restart does not queue it again.
- store.go: `StoredState` gains `cancelled`, and `Store` gains `Cancel(ctx, deliveries []uint64, at time.Time, dropJobs, dropDeliveries, dropContent []uint64) error`, one synced commit. The memory store implements it.
- store.go: `StoredState` gains `cancelled`, and `Store` gains `Cancel(ctx, deliveries []uint64, at time.Time, p Prune) error`, one synced commit. The memory store implements it.
internal/pkg/jobstore
- `Cancel`: one synced transaction that sets each delivery's `state` and `finished_at` and drops the given jobs, deliveries and contents. The `sequence` column is in the schema and written from stage 1d (RECORDS), so there is no schema step.
+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 {