Replace ntfy.state_dir with a top-level [state] dir
Security / Vulnerability check (push) Successful in 45s
Test / Lint and test (push) Successful in 2m1s

The job store is to keep its database in the directory that holds the
ntfy subscriptions' state files, so the directory moves to a section
of its own: [state] dir, or UBERBRINGER_STATE_DIR, in place of
[ntfy] state_dir. For now only the subscriptions use it. It still has
no default and is still required with a subscription, and the checks
at start name state.dir in their errors.

install.sh writes [state] dir into new configs, and the Docker image
sets UBERBRINGER_STATE_DIR. ntfy.state_dir has never been in a
release, so its CHANGELOG entry changes in place and there is no
fallback: a config that still sets it fails to load with an unknown
key until the line moves to [state].

The image itself was not built, since the workstation has no Docker.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 12:21:29 -06:00
1 parent f0b5bf020e
commit 66531e7314
16 files changed
+92 -68

No files matched your search

+1 -1
View File
@@ -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
+1 -1
View File
@@ -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"]
+7 -7
View File
@@ -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
+10 -7
View File
@@ -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-<name>.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-<name>.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 |
+6 -6
View File
@@ -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,
+1 -1
View File
@@ -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.
+2 -2
View File
@@ -32,8 +32,8 @@ sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh <domain> <acme-email> <printer-addr
shows how to issue more.
- The service may write only to `/var/lib/uberbringer`, where the
[ntfy subscriptions](ntfy.md) keep their state. A config the script
creates sets `ntfy.state_dir` to it; add that line to an older config
before adding a subscription.
creates sets [`state.dir`](configuration.md#state) to it; add that
setting to an older config before adding a subscription.
- Change the systemd unit with `systemctl edit uberbringer`.
- The install log is `/var/log/uberbringer-install.log`.
+4 -4
View File
@@ -22,8 +22,8 @@ lists every key, and [ntfy](configuration.md#ntfy) the settings that shape
the cards.
```toml
[ntfy]
state_dir = "/var/lib/uberbringer"
[state]
dir = "/var/lib/uberbringer"
[[ntfy.subscriptions]]
name = "home"
@@ -36,7 +36,7 @@ the cards.
end = "07:00"
```
`install.sh` and the Docker image set `state_dir` already. In Docker, mount
`install.sh` and the Docker image set `state.dir` already. In Docker, mount
a volume for the state and the token file next to the config, as
[docker.md](docker.md#ntfy-subscriptions) shows.
@@ -86,7 +86,7 @@ a volume for the state and the token file next to the config, as
first message of a sequence prints plain, even when its publisher named
the sequence.
- **State.** The cursor, the IDs, the budget and the held messages are in
`<state_dir>/ntfy-<name>.json`, written through a temporary file and a
`<state.dir>/ntfy-<name>.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
+3 -1
View File
@@ -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.**
+2 -2
View File
@@ -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"
+3 -3
View File
@@ -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())
+14 -12
View File
@@ -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)
}
}
}
+13 -8
View File
@@ -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)
+7 -1
View File
@@ -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")
}
}
+17 -11
View File
@@ -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)
+1 -1
View File
@@ -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