Files
uberbringer/internal/app/uberbringer/ntfy.go
T
57_WolveandClaude Opus 5.5 4eb620dde0 Check state.dir at start, with or without subscriptions
Breaking: the Docker image sets state.dir, so a container that cannot
write /var/lib/uberbringer, one started --read-only without a volume
there or with a bind mount owned by root, no longer starts, ntfy
subscriptions or not: mount a named volume or a directory owned by
10001:10001.

The daemon created state.dir and checked that it could write there only
when an ntfy subscription was configured, since only subscriptions kept
files in it. The job store will keep its database there too, so the
check now runs once at start whenever state.dir is set: the directory
is created 0700 if it is missing, and one that cannot be made or
written stops the start with an error naming state.dir, before any
subscription is made. A state.dir of only spaces is refused whether or
not a subscription is configured, rather than made as a directory of
that name. Without state.dir nothing changes.

Part of stage 1d of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:39:48 -06:00

269 lines
8.6 KiB
Go

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, which keeps its state file in the state directory, checked
// already, and flushes it to disk with syncState. It reads the credential
// files, so that a mistake in one stops the daemon at startup.
func newSubscribers(cfg *config.Config, logger *slog.Logger, syncState func(*os.File) error) ([]*ntfy.Subscriber, error) {
subs := cfg.Ntfy.Subscriptions
if len(subs) == 0 {
return nil, nil
}
subscribers := make([]*ntfy.Subscriber, 0, len(subs))
for i, sc := range subs {
at := fmt.Sprintf("config ntfy.subscriptions[%d]", i)
var err error
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(cfg.State.Dir, "ntfy-"+sc.Name+".json"),
Sync: syncState,
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)
Holds(source, ref string) bool
}
// 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 the digest's reference.
type ntfyPrinter struct {
name string
jobs ntfySubmitter
env func() modules.Env
logger *slog.Logger
}
// 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
// the queue already holds, is not queued twice.
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, printqueue.Meta{Ref: m.ID, Sequence: m.Notification(), Unique: true})
}
// Queued reports whether the queue holds the card of m, which a message
// offered again after a restart may already have.
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. 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(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.
// 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, meta printqueue.Meta) error {
meta.Source = "ntfy:" + p.name
ref := meta.Ref
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, meta)
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
}