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>
This commit is contained in:
1 parent
1335ed0687
commit
fb76284129
52 files changed
+6464
-390
No files matched your search
@@ -0,0 +1,266 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/ntfy"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// weekdays are the config's day names.
|
||||
var weekdays = map[string]time.Weekday{
|
||||
"sun": time.Sunday, "mon": time.Monday, "tue": time.Tuesday, "wed": time.Wednesday,
|
||||
"thu": time.Thursday, "fri": time.Friday, "sat": time.Saturday,
|
||||
}
|
||||
|
||||
// newSubscribers returns a subscriber for each [[ntfy.subscriptions]]
|
||||
// table. It reads the credential files and makes sure the state directory
|
||||
// can be written, so that a mistake in either stops the daemon at startup.
|
||||
func newSubscribers(cfg *config.Config, logger *slog.Logger) ([]*ntfy.Subscriber, error) {
|
||||
subs := cfg.Ntfy.Subscriptions
|
||||
if len(subs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
dir := cfg.Ntfy.StateDir
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("config ntfy.state_dir: %w", err)
|
||||
}
|
||||
probe, err := os.CreateTemp(dir, ".write-check-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config ntfy.state_dir: %s cannot be written: %w", dir, err)
|
||||
}
|
||||
_ = probe.Close()
|
||||
_ = os.Remove(probe.Name())
|
||||
|
||||
subscribers := make([]*ntfy.Subscriber, 0, len(subs))
|
||||
for i, sc := range subs {
|
||||
at := fmt.Sprintf("config ntfy.subscriptions[%d]", i)
|
||||
o := ntfy.Options{
|
||||
Name: sc.Name,
|
||||
Server: sc.Server,
|
||||
Topics: sc.Topics,
|
||||
Token: sc.Token,
|
||||
User: sc.User,
|
||||
MinPriority: sc.MinPriority,
|
||||
MaxBacklog: sc.MaxBacklog,
|
||||
RateLimit: sc.RateLimit,
|
||||
RateWindow: sc.RateWindow,
|
||||
BypassPriority: sc.BypassPriority,
|
||||
Keepalive: sc.Keepalive,
|
||||
SkipUpdates: cfg.Ntfy.Format.Updates == "skip",
|
||||
StateFile: filepath.Join(dir, "ntfy-"+sc.Name+".json"),
|
||||
Logger: logger,
|
||||
Report: func(err error) { reportNtfy(sc.Name, "", err) },
|
||||
}
|
||||
if sc.TokenFile != "" {
|
||||
if o.Token, err = readSecret(sc.TokenFile, sc.Name, logger); err != nil {
|
||||
return nil, fmt.Errorf("%s.token_file: %w", at, err)
|
||||
}
|
||||
}
|
||||
if sc.PasswordFile != "" {
|
||||
if o.Password, err = readSecret(sc.PasswordFile, sc.Name, logger); err != nil {
|
||||
return nil, fmt.Errorf("%s.password_file: %w", at, err)
|
||||
}
|
||||
}
|
||||
if sc.Quiet != nil {
|
||||
if o.Quiet, err = quietHours(*sc.Quiet, cfg.Format.Timezone); err != nil {
|
||||
return nil, fmt.Errorf("%s.quiet: %w", at, err)
|
||||
}
|
||||
}
|
||||
sub, err := ntfy.New(o)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", at, err)
|
||||
}
|
||||
subscribers = append(subscribers, sub)
|
||||
}
|
||||
return subscribers, nil
|
||||
}
|
||||
|
||||
// readSecret reads a token or password from the file at path: its whole
|
||||
// content, without the spaces and line breaks around it. A file that the
|
||||
// group or others may read is logged as a warning, on systems with Unix
|
||||
// permissions.
|
||||
func readSecret(path, subscription string, logger *slog.Logger) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if info, err := os.Stat(path); err == nil && runtime.GOOS != "windows" && info.Mode().Perm()&0o077 != 0 {
|
||||
logger.Warn("ntfy credentials file can be read by others; make it 0600",
|
||||
"subscription", subscription, "file", path, "mode", fmt.Sprintf("%#o", info.Mode().Perm()))
|
||||
}
|
||||
secret := strings.TrimSpace(string(data))
|
||||
if secret == "" {
|
||||
return "", fmt.Errorf("%s is empty", path)
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
// quietHours turns the config's quiet hours into the subscriber's. The
|
||||
// zone defaults to formatZone.
|
||||
func quietHours(q config.NtfyQuiet, formatZone string) (*ntfy.Quiet, error) {
|
||||
start, err := time.Parse("15:04", q.Start)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start: %w", err)
|
||||
}
|
||||
end, err := time.Parse("15:04", q.End)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("end: %w", err)
|
||||
}
|
||||
zone := q.Timezone
|
||||
if zone == "" {
|
||||
zone = formatZone
|
||||
}
|
||||
loc, err := time.LoadLocation(zone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("timezone: %w", err)
|
||||
}
|
||||
quiet := &ntfy.Quiet{
|
||||
Start: ntfy.Clock{Hour: start.Hour(), Minute: start.Minute()},
|
||||
End: ntfy.Clock{Hour: end.Hour(), Minute: end.Minute()},
|
||||
Location: loc,
|
||||
MinPriority: q.MinPriority,
|
||||
Drop: q.Action == "drop",
|
||||
}
|
||||
for _, day := range q.Days {
|
||||
quiet.Days = append(quiet.Days, weekdays[day])
|
||||
}
|
||||
return quiet, nil
|
||||
}
|
||||
|
||||
// ntfySubmitter is the print queue as a subscription uses it.
|
||||
type ntfySubmitter interface {
|
||||
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
|
||||
}
|
||||
|
||||
// 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".
|
||||
type ntfyPrinter struct {
|
||||
name string
|
||||
jobs ntfySubmitter
|
||||
env func() modules.Env
|
||||
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.
|
||||
func (p *ntfyPrinter) Message(_ context.Context, m ntfy.Message, updated bool) error {
|
||||
n, err := modules.FromNtfy(m)
|
||||
if err != nil {
|
||||
p.logger.Debug("ntfy message has nothing to print", "subscription", p.name, "ntfy_id", m.ID)
|
||||
return nil
|
||||
}
|
||||
n.Updated = updated
|
||||
env := p.env()
|
||||
job, err := modules.Card(n, env.Card, env)
|
||||
p.reportFallback(m.ID, err)
|
||||
return p.submit(job, m.ID)
|
||||
}
|
||||
|
||||
// Digest prints the held messages on one receipt.
|
||||
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, digestRef)
|
||||
}
|
||||
|
||||
// submit validates job and queues it. Card and DigestCard return valid
|
||||
// jobs, so a job that fails validation is a bug: it is logged and
|
||||
// reported, and dropped rather than retried.
|
||||
func (p *ntfyPrinter) submit(job receipt.Job, ref string) error {
|
||||
if err := job.Validate(); err != nil {
|
||||
problems := 1
|
||||
var ve *receipt.ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
problems = len(ve.Problems)
|
||||
}
|
||||
p.logger.Error("ntfy receipt is invalid", "subscription", p.name, "ref", ref, "problems", problems)
|
||||
reportNtfy(p.name, ref, fmt.Errorf("the receipt failed validation with %d problems", problems))
|
||||
return nil
|
||||
}
|
||||
status, err := p.jobs.Submit(job, printqueue.Meta{Source: "ntfy:" + p.name, Ref: ref})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.logger.Info("ntfy receipt queued", "subscription", p.name, "ref", ref, "job_id", status.ID.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
// reportFallback logs and reports a card that fell back to the plain
|
||||
// receipt, which still prints. The error never quotes the message.
|
||||
func (p *ntfyPrinter) reportFallback(ref string, err error) {
|
||||
var fallbackErr *modules.FallbackError
|
||||
if !errors.As(err, &fallbackErr) {
|
||||
return
|
||||
}
|
||||
attrs := []any{"subscription", p.name, "ref", ref, "err", fallbackErr.Error()}
|
||||
if fallbackErr.Stack != "" {
|
||||
attrs = append(attrs, "stack", fallbackErr.Stack)
|
||||
}
|
||||
p.logger.Error("ntfy card printed its fallback receipt", attrs...)
|
||||
reportNtfy(p.name, ref, fallbackErr)
|
||||
}
|
||||
|
||||
// reportNtfy sends a subscription's fault to Sentry, tagged with the
|
||||
// subscription and the message's ID, if there is one.
|
||||
func reportNtfy(name, ref string, err error) {
|
||||
hub := sentry.CurrentHub().Clone()
|
||||
hub.Scope().SetTag("subscription", name)
|
||||
if ref != "" {
|
||||
hub.Scope().SetTag("ref", ref)
|
||||
}
|
||||
hub.CaptureException(fmt.Errorf("ntfy %s: %w", name, err))
|
||||
}
|
||||
|
||||
// ntfyHealth returns the subscriptions' states for /healthz, or nil when
|
||||
// there are none.
|
||||
func ntfyHealth(subs []*ntfy.Subscriber) func() []server.NtfyHealth {
|
||||
if len(subs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return func() []server.NtfyHealth {
|
||||
out := make([]server.NtfyHealth, len(subs))
|
||||
for i, sub := range subs {
|
||||
st := sub.Status()
|
||||
out[i] = server.NtfyHealth{
|
||||
Name: st.Name,
|
||||
State: st.State,
|
||||
ConnectedSince: timePtr(st.ConnectedSince),
|
||||
LastMessageAt: timePtr(st.LastMessageAt),
|
||||
Printed: st.Printed,
|
||||
Digested: st.Digested,
|
||||
Held: st.Held,
|
||||
LastError: st.LastError,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
// timePtr returns t in UTC, or nil for the zero time.
|
||||
func timePtr(t time.Time) *time.Time {
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
t = t.UTC().Truncate(time.Second)
|
||||
return &t
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/ntfy"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// TestServeWithSubscription runs the daemon with a subscription to a fake
|
||||
// ntfy server: a message on the stream prints, /healthz lists the
|
||||
// subscription as connected without changing its status code, and the
|
||||
// state is saved at shutdown.
|
||||
func TestServeWithSubscription(t *testing.T) {
|
||||
printer := startFakePrinter(t)
|
||||
var auth sync.Map
|
||||
ntfyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
auth.Store(r.URL.Path, r.Header.Get("Authorization"))
|
||||
if strings.HasSuffix(r.URL.Path, "/auth") {
|
||||
fmt.Fprint(w, `{"success":true}`)
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
fmt.Fprintf(w, "{\"id\":\"open1\",\"time\":%d,\"event\":\"open\",\"topic\":\"alerts\"}\n", now)
|
||||
fmt.Fprintf(w, "{\"id\":\"msg1\",\"time\":%d,\"event\":\"message\",\"topic\":\"alerts\",\"title\":\"Grüße vom Abo\",\"priority\":4}\n", now)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer ntfyServer.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
tokenFile := filepath.Join(dir, "ntfy.token")
|
||||
if err := os.WriteFile(tokenFile, []byte("tk_fromfile\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const secret = "end-to-end-secret-end-to-end-secret!"
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
body := fmt.Sprintf(`
|
||||
[api]
|
||||
secret = %q
|
||||
[printer]
|
||||
address = "127.0.0.1"
|
||||
port = %d
|
||||
[log]
|
||||
level = "error"
|
||||
[ntfy]
|
||||
state_dir = %q
|
||||
[[ntfy.subscriptions]]
|
||||
name = "home"
|
||||
server = %q
|
||||
allow_insecure = true
|
||||
topics = ["alerts"]
|
||||
token_file = %q
|
||||
`, secret, printer.addr.Port, filepath.Join(dir, "state"), ntfyServer.URL, tokenFile)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen) }()
|
||||
|
||||
waitFor(t, func() bool {
|
||||
// "Grüße" in CP437: ü is 0x81, ß is 0xE1.
|
||||
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e vom Abo"))
|
||||
})
|
||||
if got, _ := auth.Load("/alerts/json"); got != "Bearer tk_fromfile" {
|
||||
t.Errorf("Authorization %q, want the token from the file", got)
|
||||
}
|
||||
|
||||
var health struct {
|
||||
Status string
|
||||
Ntfy []struct {
|
||||
Name, State string
|
||||
Printed int
|
||||
}
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
resp, err := http.Get("http://" + ln.Addr().String() + "/healthz")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_ = json.NewDecoder(resp.Body).Decode(&health)
|
||||
return len(health.Ntfy) == 1 && health.Ntfy[0].Printed == 1
|
||||
})
|
||||
if n := health.Ntfy[0]; n.Name != "home" || n.State != "connected" {
|
||||
t.Errorf("ntfy health %+v", n)
|
||||
}
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-served:
|
||||
if err != nil {
|
||||
t.Fatalf("serve returned %v after shutdown", err)
|
||||
}
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("serve did not shut down")
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, "state", "ntfy-home.json"))
|
||||
if err != nil || !bytes.Contains(data, []byte(`"msg1"`)) {
|
||||
t.Errorf("state file %s, %v; want it to remember msg1", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The daemon refuses to start with a credentials file it cannot read, or
|
||||
// one that is empty.
|
||||
func TestNewSubscribersErrors(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
empty := filepath.Join(dir, "empty")
|
||||
if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := config.Default()
|
||||
cfg.Ntfy.StateDir = filepath.Join(dir, "state")
|
||||
sub := config.DefaultSubscription()
|
||||
sub.Name, sub.Server, sub.Topics = "home", "https://ntfy.sh", []string{"alerts"}
|
||||
for _, tt := range []struct {
|
||||
file, want string
|
||||
}{
|
||||
{filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
|
||||
{empty, "is empty"},
|
||||
} {
|
||||
sub.TokenFile = tt.file
|
||||
cfg.Ntfy.Subscriptions = []config.NtfySubscription{sub}
|
||||
if _, err := newSubscribers(&cfg, slog.New(slog.DiscardHandler)); err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Errorf("token_file %s: err = %v, want %q", tt.file, err, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A credentials file others may read is accepted with a warning.
|
||||
func TestReadSecretWarnsAboutPermissions(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Windows has no Unix permissions")
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "token")
|
||||
if err := os.WriteFile(path, []byte("tk_secret\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
got, err := readSecret(path, "home", slog.New(slog.NewTextHandler(&logs, nil)))
|
||||
if err != nil || got != "tk_secret" {
|
||||
t.Fatalf("readSecret = %q, %v", got, err)
|
||||
}
|
||||
if out := logs.String(); !strings.Contains(out, "can be read by others") || strings.Contains(out, "tk_secret") {
|
||||
t.Errorf("log %q, want a warning without the secret", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuietHours(t *testing.T) {
|
||||
q, err := quietHours(config.NtfyQuiet{Start: "22:30", End: "06:45", Days: []string{"fri", "sat"},
|
||||
MinPriority: 4, Action: "drop"}, "Europe/London")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if q.Start != (ntfy.Clock{Hour: 22, Minute: 30}) || q.End != (ntfy.Clock{Hour: 6, Minute: 45}) ||
|
||||
q.Location.String() != "Europe/London" || q.MinPriority != 4 || !q.Drop ||
|
||||
len(q.Days) != 2 || q.Days[0] != time.Friday || q.Days[1] != time.Saturday {
|
||||
t.Errorf("quiet %+v", q)
|
||||
}
|
||||
q, err = quietHours(config.DefaultQuiet(), "UTC")
|
||||
if err != nil || q.Location != time.UTC || q.Drop || len(q.Days) != 7 {
|
||||
t.Errorf("quiet %+v, %v", q, err)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeQueue records the jobs submitted to it, or refuses them.
|
||||
type fakeQueue struct {
|
||||
jobs []receipt.Job
|
||||
metas []printqueue.Meta
|
||||
err error
|
||||
}
|
||||
|
||||
func (q *fakeQueue) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error) {
|
||||
if q.err != nil {
|
||||
return printqueue.Status{}, q.err
|
||||
}
|
||||
q.jobs = append(q.jobs, job)
|
||||
q.metas = append(q.metas, meta)
|
||||
return printqueue.Status{}, nil
|
||||
}
|
||||
|
||||
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"}
|
||||
}
|
||||
|
||||
// The handler prints a message as a card with its source and ID, marks an
|
||||
// update, prints a digest, skips what has nothing to print, and hands a
|
||||
// full queue back for a retry. Its log lines carry no text.
|
||||
func TestNtfyPrinter(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
q := &fakeQueue{}
|
||||
p := &ntfyPrinter{name: "home", jobs: q, env: testEnv, logger: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))}
|
||||
ctx := context.Background()
|
||||
|
||||
m := ntfy.Message{ID: "msg1", Event: "message", Topic: "alerts", Title: "Disk almost full", Message: "SecretBody"}
|
||||
if err := p.Message(ctx, m, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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 {
|
||||
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"}) || q.metas[1] != (printqueue.Meta{Source: "ntfy:home", Ref: "digest"}) {
|
||||
t.Errorf("metas %+v", q.metas)
|
||||
}
|
||||
if title := q.jobs[0].Elements[0].Title; title != "Disk almost full (updated)" {
|
||||
t.Errorf("card title %q, want the update marked", title)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
p.reportFallback("msg1", &modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"})
|
||||
p.reportFallback("msg2", nil)
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, "ntfy card printed its fallback receipt") || !strings.Contains(out, "ref=msg1") ||
|
||||
!strings.Contains(out, "goroutine 1") || strings.Contains(out, "msg2") {
|
||||
t.Errorf("log %q, want the fallback logged with the ID", out)
|
||||
}
|
||||
for _, secret := range []string{"Disk almost full", "SecretBody", "SecretRow"} {
|
||||
if strings.Contains(out, secret) {
|
||||
t.Errorf("the log holds %q", secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func TestPreviewCommandReadsStdin(t *testing.T) {
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := " ── stdin ──\n - - - - - - - partial cut - - - - - - - -\n"; out.String() != want {
|
||||
if want := " ── stdin ──\n\n\n\n - - - - - - - partial cut - - - - - - - -\n"; out.String() != want {
|
||||
t.Errorf("output = %q, want %q", out.String(), want)
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ func TestPreviewCommandErrors(t *testing.T) {
|
||||
{"unknown field", `{"elements":[{"type":"rule","colour":"red"}]}`, "", `unknown field "colour"`},
|
||||
{"invalid", `{"elements":[{"type":"box"},{"type":"kv"}]}`, "",
|
||||
"invalid job:\n elements[0] (box): text or children is required\n elements[1] (kv): pairs: at least one pair is required"},
|
||||
{"too many lines", `{"elements":[{"type":"feed","lines":20}]}`, "[format]\nmax_lines = 10\n", "receipt would print 20 lines, limit is 10"},
|
||||
{"too many lines", `{"elements":[{"type":"feed","lines":20}]}`, "[format]\nmax_lines = 10\n", "receipt would print 23 lines, limit is 10"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -129,6 +129,7 @@ func TestPreviewCommandModule(t *testing.T) {
|
||||
"│ [ ] Milk │\n" +
|
||||
"│ [√] Eggs │\n" +
|
||||
"└───────────────────────────── kitchen ──┘\n" +
|
||||
"\n\n\n" +
|
||||
" - - - - - - - partial cut - - - - - - - -\n"
|
||||
if out.String() != want || errOut.Len() != 0 {
|
||||
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
|
||||
@@ -159,6 +160,7 @@ func TestPreviewCommandNtfy(t *testing.T) {
|
||||
"║ Tags: nas01 ║",
|
||||
"╚══════════════ backups · 29 Nov 21:04 ══╝",
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
"", "", "",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
{"compact, with markers", "[format]\ntimezone = \"UTC\"\n[ntfy.format]\nstyle = \"compact\"\n" +
|
||||
@@ -167,6 +169,7 @@ func TestPreviewCommandNtfy(t *testing.T) {
|
||||
"/!\\ Backup FAILED on nas01",
|
||||
"Job nightly-offsite exited with code 2",
|
||||
"after 3h12m. Last good run: 2 days ago.",
|
||||
"", "", "",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
}
|
||||
|
||||
@@ -71,6 +71,11 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
}
|
||||
defer flushSentry()
|
||||
|
||||
subscribers, err := newSubscribers(cfg, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fetcher := safehttp.New(safehttp.Options{
|
||||
Timeout: cfg.Images.Timeout,
|
||||
MaxBytes: cfg.Images.MaxBytes,
|
||||
@@ -113,6 +118,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
Previewer: renderer,
|
||||
Modules: registry,
|
||||
ModuleEnv: env,
|
||||
Ntfy: ntfyHealth(subscribers),
|
||||
}, logger)
|
||||
|
||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||
@@ -130,6 +136,10 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
group, groupCtx := errgroup.WithContext(ctx)
|
||||
group.Go(func() error { return queue.Run(groupCtx) })
|
||||
group.Go(func() error { return srv.Serve(groupCtx, ln) })
|
||||
for _, sub := range subscribers {
|
||||
handler := &ntfyPrinter{name: sub.Status().Name, jobs: queue, env: env, logger: logger}
|
||||
group.Go(func() error { return sub.Run(groupCtx, handler) })
|
||||
}
|
||||
err = group.Wait()
|
||||
logger.Info("shutdown complete")
|
||||
return err
|
||||
@@ -157,6 +167,7 @@ func rendererOptions(cfg *config.Config) (receipt.Options, error) {
|
||||
MaxHeight: cfg.Images.MaxHeight,
|
||||
MaxLines: cfg.Format.MaxLines,
|
||||
BoxLineSpacing: cfg.Printer.BoxLineSpacing,
|
||||
CutFeed: cfg.Printer.CutFeed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -183,12 +183,43 @@ type printerHealth struct {
|
||||
// healthResponse is the body of GET /healthz.
|
||||
type healthResponse struct {
|
||||
// Status is ok, degraded when the printer is not ready, or unavailable
|
||||
// when it is unreachable or did not answer in time.
|
||||
// when it is unreachable or did not answer in time. It depends on the
|
||||
// printer alone.
|
||||
Status string `json:"status" jsonschema:"enum=ok,enum=degraded,enum=unavailable"`
|
||||
// Printer is the printer's state.
|
||||
Printer printerHealth `json:"printer"`
|
||||
// Queue is the print queue's state.
|
||||
Queue queueHealth `json:"queue"`
|
||||
// Ntfy is the state of each ntfy subscription, in the order of the
|
||||
// config; absent when none is configured.
|
||||
Ntfy []NtfyHealth `json:"ntfy,omitempty"`
|
||||
}
|
||||
|
||||
// NtfyHealth is the state of an ntfy subscription. It holds no
|
||||
// credentials and nothing a message says.
|
||||
type NtfyHealth struct {
|
||||
// Name is the subscription's name from the config.
|
||||
Name string `json:"name"`
|
||||
// State is connecting, connected, backoff while it waits to reconnect
|
||||
// after a failure, or unauthorized when the server refused its
|
||||
// credentials; it then tries again every five minutes.
|
||||
State string `json:"state" jsonschema:"enum=connecting,enum=connected,enum=backoff,enum=unauthorized"`
|
||||
// ConnectedSince is when the current connection opened; absent while
|
||||
// there is none.
|
||||
ConnectedSince *time.Time `json:"connected_since,omitempty"`
|
||||
// LastMessageAt is when the last message arrived; absent until one
|
||||
// has.
|
||||
LastMessageAt *time.Time `json:"last_message_at,omitempty"`
|
||||
// Printed is how many messages printed on a card of their own since
|
||||
// the daemon started.
|
||||
Printed int `json:"printed"`
|
||||
// Digested is how many messages were held for a digest since the
|
||||
// daemon started: over the rate limit, or in quiet hours.
|
||||
Digested int `json:"digested"`
|
||||
// Held is how many messages wait for the next digest.
|
||||
Held int `json:"held"`
|
||||
// LastError says why the last connection failed; empty once one opens.
|
||||
LastError string `json:"last_error"`
|
||||
}
|
||||
|
||||
// queueHealth is the queue part of the /healthz response.
|
||||
@@ -205,6 +236,9 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
|
||||
|
||||
var resp healthResponse
|
||||
resp.Queue.Pending = s.jobs.Pending()
|
||||
if s.ntfy != nil {
|
||||
resp.Ntfy = s.ntfy()
|
||||
}
|
||||
httpStatus := fiber.StatusOK
|
||||
|
||||
st, err := s.settledPrinterStatus(ctx)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
gotoken "go/token"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// /healthz lists the subscriptions, and its status code still follows the
|
||||
// printer alone: a subscription that is down turns nothing to 503, and
|
||||
// one that is up turns nothing to 200.
|
||||
func TestHealthListsSubscriptions(t *testing.T) {
|
||||
since := time.Date(2026, 11, 29, 20, 58, 1, 0, time.UTC)
|
||||
last := time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC)
|
||||
subs := []NtfyHealth{
|
||||
{Name: "home", State: "connected", ConnectedSince: &since, LastMessageAt: &last, Printed: 12, Digested: 2, Held: 1},
|
||||
{Name: "work", State: "unauthorized", LastError: "HTTP 401: the server refused the credentials"},
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
printer *fakePrinter
|
||||
want int
|
||||
}{
|
||||
{"printer ready", &fakePrinter{statuses: []escpos.Status{{Online: true}}}, http.StatusOK},
|
||||
{"printer unreachable", &fakePrinter{err: errors.New("connection refused")}, http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, tt.printer)
|
||||
s.ntfy = func() []NtfyHealth { return subs }
|
||||
resp, body := send(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status %d, want %d", resp.StatusCode, tt.want)
|
||||
}
|
||||
var got healthResponse
|
||||
if err := json.Unmarshal(body, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Ntfy, subs) {
|
||||
t.Errorf("ntfy = %+v, want %+v", got.Ntfy, subs)
|
||||
}
|
||||
for _, want := range []string{`"name":"home","state":"connected","connected_since":"2026-11-29T20:58:01Z"`,
|
||||
`"printed":12,"digested":2,"held":1,"last_error":""`, `"name":"work","state":"unauthorized","printed":0`} {
|
||||
if !strings.Contains(string(body), want) {
|
||||
t.Errorf("body %s lacks %s", body, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{statuses: []escpos.Status{{Online: true}}})
|
||||
_, body := send(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
if strings.Contains(string(body), `"ntfy"`) {
|
||||
t.Errorf("body %s lists ntfy without subscriptions", body)
|
||||
}
|
||||
}
|
||||
|
||||
// The state enum of a subscription lists exactly the ntfy package's
|
||||
// states.
|
||||
func TestNtfyStateEnumListsEveryState(t *testing.T) {
|
||||
file, err := parser.ParseFile(gotoken.NewFileSet(), "../../../pkg/ntfy/status.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var states []string
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
spec, ok := n.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
for i, name := range spec.Names {
|
||||
if !strings.HasPrefix(name.Name, "State") || i >= len(spec.Values) {
|
||||
continue
|
||||
}
|
||||
if lit, ok := spec.Values[i].(*ast.BasicLit); ok && lit.Kind == gotoken.STRING {
|
||||
v, _ := strconv.Unquote(lit.Value)
|
||||
states = append(states, v)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
slices.Sort(states)
|
||||
if enum := enumOf(t, reflect.TypeFor[NtfyHealth](), "State"); len(states) == 0 || !slices.Equal(states, enum) {
|
||||
t.Errorf("NtfyHealth.State enum %v, ntfy State constants %v", enum, states)
|
||||
}
|
||||
}
|
||||
@@ -167,10 +167,12 @@ func Routes() []Route {
|
||||
Method: http.MethodGet,
|
||||
Path: "/healthz",
|
||||
OperationID: "getHealth",
|
||||
Summary: "Printer and queue health",
|
||||
Summary: "Printer, queue and subscription health",
|
||||
Description: "Reads the printer's real-time status. A printer that looks not ready is read again " +
|
||||
"750 ms later, and only a problem that is still there gives 503. A printer that does not " +
|
||||
"answer status requests is reported as status unknown with 200.",
|
||||
"answer status requests is reported as status unknown with 200. The ntfy subscriptions, " +
|
||||
"when any are configured, are listed with their state; the status code depends on the " +
|
||||
"printer alone.",
|
||||
Tag: "health",
|
||||
NoStore: true,
|
||||
Responses: []Response{
|
||||
|
||||
@@ -58,6 +58,10 @@ type Deps struct {
|
||||
// ModuleEnv returns what a module may know when it builds a job: the
|
||||
// time now, and the zone and layout times print in.
|
||||
ModuleEnv func() modules.Env
|
||||
|
||||
// Ntfy returns the state of each ntfy subscription for /healthz. Nil
|
||||
// when none is configured.
|
||||
Ntfy func() []NtfyHealth
|
||||
}
|
||||
|
||||
// Info describes the running build for the index route.
|
||||
@@ -114,6 +118,7 @@ type Server struct {
|
||||
previewer Previewer
|
||||
modules Modules
|
||||
moduleEnv func() modules.Env
|
||||
ntfy func() []NtfyHealth
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
@@ -139,6 +144,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
||||
previewer: deps.Previewer,
|
||||
modules: deps.Modules,
|
||||
moduleEnv: deps.ModuleEnv,
|
||||
ntfy: deps.Ntfy,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
|
||||
@@ -10,4 +10,7 @@ Used ................................. 94%
|
||||
Inverted <b>not a tag</b> ?
|
||||
[image 384 dots: logo.png]
|
||||
[qr: https://example.com]
|
||||
|
||||
|
||||
|
||||
- - - - - - - partial cut - - - - - - - -
|
||||
Reference in new issue
Block a user