Add ntfy subscriptions with digests, quiet hours and a cut feed
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s

[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics
itself and print each message as a notification card, so the phone's
ntfy app is the only client. Each subscription is one ntfy.Subscriber in
the daemon's errgroup: one event loop owns its state, and one goroutine
per connection reads the JSON stream. internal/app hands its messages to
modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name>
and the message's ID as ref, so ntfy never imports modules.

The cursor is ntfy server time, never an ID. ntfy sends open before the
replay, so only keepalives and messages dealt with move it, and a
reconnect asks for two minutes before it, since a message is dated
before its attachment is stored. The IDs of the messages a replay could
send again are kept, at least the last 512 and 20,000 at most, so a
flood in the overlap never reprints; when the cap forgets IDs a replay
could send, the floor rises past them. A saved floor bounds replays: a
first start sets it to the open event's time, and max_backlog (default
1h, at most 12h), measured by the server's clock as each connection
tells it (its open event, else its Date, then the monotonic clock), never the
host's, so replays are requested unclamped and filtered as they arrive,
raises it when it clamps, so what it left out stays out. The
state, with the held messages and the receipt times, is written
atomically at most once a second and at shutdown. Redirects are never
followed, so credentials never go to another address or over plain http.
A stalled stream reconnects after twice the keepalive plus 15 s,
failures back off 5 to 120 s with jitter, a 429 waits for Retry-After,
and refused credentials, checked at startup through /auth, show as
unauthorized and retry every 5 minutes. A full print queue pauses
reading and retries the message from 1 s to 30 s, and the cursor moves
past it only once it is queued.

The paper budget is a strict window: at most rate_limit receipts (5) in
any rate_window (10m), digests included; the rest are held and print on
one digest card once there is room, and outside quiet hours
bypass_priority (5) and above print at once. Quiet hours hold everything
below their min_priority for one Overnight digest when the window ends,
or drop it; windows cross midnight and keep their times of day when
clocks change, also where the change skips midnight or a window's end.
A message whose sequence printed before, on a card or a digest row, is marked
(updated), or skipped with ntfy.format.updates = "skip"; the first of a
sequence its publisher named prints plain.

/healthz lists the subscriptions without changing how its status code is
decided, and no credential, topic or message text reaches it, the logs
or a config error. Subscriptions come from the file only, with strict
keys and per-entry defaults; credentials are optional, at most one kind.
ntfy.state_dir is required with a subscription: the unit gains
StateDirectory=uberbringer, install.sh writes the path into a new
config, and the Docker image sets it for a volume and runs as the fixed
user 10001. README explains how to lock a self-hosted ntfy server down
so that only your publishers can print.

Breaking: printer.cut_feed (default 3) feeds blank lines before every
cut, so the last line no longer sits right at the cut. They count toward
format.max_lines once per copy, so a job within 3 lines a copy of the
limit now fails. The renderer's option is 0 unless set, so the pinned
receipts keep their bytes.

testing/synctest drives the subscriber on a virtual clock, including a
24-hour soak with floods, repeats, refusals, a full queue, quiet hours
and a restart that fails on any leaked goroutine; it replaces a 24-hour
run on hardware. Tests over real sockets cover net/http's goroutines and
redirects to plain http and to another port.

Checked on the TM-T88IV against a live ntfy server: a phone message, quiet
hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a
30-minute outage with an update, a wrong token, and the three-line cut
feed. The digest and the cut-feed card are pinned in TestPaperReceipts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 17:50:23 -06:00
1 parent 1335ed0687
commit fb76284129
52 files changed
+6464 -390

No files matched your search

