diff --git a/CHANGELOG.md b/CHANGELOG.md index 63b5b0d..5de1a38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,7 +64,7 @@ version may break callers; such changes are listed under **Breaking**. when it ends. - A message that replaces one the subscription printed is marked `(updated)`, or left out with `ntfy.format.updates = "skip"`. - - `ntfy.state_dir` keeps each subscription's state across restarts. + - `state.dir` keeps each subscription's state across restarts. `install.sh` writes it into a new config and the systemd unit gains `StateDirectory=uberbringer`, so `/var/lib/uberbringer` is writable; the Docker image sets it to that path, for a volume, and runs as user diff --git a/Dockerfile b/Dockerfile index f5a834f..f1cd345 100644 --- a/Dockerfile +++ b/Dockerfile @@ -37,6 +37,6 @@ WORKDIR /etc/uberbringer # 0.0.0.0 and trusted_proxies must hold the proxy's address. Mount a volume on # /var/lib/uberbringer to keep the subscriptions' state across containers. ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml \ - UBERBRINGER_NTFY_STATE_DIR=/var/lib/uberbringer + UBERBRINGER_STATE_DIR=/var/lib/uberbringer EXPOSE 8080 ENTRYPOINT ["/usr/local/bin/uberbringer"] diff --git a/configs/config.example.toml b/configs/config.example.toml index 086306e..6c96754 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -83,13 +83,6 @@ timezone = "Local" time_layout = "02 Jan 15:04" -[ntfy] - # The directory the subscriptions below keep their state in, so that a - # restart neither prints a message twice nor loses one. Required with a - # subscription. install.sh writes "/var/lib/uberbringer", and the Docker - # image sets it with UBERBRINGER_NTFY_STATE_DIR. - state_dir = "" - [ntfy.format] # How notifications are laid out, from the notify and ntfy modules and # from the subscriptions. "auto" picks the form from the priority: urgent @@ -144,6 +137,13 @@ size = 100 # jobs that may wait; more get 503 history = 1000 # finished jobs whose status is kept +[state] + # The directory the ntfy subscriptions keep their state in, so that a + # restart neither prints a message twice nor loses one. Required with a + # subscription. install.sh writes "/var/lib/uberbringer", and the Docker + # image sets it with UBERBRINGER_STATE_DIR. + dir = "" + [images] timeout = "10s" max_bytes = 10485760 # 10 MiB download limit diff --git a/docs/configuration.md b/docs/configuration.md index 7725f53..ed1de4c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -13,7 +13,7 @@ shows every setting with its default: copy it to `config.toml` to start. - [Settings](#settings): [webserver](#webserver), [api](#api), [printer](#printer), [format](#format), [ntfy](#ntfy), [ntfy subscriptions](#ntfy-subscriptions), [queue](#queue), - [images](#images), [sentry](#sentry), [log](#log) + [state](#state), [images](#images), [sentry](#sentry), [log](#log) - [Logs](#logs) ## Loading @@ -121,10 +121,6 @@ These settings shape the [notification cards](api.md#notification-cards) of the `notify` and `ntfy` modules and of the [ntfy subscriptions](ntfy.md), and their [digests](api.md#digests). -| Key | Default | Meaning | -|-----|---------|---------| -| `state_dir` | none | The directory the ntfy subscriptions keep their state in, one `ntfy-.json` file each, readable by the daemon's user only. Required with a subscription. `install.sh` and the Docker image set it to `/var/lib/uberbringer` | - `[ntfy.format]`: | Key | Default | Meaning | @@ -143,8 +139,9 @@ tags, at most 16 characters each, and `""` hides a tag: `backup = "[B]"`, ### ntfy subscriptions Each `[[ntfy.subscriptions]]` table is one connection to one ntfy server, -for one or more topics. They are set in the file only. -[ntfy.md](ntfy.md) shows an example and how a subscription behaves. +for one or more topics. They are set in the file only, and need +[`state.dir`](#state). [ntfy.md](ntfy.md) shows an example and how a +subscription behaves. | Key | Default | Meaning | |-----|---------|---------| @@ -178,6 +175,12 @@ Quiet hours are off unless the subscription has a | `size` | `100` | Jobs that may wait to print; more get `503` `queue_full` | | `history` | `1000` | Finished jobs whose status is kept; an older job's ID answers `404` `job_not_found` | +### state + +| Key | Default | Meaning | +|-----|---------|---------| +| `dir` | none | The directory the [ntfy subscriptions](#ntfy-subscriptions) keep their state in, one `ntfy-.json` file each, readable by the daemon's user only. Required with a subscription. `install.sh` and the Docker image set it to `/var/lib/uberbringer` | + ### images | Key | Default | Meaning | diff --git a/docs/design.md b/docs/design.md index faefcc0..f71baa0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -367,7 +367,7 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( deliberately left out. A message queued but not yet printed when the daemon stops is lost, as any waiting job is: the queue stays in memory, because ESC/POS cannot say what printed. - - State is one JSON file per subscription in `ntfy.state_dir`, written + - State is one JSON file per subscription in `state.dir`, written atomically (temporary file, fsync, rename), mode 0600 since held messages carry titles. A change a restart must see, such as a message printed, held or left out, is written within a second, and so is the @@ -377,7 +377,7 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( day per subscription, which wears an SD card. A saved cursor that is behind costs only a longer replay after a crash, and the saved IDs drop the messages it sends again. A damaged - file means a fresh start with a warning. `state_dir` has no default, + file means a fresh start with a warning. `state.dir` has no default, since the daemon also runs on Windows; `install.sh` writes the unit's `StateDirectory`, `/var/lib/uberbringer`, and the image sets the same path. @@ -445,10 +445,10 @@ before anything is built. They come in this order. the owner accepted every proposed default, 2026-12-01). - Jobs survive a restart in SQLite, through `modernc.org/sqlite` and `database/sql`, not GORM: WAL mode, one connection, exclusive - locking. `jobs.db` lives in `[state] dir`, which replaces - `ntfy.state_dir` and keeps the ntfy state files too; empty keeps the - queue in memory. modernc's exact `modernc.org/libc` is the one - exception to "latest stable", held by a gate check. + locking. `jobs.db` lives in `[state] dir`, beside the ntfy state + files; empty keeps the queue in memory. modernc's exact + `modernc.org/libc` is the one exception to "latest stable", held by + a gate check. - A job has one delivery per printer, each with its own state. A delivery's `sending` mark is synced before its first byte, and one found in `sending` at start ends `uncertain`, a new terminal status, diff --git a/docs/docker.md b/docs/docker.md index c6c97ce..9135fbd 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -54,7 +54,7 @@ alerting better than restarting the container. ## ntfy subscriptions [ntfy subscriptions](ntfy.md) keep their state in `/var/lib/uberbringer`, -which the image sets as `ntfy.state_dir`. Mount a volume there: without one +which the image sets as `state.dir`. Mount a volume there: without one the state lives in the container, and a new container, after a pull or an upgrade, forgets what was printed and what was held. diff --git a/docs/install.md b/docs/install.md index 88a199b..b943ff3 100644 --- a/docs/install.md +++ b/docs/install.md @@ -32,8 +32,8 @@ sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh /ntfy-.json`, written through a temporary file and a + `/ntfy-.json`, written through a temporary file and a rename, so a crash leaves the old file or the new one. It is written 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 diff --git a/docs/plans/job-store.md b/docs/plans/job-store.md index cae7102..58ec7ef 100644 --- a/docs/plans/job-store.md +++ b/docs/plans/job-store.md @@ -1,6 +1,6 @@ # Plan: persistent job store and image previews -Status: **planned; stage 1a's measurements are done (Investigation findings), and nothing is 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 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. ## Decisions (owner, 2026-11-30) @@ -623,6 +623,8 @@ On leil-test-1, otherwise idle, since the device counters include every process' ### Stage 1b: `[state] dir` +Done on 2026-12-01. + **Goal.** `[state] dir` replaces `ntfy.state_dir` (decision 4). Nothing else changes: the directory is still used only by ntfy subscriptions. **Work.** diff --git a/install.sh b/install.sh index f7f3ded..eb762a6 100755 --- a/install.sh +++ b/install.sh @@ -210,9 +210,9 @@ write_config() { [printer] address = "$PRINTER_ADDRESS" -[ntfy] +[state] # The unit's StateDirectory; ntfy subscriptions keep their state here. - state_dir = "/var/lib/uberbringer" + dir = "/var/lib/uberbringer" EOT ) chown root:"$SERVICE_USER" "$CONFIG" diff --git a/internal/app/uberbringer/ntfy.go b/internal/app/uberbringer/ntfy.go index a73879b..05cdec9 100644 --- a/internal/app/uberbringer/ntfy.go +++ b/internal/app/uberbringer/ntfy.go @@ -36,13 +36,13 @@ func newSubscribers(cfg *config.Config, logger *slog.Logger, syncState func(*os. if len(subs) == 0 { return nil, nil } - dir := cfg.Ntfy.StateDir + dir := cfg.State.Dir if err := os.MkdirAll(dir, 0o700); err != nil { - return nil, fmt.Errorf("config ntfy.state_dir: %w", err) + return nil, fmt.Errorf("config 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) + return nil, fmt.Errorf("config state.dir: %s cannot be written: %w", dir, err) } _ = probe.Close() _ = os.Remove(probe.Name()) diff --git a/internal/app/uberbringer/ntfy_test.go b/internal/app/uberbringer/ntfy_test.go index 85465e6..2c18c8b 100644 --- a/internal/app/uberbringer/ntfy_test.go +++ b/internal/app/uberbringer/ntfy_test.go @@ -34,7 +34,7 @@ func skipSync(*os.File) error { return nil } // 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. +// state is saved in state.dir at shutdown. func TestServeWithSubscription(t *testing.T) { printer := startFakePrinter(t) var auth sync.Map @@ -67,8 +67,8 @@ address = "127.0.0.1" port = %d [log] level = "error" -[ntfy] -state_dir = %q +[state] +dir = %q [[ntfy.subscriptions]] name = "home" server = %q @@ -138,28 +138,30 @@ token_file = %q } } -// The daemon refuses to start with a credentials file it cannot read, or -// one that is empty. +// The daemon refuses to start with a state directory it cannot create, or +// with a credentials file it cannot read or 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") + state := 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 + stateDir, tokenFile, want string }{ - {filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"}, - {empty, "is empty"}, + {empty, "", "config state.dir"}, + {state, filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"}, + {state, empty, "is empty"}, } { - sub.TokenFile = tt.file + cfg := config.Default() + cfg.State.Dir = tt.stateDir + sub.TokenFile = tt.tokenFile cfg.Ntfy.Subscriptions = []config.NtfySubscription{sub} if _, err := newSubscribers(&cfg, slog.New(slog.DiscardHandler), skipSync); err == nil || !strings.Contains(err.Error(), tt.want) { - t.Errorf("token_file %s: err = %v, want %q", tt.file, err, tt.want) + t.Errorf("state.dir %s, token_file %s: err = %v, want %q", tt.stateDir, tt.tokenFile, err, tt.want) } } } diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 4bd34e0..e52e513 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -53,6 +53,7 @@ type Config struct { Format FormatConfig `mapstructure:"format"` Ntfy NtfyConfig `mapstructure:"ntfy"` Queue QueueConfig `mapstructure:"queue"` + State StateConfig `mapstructure:"state"` Images ImagesConfig `mapstructure:"images"` Sentry SentryConfig `mapstructure:"sentry"` Log LogConfig `mapstructure:"log"` @@ -180,11 +181,6 @@ type NtfyConfig struct { // marker hides the tag. Markers map[string]string `mapstructure:"markers"` - // StateDir is the directory each subscription keeps its state in: its - // cursor, the IDs it has seen and the messages it holds. Required when - // a subscription is configured. - StateDir string `mapstructure:"state_dir"` - // Subscriptions are the ntfy servers and topics whose messages print. // They come from the file only: a list of tables has no environment // variable. @@ -319,6 +315,15 @@ type QueueConfig struct { History int `mapstructure:"history"` } +// StateConfig configures where the daemon keeps what must survive a +// restart. +type StateConfig struct { + // Dir is the directory each ntfy subscription keeps its state in: its + // cursor, the IDs it has seen and the messages it holds. It has no + // default, and is required when a subscription is configured. + Dir string `mapstructure:"dir"` +} + // ImagesConfig configures image elements. type ImagesConfig struct { Timeout time.Duration `mapstructure:"timeout"` @@ -974,6 +979,9 @@ func (c *Config) Validate() error { check(c.Queue.Size > 0, "queue.size must be positive") check(c.Queue.History >= 0, "queue.history must not be negative") + check(len(c.Ntfy.Subscriptions) == 0 || strings.TrimSpace(c.State.Dir) != "", + `state.dir is required when an ntfy subscription is configured, e.g. "/var/lib/uberbringer"`) + img := c.Images check(img.Timeout > 0, "images.timeout must be positive") check(img.MaxBytes > 0, "images.max_bytes must be positive") @@ -1004,9 +1012,6 @@ var ( // The server URL is never quoted, since it could hold a password. func validateSubscriptions(n NtfyConfig) []error { var errs []error - if len(n.Subscriptions) > 0 && strings.TrimSpace(n.StateDir) == "" { - errs = append(errs, errors.New(`ntfy.state_dir is required when a subscription is configured, e.g. "/var/lib/uberbringer"`)) - } names := make(map[string]int) for i, s := range n.Subscriptions { at := fmt.Sprintf("ntfy.subscriptions[%d]", i) diff --git a/internal/pkg/config/config_test.go b/internal/pkg/config/config_test.go index 89f4ad0..2e196a9 100644 --- a/internal/pkg/config/config_test.go +++ b/internal/pkg/config/config_test.go @@ -39,11 +39,17 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) { [printer] address = "192.168.1.245" + +[state] + dir = "/var/lib/uberbringer" `) cfg, err := config.Load(path) if err != nil { t.Fatalf("Load: %v", err) } + if cfg.State.Dir != "/var/lib/uberbringer" { + t.Errorf("state.dir = %q", cfg.State.Dir) + } if cfg.Printer.Port != 9100 || cfg.Printer.Model != "tm-t88" || cfg.Printer.CodePage != "cp437" { t.Errorf("printer defaults not applied: %+v", cfg.Printer) } @@ -400,7 +406,7 @@ func TestExampleConfigLoads(t *testing.T) { cfg.Printer.CutFeed != def.Printer.CutFeed || cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout || cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 || - cfg.Ntfy.StateDir != def.Ntfy.StateDir || len(cfg.Ntfy.Subscriptions) != 0 { + cfg.State != def.State || len(cfg.Ntfy.Subscriptions) != 0 { t.Error("example config values drifted from the defaults it documents") } } diff --git a/internal/pkg/config/subscriptions_test.go b/internal/pkg/config/subscriptions_test.go index 0c3ebbf..87709d1 100644 --- a/internal/pkg/config/subscriptions_test.go +++ b/internal/pkg/config/subscriptions_test.go @@ -11,8 +11,9 @@ import ( "uberbringer/internal/pkg/config" ) -// base is a config with the required settings and a state directory. -const base = "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[ntfy]\nstate_dir = \"state\"\n" +// base is a config with the required settings and a state directory, which +// ends in the [ntfy] table, so that keys appended to it set ntfy keys. +const base = "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[state]\ndir = \"state\"\n[ntfy]\n" func TestLoadSubscriptions(t *testing.T) { cfg, err := config.Load(writeConfig(t, base+` @@ -53,6 +54,9 @@ topics = ["long-random-topic-name"] if err != nil { t.Fatal(err) } + if cfg.State.Dir != "state" { + t.Errorf("state.dir = %q, want state", cfg.State.Dir) + } subs := cfg.Ntfy.Subscriptions if len(subs) != 3 { t.Fatalf("%d subscriptions, want 3", len(subs)) @@ -98,8 +102,8 @@ func TestSubscriptionDefaults(t *testing.T) { if q.Start != "22:00" || q.End != "07:00" || len(q.Days) != 7 || q.Timezone != "" || q.MinPriority != 5 || q.Action != "digest" { t.Errorf("quiet defaults %+v", q) } - if cfg := config.Default(); cfg.Ntfy.StateDir != "" || cfg.Ntfy.Subscriptions != nil || cfg.Ntfy.Format.Updates != "print" { - t.Errorf("ntfy defaults %+v", cfg.Ntfy) + if cfg := config.Default(); cfg.State.Dir != "" || cfg.Ntfy.Subscriptions != nil || cfg.Ntfy.Format.Updates != "print" { + t.Errorf("state defaults %+v, ntfy defaults %+v", cfg.State, cfg.Ntfy) } } @@ -151,7 +155,9 @@ func TestLoadSubscriptionErrors(t *testing.T) { tests := []struct { name, body, wantErr string }{ - {"no state dir", strings.Replace(base, "state_dir = \"state\"", "", 1) + sub, "ntfy.state_dir is required"}, + {"no state dir", strings.Replace(base, "dir = \"state\"", "", 1) + sub, "state.dir is required"}, + {"blank state dir", strings.Replace(base, "dir = \"state\"", "dir = \" \"", 1) + sub, "state.dir is required"}, + {"state dir under ntfy", "state_dir = \"state\"\n", "unknown keys: ntfy.state_dir"}, {"unknown key", sub + "topic = \"x\"\n", "unknown keys: ntfy.subscriptions[0].topic"}, {"unknown quiet key", quiet + "begin = \"22:00\"\n", "unknown keys: ntfy.subscriptions[0].quiet.begin"}, {"keys that differ in case", sub + "Name = \"x\"\n", "keys that differ only in case: ntfy.subscriptions[0].Name and ntfy.subscriptions[0].name"}, @@ -226,7 +232,7 @@ func TestLoadSubscriptionErrorHidesSecrets(t *testing.T) { func TestLoadSubscriptionsHaveNoVariable(t *testing.T) { t.Setenv("UBERBRINGER_API_SECRET", validSecret) t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p") - t.Setenv("UBERBRINGER_NTFY_STATE_DIR", "/var/lib/uberbringer") + t.Setenv("UBERBRINGER_STATE_DIR", "/var/lib/uberbringer") t.Setenv("UBERBRINGER_NTFY_SUBSCRIPTIONS", "home") t.Setenv("UBERBRINGER_NTFY_SUBSCRIPTIONS_NAME", "home") t.Setenv("UBERBRINGER_LOG_LEVEL", "loud") @@ -243,17 +249,17 @@ func TestLoadSubscriptionsHaveNoVariable(t *testing.T) { if err != nil { t.Fatal(err) } - if cfg.Ntfy.StateDir != "/var/lib/uberbringer" || len(cfg.Ntfy.Subscriptions) != 0 { - t.Errorf("ntfy = %+v", cfg.Ntfy) + if cfg.State.Dir != "/var/lib/uberbringer" || len(cfg.Ntfy.Subscriptions) != 0 { + t.Errorf("state = %+v, ntfy = %+v", cfg.State, cfg.Ntfy) } } func TestValueOfSubscriptions(t *testing.T) { cfg := config.Default() - cfg.Ntfy.StateDir = "/var/lib/uberbringer" + cfg.State.Dir = "/var/lib/uberbringer" cfg.Ntfy.Subscriptions = []config.NtfySubscription{{Name: "home", Token: "tk_secret"}} - if got, err := cfg.Value("ntfy.state_dir"); err != nil || got != "/var/lib/uberbringer" { - t.Errorf("state_dir = %q, %v", got, err) + if got, err := cfg.Value("state.dir"); err != nil || got != "/var/lib/uberbringer" { + t.Errorf("state.dir = %q, %v", got, err) } if got, err := cfg.Value("ntfy.format.updates"); err != nil || got != "print" { t.Errorf("updates = %q, %v", got, err) diff --git a/packaging/uberbringer.service b/packaging/uberbringer.service index b87809e..3405087 100644 --- a/packaging/uberbringer.service +++ b/packaging/uberbringer.service @@ -32,7 +32,7 @@ NoNewPrivileges=true # The daemon reads its config and the system CA bundle, writes only the state # of its ntfy subscriptions and opens no devices. The file system is read-only # to it, apart from /var/lib/uberbringer, which systemd creates for the -# service user (ntfy.state_dir). +# service user (state.dir). StateDirectory=uberbringer StateDirectoryMode=0700 ProtectSystem=strict