Files
uberbringer/internal/pkg/receipt/render.go
T
57_WolveandClaude Opus 5.5 fb76284129
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s
Add ntfy subscriptions with digests, quiet hours and a cut feed
[[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>
2026-11-30 17:50:23 -06:00

528 lines
14 KiB
Go

package receipt
import (
"bytes"
"context"
"fmt"
"image"
"strings"
"unicode/utf8"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/raster"
)
// unavailableImage is the line printed in place of an optional image that
// failed to load.
const unavailableImage = "[image unavailable]"
// Fetcher downloads remote image data.
type Fetcher interface {
Fetch(ctx context.Context, url string) ([]byte, error)
}
// Options configures a Renderer.
type Options struct {
// Profile describes the printer; its DotsPerLine is the image width.
Profile escpos.Profile
// CodePage is the character table text is transcoded to.
CodePage escpos.CodePage
// Columns, when positive, overrides the Font A characters per line used
// for word wrapping and block widths.
Columns int
// MaxPixels caps decoded image size; MaxHeight caps printed image height
// in dots.
MaxPixels int
MaxHeight int
// MaxLines, when positive, fails a job that would print more lines,
// all copies counted. It is a backstop against runaway text.
MaxLines int
// BoxLineSpacing, when positive, is the line spacing in motion units
// (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
// Options.MaxLines allows.
type LineLimitError struct {
Lines, Limit int
}
// Error implements error.
func (e *LineLimitError) Error() string {
return fmt.Sprintf("receipt would print %d lines, limit is %d", e.Lines, e.Limit)
}
// Renderer turns jobs into ESC/POS command streams. It is safe for concurrent
// use.
type Renderer struct {
options Options
fetcher Fetcher
}
// NewRenderer returns a Renderer. fetcher loads images given by URL.
func NewRenderer(options Options, fetcher Fetcher) *Renderer {
if fetcher == nil {
panic("receipt.NewRenderer: fetcher must not be nil")
}
if options.Profile.DotsPerLine <= 0 || options.Profile.FontAWidth <= 0 || options.Profile.FontBWidth <= 0 {
panic("receipt.NewRenderer: profile must be set")
}
if options.MaxPixels <= 0 || options.MaxHeight <= 0 {
panic("receipt.NewRenderer: image limits must be positive")
}
if options.MaxLines < 0 || options.BoxLineSpacing < 0 || options.BoxLineSpacing > escpos.MaxLineSpacing {
panic("receipt.NewRenderer: MaxLines must not be negative and BoxLineSpacing must be 0-255")
}
return &Renderer{options: options, fetcher: fetcher}
}
// Render validates job, loads its images and returns the complete command
// stream. Nothing is returned unless the whole receipt rendered, so a failure
// never reaches the printer half-done.
func (r *Renderer) Render(ctx context.Context, job Job) ([]byte, error) {
if err := job.Validate(); err != nil {
return nil, err
}
images, err := r.loadImages(ctx, job)
if err != nil {
return nil, err
}
out, err := r.render(job, images)
if err != nil {
return nil, err
}
return out.stream, nil
}
// rendered is a job's command stream and what Preview needs to read it back.
type rendered struct {
stream []byte
// raw holds the byte range of every raw element in stream.
raw []escpos.Span
// lines is the number of lines the stream prints.
lines int
// unknown counts, by element index, the characters printed as '?'.
unknown map[int]int
}
// render lays out a validated job with its images loaded.
func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, error) {
var body escpos.Builder
p := printer{
b: &body,
lineDots: r.textLineDots(),
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 {
if err := p.element(el, images[i]); err != nil {
return rendered{}, fmt.Errorf("rendering elements[%d] (%s): %w", i, el.Type, err)
}
if p.unknown > 0 {
unknown[i] = p.unknown
p.unknown = 0
}
}
p.endLine()
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
p.cut(escpos.CutPartial)
}
lines := p.lines * job.copies()
if limit := r.options.MaxLines; limit > 0 && lines > limit {
return rendered{}, &LineLimitError{Lines: lines, Limit: limit}
}
var out escpos.Builder
out.Initialize()
out.SelectCodePage(r.options.CodePage)
var spans []escpos.Span
for range job.copies() {
offset := out.Len()
for _, s := range p.raw {
spans = append(spans, escpos.Span{From: s.From + offset, To: s.To + offset})
}
out.Raw(body.Bytes())
}
return rendered{stream: bytes.Clone(out.Bytes()), raw: spans, lines: lines, unknown: unknown}, nil
}
// textLineDots is the line width used for text layout.
func (r *Renderer) textLineDots() int {
if r.options.Columns > 0 {
return r.options.Columns * r.options.Profile.FontAWidth
}
return r.options.Profile.DotsPerLine
}
// loadImages fetches, decodes and dithers every image before anything is
// rendered, keyed by element index. An optional image that fails to load
// has no entry, and prints as unavailableImage.
func (r *Renderer) loadImages(ctx context.Context, job Job) (map[int]*image.Paletted, error) {
images := make(map[int]*image.Paletted)
for i, el := range job.Elements {
if el.Type != TypeImage {
continue
}
img, err := r.loadImage(ctx, el)
if err != nil && el.Optional {
continue
}
if err != nil {
return nil, fmt.Errorf("elements[%d] (image): %w", i, err)
}
images[i] = img
}
return images, nil
}
func (r *Renderer) loadImage(ctx context.Context, el Element) (*image.Paletted, error) {
spec, err := el.imageSpec()
if err != nil {
return nil, err
}
data := spec.data
if spec.url != "" {
if data, err = r.fetcher.Fetch(ctx, spec.url); err != nil {
return nil, err
}
}
src, err := raster.Decode(data, r.options.MaxPixels)
if err != nil {
return nil, err
}
paper := r.options.Profile.DotsPerLine
width := min(src.Bounds().Dx(), paper)
if spec.width > 0 {
if spec.width > paper && !el.Optional {
return nil, fmt.Errorf("width %d is wider than the %d-dot paper", spec.width, paper)
}
// An optional image never fails for its width: it shrinks to the
// paper.
width = min(spec.width, paper)
}
mono, err := raster.Monochrome(src, width)
if err != nil {
return nil, err
}
if h := mono.Bounds().Dy(); h > r.options.MaxHeight {
return nil, fmt.Errorf("image is %d dots tall after scaling, limit is %d", h, r.options.MaxHeight)
}
var x int
switch spec.align {
case escpos.JustifyCenter:
x = (paper - width) / 2
case escpos.JustifyRight:
x = paper - width
}
return raster.Place(mono, paper, x)
}
// printer writes elements to a Builder while tracking the horizontal print
// position, in dots, so inline text can continue and wrap across elements.
type printer struct {
b *escpos.Builder
lineDots int
profile escpos.Profile
codePage escpos.CodePage
lineSpacing int
cutFeed int
x int
// lines counts printed lines: text lines, fed lines, and one for each
// QR code, barcode and image.
lines int
// unknown counts the characters of the current element printed as '?'.
unknown int
// raw holds the byte range of each raw element in the Builder.
raw []escpos.Span
}
func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type {
case TypeText:
return p.text(el)
case TypeBox, TypeRule, TypeKV, TypeList:
return p.block(el)
case TypeFeed:
lines, err := el.feedLines()
if err != nil {
return err
}
p.b.Feed(lines)
p.lines += int(lines)
p.x = 0
case TypeQR:
spec, err := el.qrSpec()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
p.lines++
return p.b.QRCode([]byte(el.Data), p.qrSize(len(el.Data), spec), spec.correction)
case TypeBarcode:
spec, err := el.barcodeSpec()
if err != nil {
return err
}
p.endLine()
p.b.Justify(spec.align)
p.b.BarcodeHeight(uint8(spec.height))
if err := p.b.BarcodeWidth(spec.width); err != nil {
return err
}
p.b.BarcodeHRI(spec.hri)
p.lines++
return p.b.Barcode(spec.symbology, el.Data)
case TypeImage:
p.endLine()
if img == nil {
return p.text(Element{Type: TypeText, Text: unavailableImage, Align: el.Align})
}
// Alignment is baked into the image; see Renderer.loadImage.
p.b.Justify(escpos.JustifyLeft)
p.lines++
return p.b.RasterImage(img)
case TypeRaw:
data, err := el.rawBytes()
if err != nil {
return err
}
from := p.b.Len()
p.b.Raw(data)
p.raw = append(p.raw, escpos.Span{From: from, To: p.b.Len()})
// The position after arbitrary bytes is unknown; assume a fresh line.
p.x = 0
case TypeCut:
mode, err := el.cutMode()
if err != nil {
return err
}
p.endLine()
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,
// so a code of digits may shrink before it strictly has to.
func (p *printer) qrSize(n int, spec qrSpec) int {
size := spec.size
modules := escpos.QRModules(n, spec.correction)
for modules > 0 && size > escpos.MinQRModuleSize && modules*size > p.profile.DotsPerLine {
size--
}
return size
}
func (p *printer) text(el Element) error {
spec, err := el.textSpec()
if err != nil {
return err
}
glyph := p.profile.GlyphWidth(spec.font) * spec.width
p.b.Justify(spec.align)
p.b.Font(spec.font)
if err := p.b.Size(spec.width, spec.height); err != nil {
return err
}
p.b.Bold(spec.bold)
p.b.Underline(spec.underline)
p.b.Reverse(spec.invert)
text, unknown := normalize(el.Text, p.codePage)
p.unknown += unknown
if spec.wrap {
text = expandTabs(text, p.x/glyph)
lines := wrap(text, (p.lineDots-p.x)/glyph, p.lineDots/glyph)
for i, line := range lines {
if i > 0 {
p.lineFeed()
}
p.b.Text(p.codePage.Encode(line))
p.x += utf8.RuneCountInString(line) * glyph
}
} else {
p.b.Text(p.codePage.Encode(text))
p.lines += strings.Count(text, "\n")
p.advance(text, glyph)
}
if spec.newline {
p.lineFeed()
}
return p.resetStyle()
}
// resetStyle restores plain Font A at scale 1, so styles cannot leak into
// barcodes, QR codes or raw data.
func (p *printer) resetStyle() error {
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
if err := p.b.Size(1, 1); err != nil {
return err
}
p.b.Font(escpos.FontA)
return nil
}
// block lays out a box, rule, kv or list element and prints it line by
// line, each line left-justified and exactly as wide as the layout made it.
func (p *printer) block(el Element) error {
lo := layout{cp: p.codePage}
var (
lines []blockLine
size int
font escpos.Font
box bool
)
switch el.Type {
case TypeBox:
spec, err := el.boxSpec()
if err != nil {
return err
}
size, font, box = spec.size, spec.font, true
lines = lo.box(el, spec, p.blockColumns(font, size))
case TypeRule:
spec, err := el.ruleSpec(false)
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.rule(el, spec, p.blockColumns(font, size))
case TypeList:
spec, err := el.listSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.list(el, spec, p.blockColumns(font, size))
default:
spec, err := el.kvSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.kv(el, spec, p.blockColumns(font, size))
}
p.unknown += lo.unknown
p.endLine()
spaced := box && p.lineSpacing > 0
if spaced {
p.b.LineSpacing(uint8(p.lineSpacing))
}
p.b.Justify(escpos.JustifyLeft)
p.b.Font(font)
if err := p.b.Size(size, size); err != nil {
return err
}
var current textStyle
p.b.Bold(false)
p.b.Underline(escpos.UnderlineNone)
p.b.Reverse(false)
for _, line := range lines {
for _, r := range line {
if r.text == "" {
continue
}
p.changeStyle(current, r.style)
current = r.style
p.b.Text(p.codePage.Encode(r.text))
}
p.lineFeed()
}
if err := p.resetStyle(); err != nil {
return err
}
if spaced {
p.b.DefaultLineSpacing()
}
return nil
}
// blockColumns is how many characters of font at size fit on a text line.
func (p *printer) blockColumns(font escpos.Font, size int) int {
return max(p.lineDots/(p.profile.GlyphWidth(font)*size), 1)
}
// changeStyle sends the commands that turn style from into style to.
func (p *printer) changeStyle(from, to textStyle) {
if from.bold != to.bold {
p.b.Bold(to.bold)
}
if from.underline != to.underline {
p.b.Underline(to.underline)
}
if from.invert != to.invert {
p.b.Reverse(to.invert)
}
}
// lineFeed ends the current line.
func (p *printer) lineFeed() {
p.b.LineFeed()
p.lines++
p.x = 0
}
// advance updates the position after unwrapped text, which the printer wraps
// by itself when it overflows.
func (p *printer) advance(text string, glyph int) {
if i := strings.LastIndexByte(text, '\n'); i >= 0 {
p.x = 0
text = text[i+1:]
}
p.x += utf8.RuneCountInString(text) * glyph
if p.lineDots > 0 {
p.x %= p.lineDots
}
}
// endLine finishes a partially printed line so the next element starts at
// the left margin.
func (p *printer) endLine() {
if p.x > 0 {
p.lineFeed()
}
}