+12 -4
View File
@@ -75,10 +75,15 @@ func TestRenderCompat(t *testing.T) {
var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex from the current renderer")
// paperReceipts are jobs whose printed result was checked on the TM-T88IV,
// with the file their bytes are pinned in and, for a job with an image
// URL, the image it was printed with. The bytes are rendered for a TM-T88
// in CP437 with the default options.
var paperReceipts = []struct{ job, hex, image string }{
// with the file their bytes are pinned in, for a job with an image URL the
// image it was printed with, and the blank lines it fed before its cut.
// The bytes are rendered for a TM-T88 in CP437 with the default options
// otherwise. ntfy-cutfeed's topic is replaced by a name of the same
// length.
var paperReceipts = []struct {
job, hex, image string
cutFeed int
}{
{job: filepath.Join("..", "..", "..", "examples", "blocks.json"), hex: filepath.Join("testdata", "paper", "blocks.hex")},
{job: filepath.Join("testdata", "paper", "note.json"), hex: filepath.Join("testdata", "paper", "note.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-high.json"), hex: filepath.Join("testdata", "paper", "ntfy-high.hex"),
@@ -86,6 +91,8 @@ var paperReceipts = []struct{ job, hex, image string }{
{job: filepath.Join("testdata", "paper", "ntfy-urgent.json"), hex: filepath.Join("testdata", "paper", "ntfy-urgent.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-default.json"), hex: filepath.Join("testdata", "paper", "ntfy-default.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-min.json"), hex: filepath.Join("testdata", "paper", "ntfy-min.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-digest.json"), hex: filepath.Join("testdata", "paper", "ntfy-digest.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-cutfeed.json"), hex: filepath.Join("testdata", "paper", "ntfy-cutfeed.hex"), cutFeed: 3},
}
// TestPaperReceipts fails when the bytes of a receipt checked on paper
@@ -110,6 +117,7 @@ func TestPaperReceipts(t *testing.T) {
MaxPixels: 25_000_000,
MaxHeight: 4000,
MaxLines: 2000,
CutFeed: receiptFile.cutFeed,
}, fetcher)
got, err := r.Render(context.Background(), readJob(t, receiptFile.job))
if err != nil {
+79
View File
@@ -0,0 +1,79 @@
package receipt_test
import (
"bytes"
"context"
"errors"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// cutFeedRenderer is a TM-T20 renderer that feeds feed lines before each
// cut and fails a job over maxLines.
func cutFeedRenderer(t *testing.T, feed, maxLines int) *receipt.Renderer {
t.Helper()
return receipt.NewRenderer(receipt.Options{
Profile: tmT20(t), CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000,
MaxLines: maxLines, CutFeed: feed,
}, &fakeFetcher{})
}
// CutFeed feeds blank lines before every cut: the one added at the end of
// each copy and an explicit cut element alike. Zero feeds nothing.
func TestRenderCutFeed(t *testing.T) {
job := receipt.Job{Copies: 2, Elements: []receipt.Element{
{Type: "text", Text: "first"},
{Type: "cut", Mode: "full"},
{Type: "text", Text: "second"},
}}
feedThenPartial := append([]byte{0x1B, 'd', 3}, partialCut...)
feedThenFull := []byte{0x1B, 'd', 3, 0x1D, 0x56, 65, 0}
out, err := cutFeedRenderer(t, 3, 0).Render(context.Background(), job)
if err != nil {
t.Fatal(err)
}
if n := bytes.Count(out, feedThenPartial); n != 2 {
t.Errorf("%d fed partial cuts, want one per copy", n)
}
if n := bytes.Count(out, feedThenFull); n != 2 {
t.Errorf("%d fed full cuts, want one per copy", n)
}
if !bytes.HasSuffix(out, feedThenPartial) {
t.Errorf("the receipt ends % X, want the feed and the cut", out[max(len(out)-8, 0):])
}
out, err = cutFeedRenderer(t, 0, 0).Render(context.Background(), job)
if err != nil {
t.Fatal(err)
}
if bytes.Contains(out, []byte{0x1B, 'd'}) || !bytes.HasSuffix(out, partialCut) {
t.Errorf("CutFeed 0 fed paper: % X", out[max(len(out)-8, 0):])
}
}
// The preview shows the fed lines as blank lines before the cut, and they
// count toward the line limit.
func TestPreviewAndLimitCountCutFeed(t *testing.T) {
job := receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "one line"}}}
p, err := cutFeedRenderer(t, 3, 0).Preview(context.Background(), job)
if err != nil {
t.Fatal(err)
}
var kinds []string
for _, l := range p.Lines {
kinds = append(kinds, l.Kind+":"+l.Text)
}
if len(p.Lines) != 5 || p.Lines[0].Text != "one line" || p.Lines[1].Text != "" || p.Lines[3].Text != "" ||
p.Lines[4].Kind != escpos.LineCut {
t.Errorf("preview lines %q, want the text, three blank lines and the cut", kinds)
}
_, err = cutFeedRenderer(t, 3, 3).Render(context.Background(), job)
var limit *receipt.LineLimitError
if !errors.As(err, &limit) || limit.Lines != 4 {
t.Errorf("err = %v, want 4 lines over the limit of 3", err)
}
}
+19 -2
View File
@@ -46,6 +46,11 @@ type Options struct {
// (ESC 3) used while a box prints, to close the gaps in its vertical
// borders. Zero keeps the printer's default spacing.
BoxLineSpacing int
// CutFeed is how many blank lines, 0-255, feed before each cut, so that
// the last printed line does not sit right at the cut. The cut itself
// feeds the last line past the cutter first.
CutFeed int
}
// LineLimitError is returned for a job that would print more lines than
@@ -124,6 +129,7 @@ func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, er
profile: r.options.Profile,
codePage: r.options.CodePage,
lineSpacing: r.options.BoxLineSpacing,
cutFeed: r.options.CutFeed,
}
unknown := make(map[int]int)
for i, el := range job.Elements {
@@ -137,7 +143,7 @@ func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, er
}
p.endLine()
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
body.Cut(escpos.CutPartial, 0)
p.cut(escpos.CutPartial)
}
lines := p.lines * job.copies()
if limit := r.options.MaxLines; limit > 0 && lines > limit {
@@ -239,6 +245,7 @@ type printer struct {
profile escpos.Profile
codePage escpos.CodePage
lineSpacing int
cutFeed int
x int
// lines counts printed lines: text lines, fed lines, and one for each
@@ -314,13 +321,23 @@ func (p *printer) element(el Element, img *image.Paletted) error {
return err
}
p.endLine()
p.b.Cut(mode, 0)
p.cut(mode)
default:
return fmt.Errorf("unknown type %q", el.Type)
}
return nil
}
// cut feeds the blank lines before a cut, which count as printed lines,
// then cuts. The current line must have ended.
func (p *printer) cut(mode escpos.CutMode) {
if p.cutFeed > 0 {
p.b.Feed(uint8(min(p.cutFeed, 255)))
p.lines += min(p.cutFeed, 255)
}
p.b.Cut(mode, 0)
}
// qrSize returns the module size of a QR code holding n bytes: the size
// spec asks for, made smaller, down to one dot, while the code could be
// wider than the paper. The width is worked out as if the data were bytes,
+6
View File
@@ -0,0 +1,6 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac4201b4501437574
206665656420746573741b450020c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4bf0ab320546872656520626c616e6b206c696e6573206265666f
726520746865206375742e202020202020b30ac0c4c4c4c4c4206e7466792d70
617065722d746f70696320fa203330204e6f762031353a303220c4c4d90a1b45
001b2d001d42001d21001b4d001b64031d564200
+16
View File
@@ -0,0 +1,16 @@
{
"elements": [
{
"type": "box",
"children": [
{
"type": "text",
"text": "Three blank lines before the cut."
}
],
"title": "Cut feed test",
"title_bold": true,
"footer": "ntfy-paper-topic · 30 Nov 15:02"
}
]
}
+6
View File
@@ -0,0 +1,6 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac4201b45014f7665
726e6967687420fa20312068656c641b450020c4c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4bf0ab32031343a35372051756965742074687265652020202020
2020202020202020202020202020202020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4c4c4c4c4c4c4c42031343a35372d31353a303220c4c4d90a1b45
001b2d001d42001d21001b4d001d564200
+16
View File
@@ -0,0 +1,16 @@
{
"elements": [
{
"type": "box",
"children": [
{
"type": "text",
"text": "14:57 Quiet three"
}
],
"title": "Overnight · 1 held",
"title_bold": true,
"footer": "14:57-15:02"
}
]
}