Add ntfy subscriptions with digests, quiet hours and a cut feed
Security / Vulnerability check (push) Successful in 40s
Test / Lint and test (push) Failing after 6m43s

[[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:
57_WolveandClaude Opus 5.5 committed 2026-11-30 17:50:23 -06:00
1 parent 1335ed0687
commit fb76284129
52 files changed
+6461 -387

No files matched your search

+37 -3
View File
@@ -14,6 +14,13 @@ version may break callers; such changes are listed under **Breaking**.
included, gets `403` `token_scope` for it and keeps every other route. included, gets `403` `token_scope` for it and keeps every other route.
Re-issue tokens with `--raw` for the clients that send ESC/POS bytes of Re-issue tokens with `--raw` for the clients that send ESC/POS bytes of
their own. their own.
- Every receipt feeds `printer.cut_feed` blank lines (default 3) before
each cut, so that its last line no longer sits right at the cut.
Previews show them before the cut, and they count toward
`format.max_lines`: 3 lines for each cut in each copy, the final cut and
every `cut` element. So a job close to the limit can now fail: 400 lines
in 5 copies was 2000 and is now 2015, and with one `cut` element inside
each copy, 2030. Set `cut_feed = 0` for the old spacing and count.
### Added ### Added
@@ -43,9 +50,36 @@ version may break callers; such changes are listed under **Breaking**.
and the module list. Any other route answers `403` with the new error code and the module list. Any other route answers `403` with the new error code
`token_scope`. A token whose `mod` claim is `null`, or whose `mod` or `token_scope`. A token whose `mod` claim is `null`, or whose `mod` or
`raw` claim is written in another letter case, is refused with `401`. `raw` claim is written in another letter case, is refused with `401`.
- `GET /api/v1/jobs/:id` reports the job's `source`: `print`, or - ntfy subscriptions: `[[ntfy.subscriptions]]` tables in the config make
`module:<name>`. The worker's log lines carry the source and the ID of the the daemon subscribe to ntfy topics itself and print each message as a
request that sent the job. notification card, so no other client is needed.
- After a restart or an outage, the messages missed print once each, up
to `max_backlog` (default 1 hour) back; repeats never print twice.
- A paper budget, `rate_limit` receipts per `rate_window` (default 5 in
10 minutes), holds the rest of a flood and prints it on one digest
receipt once there is room. By default, priority 5 always prints at
once.
- Optional quiet hours (`[ntfy.subscriptions.quiet]`) print only urgent
messages during a daily window and the rest on one `Overnight` digest
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.
`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
and group `10001`, so a mounted token file can be given to it.
- A redirect from the server is never followed, so credentials never
go to another address or over plain http; the connection fails, and
its error says that the server redirects and to set `server` to the
address it redirects to.
- `GET /healthz` lists the ntfy subscriptions in an `ntfy` array, with
their state, counts and last error. Its status code still depends on the
printer alone.
- `GET /api/v1/jobs/:id` reports the job's `source`: `print`,
`module:<name>`, or `ntfy:<subscription>`. The worker's log lines carry
the source and the ID of the request, or of the ntfy message, that sent
the job.
- `image` elements take `"optional": true`: an image that cannot be fetched - `image` elements take `"optional": true`: an image that cannot be fetched
or decoded prints as `[image unavailable]` instead of failing the job, or decoded prints as `[image unavailable]` instead of failing the job,
and one whose `width` is wider than the paper shrinks to it. and one whose `width` is wider than the paper shrinks to it.
+13 -4
View File
@@ -16,16 +16,25 @@ RUN CGO_ENABLED=0 go build -trimpath \
FROM alpine:3.24 FROM alpine:3.24
# ca-certificates for fetching https images, tzdata for local log times. # ca-certificates for fetching https images, tzdata for local log times.
# The user and group have the fixed ID 10001, so that files mounted from the
# host, such as an ntfy token file, can be given to it. /var/lib/uberbringer
# holds the state of the ntfy subscriptions; a named volume mounted there
# takes over its owner, so the daemon can write to it.
RUN apk add --no-cache ca-certificates tzdata \ RUN apk add --no-cache ca-certificates tzdata \
&& addgroup -S uberbringer \ && addgroup -S -g 10001 uberbringer \
&& adduser -S -D -H -G uberbringer -h /etc/uberbringer uberbringer && adduser -S -D -H -u 10001 -G uberbringer -h /etc/uberbringer uberbringer \
&& mkdir -p /var/lib/uberbringer \
&& chown uberbringer:uberbringer /var/lib/uberbringer \
&& chmod 0700 /var/lib/uberbringer
COPY --from=build /out/uberbringer /usr/local/bin/uberbringer COPY --from=build /out/uberbringer /usr/local/bin/uberbringer
USER uberbringer USER uberbringer
WORKDIR /etc/uberbringer WORKDIR /etc/uberbringer
# Plain HTTP for a reverse proxy in front, which terminates TLS. Mount # Plain HTTP for a reverse proxy in front, which terminates TLS. Mount
# config.toml at /etc/uberbringer/config.toml, or set UBERBRINGER_CONFIG to "" # config.toml at /etc/uberbringer/config.toml, or set UBERBRINGER_CONFIG to ""
# and give the settings as UBERBRINGER_* variables. Either way, bind_ip must be # and give the settings as UBERBRINGER_* variables. Either way, bind_ip must be
# 0.0.0.0 and trusted_proxies must hold the proxy's address. # 0.0.0.0 and trusted_proxies must hold the proxy's address. Mount a volume on
ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml # /var/lib/uberbringer to keep the subscriptions' state across containers.
ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml \
UBERBRINGER_NTFY_STATE_DIR=/var/lib/uberbringer
EXPOSE 8080 EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/uberbringer"] ENTRYPOINT ["/usr/local/bin/uberbringer"]
+243 -7
View File
@@ -18,10 +18,12 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
checkbox lists, sized to the paper when the job prints. checkbox lists, sized to the paper when the job prints.
- **Modules**: send a few plain fields, such as a note's title, text and - **Modules**: send a few plain fields, such as a note's title, text and
checklist, and get a laid-out receipt back. checklist, and get a laid-out receipt back.
- **Notifications**: print [ntfy](https://ntfy.sh) messages as they arrive, - **Notifications**: subscribe to [ntfy](https://ntfy.sh) topics from the
through the ntfy client with no other tools, or post a title, message, config and print their messages as they arrive, with no other client,
priority and tags from any script. Each prints as a card styled by its a paper budget that folds floods into one digest, and quiet hours; or
priority, with links as QR codes. print them through the ntfy client, or post a title, message, priority
and tags from any script. Each prints as a card styled by its priority,
with links as QR codes.
- **Scoped tokens**: integration tokens reach only their modules, and only - **Scoped tokens**: integration tokens reach only their modules, and only
tokens issued for it can send raw ESC/POS. tokens issued for it can send raw ESC/POS.
- **Preview**: see the exact lines a job prints, without using paper. - **Preview**: see the exact lines a job prints, without using paper.
@@ -43,6 +45,7 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
- [Quick start](#quick-start) - [Quick start](#quick-start)
- [API](#api), in [docs/api.md](docs/api.md) - [API](#api), in [docs/api.md](docs/api.md)
- [Configuration](#configuration) - [Configuration](#configuration)
- [ntfy subscriptions](#ntfy-subscriptions)
- [Command line](#command-line) - [Command line](#command-line)
- [Development](#development) - [Development](#development)
- [License](#license) - [License](#license)
@@ -70,6 +73,10 @@ sudo ./install.sh printer.example.com you@example.com 192.168.1.245
- Re-running the script upgrades the install and keeps the config. After - Re-running the script upgrades the install and keeps the config. After
editing the config, run `systemctl restart uberbringer`; after changing editing the config, run `systemctl restart uberbringer`; after changing
`webserver.body_limit`, `bind_ip` or `port`, re-run the script instead. `webserver.body_limit`, `bind_ip` or `port`, re-run the script instead.
- The service keeps [ntfy subscriptions](#ntfy-subscriptions)' state in
`/var/lib/uberbringer`, the only directory it may write to. A config the
script creates sets `ntfy.state_dir` to it; add that line to an older
config before adding a subscription.
- Change the systemd unit with `systemctl edit uberbringer`. - Change the systemd unit with `systemctl edit uberbringer`.
- The install log is `/var/log/uberbringer-install.log`. - The install log is `/var/log/uberbringer-install.log`.
@@ -119,6 +126,26 @@ container health checks, use `GET /` to see whether the daemon is up.
`/healthz` answers `503` while the printer is unreachable, so it suits `/healthz` answers `503` while the printer is unreachable, so it suits
alerting better than restarting the container. alerting better than restarting the container.
[ntfy subscriptions](#ntfy-subscriptions) keep their state in
`/var/lib/uberbringer`, which the image sets as `ntfy.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.
```sh
docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" \
-v uberbringer-state:/var/lib/uberbringer uberbringer
```
Subscriptions are set in `config.toml` only, so a container with one needs
the file. The image runs as user and group `10001`, so give a token file
to that ID, mode `600`, and mount it read-only next to the config:
```sh
sudo chown 10001:10001 ntfy.token && sudo chmod 600 ntfy.token
docker run ... -v "$PWD/ntfy.token:/etc/uberbringer/ntfy.token:ro" uberbringer
```
### From source ### From source
```sh ```sh
@@ -148,7 +175,8 @@ case. A duration is a string such as `"5s"`; a bare number is refused.
Every key can also be set by an environment variable named Every key can also be set by an environment variable named
`UBERBRINGER_<SECTION>_<KEY>`, such as `UBERBRINGER_PRINTER_ADDRESS` for `UBERBRINGER_<SECTION>_<KEY>`, such as `UBERBRINGER_PRINTER_ADDRESS` for
`printer.address`, and a variable wins over the file: `printer.address`, and a variable wins over the file. The exception is
`[[ntfy.subscriptions]]`, a list of tables, which only the file sets.
- Values are written without quotes: decimal digits for a number, `true` or - Values are written without quotes: decimal digits for a number, `true` or
`false` for a flag, `5s` for a duration. Lists take comma-separated values, `false` for a flag, `5s` for a duration. Lists take comma-separated values,
@@ -190,6 +218,10 @@ Settings worth knowing:
small gaps in the vertical borders at the printer's default spacing; a small gaps in the vertical borders at the printer's default spacing; a
value checked on paper closes them. `0` keeps the default, which was value checked on paper closes them. `0` keeps the default, which was
checked on a TM-T88IV with `examples/blocks.json` and looks fine. checked on a TM-T88IV with `examples/blocks.json` and looks fine.
- `printer.cut_feed` (default `3`): blank lines, 0–255, fed before every
cut, the one after each copy and `cut` elements alike, so that the last
printed line does not sit right at the cut. They show as blank lines
before the cut in previews and count toward `format.max_lines`.
- `format.max_lines` (default `2000`): a job that would print more lines, - `format.max_lines` (default `2000`): a job that would print more lines,
all copies counted, fails instead of printing. It is a backstop against all copies counted, fails instead of printing. It is a backstop against
runaway text; `/api/v1/preview` answers such a job with `422`. runaway text; `/api/v1/preview` answers such a job with `422`.
@@ -202,7 +234,9 @@ Settings worth knowing:
e.g. `2006-01-02 15:04`. A layout that shows no part of a date is an e.g. `2006-01-02 15:04`. A layout that shows no part of a date is an
error. error.
- `[ntfy.format]` shapes the [notification cards](docs/api.md#notification-cards) - `[ntfy.format]` shapes the [notification cards](docs/api.md#notification-cards)
of the `notify` and `ntfy` modules: of the `notify` and `ntfy` modules and of the
[ntfy subscriptions](#ntfy-subscriptions), and their
[digests](docs/api.md#digests):
| Key | Default | Values | | Key | Default | Values |
|-----|---------|--------| |-----|---------|--------|
@@ -211,9 +245,16 @@ Settings worth knowing:
| `qr` | `all` | Which links print as QR codes: `all`, `first` (the rest as text) or `none` | | `qr` | `all` | Which links print as QR codes: `all`, `first` (the rest as text) or `none` |
| `images` | `true` | `false` names attached images on a `File` row instead of printing them | | `images` | `true` | `false` names attached images on a `File` row instead of printing them |
| `markdown` | `true` | `false` prints markdown messages as written | | `markdown` | `true` | `false` prints markdown messages as written |
| `updates` | `print` | What a [subscription](#ntfy-subscriptions) does with a message that replaces one it printed: `print` marks its title `(updated)`, `skip` leaves it out |
- `[ntfy.markers]` adds or changes the [markers](docs/api.md#markers) - `[ntfy.markers]` adds or changes the [markers](docs/api.md#markers)
printed for tags, at most 16 characters each, and `""` hides a tag: printed for tags, at most 16 characters each, and `""` hides a tag:
`backup = "[B]"`, `nas01 = ""`. `backup = "[B]"`, `nas01 = ""`.
- `ntfy.state_dir` (no default): 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`.
- `[[ntfy.subscriptions]]`: see [ntfy subscriptions](#ntfy-subscriptions).
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for - `webserver.trusted_proxies` / `proxy_header`: the real client IP for
per-client rate limits comes from the `X-Real-IP` header set by the reverse per-client rate limits comes from the `X-Real-IP` header set by the reverse
proxy (Caddy, as `install.sh` configures it) on `127.0.0.1`. proxy (Caddy, as `install.sh` configures it) on `127.0.0.1`.
@@ -243,10 +284,205 @@ Settings worth knowing:
and is logged as ERROR `module printed its fallback receipt`, with the and is logged as ERROR `module printed its fallback receipt`, with the
`module`, the cause in `err` and, after a panic, its `stack`, and is `module`, the cause in `err` and, after a panic, its `stack`, and is
reported to Sentry once. Neither quotes the notification. reported to Sentry once. Neither quotes the notification.
- Each [ntfy subscription](#ntfy-subscriptions) logs with its
`subscription` name, and with the message's `ntfy_id` where there is
one, never with what a message says or its topic: `ntfy connected` at
INFO; `ntfy connection lost` and `ntfy credentials refused` at WARN,
with the cause in `err` and the wait in `retry_in`; `ntfy receipt
queued` at INFO, with the `ref` (the message's ID, or `digest`) and the
`job_id`; `ntfy message waits to print` at WARN while the queue is
full. A card or digest that falls back to a plain receipt is logged at
ERROR as `ntfy card printed its fallback receipt` and reported to
Sentry once, and so is a state file that cannot be written
(`ntfy state not saved`). At DEBUG, each message's fate: held,
dropped in quiet hours, repeated or skipped.
- Refusals are never logged at ERROR and never go to Sentry. Refusals are - Refusals are never logged at ERROR and never go to Sentry. Refusals are
4xx answers other than `module_failed`, the `queue_full` and 4xx answers other than `module_failed`, the `queue_full` and
`shutting_down` 503s, and 503s from `/healthz`. `shutting_down` 503s, and 503s from `/healthz`.
## ntfy subscriptions
The daemon can subscribe to [ntfy](https://ntfy.sh) topics itself and print
each message as a [notification card](docs/api.md#notification-cards), so
the phone's ntfy app, or anything else that publishes, is the only client.
Each `[[ntfy.subscriptions]]` table in `config.toml` is one connection to
one server, for one or more topics:
```toml
[ntfy]
state_dir = "/var/lib/uberbringer"
[[ntfy.subscriptions]]
name = "home"
server = "https://ntfy.example.com"
topics = ["alerts", "backups"]
token_file = "/etc/uberbringer/ntfy.token"
[ntfy.subscriptions.quiet]
start = "22:00"
end = "07:00"
```
| Key | Default | Meaning |
|-----|---------|---------|
| `name` | required | 1–32 lowercase letters, digits, `-` and `_`. It names the subscription in `/healthz`, in logs, in its state file and in its jobs' source, `ntfy:<name>`; each must be unique |
| `server` | required | The server's base URL. It must be `https` unless `allow_insecure = true`. A redirect is never followed: the connection fails, and `last_error` says to set the address it points to |
| `allow_insecure` | `false` | `true` allows a plain `http` server, whose credentials and messages cross the network unencrypted |
| `topics` | required | 1–150 topic names, each 1–64 letters, digits, `-` and `_` |
| `token`, `token_file`, or `user` with `password_file` | none | The credentials, at most one kind. A file holds the secret alone; spaces and line breaks around it are ignored, and a file the group or others can read is accepted with a warning. Without any, the subscription reads as anyone may |
| `min_priority` | `1` | The lowest priority that prints; the server filters by it |
| `max_backlog` | `"1h"` | How far back messages missed during a restart or an outage still print, at most `12h`, the time ntfy keeps them by default |
| `rate_limit`, `rate_window` | `5`, `"10m"` | The paper budget: at most this many receipts in any window. Messages over it are held, and print together on one [digest](docs/api.md#digests) once the budget has room |
| `bypass_priority` | `5` | Outside quiet hours, messages of this priority and above print at once, outside the budget. During quiet hours, `quiet.min_priority` decides first |
| `keepalive` | `"45s"` | The server's keepalive interval, 5s–1h. A connection silent for twice this plus 15 s is opened again |
Quiet hours are off unless the subscription has a
`[ntfy.subscriptions.quiet]` table, which goes right after its
`[[ntfy.subscriptions]]` table:
| Key | Default | Meaning |
|-----|---------|---------|
| `start`, `end` | `"22:00"`, `"07:00"` | The window, as HH:MM. An end before the start is on the next day; the times hold on the nights the clocks change |
| `days` | every day | The days a window starts on: `mon`, `tue`, `wed`, `thu`, `fri`, `sat`, `sun`. With `["fri"]`, Friday's window runs into Saturday morning |
| `timezone` | `format.timezone` | The zone of `start` and `end` |
| `min_priority` | `5` | The lowest priority that prints during the window |
| `action` | `"digest"` | `digest` holds the other messages and prints them on one `Overnight` digest when the window ends; `drop` leaves them out |
How a subscription behaves:
- **First start.** With no state yet, it prints only messages published
from then on, also after a reconnect soon after.
- **Restarts and outages.** It keeps a cursor, the newest server time it
has dealt with, and when it reconnects or starts again it asks for the
messages since then, two minutes earlier to catch late ones. Of those,
it prints only the ones no older than `max_backlog`, measured by ntfy's
own clock as the stream tells it (the time of its first, `open` event,
or else the answer's `Date`), never by this host's, and leaves the
older ones out as they arrive; they stay out, even after a restart with
a longer backlog. It keeps the
IDs of the messages a replay could send again, at least the last 512
and at most 20,000, so a message the server sends again, after a
reconnect or as ntfy's own repeat, never prints twice, even after a
flood; past 20,000, the next replay starts after the IDs it forgot.
- **Failures.** A dropped connection is opened again after 5, 10, 20, 30,
60 and then every 120 seconds, each ± 20%, from 5 seconds again once a
connection has lasted two minutes. A `429` waits as long as its
`Retry-After` says. Refused credentials (`401` or `403`) are checked at
startup, and while the server refuses them the subscription is
`unauthorized` in `/healthz` and tries every five minutes. Printing goes
on meanwhile.
- **A full print queue** pauses the subscription: it stops reading the
stream, offers the message again after 1 second, then after twice as
long each time, up to 30 seconds, and moves its cursor only once the
message is queued. A digest that cannot be queued waits the same way.
- **Updates.** ntfy lets a publisher replace a notification with a later
message of the same sequence (`sequence_id`). When a message's sequence
printed before, on a card or a digest row (not only counted on a
digest), and is among the last 512 it remembers, its card says
`(updated)`, or with `ntfy.format.updates =
"skip"` it is left out. The 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 at most once a second and at
shutdown, through a temporary file and a rename, so a crash leaves the
old file or the new one. A damaged file is ignored with a warning, and
the subscription starts as if new. Held messages survive a restart.
- **Jobs.** Each card and digest is an ordinary job with the source
`ntfy:<name>`. Like any job, one that is still waiting when the daemon
shuts down is marked failed, and is not printed after the restart.
`/healthz` lists each subscription's state, counts and last error; see
[Health](docs/api.md#health).
> [!WARNING]
> Whoever can publish to a subscribed topic prints on your printer, and
> with priority 5 past the paper budget. On the public `ntfy.sh`, anyone
> who knows a topic's name can publish to it: reserve the topic so that
> others may not write to it, or at the very least use a long random name.
> Your own ntfy server lets everyone publish too, unless access control is
> on: set `auth-file`, set `auth-default-access` to `deny-all` (or
> `read-only`), since it defaults to `read-write`, and give write access
> only to your publishers.
On your own ntfy server, with in its `server.yml`
```yaml
auth-file: /var/lib/ntfy/user.db
auth-default-access: deny-all
```
give the printer a user of its own that may only read its topics, and
each publisher one that may only write to them:
```sh
sudo ntfy user add printer # asks for a password
sudo ntfy access printer alerts read-only # once for each topic
sudo ntfy user add phone
sudo ntfy access phone alerts write-only
```
Then create the printer's access token and write it straight into a file
only the daemon can read, so that it never shows on the screen, on a
command line or in your shell history. `ntfy token add` prints the token
on standard error up to ntfy 2.13 and on standard output since 2.14, so
the script takes both, and keeps the token in a shell variable, which
`printf`, a shell builtin, hands to `install` on its standard input.
`install` runs under `umask 077`, so the file is readable by its owner
alone from the moment it is created, also with BusyBox's `install`,
which sets the mode only after writing; it then gets mode 600 and, on the
printer's host, the daemon's user. With ntfy on the same host:
```sh
out=$(sudo ntfy token add printer 2>&1)
token=$(printf '%s\n' "$out" | grep -o 'tk_[A-Za-z0-9]*')
if [ -z "$token" ]; then
printf 'ntfy made no token:\n%s\n' "$out" | sed 's/tk_[A-Za-z0-9]*/tk_.../g' >&2
elif printf '%s\n' "$token" | (umask 077; sudo install -m 600 -o uberbringer -g uberbringer /dev/stdin /etc/uberbringer/ntfy.token); then
unset token
else
cat >&2 <<'EOF'
The token was made but not stored. Fix the cause, then run:
printf '%s\n' "$token" | (umask 077; sudo install -m 600 -o uberbringer -g uberbringer /dev/stdin /etc/uberbringer/ntfy.token) && unset token
EOF
fi
unset out
```
With ntfy on another host, write the token there into a file of your own,
`ntfy.token` in the current directory:
```sh
out=$(sudo ntfy token add printer 2>&1)
token=$(printf '%s\n' "$out" | grep -o 'tk_[A-Za-z0-9]*')
if [ -z "$token" ]; then
printf 'ntfy made no token:\n%s\n' "$out" | sed 's/tk_[A-Za-z0-9]*/tk_.../g' >&2
elif printf '%s\n' "$token" | (umask 077; install -m 600 /dev/stdin ntfy.token); then
unset token
else
cat >&2 <<'EOF'
The token was made but not stored. Fix the cause, then run:
printf '%s\n' "$token" | (umask 077; install -m 600 /dev/stdin ntfy.token) && unset token
EOF
fi
unset out
```
Copy it to the printer's host, place it there with
`sudo install -m 600 -o uberbringer -g uberbringer ntfy.token /etc/uberbringer/ntfy.token`,
and delete both copies of `ntfy.token`.
When no token comes out, the script shows what ntfy said, with any token
in it masked, such as that the user does not exist. When a token was
made but could not be stored, for example because `/etc/uberbringer` is
missing, nothing is written, and the token stays in `$token` until the
printed line stores it: never look it up with `ntfy token list`, which
prints every token in full, and removing one with `ntfy token remove`
needs the token on its command line. If the ntfy web app lets users sign
in (`enable-login: true`, which is off by default), you can also create
the token there under Account and paste it in with `sudoedit`, after
`sudo install -m 600 -o uberbringer -g uberbringer /dev/null /etc/uberbringer/ntfy.token`
has made the empty file.
## Command line ## Command line
```text ```text
@@ -352,7 +588,7 @@ internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper)
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter
internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview
internal/pkg/modules/ Modules that build jobs from plain payloads: note, notify, ntfy; notification cards, markdown internal/pkg/modules/ Modules that build jobs from plain payloads: note, notify, ntfy; notification cards, markdown
internal/pkg/ntfy/ ntfy's message types internal/pkg/ntfy/ ntfy's message types; the subscriber: stream, cursor, repeats, paper budget, quiet hours
internal/pkg/raster/ Image decoding, scaling and dithering internal/pkg/raster/ Image decoding, scaling and dithering
internal/pkg/safehttp/ SSRF-guarded image fetching internal/pkg/safehttp/ SSRF-guarded image fetching
internal/pkg/printer/ TCP printer client (port 9100) and status queries internal/pkg/printer/ TCP printer client (port 9100) and status queries
+47 -4
View File
@@ -63,6 +63,10 @@
# default spacing. # default spacing.
box_line_spacing = 0 box_line_spacing = 0
# Blank lines fed before each cut (0-255), so that the last printed line
# does not sit right at the cut.
cut_feed = 3
dial_timeout = "5s" dial_timeout = "5s"
write_timeout = "30s" write_timeout = "30s"
retries = 3 # resend attempts when the printer is unreachable retries = 3 # resend attempts when the printer is unreachable
@@ -79,16 +83,27 @@
timezone = "Local" timezone = "Local"
time_layout = "02 Jan 15:04" 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] [ntfy.format]
# How the notify and ntfy modules lay out a notification. "auto" picks the # How notifications are laid out, from the notify and ntfy modules and
# form from the priority: urgent and high print in double boxes, default # from the subscriptions. "auto" picks the form from the priority: urgent
# in a single box, low and min under a rule with no box. "box" and # and high print in double boxes, default in a single box, low and min
# "compact" print every priority boxed or without a box. # under a rule with no box. "box" and "compact" print every priority boxed
# or without a box.
style = "auto" style = "auto"
max_lines = 40 # lines of the message that print, as written, 1-400 max_lines = 40 # lines of the message that print, as written, 1-400
qr = "all" # links printed as QR codes: all, first or none qr = "all" # links printed as QR codes: all, first or none
images = true # print attached images; false names them instead images = true # print attached images; false names them instead
markdown = true # lay out markdown messages; false prints them as written markdown = true # lay out markdown messages; false prints them as written
# A subscription's message that replaces one it printed (same sequence):
# "print" marks its title "(updated)", "skip" leaves it out.
updates = "print"
[ntfy.markers] [ntfy.markers]
# Markers printed in front of the title for ntfy's tags, at most 16 # Markers printed in front of the title for ntfy's tags, at most 16
@@ -97,6 +112,34 @@
# backup = "[B]" # backup = "[B]"
# nas01 = "" # nas01 = ""
# A subscription prints the messages of ntfy topics as they arrive. Each is
# a [[ntfy.subscriptions]] table, and they are set in this file only. Remove
# the "# " in front of the lines to use this one.
# [[ntfy.subscriptions]]
# name = "home" # in /healthz, logs and job sources (ntfy:home)
# server = "https://ntfy.example.com" # redirects are not followed
# allow_insecure = false # true allows a plain http server
# topics = ["alerts", "backups"]
# # At most one of: token = "tk_...", token_file, or user with
# # password_file. A file holds only the secret; keep it mode 0600.
# token_file = "/etc/uberbringer/ntfy.token"
# min_priority = 1 # the lowest priority that prints, 1-5
# max_backlog = "1h" # how far back missed messages print, up to 12h
# rate_limit = 5 # receipts per rate_window; the rest wait for
# rate_window = "10m" # room and print together on one digest
# bypass_priority = 5 # outside quiet hours, this priority and above
# # print at once, outside the budget
# keepalive = "45s" # the server's keepalive interval
#
# [ntfy.subscriptions.quiet] # quiet hours; off without this table
# start = "22:00"
# end = "07:00" # an end before the start is on the next day
# days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] # days the window starts on
# timezone = "" # "" is format.timezone
# min_priority = 5 # prints during the window; the rest are held
# action = "digest" # digest prints what was held when the window
# # ends; drop leaves it out
[queue] [queue]
size = 100 # jobs that may wait; more get 503 size = 100 # jobs that may wait; more get 503
history = 1000 # finished jobs whose status is kept history = 1000 # finished jobs whose status is kept
+74 -6
View File
@@ -20,6 +20,7 @@ the daemon.
- [`notify`](#notify) - [`notify`](#notify)
- [`ntfy`](#ntfy) - [`ntfy`](#ntfy)
- [Notification cards](#notification-cards) - [Notification cards](#notification-cards)
- [Digests](#digests)
## API ## API
@@ -68,7 +69,7 @@ included, carry `Cache-Control: no-store`.
| POST | `/api/v1/preview/:module` | Show the lines that receipt prints, without printing it | | POST | `/api/v1/preview/:module` | Show the lines that receipt prints, without printing it |
| GET | `/api/v1/modules` | List the modules | | GET | `/api/v1/modules` | List the modules |
| GET | `/api/v1/jobs/:id` | Job status | | GET | `/api/v1/jobs/:id` | Job status |
| GET | `/healthz` | Printer and queue health (no auth) | | GET | `/healthz` | Printer, queue and subscription health (no auth) |
| GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) | | GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) |
| GET | `/` | Version information (no auth) | | GET | `/` | Version information (no auth) |
@@ -131,8 +132,9 @@ curl -H @"$HOME/.uberbringer-auth" https://printer.example.com/api/v1/jobs/job_0
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an `status` is `queued`, `printing`, `done` or `failed`. A failed job includes an
`error` field. `source` says where the job came from: `print` for `error` field. `source` says where the job came from: `print` for
`/api/v1/print`, or `module:<name>` for a [module](#modules) route. The last `/api/v1/print`, `module:<name>` for a [module](#modules) route, or
`queue.history` finished jobs are kept. `ntfy:<name>` for an [ntfy subscription](../README.md#ntfy-subscriptions)
in the config. The last `queue.history` finished jobs are kept.
### Preview a receipt ### Preview a receipt
@@ -153,12 +155,16 @@ curl -X POST https://printer.example.com/api/v1/preview \
│ !!! ACHTUNG !!! │ │ !!! ACHTUNG !!! │
└─────────────────────┘ └─────────────────────┘
[qr: https://example.com] [qr: https://example.com]
- - - - - - - partial cut - - - - - - - - - - - - - - - partial cut - - - - - - - -
``` ```
- The preview is read back from the bytes the job renders to, so it shows - The preview is read back from the bytes the job renders to, so it shows
what the printer receives: wrapping, folded characters, `?` for missing what the printer receives: wrapping, folded characters, `?` for missing
ones and the final cut. ones, the blank lines [`printer.cut_feed`](../README.md#configuration)
feeds before a cut (3 by default) and the final cut.
- Centred and right-aligned text is indented as the printer places it, - Centred and right-aligned text is indented as the printer places it,
counted in Font A columns. Text at a larger size shows each character counted in Font A columns. Text at a larger size shows each character
once. once.
@@ -172,11 +178,12 @@ With `Accept: application/json` the answer carries the styles too. For
{"type": "qr", "data": "https://example.com"}]`: {"type": "qr", "data": "https://example.com"}]`:
```json ```json
{"columns": 42, "codepage": "cp437", "line_count": 3, {"columns": 42, "codepage": "cp437", "line_count": 6,
"lines": [{"kind": "text", "text": "Total ............................. £12.50", "lines": [{"kind": "text", "text": "Total ............................. £12.50",
"runs": [{"from": 0, "to": 5, "bold": true}, {"from": 36, "to": 42, "bold": true}]}, "runs": [{"from": 0, "to": 5, "bold": true}, {"from": 36, "to": 42, "bold": true}]},
{"kind": "text", "text": " Thanks ?"}, {"kind": "text", "text": " Thanks ?"},
{"kind": "qr", "text": "[qr: https://example.com]", "data": "https://example.com"}, {"kind": "qr", "text": "[qr: https://example.com]", "data": "https://example.com"},
{"kind": "text", "text": ""}, {"kind": "text", "text": ""}, {"kind": "text", "text": ""},
{"kind": "cut", "text": " - - - - - - - partial cut - - - - - - - -", "data": "partial"}], {"kind": "cut", "text": " - - - - - - - partial cut - - - - - - - -", "data": "partial"}],
"warnings": ["elements[1]: 1 character not in cp437 printed as ?"]} "warnings": ["elements[1]: 1 character not in cp437 printed as ?"]}
``` ```
@@ -210,6 +217,28 @@ when the worker renders it, before anything is sent; its `error` reads
A printer that accepts connections but does not answer status requests is A printer that accepts connections but does not answer status requests is
reported as `"status": "unknown"` with HTTP `200`. reported as `"status": "unknown"` with HTTP `200`.
With [ntfy subscriptions](../README.md#ntfy-subscriptions) configured, an
`ntfy` array lists each one, in the order of the config. The status code
still depends on the printer alone, so a subscription that cannot connect
never turns `/healthz` to `503`:
```json
"ntfy": [{"name": "home", "state": "connected", "connected_since": "2026-11-29T20:58:01Z",
"last_message_at": "2026-11-29T21:04:05Z", "printed": 12, "digested": 2, "held": 0, "last_error": ""}]
```
| Field | Meaning |
|-------|---------|
| `state` | `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 |
| `connected_since` | When the current connection opened; absent while there is none |
| `last_message_at` | When the last message arrived; absent until one has |
| `printed` | Messages printed on a card of their own since the daemon started |
| `digested` | Messages held for a [digest](#digests) since the daemon started |
| `held` | Messages waiting for the next digest |
| `last_error` | Why the last connection failed, such as `HTTP 401: the server refused the credentials` or `no data for 1m45s`; empty once one opens |
Credentials, topic names and message text never appear.
Details: Details:
- **Brief problems are re-checked.** A printer that looks not ready is read - **Brief problems are re-checked.** A printer that looks not ready is read
@@ -282,7 +311,8 @@ rendered.
A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is
cut separately. A partial cut is added after the last element unless that cut separately. A partial cut is added after the last element unless that
element is already a `cut`. Boxes, rules, key-value rows and lists are element is already a `cut`. Before every cut, `printer.cut_feed` blank lines
feed (3 by default), so that the last line does not sit right at the cut. Boxes, rules, key-value rows and lists are
described under [Blocks](#blocks). described under [Blocks](#blocks).
### `text` ### `text`
@@ -652,6 +682,9 @@ curl -X POST https://printer.example.com/api/v1/print/notify \
[qr: https://grafana.lan/d/disk] [qr: https://grafana.lan/d/disk]
Open dashboard Open dashboard
- - - - - - - partial cut - - - - - - - - - - - - - - - partial cut - - - - - - - -
``` ```
@@ -704,6 +737,9 @@ attachment expires:
Open dashboard Open dashboard
[image 384 dots: sPs71M8A2Tq9.png] [image 384 dots: sPs71M8A2Tq9.png]
- - - - - - - partial cut - - - - - - - - - - - - - - - partial cut - - - - - - - -
``` ```
@@ -728,6 +764,8 @@ attachment expires:
- A message that updates an earlier one, with the same `sequence_id`, - A message that updates an earlier one, with the same `sequence_id`,
prints as it is, like any other: one message cannot tell whether it is prints as it is, like any other: one message cannot tell whether it is
the first of its sequence, since a publisher may choose the sequence ID. the first of its sequence, since a publisher may choose the sequence ID.
An [ntfy subscription](../README.md#ntfy-subscriptions), which remembers
what it printed, marks such a message `(updated)`.
- A message over the [limits](#notify) of `notify` is not refused; what is - A message over the [limits](#notify) of `notify` is not refused; what is
over them is cut or left out. A title, topic, tag, label or file name is over them is cut or left out. A title, topic, tag, label or file name is
cut with `...`, and the message after 4096 bytes. Tags after the 20th are cut with `...`, and the message after 4096 bytes. Tags after the 20th are
@@ -850,6 +888,36 @@ bold, the message, then the topic and time. That is a bug: it is logged at
ERROR as `module printed its fallback receipt` and reported to Sentry, and ERROR as `module printed its fallback receipt` and reported to Sentry, and
`uberbringer preview --module` prints a warning. `uberbringer preview --module` prints a warning.
A card an [ntfy subscription](../README.md#ntfy-subscriptions) prints for
a message that replaces one it printed before, of the same `sequence_id`,
has `(updated)` after its title, unless `ntfy.format.updates = "skip"`
leaves such messages out.
#### Digests
An ntfy subscription prints the messages it held back on one digest: those
over its rate limit as soon as the limit has room again, and those held in
quiet hours when the window ends. A row gives each message's time, its tag
markers and its title, or the first line of a message without one, or else
its topic, cut to 60 characters, in the order they arrived; the bottom
border holds the time from the first held message to the digest.
```text
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
│ 21:05 [!] Disk almost full (updated) │
│ 21:06 (!) Backup FAILED on nas01 │
│ 21:07 Watchtower │
│ 21:07 Jellyseerr │
│ 21:09 [x] grafana is DOWN │
└───────────────────────── 21:04-21:14 ──┘
```
A digest that holds a message from quiet hours is titled
`Overnight · N held`. It lists 50 messages and counts the rest on a last
row, `... and 13 more`. A digest that cannot be laid out prints as a plain
list of its rows, logged and reported like a card's fallback.
#### Markers #### Markers
Up to two tags with a marker print it in front of the title, each marker Up to two tags with a marker print it in front of the title, each marker
+138 -18
View File
@@ -43,6 +43,13 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
resends the same bytes and does not render again. A send that fails resends the same bytes and does not render again. A send that fails
part-way can print part of a receipt twice. That is accepted, because part-way can print part of a receipt twice. That is accepted, because
retries are what let a job survive a printer that is briefly offline. retries are what let a job survive a printer that is briefly offline.
- **Blank paper before the cut (owner, 2026-11-30).** The cut, `GS V 66 0`,
feeds the last printed line just past the cutter, so the cut fell right
under it. `printer.cut_feed` blank lines (3) now feed before every cut.
They are `ESC d` lines rather than `GS V`'s extra motion units, because
a line is the same on every model while the motion unit is not. The
renderer's option is 0 unless set, so receipts whose bytes tests pin
keep their bytes; the daemon's default is 3.
- **Text in, code page out.** Clients send UTF-8, which is transcoded to - **Text in, code page out.** Clients send UTF-8, which is transcoded to
`printer.codepage`. The default is CP437, for the box drawing and shading `printer.codepage`. The default is CP437, for the box drawing and shading
the owner prints (owner, 2026-11-29). Control characters are stripped, so the owner prints (owner, 2026-11-29). Control characters are stripped, so
@@ -107,7 +114,7 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
and each module checks its own payload. and each module checks its own payload.
- **Notifications print as one card.** The `notify` and `ntfy` modules turn - **Notifications print as one card.** The `notify` and `ntfy` modules turn
their payloads into a `Notice` and lay it out with the same `Card`, which their payloads into a `Notice` and lay it out with the same `Card`, which
phase 4's subscriber will use too. the ntfy subscriptions use too.
- `ntfy` decodes leniently, so that messages from newer ntfy versions - `ntfy` decodes leniently, so that messages from newer ntfy versions
still print, while `notify`, which scripts write by hand, is strict like still print, while `notify`, which scripts write by hand, is strict like
`note`. A message without an `event` counts as a message, so that a `note`. A message without an `event` counts as a message, so that a
@@ -182,8 +189,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
`raw` written in another letter case, which `encoding/json` would `raw` written in another letter case, which `encoding/json` would
match. A malformed scope can therefore never widen access. match. A malformed scope can therefore never widen access.
- **Jobs remember their source.** `Submit` takes a `Meta`: the source - **Jobs remember their source.** `Submit` takes a `Meta`: the source
(`print`, `module:<name>`, later `ntfy:<subscription>`) and a reference, (`print`, `module:<name>` or `ntfy:<subscription>`) and a reference, the
the request ID on the HTTP routes. Job status shows the source and every request ID on the HTTP routes and the message's ID, or `digest`, for a
subscription. Job status shows the source and every
worker log line of the job carries both, so a printed receipt can be worker log line of the job carries both, so a printed receipt can be
traced to its request without logging what it says. The server copies traced to its request without logging what it says. The server copies
both strings, since a request ID the client sent lives in a buffer that both strings, since a request ID the client sent lives in a buffer that
@@ -285,22 +293,133 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
the operator's own reverse proxy, whose address goes in the operator's own reverse proxy, whose address goes in
`webserver.trusted_proxies`. `webserver.trusted_proxies`.
- **ntfy subscriptions run in the daemon.** ntfy is an input: its
notifications are printed (owner, 2026-11-29). The owner's server is
self-hosted at a public URL and attachments come from a public host, so
image fetches need no private-network exception. Each
`[[ntfy.subscriptions]]` table is one `ntfy.Subscriber`, run as one
goroutine of the daemon's errgroup that never fails it: connection and
print failures are retried, and `Run` returns nil when the daemon stops.
The subscriber hands messages and digests to a handler in
`internal/app`, which builds them with `modules` and submits them, so
`ntfy` never imports `modules`.
- One connection per subscription reads `GET /<topics>/json` as a
stream: dial, TLS and header timeouts, no overall one. A loop owns all
state and one goroutine per connection reads lines, so the loop can
stop reading (TCP backpressure) while the print queue is full, and
every timer (reconnect, stall, retry, digest, save) is one deadline
in it.
- The cursor is ntfy server time, never `since=<id>`: an unknown or
expired ID makes ntfy replay the topic's whole history. ntfy sends
`open` before the replay, so only a keepalive or a dealt-with message
moves the cursor, except on a first start without `since`, where
nothing is replayed and `open`'s time is safe. ntfy dates a message
before it stores its attachment, so one can arrive after others dated
later; a reconnect therefore asks for two minutes before the cursor.
The IDs of the messages a replay could send again, those dated at or
after where a replay can start, are kept, so the repeats of a flood
drop, as do ntfy 2.31+'s same-second repeats; the last 512 are kept
anyway, and 20,000 in all at most. When that cap forgets IDs a replay
could still send, the floor rises past them.
- A saved floor bounds every replay from below. A first start sets it to
`open`'s time, so a reconnect soon after never reaches before the
start. `max_backlog`, at most ntfy's 12-hour cache, clamps a replay
by the server's clock, never the host's, so a host clock that is off,
or is stepped, can neither widen a replay nor lose messages. A
connection asks for its replay unclamped; its `open` event, which ntfy
sends first, before any replay, tells ntfy's own clock, the one it
dates messages by. The answer's `Date` stands in only when the open
event has no time, since a proxy in front of ntfy may write it from a
clock of its own. The time since the clock was read is measured on
the monotonic clock. The replay's messages
older than the backlog are then left out as they arrive. Each
connection learns the clock afresh, so nothing learned earlier, before
a step of the host's clock, carries over; keepalives do not count,
since they can wait in the connection while a full queue pauses
reading. The clamp raises the floor at once, so a later start with a
longer backlog never prints what it left out, even if no keepalive
came before the daemon stopped. An unclamped request after a long
outage costs only a larger replay, bounded by the server's cache.
- Redirects are never followed. Go would resend the credentials to the
same host over plain `http`, and a redirect to another host or port,
such as the printer's raw port, would carry the request there and
print what came back; a `3xx` is a failed connection whose error
says to set the address it points to.
- The cursor moves past a message only once it is queued, held or
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
atomically (temporary file, fsync, rename) at most once a second and
at shutdown, mode 0600 since held messages carry titles. A damaged
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.
- Credentials are optional, at most one kind, so that a long random
topic on a public server works without an account. Refused
credentials show at startup through `/<topics>/auth`, then as
`unauthorized` in `/healthz`, retried every five minutes. Failures
back off 5 s to 120 s with ±20% jitter, a `429` waits for its
`Retry-After`, and a stream silent for twice the keepalive plus 15 s
is reconnected.
- `/healthz` lists the subscriptions but its status code still depends
on the printer alone. `last_error` is built from the failure without
the request URL, which names the topics, and a topic on a public
server can be a secret.
- Which priorities print is set per subscription with `min_priority`
(default all), which the server filters by. How priorities 1 and 2
print, compact by default, is `ntfy.format.style`, shared by every
source of cards.
- Subscriptions come from the file only: a list of tables has no
environment variable, and each entry starts from its own defaults,
which Viper cannot give the entries of a list.
- **The paper budget is a strict window (owner, 2026-11-30).** At most
`rate_limit` receipts print in any `rate_window` (5 in 10 minutes by
default), digests included, so a flood never prints more than that,
even in its first minutes. Messages over it are held and print on one
digest once the window has room, and outside quiet hours, while a
digest is waiting, later messages join it, so they print in order.
Outside quiet hours, `bypass_priority` (5) and above print at once;
during them, `quiet.min_priority` decides first. The receipt times are
saved, so a restart cannot reset the budget. A digest lists 50
messages and counts the rest; only those with a row count as printed
for updates.
- **Quiet hours print a morning digest (owner, 2026-11-30).** During a
subscription's daily window only `quiet.min_priority` (5) and above
print; the rest are held in the same digest buffer and print as one
`Overnight` digest when the window ends, or are dropped with
`action = "drop"`. A window's bounds are the instants the zone's clocks
show its times of day, so a window crossing midnight or a change of
clocks keeps them. A bound the clocks skip is the first instant after
the gap, and one they show twice is the one Go's `time.Date` gives;
days are taken at noon, which every zone has. The zone defaults to
`format.timezone`, the zone the cards print in. Held messages are saved
with the state.
- **A subscription marks updates by what it printed (owner, 2026-11-30).**
A message is an update when its sequence (`sequence_id`, or its ID)
printed before, on a card or a digest row, among the last 512 sequences
remembered. So the first message of a sequence its publisher named
prints plain, and the routes, which remember nothing, never mark
updates. `ntfy.format.updates = "skip"` leaves updates out instead.
- **The subscriber is tested on a virtual clock (owner, 2026-11-30).**
`testing/synctest` runs it against an in-memory ntfy server:
reconnects, stalls, backoff, `Retry-After`, quiet nights across clock
changes and a 24-hour soak with floods, repeats, refusals, a full queue
and a restart, in seconds. `synctest.Test` fails if a goroutine
outlives the test, so the soak replaces a 24-hour leak run on
hardware; a short test over real sockets covers `net/http`'s own
goroutines. Both run in every `go test`.
## Planned: formatters ## Planned: formatters
Modules, ntfy among them, that turn plain input into receipts built from the Modules, ntfy among them, that turn plain input into receipts built from the
blocks. The plan is `docs/plans/formatters.md`. Its first three phases are blocks. The plan is `docs/plans/formatters.md`. Its first four phases are
built: the blocks and the preview; the `list` block, the module layer and built: the blocks and the preview; the `list` block, the module layer and
the `note` module; then the `notify` and `ntfy` modules and scoped tokens. the `note` module; the `notify` and `ntfy` modules and scoped tokens; and
Next is the built-in ntfy subscriber. Decided so far (owner, 2026-11-29): the ntfy subscriptions. What is left, phase 5, is built only when a need
appears. Labels are in English, and the footer's time zone and date format
- ntfy is an input: its notifications are printed. The server is come from the config (owner, 2026-11-29).
self-hosted at a public URL, the subscriber authenticates with a token, and
attachments come from a public host, so image fetches need no
private-network exception.
- Which priorities print is configurable per subscription. By default every
priority prints, and priorities 1 and 2 print in a compact form.
- Labels are in English. The footer's time zone and date format come from
the config.
## Deferred ## Deferred
@@ -313,9 +432,10 @@ Next is the built-in ntfy subscriber. Decided so far (owner, 2026-11-29):
built): built):
- Jobs stored with GORM on SQLite, so queued jobs, statuses and history - Jobs stored with GORM on SQLite, so queued jobs, statuses and history
survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite
driver must be pure Go (for example `github.com/glebarez/sqlite`), and the driver must be pure Go (for example `github.com/glebarez/sqlite`), and
systemd unit needs a `StateDirectory` because its file system is the database belongs in the unit's `StateDirectory`,
read-only. The plan must also say how to tell which receipts printed `/var/lib/uberbringer`, the only directory it may write. The plan must
also say how to tell which receipts printed
before a crash, so a restart never prints a receipt twice. before a crash, so a restart never prints a receipt twice.
- A print preview as an image: a digital test print of a job that shows - A print preview as an image: a digital test print of a job that shows
what the paper would look like, without printing. Formatters phase 1 adds what the paper would look like, without printing. Formatters phase 1 adds
+14 -293
View File
@@ -1,314 +1,35 @@
# Plan: CP437 blocks, modules and ntfy printing # Plan: CP437 blocks, modules and ntfy printing
Status: **phases 1-3 are done**. Phase 1: box, rule and kv, text folding and the preview. Phase 2: the list block, the module layer, the note module and its routes, and `[format] timezone` and `time_layout`. Phase 3: the notify and ntfy modules and their cards, scoped tokens, optional images and job sources. All three are built and checked on paper (docs/api.md § Blocks and § Modules, design.md). Phases 4-5 are not started. Every design decision for phase 4 is made; the open questions left are config values and the second printer. Each phase runs in its own session, briefed from its section. Status: **phases 1-4 are done**: the blocks and the preview; the list block, the module layer and the note module; the notify and ntfy modules, their cards and scoped tokens; and the ntfy subscriptions, with their digest, paper budget and quiet hours. All four are built and checked on paper, and docs/api.md, README.md and design.md describe them. Phase 5 is a list of items built one at a time, each when a real need appears, in its own session briefed from its item.
## Decisions (owner, 2026-11-29)
- **ntfy server:** self-hosted at a public URL. The subscriber authenticates
with a token. Attachments come from a public host, so no private-network
exception in safehttp is needed.
- **Which priorities print:** configurable per subscription (minimum priority,
and whether priorities 1-2 print in the compact form). Default: all
priorities, 1-2 compact.
- **Text folding on /print:** yes. Characters the code page lacks fold to
ASCII look-alikes (smart quotes, dashes, ellipsis) and an emoji sequence
prints as one '?'.
- **Language:** English labels ('URGENT', 'HIGH', 'Tags:', '... N more
lines'). Footer time zone and format come from config, default local time
and "02 Jan 15:04".
## Decisions (owner, 2026-11-30)
- **Links:** every link prints as a QR code: the click URL and the view
actions, deduplicated, at most 3. `[ntfy.format] qr` defaults to "all".
- **Image attachments** print (`images = true`).
- **Edited messages** print again, marked "(updated)" (`updates = "print"`).
- **Paper budget:** 5 receipts per 10 minutes per subscription by default,
configurable; the rest fold into one digest receipt. Priority 5 always
prints.
- **Quiet hours:** wanted, as a morning digest, and part of phase 4. During
a configured window only priority 5 prints; everything else is held and
printed as one digest receipt when the window ends. Window, days and time
zone come from config (default 22:00-07:00 every day, local time); off
unless configured.
## Overview
FOUNDATION
The plan starts from Design 1 (components): layout blocks inside the existing element list, small Go modules that turn a plain payload into an ordinary receipt.Job, and ntfy as one of those modules. It is cut down to the vocabulary that notes and notifications actually need:
- box, rule and kv in phase 1
- list in phase 2
Ideas taken from the other designs:
- From Design 2 (templates): fit boxes, a hand-written markdown subset with no new dependency, a plain fallback receipt, a since=<time> cursor, token scopes, and '?' warnings in preview.
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
WHAT SHIPS WHEN (about 5 developer days left to the end of phase 4)
1. Boxes and preview: done.
2. Notes and modules: done. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
3. Notifications: done. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged, so ntfy printing needs only a client.yml entry and no jq.
4. Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
5. Later, on demand: the second-printer pool, user templates, an ntfy-compatible publish endpoint, table/banner/spans, and webhooks.
BACKWARD COMPATIBILITY
- Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later phases keep them passing.
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
WHERE THE JUDGES DISAGREED, AND WHAT THIS PLAN CHOSE
- list: in (phase 2), because the note module needs checklists.
- spans, table, group, banner, nested boxes and goldmark: deferred.
- Geometry checks in the HTTP handler (Renderer.Check): rejected. Layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
- Scoped tokens: built in phase 3; design.md records the decision.
- Quiet hours: phase 4, as a morning digest (owner decision).
## Open questions ## Open questions
Before phase 4 (config, not design):
1. Topics and auth: which topics and quiet-hours window to configure. A
dedicated read-only ntfy user with an access token is assumed.
When the second printer arrives: When the second printer arrives:
2. Which jobs and ntfy topics go to which printer, and should urgent messages 1. Which jobs and ntfy subscriptions go to which printer, and should urgent messages print on both?
print on both?
## Mockups (42 columns, CP437) ## Rules for phase 5
The notification cards are built: docs/api.md § Notification cards shows BACKWARD COMPATIBILITY
the four priority forms as they printed. Still to come: - Every existing element, field and response keeps its meaning, and /print stays strictly decoded.
- TestRenderCompat (receipt/testdata/compat) and TestPaperReceipts pin the bytes of existing jobs; later work keeps them passing.
- Emoji are removed only on the module and ntfy paths; /print prints an emoji sequence as one '?'.
```text DEFERRED UNTIL A NEED APPEARS
All lines are at most 42 columns; every - spans, table, group, banner, nested boxes and goldmark.
glyph is a CP437 byte >= 0x20 (checked - Geometry checks in the HTTP handler (Renderer.Check) stay rejected: layout never fails on a valid job, preview shows the result and line count synchronously, and each module caps its own length.
with Python cp437). Ruler, not printed:
1 2 3 4
123456789012345678901234567890123456789012
--- 12. Rate-limit digest (phase 4)
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
│ 21:05 [!] Disk almost full (updated) │
│ 21:06 (!) Backup FAILED on nas01 │
│ 21:07 Watchtower │
│ 21:07 Jellyseerr │
│ 21:09 [x] grafana is DOWN │
└───────────────────────── 21:04-21:14 ──┘
One row per held message, in arrival
order. Priority 5 never waits.
Glyphs never used: • (only cp1252 has
it), ► ◄ → ← and other 0x01-0x1F
glyphs (printer control codes), emoji.
Use · ∙ ■ » √ ° instead.
```
## API
All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"error","details"}. Successful print responses keep today's 202 body plus a Location header:
{"id":"job_01kbx4n6m3ex8tq0wq3r5vrzq1","status":"queued","source":"print","created_at":"2026-11-29T21:04:05Z"}
==== PHASE 4: configuration ====
Keys go through internal/pkg/config as today: strict keys in the file, an UBERBRINGER_<SECTION>_<KEY> variable for each setting. [format] and the card settings [ntfy.format] and [ntfy.markers] are built (README § Configuration).
[ntfy.format]
updates = "print" # print | skip: a message replacing one the subscriber printed
[ntfy]
state_dir = "/var/lib/uberbringer"
[[ntfy.subscriptions]]
name = "home"
server = "https://ntfy.sh"
topics = ["alerts", "backups"] # ^[-_A-Za-z0-9]{1,64}$, at most 150
token_file = "/etc/uberbringer/ntfy.token" # or user + password_file; exactly one
min_priority = 3 # sent to ntfy as ?priority=3,4,5
max_backlog = "1h" # 12h at most (the ntfy cache)
rate_limit = 5 # receipts per rate_window; the rest go into one digest
rate_window = "10m"
bypass_priority = 5
keepalive = "45s"
[ntfy.subscriptions.quiet] # optional; quiet hours are off without this table
start = "22:00"
end = "07:00" # may cross midnight
days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
timezone = "Local"
min_priority = 5 # prints during the window; the rest are held
action = "digest" # digest | drop; digest prints the held messages when the window ends
GET /healthz (phase 4) adds a field. The HTTP status still depends only on the printer:
"ntfy":[{"name":"home","state":"connected","connected_since":"2026-11-29T20:58:01Z","last_message_at":"2026-11-29T21:04:05Z","printed":12,"digested":2,"last_error":""}]
- state is one of connecting, connected, backoff or unauthorized.
- Tokens are never returned.
## Architecture
LAYERS (each calls only downward)
- server (Fiber v3 handlers) -> modules (payload to receipt.Job) -> receipt (blocks, layout, render, preview) -> escpos (bytes, code pages, interpreter).
- internal/pkg/ntfy holds the ntfy wire types (built) and the subscriber (phase 4). modules imports it for the Message type. serve.go connects the subscriber to modules through a callback, so ntfy never imports modules.
- printqueue takes Submit(job, Meta) (built).
INVARIANTS (all match the current code) INVARIANTS (all match the current code)
1. receipt.Job stays printer-neutral. Blocks are sized at render time from Options.Columns or Profile.Columns(font). The same job therefore prints correctly on a TM-T88IV, TM-T88VII or TM-m50II, and on several printers later. 1. receipt.Job stays printer-neutral. Blocks are sized at render time from Options.Columns or Profile.Columns(font). The same job therefore prints correctly on a TM-T88IV, TM-T88VII or TM-m50II, and on several printers later.
2. Job.Validate stays structural and independent of geometry, so handlePrint keeps its Validate-then-Submit flow. New checks: 2. Job.Validate stays structural and independent of geometry, so handlePrint keeps its Validate-then-Submit flow.
- nested problem paths, e.g. elements[0].children[3] 3. Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only render-time failure is the [format].max_lines backstop (default 2000).
- checkFields: a field that does not apply to a new type is an error 4. Renderer.Render is the only path to printer bytes, and is all-or-nothing.
- child rules
- children count toward MaxElements (500)
- one level of nesting only
3. Layout never fails on a valid job. Widths clamp, titles are cut with "...", and over-long words split the way wrap() already splits them. The only new render-time failure is the [format].max_lines backstop (default 2000).
4. Renderer.Render is still the only path to printer bytes, and still all-or-nothing.
5. New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, to tokens issued with --raw. 5. New code never emits raw ESC/POS. Payload text only ever lands in string fields of elements. The raw element stays available on /print only, to tokens issued with --raw.
6. /print stays strictly decoded (DisallowUnknownFields). A byte-compatibility test pins today's bytes. 6. /print stays strictly decoded (DisallowUnknownFields). A byte-compatibility test pins today's bytes.
7. Layers call only downward: server -> modules -> receipt -> escpos. ntfy never imports modules; internal/app connects the subscriptions to modules.
DATA FLOW
- /print: strict decode -> Validate -> Submit -> worker -> Render.
- Render runs Validate, normalize, layout, loadImages, then builds the bytes, and sends them in one write.
- /preview: strict decode -> Validate -> Renderer.Preview -> escpos.Interpret -> text/plain or JSON.
- Preview uses a placeholder fetcher, so no network.
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:<name>"}).
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:<sub>", Ref: <ntfy id>}).
KEY TYPES (the blocks, the preview, the module layer, the notification card and the ntfy wire types are built; docs/api.md and design.md describe them)
modules (built)
type Notice; type CardOptions (zero value is the default; Env.Card carries it)
func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events and base64 bodies
func Card(n Notice, o CardOptions, env Env) (receipt.Job, error) // the job always prints; a *FallbackError comes with the plain receipt, for the caller to log and report
ntfy
type Message, Action, Attachment // built
type Subscriber // phase 4
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
printqueue (built)
Submit(job receipt.Job, meta Meta) (Status, error); type Meta struct{ Source, Ref string }; Status.Source
The subscriber marks and skips updates itself (Dedupe and state below); Card prints the notice it is given.
SUBSCRIBER (phase 4, internal/pkg/ntfy)
Connection
- One request per subscription: GET {server}/{t1,t2}/json?since=<S>&priority=<min..5>.
- Auth is Bearer tk_... or Basic. The User-Agent is generic.
- Dial, TLS and response-header timeouts apply, with no overall timeout, because the response is a stream.
Cursor
- The cursor C is ntfy server time in Unix seconds, and is persisted.
- At start: since=C when C is no older than max_backlog; otherwise since = now - max_backlog. With no saved state, since is left out, so only new messages print.
- since=<id> is never used. An unknown or expired id makes ntfy replay the topic's whole history.
- C moves to a message's time only once its Submit has succeeded (or the message was deliberately skipped). It moves to an open or keepalive event's time only when no message is waiting to be retried.
Dedupe and state
- A ring of the last 512 ids is persisted. It drops ntfy 2.31+ same-second repeats and the overlap after a reconnect.
- Updates: the sequence IDs of printed messages are remembered with the ids. A message whose sequence was printed before sets Notice.Updated, so its card shows "(updated)", or with updates = "skip" it is left out. The module routes print every message plain (design.md).
- State is JSON in state_dir, written as temp file, then fsync, then rename. It is written at most once a second, and on shutdown.
Reconnects
- If no line arrives for 2 × keepalive + 15 s (105 s by default), the subscriber reconnects.
- Backoff is 5, 10, 20, 30, 60, then 120 s, with ±20% jitter. It resets after 2 minutes connected.
- A 429 follows Retry-After.
- 401 or 403 sets the state to "unauthorized" and retries every 5 minutes.
- GET /{topic}/auth is called at startup so bad credentials show up early.
Queue full
- On ErrQueueFull the subscriber stops reading the stream (TCP backpressure is fine) and retries the same message, waiting from 1 s up to 30 s.
Rate limit
- A token bucket allows rate_limit receipts per rate_window.
- Messages over the limit go into one digest receipt, printed when tokens return. The digest holds 50 rows; after that, messages are only counted.
- Messages at or above bypass_priority skip the bucket.
Quiet hours
- During a subscription's quiet window, messages below quiet.min_priority are held (action = digest) or dropped (action = drop). Held messages share the digest buffer and print as one "Overnight" digest when the window ends.
Images and logging
- Attachment images are fetched through safehttp like any image URL; the ntfy server is public, so no private-network exception is needed.
- Logs carry the source, ntfy id and job id, never the message text. No notification content goes to Sentry, matching sentryMiddleware's existing rule of attaching no bodies.
## Phases ## Phases
### Phase 4: Built-in ntfy subscriber (5 days)
**Goal.** No client code and no extra programs: add [[ntfy.subscriptions]] to the config and the phone's ntfy app becomes the only client. Restarts and outages must not lose a flood's worth of paper or reprint old messages, and nothing but urgent messages prints during quiet hours.
**Work.**
internal/pkg/ntfy
- subscriber.go:
- The JSON-stream client, reading lines through bufio with a 1 MiB cap.
- The since cursor, the stall watchdog, backoff with jitter and Retry-After, the /auth precheck, and the unauthorized state.
- Run(ctx, handle).
- state.go: the cursor plus the 512-id dedupe ring, written atomically (temp file, fsync, rename), at most once a second and on shutdown.
- ratelimit.go: the token bucket plus the digest buffer, with an injectable clock.
- quiet.go: quiet hours. During the window, messages below min_priority are held (action = digest) or dropped (action = drop); held messages print as one digest when the window ends, sharing the digest buffer and its 50-row cap. Boundaries are computed with time.Date in the configured zone, so windows cross midnight and handle DST. Held messages are persisted with the cursor state, so a restart during the night does not lose them.
- status.go: snapshots for /healthz.
internal/pkg/modules
- digest.go: the digest card (mockup 12), titled "ntfy digest · N held" for rate-limit overflow and "Overnight · N held" for quiet hours.
internal/app/uberbringer
- serve.go: one group.Go(sub.Run) per subscription.
- handle does FromNtfy, Card, Validate, then queue.Submit with Meta{Source:"ntfy:<name>", Ref:id}.
- On ErrQueueFull it retries and pauses the stream. If formatting fails, it prints the fallback receipt.
- Run returns nil on cancel and never fails the errgroup on temporary errors.
internal/pkg/config
- [ntfy] state_dir and [[ntfy.subscriptions]], with validation:
- unique names
- https unless allow_insecure is set
- the topic regex, at most 150 topics
- exactly one of token, token_file, or user + password_file
- max_backlog of 12h or less
- rate_limit greater than 0 (default 5 per 10m)
- quiet: start and end as HH:MM, known day names, a loadable time zone, min_priority 1-5, action digest or drop
- a warning when the token file can be read by group or others
internal/app/uberbringer/server
- /healthz gains the ntfy array without changing how the status code is decided.
Deployment
- install.sh: StateDirectory=uberbringer in the unit, because ProtectSystem=strict makes /var/lib read-only otherwise. Also write [ntfy] state_dir.
- Dockerfile and README: document a /var/lib/uberbringer volume.
- README: a Subscriber section with ntfy.sh security advice (a reserved or access-controlled topic, or a long random name, plus a dedicated read-only ntfy user).
**Tests.**
internal/pkg/ntfy (fake clock and fake sleeper)
Use an httptest server that streams NDJSON open, keepalive and message events. Cases:
- first start sends no since
- reconnect after EOF uses since=<cursor>
- a stored cursor older than max_backlog is clamped
- a stall triggers a reconnect after 2×keepalive+15s
- backoff follows its sequence and resets after a stable connection
- 429 honours Retry-After
- 401 sets the unauthorized state
- same-second duplicates and reconnect overlap are deduped, also after the state is reloaded from disk
- the cursor never advances past a message whose Submit failed (ErrQueueFull)
- the state file survives a restart, and a partial or corrupt file is treated as no state with a warning
- multi-topic URLs
- min_priority is sent as the priority filter
- the rate limit sends overflow to a digest, priority 5 bypasses it, and the digest caps at 50 rows
- quiet hours: a window crossing midnight, a DST change night, priority 5 printing during the window, held messages printed as one digest at the window's end, action = drop, and held messages surviving a restart
internal/pkg/config
- Table tests for every validation rule.
internal/app/uberbringer/server
- /healthz shows subscription status, and the status code is unchanged when ntfy is down.
Logs
- A test logger asserts no message text is logged.
**Done when.**
- A message published from the phone prints within a few seconds.
- Stopping uberbringer for 30 minutes while messages are published, then starting it, prints each missed message once (or one digest), with no reprints.
- A stored cursor older than max_backlog never replays older messages.
- A wrong token shows state 'unauthorized' in /healthz while printing keeps working.
- With quiet hours set a few minutes ahead, a priority 3 message published inside the window prints only in the digest at its end, while a priority 5 message prints at once.
- A 24-hour run shows no leaked goroutines.
- The full gate passes (CLAUDE.md lists it).
### Phase 5: Later, on demand (1-3 days each; build only when a real need appears) ### Phase 5: Later, on demand (1-3 days each; build only when a real need appears)
**Goal.** Keep the core small. Each item below is independent and waits for real demand or an owner decision. **Goal.** Keep the core small. Each item below is independent and waits for real demand or an owner decision.
+65 -4
View File
@@ -294,6 +294,13 @@
"HealthResponse": { "HealthResponse": {
"description": "HealthResponse is the body of GET /healthz.", "description": "HealthResponse is the body of GET /healthz.",
"properties": { "properties": {
"ntfy": {
"description": "ntfy is the state of each ntfy subscription, in the order of the config; absent when none is configured.",
"items": {
"$ref": "#/components/schemas/NtfyHealth"
},
"type": "array"
},
"printer": { "printer": {
"$ref": "#/components/schemas/PrinterHealth", "$ref": "#/components/schemas/PrinterHealth",
"description": "printer is the printer's state." "description": "printer is the printer's state."
@@ -303,7 +310,7 @@
"description": "queue is the print queue's state." "description": "queue is the print queue's state."
}, },
"status": { "status": {
"description": "status is ok, degraded when the printer is not ready, or unavailable when it is unreachable or did not answer in time.", "description": "status is ok, degraded when the printer is not ready, or unavailable when it is unreachable or did not answer in time. It depends on the printer alone.",
"enum": [ "enum": [
"ok", "ok",
"degraded", "degraded",
@@ -407,7 +414,7 @@
"type": "string" "type": "string"
}, },
"source": { "source": {
"description": "source says where the job came from: print for POST /api/v1/print, or module:<name> for a module route, e.g. module:ntfy.", "description": "source says where the job came from: print for POST /api/v1/print, module:<name> for a module route, e.g. module:ntfy, or ntfy:<subscription> for an ntfy subscription in the config.",
"type": "string" "type": "string"
}, },
"started_at": { "started_at": {
@@ -462,6 +469,60 @@
"description": "ModulePayload is a module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.", "description": "ModulePayload is a module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.",
"type": "object" "type": "object"
}, },
"NtfyHealth": {
"description": "NtfyHealth is the state of an ntfy subscription. It holds no credentials and nothing a message says.",
"properties": {
"connected_since": {
"description": "connected_since is when the current connection opened; absent while there is none.",
"format": "date-time",
"type": "string"
},
"digested": {
"description": "digested is how many messages were held for a digest since the daemon started: over the rate limit, or in quiet hours.",
"type": "integer"
},
"held": {
"description": "held is how many messages wait for the next digest.",
"type": "integer"
},
"last_error": {
"description": "last_error says why the last connection failed; empty once one opens.",
"type": "string"
},
"last_message_at": {
"description": "last_message_at is when the last message arrived; absent until one has.",
"format": "date-time",
"type": "string"
},
"name": {
"description": "name is the subscription's name from the config.",
"type": "string"
},
"printed": {
"description": "printed is how many messages printed on a card of their own since the daemon started.",
"type": "integer"
},
"state": {
"description": "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.",
"enum": [
"connecting",
"connected",
"backoff",
"unauthorized"
],
"type": "string"
}
},
"required": [
"name",
"state",
"printed",
"digested",
"held",
"last_error"
],
"type": "object"
},
"OpenAPIDocument": { "OpenAPIDocument": {
"description": "OpenAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1 document, generated from the route table.", "description": "OpenAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1 document, generated from the route table.",
"properties": { "properties": {
@@ -1679,7 +1740,7 @@
}, },
"/healthz": { "/healthz": {
"get": { "get": {
"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.", "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. The ntfy subscriptions, when any are configured, are listed with their state; the status code depends on the printer alone.",
"operationId": "getHealth", "operationId": "getHealth",
"responses": { "responses": {
"200": { "200": {
@@ -1717,7 +1778,7 @@
} }
}, },
"security": [], "security": [],
"summary": "Printer and queue health", "summary": "Printer, queue and subscription health",
"tags": [ "tags": [
"health" "health"
] ]
+4
View File
@@ -209,6 +209,10 @@ write_config() {
[printer] [printer]
address = "$PRINTER_ADDRESS" address = "$PRINTER_ADDRESS"
[ntfy]
# The unit's StateDirectory; ntfy subscriptions keep their state here.
state_dir = "/var/lib/uberbringer"
EOT EOT
) )
chown root:"$SERVICE_USER" "$CONFIG" chown root:"$SERVICE_USER" "$CONFIG"
+266
View File
@@ -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
}
+264
View File
@@ -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)
}
}
}
+5 -2
View File
@@ -69,7 +69,7 @@ func TestPreviewCommandReadsStdin(t *testing.T) {
if err := cmd.Execute(); err != nil { if err := cmd.Execute(); err != nil {
t.Fatal(err) 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) 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"`}, {"unknown field", `{"elements":[{"type":"rule","colour":"red"}]}`, "", `unknown field "colour"`},
{"invalid", `{"elements":[{"type":"box"},{"type":"kv"}]}`, "", {"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"}, "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 { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@@ -129,6 +129,7 @@ func TestPreviewCommandModule(t *testing.T) {
"│ [ ] Milk │\n" + "│ [ ] Milk │\n" +
"│ [√] Eggs │\n" + "│ [√] Eggs │\n" +
"└───────────────────────────── kitchen ──┘\n" + "└───────────────────────────── kitchen ──┘\n" +
"\n\n\n" +
" - - - - - - - partial cut - - - - - - - -\n" " - - - - - - - partial cut - - - - - - - -\n"
if out.String() != want || errOut.Len() != 0 { if out.String() != want || errOut.Len() != 0 {
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String()) 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 ║", "║ Tags: nas01 ║",
"╚══════════════ backups · 29 Nov 21:04 ══╝", "╚══════════════ backups · 29 Nov 21:04 ══╝",
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓", "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
"", "", "",
" - - - - - - - partial cut - - - - - - - -", " - - - - - - - partial cut - - - - - - - -",
}}, }},
{"compact, with markers", "[format]\ntimezone = \"UTC\"\n[ntfy.format]\nstyle = \"compact\"\n" + {"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", "/!\\ Backup FAILED on nas01",
"Job nightly-offsite exited with code 2", "Job nightly-offsite exited with code 2",
"after 3h12m. Last good run: 2 days ago.", "after 3h12m. Last good run: 2 days ago.",
"", "", "",
" - - - - - - - partial cut - - - - - - - -", " - - - - - - - partial cut - - - - - - - -",
}}, }},
} }
+11
View File
@@ -71,6 +71,11 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
} }
defer flushSentry() defer flushSentry()
subscribers, err := newSubscribers(cfg, logger)
if err != nil {
return err
}
fetcher := safehttp.New(safehttp.Options{ fetcher := safehttp.New(safehttp.Options{
Timeout: cfg.Images.Timeout, Timeout: cfg.Images.Timeout,
MaxBytes: cfg.Images.MaxBytes, MaxBytes: cfg.Images.MaxBytes,
@@ -113,6 +118,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
Previewer: renderer, Previewer: renderer,
Modules: registry, Modules: registry,
ModuleEnv: env, ModuleEnv: env,
Ntfy: ntfyHealth(subscribers),
}, logger) }, logger)
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port)) 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, groupCtx := errgroup.WithContext(ctx)
group.Go(func() error { return queue.Run(groupCtx) }) group.Go(func() error { return queue.Run(groupCtx) })
group.Go(func() error { return srv.Serve(groupCtx, ln) }) 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() err = group.Wait()
logger.Info("shutdown complete") logger.Info("shutdown complete")
return err return err
@@ -157,6 +167,7 @@ func rendererOptions(cfg *config.Config) (receipt.Options, error) {
MaxHeight: cfg.Images.MaxHeight, MaxHeight: cfg.Images.MaxHeight,
MaxLines: cfg.Format.MaxLines, MaxLines: cfg.Format.MaxLines,
BoxLineSpacing: cfg.Printer.BoxLineSpacing, BoxLineSpacing: cfg.Printer.BoxLineSpacing,
CutFeed: cfg.Printer.CutFeed,
}, nil }, nil
} }
+35 -1
View File
@@ -183,12 +183,43 @@ type printerHealth struct {
// healthResponse is the body of GET /healthz. // healthResponse is the body of GET /healthz.
type healthResponse struct { type healthResponse struct {
// Status is ok, degraded when the printer is not ready, or unavailable // 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"` Status string `json:"status" jsonschema:"enum=ok,enum=degraded,enum=unavailable"`
// Printer is the printer's state. // Printer is the printer's state.
Printer printerHealth `json:"printer"` Printer printerHealth `json:"printer"`
// Queue is the print queue's state. // Queue is the print queue's state.
Queue queueHealth `json:"queue"` 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. // queueHealth is the queue part of the /healthz response.
@@ -205,6 +236,9 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
var resp healthResponse var resp healthResponse
resp.Queue.Pending = s.jobs.Pending() resp.Queue.Pending = s.jobs.Pending()
if s.ntfy != nil {
resp.Ntfy = s.ntfy()
}
httpStatus := fiber.StatusOK httpStatus := fiber.StatusOK
st, err := s.settledPrinterStatus(ctx) 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)
}
}
+4 -2
View File
@@ -167,10 +167,12 @@ func Routes() []Route {
Method: http.MethodGet, Method: http.MethodGet,
Path: "/healthz", Path: "/healthz",
OperationID: "getHealth", 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 " + 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 " + "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", Tag: "health",
NoStore: true, NoStore: true,
Responses: []Response{ Responses: []Response{
@@ -58,6 +58,10 @@ type Deps struct {
// ModuleEnv returns what a module may know when it builds a job: the // ModuleEnv returns what a module may know when it builds a job: the
// time now, and the zone and layout times print in. // time now, and the zone and layout times print in.
ModuleEnv func() modules.Env 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. // Info describes the running build for the index route.
@@ -114,6 +118,7 @@ type Server struct {
previewer Previewer previewer Previewer
modules Modules modules Modules
moduleEnv func() modules.Env moduleEnv func() modules.Env
ntfy func() []NtfyHealth
logger *slog.Logger logger *slog.Logger
} }
@@ -139,6 +144,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
previewer: deps.Previewer, previewer: deps.Previewer,
modules: deps.Modules, modules: deps.Modules,
moduleEnv: deps.ModuleEnv, moduleEnv: deps.ModuleEnv,
ntfy: deps.Ntfy,
logger: logger, logger: logger,
} }
+3
View File
@@ -10,4 +10,7 @@ Used ................................. 94%
Inverted <b>not a tag</b> ? Inverted <b>not a tag</b> ?
[image 384 dots: logo.png] [image 384 dots: logo.png]
[qr: https://example.com] [qr: https://example.com]
- - - - - - - partial cut - - - - - - - - - - - - - - - partial cut - - - - - - - -
+377 -16
View File
@@ -8,8 +8,10 @@ import (
"fmt" "fmt"
"maps" "maps"
"net/netip" "net/netip"
"net/url"
"os" "os"
"reflect" "reflect"
"regexp"
"slices" "slices"
"strconv" "strconv"
"strings" "strings"
@@ -34,6 +36,9 @@ const MinSecretLength = 32
// takes. // takes.
const MaxLineSpacing = 255 const MaxLineSpacing = 255
// MaxCutFeed is the largest printer.cut_feed, the most ESC d feeds at once.
const MaxCutFeed = 255
// Log formats accepted by [LogConfig.Format]. // Log formats accepted by [LogConfig.Format].
const ( const (
LogFormatText = "text" LogFormatText = "text"
@@ -106,6 +111,10 @@ type PrinterConfig struct {
// keeps the printer's default spacing. // keeps the printer's default spacing.
BoxLineSpacing int `mapstructure:"box_line_spacing"` BoxLineSpacing int `mapstructure:"box_line_spacing"`
// CutFeed is how many blank lines feed before each cut, so that the
// last printed line does not sit right at the cut.
CutFeed int `mapstructure:"cut_feed"`
DialTimeout time.Duration `mapstructure:"dial_timeout"` DialTimeout time.Duration `mapstructure:"dial_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"` WriteTimeout time.Duration `mapstructure:"write_timeout"`
@@ -129,27 +138,152 @@ type FormatConfig struct {
TimeLayout string `mapstructure:"time_layout"` TimeLayout string `mapstructure:"time_layout"`
} }
// Values of NtfyFormatConfig's settings. // Values of the ntfy settings.
var ( var (
NtfyStyles = []string{"auto", "box", "compact"} NtfyStyles = []string{"auto", "box", "compact"}
NtfyQRModes = []string{"all", "first", "none"} NtfyQRModes = []string{"all", "first", "none"}
NtfyUpdateModes = []string{"print", "skip"}
NtfyQuietActions = []string{"digest", "drop"}
NtfyDays = []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"}
) )
// Limits of the ntfy settings: the largest ntfy.format.max_lines, and the // Limits of the ntfy settings.
// most characters in a marker.
const ( const (
// MaxNtfyLines is the largest ntfy.format.max_lines.
MaxNtfyLines = 400 MaxNtfyLines = 400
// MaxMarker is the most characters in a marker.
MaxMarker = 16 MaxMarker = 16
// MaxNtfyTopics is how many topics one subscription may name, as many
// as ntfy serves on one connection.
MaxNtfyTopics = 150
// MaxNtfyBacklog is the longest max_backlog: ntfy keeps messages for
// 12 hours by default.
MaxNtfyBacklog = 12 * time.Hour
// MaxNtfyRateLimit is the largest rate_limit.
MaxNtfyRateLimit = 1000
// MinNtfyKeepalive and MaxNtfyKeepalive bound keepalive.
MinNtfyKeepalive = 5 * time.Second
MaxNtfyKeepalive = time.Hour
) )
// NtfyConfig configures how notifications print, from the notify and ntfy // NtfyConfig configures how notifications print, from the notify and ntfy
// modules. // modules and from the subscriptions.
type NtfyConfig struct { type NtfyConfig struct {
Format NtfyFormatConfig `mapstructure:"format"` Format NtfyFormatConfig `mapstructure:"format"`
// Markers override the markers printed for tags, by tag: an empty // Markers override the markers printed for tags, by tag: an empty
// marker hides the tag. // marker hides the tag.
Markers map[string]string `mapstructure:"markers"` 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.
Subscriptions []NtfySubscription `mapstructure:"subscriptions"`
}
// NtfySubscription is one connection to an ntfy server, for one or more
// topics.
type NtfySubscription struct {
// Name names the subscription in /healthz, in logs, in job sources
// (ntfy:<name>) and in its state file.
Name string `mapstructure:"name"`
// Server is the ntfy server's base URL, e.g. https://ntfy.sh.
Server string `mapstructure:"server"`
// Topics are the topics to print.
Topics []string `mapstructure:"topics"`
// Token, TokenFile, or User with PasswordFile authenticate the
// subscription; at most one of them is set. A file holds the secret
// alone, and spaces around it are ignored.
Token string `mapstructure:"token"`
TokenFile string `mapstructure:"token_file"`
User string `mapstructure:"user"`
PasswordFile string `mapstructure:"password_file"`
// AllowInsecure allows a server URL that is http rather than https.
AllowInsecure bool `mapstructure:"allow_insecure"`
// MinPriority is the lowest priority that prints, 1-5.
MinPriority int `mapstructure:"min_priority"`
// MaxBacklog is how far back missed messages are printed after a
// restart or an outage.
MaxBacklog time.Duration `mapstructure:"max_backlog"`
// RateLimit receipts print per RateWindow at most; messages over it
// are held and print together on one digest receipt.
RateLimit int `mapstructure:"rate_limit"`
RateWindow time.Duration `mapstructure:"rate_window"`
// BypassPriority is the lowest priority that prints at once, outside
// the rate limit, 1-5.
BypassPriority int `mapstructure:"bypass_priority"`
// Keepalive is the server's keepalive interval. A connection that
// sends nothing for twice this, plus 15 seconds, is reconnected.
Keepalive time.Duration `mapstructure:"keepalive"`
// Quiet sets quiet hours; nil leaves them off.
Quiet *NtfyQuiet `mapstructure:"quiet"`
}
// NtfyQuiet configures a subscription's quiet hours: a daily window in
// which only urgent messages print.
type NtfyQuiet struct {
// Start and End are the window's times of day, HH:MM. An End before
// Start ends the window on the next day.
Start string `mapstructure:"start"`
End string `mapstructure:"end"`
// Days are the days the window starts on: mon, tue, wed, thu, fri,
// sat or sun.
Days []string `mapstructure:"days"`
// Timezone is the zone Start and End are in; "" means format.timezone.
Timezone string `mapstructure:"timezone"`
// MinPriority is the lowest priority that prints during the window.
MinPriority int `mapstructure:"min_priority"`
// Action is digest, to print the held messages on one receipt when the
// window ends, or drop.
Action string `mapstructure:"action"`
}
// DefaultSubscription returns a subscription with every optional setting
// at its default. Name, Server and Topics have no defaults.
func DefaultSubscription() NtfySubscription {
return NtfySubscription{
MinPriority: 1,
MaxBacklog: time.Hour,
RateLimit: 5,
RateWindow: 10 * time.Minute,
BypassPriority: 5,
Keepalive: 45 * time.Second,
}
}
// DefaultQuiet returns quiet hours with every setting at its default.
func DefaultQuiet() NtfyQuiet {
return NtfyQuiet{
Start: "22:00",
End: "07:00",
Days: slices.Clone(NtfyDays),
MinPriority: 5,
Action: "digest",
}
} }
// NtfyFormatConfig configures the layout of a notification. // NtfyFormatConfig configures the layout of a notification.
@@ -169,6 +303,11 @@ type NtfyFormatConfig struct {
// Markdown lays out markdown messages. // Markdown lays out markdown messages.
Markdown bool `mapstructure:"markdown"` Markdown bool `mapstructure:"markdown"`
// Updates says what a subscription does with a message that replaces
// one it printed: print marks its title "(updated)", skip leaves it
// out. The module routes print every message plain.
Updates string `mapstructure:"updates"`
} }
// QueueConfig configures the print queue. // QueueConfig configures the print queue.
@@ -237,6 +376,7 @@ func Default() Config {
// printer makes it break words at the right edge. // printer makes it break words at the right edge.
Model: "tm-t88", Model: "tm-t88",
CodePage: "cp437", CodePage: "cp437",
CutFeed: 3,
DialTimeout: 5 * time.Second, DialTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second,
Retries: 3, Retries: 3,
@@ -254,6 +394,7 @@ func Default() Config {
QR: "all", QR: "all",
Images: true, Images: true,
Markdown: true, Markdown: true,
Updates: "print",
}, },
}, },
Queue: QueueConfig{ Queue: QueueConfig{
@@ -293,7 +434,7 @@ func Load(path string) (*Config, error) {
var envSet []string var envSet []string
bound := map[string]bool{PathEnvVar: true} bound := map[string]bool{PathEnvVar: true}
for _, key := range slices.Sorted(maps.Keys(keys)) { for _, key := range slices.Sorted(maps.Keys(keys)) {
if keys[key] == section { if kind := keys[key]; kind != setting && kind != tableSetting {
continue continue
} }
name := envVar(key) name := envVar(key)
@@ -340,13 +481,7 @@ func Load(path string) (*Config, error) {
var cfg Config var cfg Config
err := v.Unmarshal(&cfg, err := v.Unmarshal(&cfg,
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc( viper.DecodeHook(decodeHooks()),
durations(),
stringToList(),
stringToTable(),
refuseFractions(),
stringToNumberOrFlag(),
)),
// Values are taken as written, apart from the strings that hooks // Values are taken as written, apart from the strings that hooks
// above parse: environment variables are strings. // above parse: environment variables are strings.
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false }, func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
@@ -417,14 +552,21 @@ func readFile(path string) (map[string]any, error) {
return table, nil return table, nil
} }
// keyKind tells a setting from a section that holds settings, and from a // keyKind tells a setting from a section that holds settings, from a
// table setting, whose keys are the user's own. // table setting, whose keys are the user's own, and from a list of tables.
type keyKind int type keyKind int
const ( const (
setting keyKind = iota + 1 setting keyKind = iota + 1
section section
tableSetting tableSetting
// tableList is a list of tables, such as ntfy.subscriptions, which only
// the file sets. listSetting and listSection are the keys of its
// entries.
tableList
listSetting
listSection
) )
// registerDefaults sets every field of the config struct rv as a Viper // registerDefaults sets every field of the config struct rv as a Viper
@@ -449,6 +591,14 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
// A default table would merge with the file's instead of // A default table would merge with the file's instead of
// giving way to it; the table settings default to empty. // giving way to it; the table settings default to empty.
keys[key] = tableSetting keys[key] = tableSetting
case reflect.Slice:
if elem := field.Type().Elem(); elem.Kind() == reflect.Struct {
keys[key] = tableList
registerListKeys(key, elem, keys)
continue
}
v.SetDefault(key, field.Interface())
keys[key] = setting
default: default:
v.SetDefault(key, field.Interface()) v.SetDefault(key, field.Interface())
keys[key] = setting keys[key] = setting
@@ -456,6 +606,29 @@ func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[
} }
} }
// registerListKeys records the keys of an entry of a list of tables, a
// struct of type t, under prefix. They have no Viper defaults: decodeHooks
// starts each entry from its own defaults.
func registerListKeys(prefix string, t reflect.Type, keys map[string]keyKind) {
for i := range t.NumField() {
tag := t.Field(i).Tag.Get("mapstructure")
if tag == "" {
continue
}
key := prefix + "." + tag
ft := t.Field(i).Type
if ft.Kind() == reflect.Pointer {
ft = ft.Elem()
}
if ft.Kind() == reflect.Struct {
keys[key] = listSection
registerListKeys(key, ft, keys)
continue
}
keys[key] = listSetting
}
}
// checkKeys walks the file's table under prefix. It returns the keys Config // checkKeys walks the file's table under prefix. It returns the keys Config
// does not have (unknown names, empty tables included, a setting written as // does not have (unknown names, empty tables included, a setting written as
// a table, a section written as a value, and a quoted name with a dot, which // a table, a section written as a value, and a quoted name with a dot, which
@@ -485,7 +658,7 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
kind = 0 kind = 0
} }
switch { switch {
case isTable && kind == section: case isTable && (kind == section || kind == listSection):
u, c := checkKeys(sub, path, key, keys) u, c := checkKeys(sub, path, key, keys)
unknown = append(unknown, u...) unknown = append(unknown, u...)
clashes = append(clashes, c...) clashes = append(clashes, c...)
@@ -493,7 +666,11 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
u, c := checkTable(sub, path) u, c := checkTable(sub, path)
unknown = append(unknown, u...) unknown = append(unknown, u...)
clashes = append(clashes, c...) clashes = append(clashes, c...)
case !isTable && kind == setting: case kind == tableList:
u, c := checkList(table[name], path, key, keys)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
case !isTable && (kind == setting || kind == listSetting):
default: default:
unknown = append(unknown, path) unknown = append(unknown, path)
} }
@@ -501,6 +678,38 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
return unknown, clashes return unknown, clashes
} }
// checkList checks the entries of a list of tables at path, whose dotted
// lowercase key is lookup. Each entry must be a table, whose keys are
// checked as a section's; an entry is named by its index, as
// ntfy.subscriptions[0].name. A list given as anything else is unknown.
func checkList(value any, path, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
var entries []map[string]any
switch list := value.(type) {
case []map[string]any:
entries = list
case []any:
for i, item := range list {
entry, ok := item.(map[string]any)
if !ok {
unknown = append(unknown, fmt.Sprintf("%s[%d]", path, i))
continue
}
entries = append(entries, entry)
}
if len(unknown) > 0 {
return unknown, nil
}
default:
return []string{path}, nil
}
for i, entry := range entries {
u, c := checkKeys(entry, fmt.Sprintf("%s[%d]", path, i), lookup, keys)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
}
return unknown, clashes
}
// checkTable checks the entries of a table setting at path, whose names are // checkTable checks the entries of a table setting at path, whose names are
// the user's own. Like checkKeys, it returns as unknown a name with a dot // the user's own. Like checkKeys, it returns as unknown a name with a dot
// and an entry that is itself a table, and the names that differ only in // and an entry that is itself a table, and the names that differ only in
@@ -530,6 +739,50 @@ func displayKey(name string) string {
return strconv.Quote(name) return strconv.Quote(name)
} }
// decodeHooks are the hooks that decode the config: values from strings,
// and the entries of the lists of tables from their own defaults.
func decodeHooks() mapstructure.DecodeHookFunc {
values := []mapstructure.DecodeHookFunc{
durations(),
stringToList(),
stringToTable(),
refuseFractions(),
stringToNumberOrFlag(),
}
quiet := entryDefaults(DefaultQuiet, values)
subscription := entryDefaults(DefaultSubscription, append(slices.Clone(values), quiet))
return mapstructure.ComposeDecodeHookFunc(append(values, subscription, quiet)...)
}
// entryDefaults decodes a table into a T, an entry of a list of tables or
// a table inside one, starting from defaults(): the keys the table leaves
// out keep their defaults, which Viper cannot give the entries of a list.
// hooks decode the entry's values.
func entryDefaults[T any](defaults func() T, hooks []mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {
target := reflect.TypeFor[T]()
return func(_, to reflect.Type, data any) (any, error) {
table, ok := data.(map[string]any)
if to != target || !ok {
return data, nil
}
entry := defaults()
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(hooks...),
// A list the table gives replaces the default list rather than
// overwriting its first items.
ZeroFields: true,
Result: &entry,
})
if err != nil {
return nil, err
}
if err := dec.Decode(table); err != nil {
return nil, err
}
return entry, nil
}
}
// durations decodes a duration from a string such as "1m30s". A bare number // durations decodes a duration from a string such as "1m30s". A bare number
// is refused, since the decoder would read it as nanoseconds. // is refused, since the decoder would read it as nanoseconds.
func durations() mapstructure.DecodeHookFunc { func durations() mapstructure.DecodeHookFunc {
@@ -692,6 +945,7 @@ func (c *Config) Validate() error {
check(p.Columns >= 0, "printer.columns must not be negative") check(p.Columns >= 0, "printer.columns must not be negative")
check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing, check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing,
"printer.box_line_spacing must be 0-%d", MaxLineSpacing) "printer.box_line_spacing must be 0-%d", MaxLineSpacing)
check(p.CutFeed >= 0 && p.CutFeed <= MaxCutFeed, "printer.cut_feed must be 0-%d", MaxCutFeed)
check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive") check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive")
check(p.Retries >= 0, "printer.retries must not be negative") check(p.Retries >= 0, "printer.retries must not be negative")
check(p.RetryDelay > 0, "printer.retry_delay must be positive") check(p.RetryDelay > 0, "printer.retry_delay must be positive")
@@ -714,6 +968,8 @@ func (c *Config) Validate() error {
check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker, check(utf8.RuneCountInString(c.Ntfy.Markers[tag]) <= MaxMarker,
"ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker) "ntfy.markers.%s: %q is longer than %d characters", tag, c.Ntfy.Markers[tag], MaxMarker)
} }
check(slices.Contains(NtfyUpdateModes, nf.Updates), "ntfy.format.updates: %q must be one of %s", nf.Updates, strings.Join(NtfyUpdateModes, ", "))
errs = append(errs, validateSubscriptions(c.Ntfy)...)
check(c.Queue.Size > 0, "queue.size must be positive") check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative") check(c.Queue.History >= 0, "queue.history must not be negative")
@@ -732,6 +988,111 @@ func (c *Config) Validate() error {
return errors.Join(errs...) return errors.Join(errs...)
} }
var (
// subscriptionName is the form of a subscription's name, which appears
// in job sources and in a file name.
subscriptionName = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
// ntfyTopic is the form of an ntfy topic name.
ntfyTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
// clock is a time of day, HH:MM.
clock = regexp.MustCompile(`^([01][0-9]|2[0-3]):[0-5][0-9]$`)
)
// validateSubscriptions reports every problem with the ntfy subscriptions.
// 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)
check := func(ok bool, format string, args ...any) {
if !ok {
errs = append(errs, fmt.Errorf(at+"."+format, args...))
}
}
switch other, dup := names[s.Name]; {
case s.Name == "":
check(false, "name is required")
case !subscriptionName.MatchString(s.Name):
check(false, "name: %q must be 1-32 lowercase letters, digits, - and _, starting with a letter or digit", s.Name)
case dup:
check(false, "name: %q is also the name of ntfy.subscriptions[%d]", s.Name, other)
default:
names[s.Name] = i
}
u, err := url.Parse(s.Server)
switch {
case s.Server == "":
check(false, "server is required, e.g. \"https://ntfy.sh\"")
case err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http"):
check(false, "server is not an http or https URL")
case u.User != nil:
check(false, "server holds credentials; set token, token_file, or user and password_file instead")
case u.RawQuery != "" || u.Fragment != "":
check(false, "server must have no query or fragment")
case u.Scheme == "http" && !s.AllowInsecure:
check(false, "server is not https; set allow_insecure = true to allow plain http")
}
// A topic is named by its index, never quoted: on a public server
// its name can be all that keeps others from publishing to it.
check(len(s.Topics) >= 1 && len(s.Topics) <= MaxNtfyTopics, "topics: name 1-%d topics", MaxNtfyTopics)
seen := make(map[string]int, len(s.Topics))
for j, topic := range s.Topics {
check(ntfyTopic.MatchString(topic), "topics[%d] must be 1-64 letters, digits, - and _", j)
if first, dup := seen[topic]; dup {
check(false, "topics[%d] repeats topics[%d]", j, first)
continue
}
seen[topic] = j
}
methods := 0
for _, set := range []bool{s.Token != "", s.TokenFile != "", s.User != "" || s.PasswordFile != ""} {
if set {
methods++
}
}
check(methods <= 1, "set at most one of token, token_file, or user with password_file")
check((s.User == "") == (s.PasswordFile == ""), "user and password_file go together")
check(s.MinPriority >= 1 && s.MinPriority <= 5, "min_priority must be 1-5")
check(s.BypassPriority >= 1 && s.BypassPriority <= 5, "bypass_priority must be 1-5")
check(s.MaxBacklog > 0 && s.MaxBacklog <= MaxNtfyBacklog, "max_backlog must be more than 0 and at most %s", MaxNtfyBacklog)
check(s.RateLimit >= 1 && s.RateLimit <= MaxNtfyRateLimit, "rate_limit must be 1-%d", MaxNtfyRateLimit)
check(s.RateWindow > 0, "rate_window must be positive")
check(s.Keepalive >= MinNtfyKeepalive && s.Keepalive <= MaxNtfyKeepalive,
"keepalive must be %s-%s", MinNtfyKeepalive, MaxNtfyKeepalive)
if q := s.Quiet; q != nil {
check(clock.MatchString(q.Start), "quiet.start: %q is not a time of day HH:MM", q.Start)
check(clock.MatchString(q.End), "quiet.end: %q is not a time of day HH:MM", q.End)
check(q.Start != q.End, "quiet: start and end are both %q; the window would be empty", q.Start)
check(len(q.Days) > 0, "quiet.days: name at least one day")
days := make(map[string]bool, len(q.Days))
for _, day := range q.Days {
check(slices.Contains(NtfyDays, day), "quiet.days: %q must be one of %s", day, strings.Join(NtfyDays, ", "))
check(!days[day], "quiet.days: %q is given twice", day)
days[day] = true
}
if q.Timezone != "" {
_, err := time.LoadLocation(q.Timezone)
check(err == nil, `quiet.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, q.Timezone)
}
check(q.MinPriority >= 1 && q.MinPriority <= 5, "quiet.min_priority must be 1-5")
check(slices.Contains(NtfyQuietActions, q.Action), "quiet.action: %q must be one of %s", q.Action, strings.Join(NtfyQuietActions, ", "))
}
}
return errs
}
// showsTime reports whether layout prints something of the time it // showsTime reports whether layout prints something of the time it
// formats: two times that differ in every field format differently. A // formats: two times that differ in every field format differently. A
// layout with none of Go's reference values, such as "HH:MM", prints // layout with none of Go's reference values, such as "HH:MM", prints
+19 -5
View File
@@ -53,8 +53,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
if cfg.Images.AllowPrivateNetworks { if cfg.Images.AllowPrivateNetworks {
t.Error("private networks must be blocked by default") t.Error("private networks must be blocked by default")
} }
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 { if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 || cfg.Printer.CutFeed != 3 {
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing) t.Errorf("defaults not applied: max_lines %d, box_line_spacing %d, cut_feed %d",
cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing, cfg.Printer.CutFeed)
} }
if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" { if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" {
t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout) t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout)
@@ -165,6 +166,16 @@ func TestLoadErrors(t *testing.T) {
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n", body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n",
wantErr: "printer.box_line_spacing must be 0-255", wantErr: "printer.box_line_spacing must be 0-255",
}, },
{
name: "negative cut feed",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ncut_feed = -1\n",
wantErr: "printer.cut_feed must be 0-255",
},
{
name: "cut feed too large",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ncut_feed = 256\n",
wantErr: "printer.cut_feed must be 0-255",
},
{ {
name: "unknown time zone", name: "unknown time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"Europe/Londn\"\n", body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"Europe/Londn\"\n",
@@ -386,15 +397,17 @@ func TestExampleConfigLoads(t *testing.T) {
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit || if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model || cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing || cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Printer.CutFeed != def.Printer.CutFeed ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout || 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.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 ||
cfg.Ntfy.StateDir != def.Ntfy.StateDir || len(cfg.Ntfy.Subscriptions) != 0 {
t.Error("example config values drifted from the defaults it documents") t.Error("example config values drifted from the defaults it documents")
} }
} }
func TestLoadNtfy(t *testing.T) { func TestLoadNtfy(t *testing.T) {
def := config.Default().Ntfy.Format def := config.Default().Ntfy.Format
if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true}) { if def != (config.NtfyFormatConfig{Style: "auto", MaxLines: 40, QR: "all", Images: true, Markdown: true, Updates: "print"}) {
t.Errorf("defaults %+v", def) t.Errorf("defaults %+v", def)
} }
@@ -409,6 +422,7 @@ max_lines = 400
qr = "first" qr = "first"
images = false images = false
markdown = false markdown = false
updates = "skip"
[ntfy.markers] [ntfy.markers]
backup = "[B]" backup = "[B]"
skull = "" skull = ""
@@ -417,7 +431,7 @@ skull = ""
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false} want := config.NtfyFormatConfig{Style: "compact", MaxLines: 400, QR: "first", Images: false, Markdown: false, Updates: "skip"}
if cfg.Ntfy.Format != want { if cfg.Ntfy.Format != want {
t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want) t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want)
} }
+265
View File
@@ -0,0 +1,265 @@
package config_test
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"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"
func TestLoadSubscriptions(t *testing.T) {
cfg, err := config.Load(writeConfig(t, base+`
[[ntfy.subscriptions]]
name = "home"
server = "https://ntfy.example.com/"
topics = ["alerts", "backups"]
token_file = "/etc/uberbringer/ntfy.token"
min_priority = 3
max_backlog = "12h"
rate_limit = 3
rate_window = "5m"
bypass_priority = 4
keepalive = "1m"
[ntfy.subscriptions.quiet]
start = "23:30"
end = "06:15"
days = ["sat", "sun"]
timezone = "Europe/London"
min_priority = 4
action = "drop"
[[ntfy.subscriptions]]
name = "work"
server = "http://ntfy.lan:8080"
allow_insecure = true
topics = ["ci"]
user = "printer"
password_file = "ntfy.password"
[ntfy.subscriptions.quiet]
start = "20:00"
[[ntfy.subscriptions]]
name = "open"
server = "https://ntfy.sh"
topics = ["long-random-topic-name"]
`))
if err != nil {
t.Fatal(err)
}
subs := cfg.Ntfy.Subscriptions
if len(subs) != 3 {
t.Fatalf("%d subscriptions, want 3", len(subs))
}
want := config.NtfySubscription{
Name: "home", Server: "https://ntfy.example.com/", Topics: []string{"alerts", "backups"},
TokenFile: "/etc/uberbringer/ntfy.token", MinPriority: 3, MaxBacklog: 12 * time.Hour,
RateLimit: 3, RateWindow: 5 * time.Minute, BypassPriority: 4, Keepalive: time.Minute,
Quiet: &config.NtfyQuiet{Start: "23:30", End: "06:15", Days: []string{"sat", "sun"},
Timezone: "Europe/London", MinPriority: 4, Action: "drop"},
}
if !reflect.DeepEqual(subs[0], want) {
t.Errorf("home = %+v %+v\nwant %+v %+v", subs[0], subs[0].Quiet, want, want.Quiet)
}
// Keys an entry leaves out keep their defaults, in the entry and in
// its quiet table.
work := config.DefaultSubscription()
work.Name, work.Server, work.AllowInsecure, work.Topics = "work", "http://ntfy.lan:8080", true, []string{"ci"}
work.User, work.PasswordFile = "printer", "ntfy.password"
quiet := config.DefaultQuiet()
quiet.Start = "20:00"
work.Quiet = &quiet
if !reflect.DeepEqual(subs[1], work) {
t.Errorf("work = %+v %+v\nwant %+v %+v", subs[1], subs[1].Quiet, work, work.Quiet)
}
open := config.DefaultSubscription()
open.Name, open.Server, open.Topics = "open", "https://ntfy.sh", []string{"long-random-topic-name"}
if !reflect.DeepEqual(subs[2], open) {
t.Errorf("open = %+v, want %+v without quiet hours and credentials", subs[2], open)
}
}
func TestSubscriptionDefaults(t *testing.T) {
def := config.DefaultSubscription()
if def.MinPriority != 1 || def.MaxBacklog != time.Hour || def.RateLimit != 5 || def.RateWindow != 10*time.Minute ||
def.BypassPriority != 5 || def.Keepalive != 45*time.Second || def.Quiet != nil {
t.Errorf("subscription defaults %+v", def)
}
q := config.DefaultQuiet()
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)
}
}
// The subscription in the example config, commented out there, loads and
// shows the defaults.
func TestExampleSubscriptionLoads(t *testing.T) {
example, err := os.ReadFile(filepath.Join("..", "..", "..", "configs", "config.example.toml"))
if err != nil {
t.Fatal(err)
}
var block []string
in := false
for line := range strings.SplitSeq(strings.ReplaceAll(string(example), "\r\n", "\n"), "\n") {
if strings.HasPrefix(line, "# [[ntfy.subscriptions]]") {
in = true
}
if !in {
continue
}
if !strings.HasPrefix(line, "#") {
break
}
block = append(block, strings.TrimPrefix(strings.TrimPrefix(line, "#"), " "))
}
if len(block) == 0 {
t.Fatal("the example config has no commented [[ntfy.subscriptions]] block")
}
cfg, err := config.Load(writeConfig(t, base+strings.Join(block, "\n")))
if err != nil {
t.Fatalf("example subscription: %v", err)
}
if len(cfg.Ntfy.Subscriptions) != 1 {
t.Fatalf("%d subscriptions", len(cfg.Ntfy.Subscriptions))
}
got := cfg.Ntfy.Subscriptions[0]
def := config.DefaultSubscription()
if got.MinPriority != def.MinPriority || got.MaxBacklog != def.MaxBacklog || got.RateLimit != def.RateLimit ||
got.RateWindow != def.RateWindow || got.BypassPriority != def.BypassPriority || got.Keepalive != def.Keepalive {
t.Errorf("example subscription %+v drifted from the defaults it documents", got)
}
if got.Quiet == nil || !reflect.DeepEqual(*got.Quiet, config.DefaultQuiet()) {
t.Errorf("example quiet hours %+v drifted from the defaults", got.Quiet)
}
}
func TestLoadSubscriptionErrors(t *testing.T) {
const sub = "[[ntfy.subscriptions]]\nname = \"home\"\nserver = \"https://ntfy.sh\"\ntopics = [\"alerts\"]\n"
const quiet = sub + "[ntfy.subscriptions.quiet]\n"
tests := []struct {
name, body, wantErr string
}{
{"no state dir", strings.Replace(base, "state_dir = \"state\"", "", 1) + sub, "ntfy.state_dir is required"},
{"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"},
{"subscriptions as a value", "subscriptions = \"home\"\n", "unknown keys: ntfy.subscriptions"},
{"subscription as a value", "subscriptions = [\"home\"]\n", "unknown keys: ntfy.subscriptions[0]"},
{"missing name", "[[ntfy.subscriptions]]\nserver = \"https://ntfy.sh\"\ntopics = [\"a\"]\n", "ntfy.subscriptions[0].name is required"},
{"bad name", strings.Replace(sub, `"home"`, `"Home Office"`, 1), `name: "Home Office" must be 1-32 lowercase letters`},
{"duplicate name", sub + sub, `ntfy.subscriptions[1].name: "home" is also the name of ntfy.subscriptions[0]`},
{"missing server", "[[ntfy.subscriptions]]\nname = \"a\"\ntopics = [\"a\"]\n", "ntfy.subscriptions[0].server is required"},
{"server not a URL", strings.Replace(sub, "https://ntfy.sh", "ntfy.sh", 1), "server is not an http or https URL"},
{"server with another scheme", strings.Replace(sub, "https://ntfy.sh", "ftp://ntfy.sh", 1), "server is not an http or https URL"},
{"plain http", strings.Replace(sub, "https://", "http://", 1), "server is not https; set allow_insecure"},
{"credentials in the URL", strings.Replace(sub, "https://", "https://me:hunter2@", 1), "server holds credentials"},
{"query in the URL", strings.Replace(sub, "ntfy.sh", "ntfy.sh/?x=1", 1), "server must have no query or fragment"},
{"no topics", strings.Replace(sub, `["alerts"]`, `[]`, 1), "topics: name 1-150 topics"},
{"bad topic", strings.Replace(sub, `"alerts"`, `"ok", "alerts/x"`, 1), `ntfy.subscriptions[0].topics[1] must be 1-64 letters`},
{"long topic", strings.Replace(sub, `"alerts"`, `"`+strings.Repeat("a", 65)+`"`, 1), "topics[0] must be 1-64 letters"},
{"duplicate topic", strings.Replace(sub, `"alerts"`, `"alerts", "x", "alerts"`, 1), `topics[2] repeats topics[0]`},
{"two auth methods", sub + "token = \"tk_x\"\ntoken_file = \"t\"\n", "set at most one of token, token_file, or user with password_file"},
{"token and user", sub + "token = \"tk_x\"\nuser = \"u\"\npassword_file = \"p\"\n", "set at most one of"},
{"user without password", sub + "user = \"u\"\n", "user and password_file go together"},
{"password without user", sub + "password_file = \"p\"\n", "user and password_file go together"},
{"min priority", sub + "min_priority = 0\n", "min_priority must be 1-5"},
{"bypass priority", sub + "bypass_priority = 6\n", "bypass_priority must be 1-5"},
{"backlog too long", sub + "max_backlog = \"13h\"\n", "max_backlog must be more than 0 and at most 12h0m0s"},
{"zero backlog", sub + "max_backlog = \"0s\"\n", "max_backlog must be more than 0"},
{"zero rate limit", sub + "rate_limit = 0\n", "rate_limit must be 1-1000"},
{"zero rate window", sub + "rate_window = \"0s\"\n", "rate_window must be positive"},
{"short keepalive", sub + "keepalive = \"1s\"\n", "keepalive must be 5s-1h0m0s"},
{"bad duration", sub + "keepalive = 45\n", "keepalive"},
{"quiet start", quiet + "start = \"10pm\"\n", `quiet.start: "10pm" is not a time of day HH:MM`},
{"quiet end", quiet + "end = \"24:00\"\n", `quiet.end: "24:00" is not a time of day HH:MM`},
{"quiet empty", quiet + "start = \"07:00\"\n", `quiet: start and end are both "07:00"`},
{"quiet no days", quiet + "days = []\n", "quiet.days: name at least one day"},
{"quiet bad day", quiet + "days = [\"monday\"]\n", `quiet.days: "monday" must be one of mon, tue`},
{"quiet duplicate day", quiet + "days = [\"sat\", \"sat\"]\n", `quiet.days: "sat" is given twice`},
{"quiet time zone", quiet + "timezone = \"Europe/Londn\"\n", `quiet.timezone: "Europe/Londn" is not a known time zone`},
{"quiet min priority", quiet + "min_priority = 6\n", "quiet.min_priority must be 1-5"},
{"quiet action", quiet + "action = \"hold\"\n", `quiet.action: "hold" must be one of digest, drop`},
{"updates", "[ntfy.format]\nupdates = \"mark\"\n", `ntfy.format.updates: "mark" must be one of print, skip`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := tt.body
if !strings.Contains(body, "[api]") {
body = base + body
}
_, err := config.Load(writeConfig(t, body))
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
// A server URL is never quoted in an error, since it can hold a password,
// and neither is a topic, whose name can be all that guards it.
func TestLoadSubscriptionErrorHidesSecrets(t *testing.T) {
_, err := config.Load(writeConfig(t, base+"[[ntfy.subscriptions]]\nname = \"a\"\nserver = \"https://me:hunter2@ntfy.sh\"\ntopics = [\"a\"]\n"))
if err == nil || strings.Contains(err.Error(), "hunter2") {
t.Errorf("error = %v, want a failure that does not quote the URL", err)
}
_, err = config.Load(writeConfig(t, base+"[[ntfy.subscriptions]]\nname = \"a\"\nserver = \"https://ntfy.sh\"\n"+
"topics = [\"zq7_topic_9f3a\", \"zq7_topic_9f3a\", \"zq7/topic\"]\n"))
if err == nil || strings.Contains(err.Error(), "zq7") {
t.Errorf("error = %v, want a failure that does not quote a topic", err)
}
}
// Subscriptions come from the file only; a variable named after them sets
// nothing, and the error names it as likely misspelt.
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_NTFY_SUBSCRIPTIONS", "home")
t.Setenv("UBERBRINGER_NTFY_SUBSCRIPTIONS_NAME", "home")
t.Setenv("UBERBRINGER_LOG_LEVEL", "loud")
_, err := config.Load("")
if err == nil {
t.Fatal("Load accepted log.level loud")
}
if !strings.Contains(err.Error(), "variables that set nothing: UBERBRINGER_NTFY_SUBSCRIPTIONS, UBERBRINGER_NTFY_SUBSCRIPTIONS_NAME") {
t.Errorf("error = %q, want it to name both subscription variables", err)
}
t.Setenv("UBERBRINGER_LOG_LEVEL", "")
cfg, err := config.Load("")
if err != nil {
t.Fatal(err)
}
if cfg.Ntfy.StateDir != "/var/lib/uberbringer" || len(cfg.Ntfy.Subscriptions) != 0 {
t.Errorf("ntfy = %+v", cfg.Ntfy)
}
}
func TestValueOfSubscriptions(t *testing.T) {
cfg := config.Default()
cfg.Ntfy.StateDir = "/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("ntfy.format.updates"); err != nil || got != "print" {
t.Errorf("updates = %q, %v", got, err)
}
got, err := cfg.Value("ntfy.subscriptions")
if err == nil || !strings.Contains(err.Error(), "is a list of tables") || strings.Contains(got, "tk_secret") {
t.Errorf("Value = %q, %v; want a refusal that shows no token", got, err)
}
}
+3
View File
@@ -25,6 +25,9 @@ func (c *Config) Value(key string) (string, error) {
if v.Kind() == reflect.Struct { if v.Kind() == reflect.Struct {
return "", fmt.Errorf("%q is a section; name one of its settings", key) return "", fmt.Errorf("%q is a section; name one of its settings", key)
} }
if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Struct {
return "", fmt.Errorf("%q is a list of tables, which has no single value", key)
}
switch value := v.Interface().(type) { switch value := v.Interface().(type) {
case time.Duration: case time.Duration:
return value.String(), nil return value.String(), nil
+3 -3
View File
@@ -20,10 +20,10 @@ import (
// TestNtfyBuildsThePaperJobs checks that the ntfy module still builds the // TestNtfyBuildsThePaperJobs checks that the ntfy module still builds the
// jobs whose printed result was checked on the TM-T88IV, and whose bytes // jobs whose printed result was checked on the TM-T88IV, and whose bytes
// the receipt package pins: the four messages in testdata/paper, built on // the receipt package pins: the messages in testdata/paper, built on a
// a host at UTC-6 with the default card options. // host at UTC-6 with the default card options.
func TestNtfyBuildsThePaperJobs(t *testing.T) { func TestNtfyBuildsThePaperJobs(t *testing.T) {
for _, name := range []string{"high", "urgent", "default", "min"} { for _, name := range []string{"high", "urgent", "default", "min", "cutfeed"} {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(filepath.Join("testdata", "paper", "ntfy-"+name+".json")) body, err := os.ReadFile(filepath.Join("testdata", "paper", "ntfy-"+name+".json"))
if err != nil { if err != nil {
+164
View File
@@ -0,0 +1,164 @@
package modules
import (
"errors"
"fmt"
"regexp"
"runtime/debug"
"strings"
"time"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// Digest layout.
const (
// maxDigestTitle is the most characters of a title a digest row
// prints.
maxDigestTitle = 60
// digestClock is the layout of the times on a digest.
digestClock = "15:04"
)
// DigestCard lays out messages an ntfy subscription held back as one
// receipt: a box titled "ntfy digest · N held", or "Overnight · N held"
// when quiet hours held any of them, with a row per message, its time, tag
// markers and title, in the order they arrived, and the time from the
// first held message to the digest in the bottom border. A row prints the
// first line of a message that has no title, or else its topic. The
// messages a digest does not list are counted on a last row.
//
// Like Card, it always returns a job that prints: if the layout goes
// wrong, the job is a plain list of the rows, with a *FallbackError.
func DigestCard(d ntfy.Digest, o CardOptions, env Env) (job receipt.Job, err error) {
defer func() {
if r := recover(); r != nil {
job = digestFallback(d, env)
err = &FallbackError{Cause: fmt.Sprintf("panic: %v", r), Stack: string(debug.Stack())}
}
}()
job = digestCard(d, o, env)
if verr := job.Validate(); verr != nil {
problems := 1
var ve *receipt.ValidationError
if errors.As(verr, &ve) {
problems = len(ve.Problems)
}
return digestFallback(d, env), &FallbackError{Cause: fmt.Sprintf("the digest failed validation with %d problems", problems)}
}
return job, nil
}
// digestCard is DigestCard without the fallback.
func digestCard(d ntfy.Digest, o CardOptions, env Env) receipt.Job {
cardFault()
markers := o.Markers
if markers == nil {
markers = NewMarkers(nil)
}
rows := make([]receipt.Element, 0, len(d.Rows)+1)
for _, row := range d.Rows {
titleMarkers, _ := markers.sortTags(row.Tags)
text := strings.Join(append(titleMarkers, digestTitle(row, o, markers.clean)), " ")
if row.Updated {
text += " (updated)"
}
rows = append(rows, receipt.Element{Type: receipt.TypeText, Text: digestTime(env, row.Time) + " " + text})
}
if more := d.Count - len(d.Rows); more > 0 {
rows = append(rows, receipt.Element{Type: receipt.TypeText, Text: fmt.Sprintf("... and %d more", more)})
}
if len(rows) == 0 {
rows = append(rows, receipt.Element{Type: receipt.TypeText})
}
return receipt.Job{Elements: []receipt.Element{{
Type: receipt.TypeBox,
Title: digestHeading(d),
TitleBold: true,
Footer: digestSpan(d, env),
Children: rows,
}}}
}
// digestHeading is the digest's title.
func digestHeading(d ntfy.Digest) string {
if d.Overnight {
return fmt.Sprintf("Overnight · %d held", d.Count)
}
return fmt.Sprintf("ntfy digest · %d held", d.Count)
}
// digestSpan is the time from the first held message to the digest, as
// 21:04-21:14.
func digestSpan(d ntfy.Digest, env Env) string {
until := clock(env, d.Until)
if d.Since.IsZero() {
return until
}
return clock(env, d.Since) + "-" + until
}
// digestTime is a row's time, from the message's time in Unix seconds.
func digestTime(env Env, unix int64) string {
if unix <= 0 {
return clock(env, time.Time{})
}
return clock(env, time.Unix(unix, 0))
}
// clock is t, or Now for the zero time, as HH:MM in env's zone.
func clock(env Env, t time.Time) string {
return Env{Now: env.Now, Location: env.Location, TimeLayout: digestClock}.Format(t)
}
// digestTitle is what a row says of its message: the title, the first
// line of a message without one, laid out as markdown when it is written
// in it, or the topic, cleaned and cut to maxDigestTitle.
func digestTitle(row ntfy.DigestRow, o CardOptions, clean func(string) string) string {
first := row.FirstLine
if row.Markdown && !o.NoMarkdown {
first = markdownLine(first)
}
for _, s := range []string{row.Title, first, row.Topic} {
if s = strings.TrimSpace(clean(s)); s != "" {
return cut(s, maxDigestTitle)
}
}
return "Notification"
}
// markdownLine is one line of markdown as plain text: without a heading's
// #, an item's bullet or number, a quote's >, or the inline marks.
func markdownLine(s string) string {
for _, re := range []*regexp.Regexp{mdHeading, mdBullet, mdNumbered, mdQuote} {
if m := re.FindStringSubmatch(s); m != nil {
s = m[1]
break
}
}
text, _ := markdownInline(s)
return text
}
// digestFallback is the plain receipt DigestCard returns when the layout
// goes wrong: the title in bold, a line per row and the span.
func digestFallback(d ntfy.Digest, env Env) receipt.Job {
elements := []receipt.Element{{Type: receipt.TypeText, Text: digestHeading(d), Bold: true}}
for _, row := range d.Rows {
title := row.Title
if strings.TrimSpace(title) == "" {
title = row.FirstLine
}
if title = strings.TrimSpace(receipt.StripEmoji(title)); title == "" {
title = "Notification"
}
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: digestTime(env, row.Time) + " " + cut(title, maxDigestTitle)})
}
if more := d.Count - len(d.Rows); more > 0 {
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: fmt.Sprintf("... and %d more", more)})
}
elements = append(elements, receipt.Element{Type: receipt.TypeText, Text: digestSpan(d, env)})
return receipt.Job{Elements: elements}
}
+159
View File
@@ -0,0 +1,159 @@
package modules_test
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/ntfy"
"uberbringer/internal/pkg/receipt"
)
// rateDigest is six messages held between 21:05 and 21:09, printed at
// 21:14 London time, as a rate-limit digest.
func rateDigest() ntfy.Digest {
at := func(hh, mm int) int64 { return time.Date(2026, 11, 29, hh, mm, 0, 0, time.UTC).Unix() }
return ntfy.Digest{
Rows: []ntfy.DigestRow{
{ID: "a", Time: at(21, 5), Title: "Disk almost full", Tags: []string{"warning"}},
{ID: "b", Time: at(21, 5), Title: "Disk almost full", Tags: []string{"warning"}, Updated: true},
{ID: "c", Time: at(21, 6), Title: "Backup FAILED on nas01", Tags: []string{"rotating_light", "nas01"}},
{ID: "d", Time: at(21, 7), Topic: "watchtower", FirstLine: "Watchtower"},
{ID: "e", Time: at(21, 7), Topic: "jellyseerr", FirstLine: "**Jellyseerr** 🎉", Markdown: true},
{ID: "f", Time: at(21, 9), Title: "grafana is DOWN", Tags: []string{"x"}},
},
Count: 6,
Since: time.Date(2026, 11, 29, 21, 4, 30, 0, time.UTC),
Until: time.Date(2026, 11, 29, 21, 14, 0, 0, time.UTC),
}
}
func TestDigestCardGoldens(t *testing.T) {
overnight := rateDigest()
overnight.Overnight = true
overnight.Count = 63
overnight.Since = time.Date(2026, 11, 29, 22, 13, 0, 0, time.UTC)
overnight.Until = time.Date(2026, 11, 30, 7, 0, 0, 0, time.UTC)
for name, d := range map[string]ntfy.Digest{"rate": rateDigest(), "overnight": overnight} {
t.Run(name, func(t *testing.T) {
job, err := modules.DigestCard(d, modules.CardOptions{}, fixedEnv(t))
if err != nil {
t.Fatalf("DigestCard: %v", err)
}
checkGolden(t, filepath.Join("testdata", "digest", name+".txt"), previewText(t, job))
})
}
}
// DigestCard still builds the digest whose printed result was checked on
// the TM-T88IV, and whose bytes the receipt package pins: one message held
// in quiet hours at 14:57, printed at 15:02 on a host at UTC-6.
func TestDigestBuildsThePaperJob(t *testing.T) {
env := modules.Env{Now: time.Unix(1796072520, 0), Location: time.FixedZone("UTC-6", -6*60*60), TimeLayout: "02 Jan 15:04"}
d := ntfy.Digest{
Overnight: true,
Rows: []ntfy.DigestRow{{ID: "00zMV5uPNnvg", Time: 1796072241, Topic: "ntfy-paper-topic", Title: "Quiet three", Priority: 3}},
Count: 1,
Since: time.Unix(1796072241, 0),
Until: time.Unix(1796072520, 0),
}
job, err := modules.DigestCard(d, modules.CardOptions{}, env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "ntfy-digest.json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, _ := json.Marshal(job)
want, _ := json.Marshal(paper)
if string(got) != string(want) {
t.Errorf("DigestCard builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
}
// A row prints the title, or the first line of a message without one,
// laid out as markdown when it is, or the topic, cut to 60 characters.
func TestDigestRowTitles(t *testing.T) {
long := strings.Repeat("x", 70)
tests := []struct {
row ntfy.DigestRow
o modules.CardOptions
want string
}{
{ntfy.DigestRow{Title: "Title", FirstLine: "line", Topic: "topic"}, modules.CardOptions{}, "Title"},
{ntfy.DigestRow{FirstLine: "## **Backup** done", Markdown: true}, modules.CardOptions{}, "Backup done"},
{ntfy.DigestRow{FirstLine: "- item"}, modules.CardOptions{}, "- item"},
{ntfy.DigestRow{FirstLine: "**raw**", Markdown: true}, modules.CardOptions{NoMarkdown: true}, "**raw**"},
{ntfy.DigestRow{Title: "🎉", Topic: "alerts"}, modules.CardOptions{}, "alerts"},
{ntfy.DigestRow{}, modules.CardOptions{}, "Notification"},
{ntfy.DigestRow{Title: long}, modules.CardOptions{}, long[:57] + "..."},
}
for _, tt := range tests {
d := ntfy.Digest{Rows: []ntfy.DigestRow{tt.row}, Count: 1, Until: fixedEnv(t).Now}
job, err := modules.DigestCard(d, tt.o, fixedEnv(t))
if err != nil {
t.Fatal(err)
}
if got := job.Elements[0].Children[0].Text; got != "21:04 "+tt.want {
t.Errorf("row %+v prints %q, want %q", tt.row, got, "21:04 "+tt.want)
}
}
}
// A digest of the most rows, with the longest titles, is valid and fits
// 58 mm paper too.
func TestDigestCardLimits(t *testing.T) {
d := ntfy.Digest{Count: 500, Until: fixedEnv(t).Now}
for i := range ntfy.MaxDigestRows {
d.Rows = append(d.Rows, ntfy.DigestRow{ID: fmt.Sprint(i), Title: strings.Repeat("W", 256),
Tags: []string{"warning", "x", "skull"}, Updated: true})
}
job, err := modules.DigestCard(d, modules.CardOptions{}, fixedEnv(t))
if err != nil {
t.Fatalf("DigestCard: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatal(err)
}
if n := len(job.Elements[0].Children); n != ntfy.MaxDigestRows+1 {
t.Errorf("%d rows, want %d and the count of the rest", n, ntfy.MaxDigestRows+1)
}
if got := job.Elements[0].Children[ntfy.MaxDigestRows].Text; got != "... and 450 more" {
t.Errorf("last row %q", got)
}
}
// A digest that fails to lay out still prints, as a plain list.
func TestDigestCardFallback(t *testing.T) {
restore := modules.SetCardFault(func() { panic("layout bug") })
defer restore()
job, err := modules.DigestCard(rateDigest(), modules.CardOptions{}, fixedEnv(t))
var fallbackErr *modules.FallbackError
if !errors.As(err, &fallbackErr) || !strings.Contains(fallbackErr.Cause, "layout bug") {
t.Errorf("err = %v, want a *FallbackError", err)
}
if strings.Contains(fmt.Sprint(err), "Disk") {
t.Error("the error quotes a message")
}
if err := job.Validate(); err != nil {
t.Fatalf("fallback is invalid: %v", err)
}
want := "ntfy digest · 6 held\n21:05 Disk almost full\n21:05 Disk almost full\n21:06 Backup FAILED on nas01\n" +
"21:07 Watchtower\n21:07 **Jellyseerr**\n21:09 grafana is DOWN\n21:04-21:14\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("fallback:\n%s\nwant:\n%s", got, want)
}
}
+1 -6
View File
@@ -83,12 +83,7 @@ func decodeNtfy(body []byte) (ntfy.Message, error) {
// update: a publisher may choose a message's sequence ID, so one message // update: a publisher may choose a message's sequence ID, so one message
// cannot tell the first of its sequence from one that replaces it. // cannot tell the first of its sequence from one that replaces it.
func FromNtfy(m ntfy.Message) (Notice, error) { func FromNtfy(m ntfy.Message) (Notice, error) {
switch m.Event { if !m.Printable() {
case "", ntfy.EventMessage:
default:
return Notice{}, ErrSkip
}
if strings.EqualFold(m.Encoding, ntfy.EncodingBase64) {
return Notice{}, ErrSkip return Notice{}, ErrSkip
} }
n := Notice{ n := Notice{
+10
View File
@@ -0,0 +1,10 @@
┌─ Overnight · 63 held ──────────────────┐
│ 21:05 [!] Disk almost full │
│ 21:05 [!] Disk almost full (updated) │
│ 21:06 (!) Backup FAILED on nas01 │
│ 21:07 Watchtower │
│ 21:07 Jellyseerr │
│ 21:09 [x] grafana is DOWN │
│ ... and 57 more │
└───────────────────────── 22:13-07:00 ──┘
- - - - - - - partial cut - - - - - - - -
+9
View File
@@ -0,0 +1,9 @@
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
│ 21:05 [!] Disk almost full (updated) │
│ 21:06 (!) Backup FAILED on nas01 │
│ 21:07 Watchtower │
│ 21:07 Jellyseerr │
│ 21:09 [x] grafana is DOWN │
└───────────────────────── 21:04-21:14 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"id":"74z10EC6PQZb","time":1796072566,"event":"message","topic":"ntfy-paper-topic","title":"Cut feed test","message":"Three blank lines before the cut.","priority":3}
+471
View File
@@ -0,0 +1,471 @@
package ntfy
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
)
// fakeServer is an ntfy server in memory, for tests in a synctest bubble.
// It answers the stream and the credentials check through RoundTrip: an
// open event, then the stored messages since the request's since, then
// each message as it is published, with keepalives in between. Like ntfy,
// since takes messages dated at or after it.
type fakeServer struct {
keepalive time.Duration
// skew is how far the server's clock is ahead of the host's.
skew time.Duration
// authFails makes the credentials check fail as an unreachable server
// does, and authSkew puts its answer's Date this far off the server's
// clock.
authFails bool
authSkew time.Duration
// noDate leaves the Date header out of the stream's answer, and
// dateSkew puts it this far off the server's clock, as a proxy in front
// of it with a clock of its own does.
noDate bool
dateSkew time.Duration
// openNoTime leaves the open event without a time.
openNoTime bool
mu sync.Mutex
messages []Message
conns map[*fakeConn]bool
requests []*http.Request
streamAt []time.Time
answers []fakeAnswer
authStatus int
nextID int
}
// fakeAnswer is an answer other than the stream, for a request to it.
type fakeAnswer struct {
status int
retryAfter string
}
func newFakeServer() *fakeServer {
return &fakeServer{keepalive: 45 * time.Second, conns: make(map[*fakeConn]bool)}
}
func (f *fakeServer) RoundTrip(req *http.Request) (*http.Response, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.requests = append(f.requests, req)
if strings.HasSuffix(req.URL.Path, "/auth") {
if f.authFails {
return nil, errors.New("connection refused")
}
status := f.authStatus
if status == 0 {
status = http.StatusOK
}
resp := answer(req, status, "")
resp.Header.Set("Date", time.Now().Add(f.skew+f.authSkew).UTC().Format(http.TimeFormat))
return resp, nil
}
f.streamAt = append(f.streamAt, time.Now())
if len(f.answers) > 0 {
a := f.answers[0]
f.answers = f.answers[1:]
return answer(req, a.status, a.retryAfter), nil
}
if err := req.Context().Err(); err != nil {
return nil, err
}
path := strings.TrimSuffix(strings.TrimPrefix(req.URL.Path, "/"), "/json")
c := &fakeConn{
f: f,
ctx: req.Context(),
topics: strings.Split(path, ","),
wake: make(chan struct{}, 1),
closed: make(chan struct{}),
next: len(f.messages),
keepalive: time.Now().Add(f.keepalive),
}
if p := req.URL.Query().Get("priority"); p != "" {
for _, s := range strings.Split(p, ",") {
n, _ := strconv.Atoi(s)
c.priorities = append(c.priorities, n)
}
}
open := Message{ID: f.id(), Time: time.Now().Add(f.skew).Unix(), Event: EventOpen, Topic: path}
if f.openNoTime {
open.Time = 0
}
c.queue = append(c.queue, open)
if s := req.URL.Query().Get("since"); s != "" {
since, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return answer(req, http.StatusBadRequest, ""), nil
}
for _, m := range f.messages {
if m.Time >= since && c.wants(m) {
c.queue = append(c.queue, m)
}
}
}
f.conns[c] = true
h := http.Header{}
if !f.noDate {
h.Set("Date", time.Now().Add(f.skew+f.dateSkew).UTC().Format(http.TimeFormat))
}
return &http.Response{StatusCode: http.StatusOK, Header: h, Body: c, Request: req}, nil
}
func answer(req *http.Request, status int, retryAfter string) *http.Response {
h := http.Header{}
if retryAfter != "" {
h.Set("Retry-After", retryAfter)
}
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(`{"success":true}`)), Request: req}
}
// id returns a new message ID. f.mu is held.
func (f *fakeServer) id() string {
f.nextID++
return fmt.Sprintf("m%05d", f.nextID)
}
// publish stores m, dated now, and sends it to the open connections. It
// returns m as stored.
func (f *fakeServer) publish(m Message) Message {
f.mu.Lock()
defer f.mu.Unlock()
if m.ID == "" {
m.ID = f.id()
}
if m.Time == 0 {
m.Time = time.Now().Add(f.skew).Unix()
}
if m.Event == "" {
m.Event = EventMessage
}
if m.Topic == "" {
m.Topic = "alerts"
}
f.messages = append(f.messages, m)
f.wakeAll()
return m
}
// drop ends every open connection, as a server restart does.
func (f *fakeServer) drop() {
f.mu.Lock()
defer f.mu.Unlock()
for c := range f.conns {
c.ended = true
}
f.wakeAll()
}
// stall makes every open connection go silent.
func (f *fakeServer) stall() {
f.mu.Lock()
defer f.mu.Unlock()
for c := range f.conns {
c.stalled = true
}
}
// answerNext answers the next requests to the stream with as.
func (f *fakeServer) answerNext(as ...fakeAnswer) {
f.mu.Lock()
defer f.mu.Unlock()
f.answers = append(f.answers, as...)
}
// setAuth sets the status the credentials check answers with.
func (f *fakeServer) setAuth(status int) {
f.mu.Lock()
defer f.mu.Unlock()
f.authStatus = status
}
// streams returns the requests to the stream, in order.
func (f *fakeServer) streams() []*http.Request {
f.mu.Lock()
defer f.mu.Unlock()
var out []*http.Request
for _, r := range f.requests {
if strings.HasSuffix(r.URL.Path, "/json") {
out = append(out, r)
}
}
return out
}
// streamTimes returns when each request to the stream came.
func (f *fakeServer) streamTimes() []time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return slices.Clone(f.streamAt)
}
// open returns how many connections are open.
func (f *fakeServer) open() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.conns)
}
// wakeAll wakes every connection. f.mu is held.
func (f *fakeServer) wakeAll() {
for c := range f.conns {
select {
case c.wake <- struct{}{}:
default:
}
}
}
// fakeConn is one stream, read by the subscriber.
type fakeConn struct {
f *fakeServer
ctx context.Context
topics []string
priorities []int
wake chan struct{}
closed chan struct{}
closeOnce sync.Once
// Guarded by f.mu.
queue []Message
next int
ended bool
stalled bool
keepalive time.Time
buf []byte
}
// wants reports whether the connection's topics and priorities take m.
func (c *fakeConn) wants(m Message) bool {
if !slices.Contains(c.topics, m.Topic) {
return false
}
return len(c.priorities) == 0 || slices.Contains(c.priorities, m.Priority())
}
// line returns the next line to send, if one is ready, and whether the
// stream has ended.
func (c *fakeConn) line() (line []byte, ended bool, wait time.Duration) {
c.f.mu.Lock()
defer c.f.mu.Unlock()
if c.ended {
return nil, true, 0
}
if c.stalled {
return nil, false, -1
}
for len(c.queue) == 0 && c.next < len(c.f.messages) {
m := c.f.messages[c.next]
c.next++
if c.wants(m) {
c.queue = append(c.queue, m)
}
}
if len(c.queue) > 0 {
m := c.queue[0]
c.queue = c.queue[1:]
data, _ := json.Marshal(m)
return append(data, '\n'), false, 0
}
now := time.Now()
if !now.Before(c.keepalive) {
c.keepalive = now.Add(c.f.keepalive)
data, _ := json.Marshal(Message{ID: c.f.id(), Time: now.Add(c.f.skew).Unix(), Event: EventKeepalive, Topic: strings.Join(c.topics, ",")})
return append(data, '\n'), false, 0
}
return nil, false, c.keepalive.Sub(now)
}
func (c *fakeConn) Read(p []byte) (int, error) {
for len(c.buf) == 0 {
line, ended, wait := c.line()
if ended {
return 0, io.EOF
}
if line != nil {
c.buf = line
break
}
var timer <-chan time.Time
if wait >= 0 {
timer = time.After(wait)
}
select {
case <-c.wake:
case <-timer:
case <-c.ctx.Done():
return 0, c.ctx.Err()
case <-c.closed:
return 0, errors.New("read on closed body")
}
}
n := copy(p, c.buf)
c.buf = c.buf[n:]
return n, nil
}
func (c *fakeConn) Close() error {
c.closeOnce.Do(func() {
close(c.closed)
c.f.mu.Lock()
delete(c.f.conns, c)
c.f.mu.Unlock()
})
return nil
}
// errBusy stands for a full print queue.
var errBusy = errors.New("print queue is full")
// recorder is a Handler that records what it is given. fail makes the
// next calls fail with errBusy.
type recorder struct {
mu sync.Mutex
cards []card
digests []Digest
fail int
}
// card is a message the recorder printed.
type card struct {
m Message
updated bool
at time.Time
}
func (h *recorder) Message(_ context.Context, m Message, updated bool) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.fail > 0 {
h.fail--
return errBusy
}
h.cards = append(h.cards, card{m: m, updated: updated, at: time.Now()})
return nil
}
func (h *recorder) Digest(_ context.Context, d Digest) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.fail > 0 {
h.fail--
return errBusy
}
d.Rows = slices.Clone(d.Rows)
h.digests = append(h.digests, d)
return nil
}
func (h *recorder) failNext(n int) {
h.mu.Lock()
defer h.mu.Unlock()
h.fail = n
}
// printed returns the IDs of the messages printed on cards, in order.
func (h *recorder) printed() []string {
h.mu.Lock()
defer h.mu.Unlock()
var ids []string
for _, c := range h.cards {
ids = append(ids, c.m.ID)
}
return ids
}
func (h *recorder) cardList() []card {
h.mu.Lock()
defer h.mu.Unlock()
return slices.Clone(h.cards)
}
func (h *recorder) digestList() []Digest {
h.mu.Lock()
defer h.mu.Unlock()
return slices.Clone(h.digests)
}
// testOptions returns the options of a subscription to topic alerts of f,
// keeping its state in dir.
func testOptions(f *fakeServer, dir string) Options {
return Options{
Name: "home",
Server: "https://ntfy.example.com",
Topics: []string{"alerts"},
Token: "tk_testtoken",
MinPriority: 1,
MaxBacklog: time.Hour,
RateLimit: 5,
RateWindow: 10 * time.Minute,
BypassPriority: 5,
Keepalive: 45 * time.Second,
StateFile: filepath.Join(dir, "ntfy-home.json"),
Transport: f,
}
}
// start runs a subscriber with options o and handler h in the background.
// The func it returns stops it and waits for Run to return.
func start(t *testing.T, o Options, h Handler) (*Subscriber, func()) {
t.Helper()
s, err := New(o)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
if err := s.Run(ctx, h); err != nil {
t.Errorf("Run = %v, want nil", err)
}
}()
return s, func() {
cancel()
<-done
}
}
// logBuffer collects log output safely across goroutines.
type logBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *logBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *logBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// debugLogger returns a logger that writes every level to b.
func debugLogger(b *logBuffer) *slog.Logger {
return slog.New(slog.NewTextHandler(b, &slog.HandlerOptions{Level: slog.LevelDebug}))
}
+91
View File
@@ -0,0 +1,91 @@
package ntfy
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"runtime"
"runtime/pprof"
"strings"
"sync/atomic"
"testing"
"time"
)
// Reconnecting over real sockets leaves no goroutine behind. The synctest
// tests cover the subscription's own goroutines on a fake transport; this
// one covers net/http's, which a response body left open would leak. The
// server ends streams at once or after a pause, answers 502 to every third
// request, and keeps the last stream open until the client leaves.
func TestNoGoroutineLeakOverRealConnections(t *testing.T) {
const cycles = 30
before := runtime.NumGoroutine()
var requests atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/auth") {
fmt.Fprint(w, `{"success":true}`)
return
}
n := requests.Add(1)
if n%3 == 0 && n < cycles {
http.Error(w, "bad gateway", http.StatusBadGateway)
return
}
now := time.Now().Unix()
fmt.Fprintf(w, "{\"id\":\"o%d\",\"time\":%d,\"event\":\"open\",\"topic\":\"alerts\"}\n", n, now)
fmt.Fprintf(w, "{\"id\":\"m%d\",\"time\":%d,\"event\":\"message\",\"topic\":\"alerts\",\"title\":\"t\"}\n", n, now)
w.(http.Flusher).Flush()
switch {
case n >= cycles:
<-r.Context().Done()
case n%2 == 0:
// The client is reading when the stream ends.
time.Sleep(5 * time.Millisecond)
}
}))
o := Options{
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, MinPriority: 1,
MaxBacklog: time.Hour, RateLimit: 1000, RateWindow: time.Minute, BypassPriority: 5,
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json",
}
s, err := New(o)
if err != nil {
t.Fatal(err)
}
s.backoff = []time.Duration{10 * time.Millisecond}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
h := &recorder{}
go func() {
defer close(done)
_ = s.Run(ctx, h)
}()
deadline := time.Now().Add(20 * time.Second)
for requests.Load() < cycles && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if requests.Load() < cycles {
t.Fatalf("only %d requests in 20 s", requests.Load())
}
time.Sleep(50 * time.Millisecond) // the last stream is open and read
cancel()
<-done
srv.Close()
if got := len(h.printed()); got < cycles/2 {
t.Errorf("printed %d messages, want the %d or so the streams carried", got, cycles*2/3)
}
deadline = time.Now().Add(5 * time.Second)
for runtime.NumGoroutine() > before && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if after := runtime.NumGoroutine(); after > before {
var buf bytes.Buffer
_ = pprof.Lookup("goroutine").WriteTo(&buf, 1)
t.Errorf("%d goroutines before, %d after:\n%s", before, after, buf.String())
}
}
+24 -1
View File
@@ -1,8 +1,12 @@
// Package ntfy holds the wire types of ntfy (https://ntfy.sh), the // Package ntfy holds the wire types of ntfy (https://ntfy.sh), the
// notification service: the message objects its subscribe API streams, one // notification service: the message objects its subscribe API streams, one
// JSON object per line. // JSON object per line. Its Subscriber reads that stream from a server and
// hands each message to be printed, keeping to a paper budget and to quiet
// hours.
package ntfy package ntfy
import "strings"
// Event types of a Message. // Event types of a Message.
const ( const (
EventOpen = "open" EventOpen = "open"
@@ -74,6 +78,25 @@ func (m Message) Priority() int {
return m.RawPriority return m.RawPriority
} }
// Printable reports whether m carries a notification with a text body: an
// event message, or a message without an event, that is not base64.
func (m Message) Printable() bool {
switch m.Event {
case "", EventMessage:
return !strings.EqualFold(m.Encoding, EncodingBase64)
}
return false
}
// Sequence names the notification m belongs to: its SequenceID, or its ID
// when it has none. Messages of one sequence update one notification.
func (m Message) Sequence() string {
if m.SequenceID != "" {
return m.SequenceID
}
return m.ID
}
// Action is a button on a notification. View actions open URL; http // Action is a button on a notification. View actions open URL; http
// actions send a request with Method, Headers and Body; broadcast actions // actions send a request with Method, Headers and Body; broadcast actions
// send an Android intent with Extras; copy actions copy Value to the // send an Android intent with Extras; copy actions copy Value to the
+99
View File
@@ -0,0 +1,99 @@
package ntfy
import (
"slices"
"time"
)
// Clock is a time of day.
type Clock struct {
Hour, Minute int
}
// Quiet are quiet hours: a window each day in which messages below
// MinPriority are held for a digest, or dropped.
type Quiet struct {
// Start and End are the window's times of day in Location. An End
// at or before Start ends the window on the next day.
Start, End Clock
// Days are the days a window starts on.
Days []time.Weekday
// Location is the zone of Start and End; nil means local time.
Location *time.Location
// MinPriority is the lowest priority that prints during the window.
MinPriority int
// Drop leaves out the messages held back, which otherwise print on
// one digest when the window ends.
Drop bool
}
// window returns the end of the quiet window t falls in, and whether it
// falls in one. The window's bounds are the instants the zone's clocks
// show its times of day (wallTime), so a window that crosses midnight or
// a change of clocks keeps them: 22:00 to 07:00 is nine hours on most
// nights, eight on the night clocks go forward. A bound the clocks skip is
// the first instant after the gap.
func (q *Quiet) window(t time.Time) (end time.Time, in bool) {
if q == nil {
return time.Time{}, false
}
loc := q.Location
if loc == nil {
loc = time.Local
}
t = t.In(loc)
// A window that holds t started on t's day or on the day before. The
// day is taken at noon: in a zone whose clocks go forward at midnight,
// midnight does not exist, and time.Date moves it by the gap, which
// can put it on the day before.
for back := 0; back <= 1; back++ {
day := time.Date(t.Year(), t.Month(), t.Day()-back, 12, 0, 0, 0, loc)
if !slices.Contains(q.Days, day.Weekday()) {
continue
}
start, end := q.bounds(day, loc)
if !t.Before(start) && t.Before(end) {
return end, true
}
}
return time.Time{}, false
}
// bounds returns the start and end of the window that starts on day.
func (q *Quiet) bounds(day time.Time, loc *time.Location) (start, end time.Time) {
y, m, d := day.Date()
start = wallTime(y, m, d, q.Start, loc)
endDay := d
if q.End.Hour*60+q.End.Minute <= q.Start.Hour*60+q.Start.Minute {
endDay++
}
return start, wallTime(y, m, endDay, q.End, loc)
}
// wallTime returns the instant the clocks in loc show c on the given day,
// which may be one past the end of a month. A time the clocks skip, when
// they go forward, is the first instant after the gap; time.Date moves it
// by the gap's length, to before the gap or after it depending on the
// zone (west of UTC, a skipped midnight lands on the evening before). A
// time the clocks show twice is the one time.Date gives.
func wallTime(y int, m time.Month, d int, c Clock, loc *time.Location) time.Time {
y, m, d = time.Date(y, m, d, 12, 0, 0, 0, loc).Date()
t := time.Date(y, m, d, c.Hour, c.Minute, 0, 0, loc)
asked := time.Date(y, m, d, c.Hour, c.Minute, 0, 0, time.UTC)
shown := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, time.UTC)
start, end := t.ZoneBounds()
switch {
case shown.Equal(asked):
return t
case shown.Before(asked):
// t is before the gap: the gap ends where t's zone period ends.
return end
default:
// t is after the gap: the gap ends where t's zone period starts.
return start
}
}
+286
View File
@@ -0,0 +1,286 @@
package ntfy
import (
"slices"
"testing"
"testing/synctest"
"time"
// Embeds the zone database, so that IANA names load on any host.
_ "time/tzdata"
)
func london(t *testing.T) *time.Location {
t.Helper()
loc, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
return loc
}
// nightly is 22:00 to 07:00 every day in loc.
func nightly(loc *time.Location) *Quiet {
return &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: allDays, Location: loc, MinPriority: 5}
}
func TestQuietWindow(t *testing.T) {
loc := london(t)
at := func(y int, m time.Month, d, hh, mm int) time.Time { return time.Date(y, m, d, hh, mm, 0, 0, loc) }
tests := []struct {
name string
q *Quiet
t time.Time
in bool
wantEnd time.Time
}{
{"evening before", nightly(loc), at(2026, 11, 30, 21, 59), false, time.Time{}},
{"start", nightly(loc), at(2026, 11, 30, 22, 0), true, at(2026, 12, 1, 7, 0)},
{"after midnight", nightly(loc), at(2026, 12, 1, 3, 0), true, at(2026, 12, 1, 7, 0)},
{"end", nightly(loc), at(2026, 12, 1, 7, 0), false, time.Time{}},
{"daytime window", &Quiet{Start: Clock{13, 0}, End: Clock{14, 30}, Days: allDays, Location: loc}, at(2026, 12, 1, 14, 0), true, at(2026, 12, 1, 14, 30)},
{"daytime window over", &Quiet{Start: Clock{13, 0}, End: Clock{14, 30}, Days: allDays, Location: loc}, at(2026, 12, 1, 14, 30), false, time.Time{}},
// Friday's window runs into Saturday morning; Saturday's does not
// start.
{"friday night", &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: []time.Weekday{time.Friday}, Location: loc}, at(2026, 12, 5, 3, 0), true, at(2026, 12, 5, 7, 0)},
{"saturday night", &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: []time.Weekday{time.Friday}, Location: loc}, at(2026, 12, 5, 23, 0), false, time.Time{}},
{"no quiet hours", nil, at(2026, 12, 1, 3, 0), false, time.Time{}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
end, in := tt.q.window(tt.t)
if in != tt.in || !end.Equal(tt.wantEnd) {
t.Errorf("window(%s) = %s, %v; want %s, %v", tt.t, end, in, tt.wantEnd, tt.in)
}
})
}
}
// On the nights the clocks change, the window keeps its times of day: it
// lasts eight hours when they go forward and ten when they go back.
func TestQuietWindowAcrossClockChanges(t *testing.T) {
loc := london(t)
q := nightly(loc)
for _, tt := range []struct {
night time.Time
hours time.Duration
}{
{time.Date(2026, 3, 28, 23, 0, 0, 0, loc), 8},
{time.Date(2026, 10, 24, 23, 0, 0, 0, loc), 10},
} {
end, in := q.window(tt.night)
if !in {
t.Fatalf("%s is not in the window", tt.night)
}
start := time.Date(tt.night.Year(), tt.night.Month(), tt.night.Day(), 22, 0, 0, 0, loc)
if got := end.Sub(start); got != tt.hours*time.Hour || end.In(loc).Hour() != 7 {
t.Errorf("night of %s: window %s to %s, %s long; want %dh ending 07:00", tt.night.Format("2 Jan"), start, end, got, tt.hours)
}
// Just after 07:00 local time is outside the window.
if _, in := q.window(end.Add(time.Second)); in {
t.Errorf("%s is still in the window", end.Add(time.Second))
}
if _, in := q.window(end.Add(-time.Second)); !in {
t.Errorf("%s is not in the window", end.Add(-time.Second))
}
}
}
// In zones whose clocks go forward at midnight, the evening of that day
// still has its window.
func TestQuietWindowWhenMidnightIsSkipped(t *testing.T) {
for _, tt := range []struct {
zone string
y int
m time.Month
d int
}{
{"America/Santiago", 2026, time.September, 6},
{"America/Havana", 2026, time.March, 8},
} {
t.Run(tt.zone, func(t *testing.T) {
loc, err := time.LoadLocation(tt.zone)
if err != nil {
t.Fatal(err)
}
if mid := time.Date(tt.y, tt.m, tt.d, 0, 0, 0, 0, loc); mid.Day() == tt.d && mid.Hour() == 0 {
t.Skipf("midnight of %d-%02d-%02d exists in this zone database", tt.y, tt.m, tt.d)
}
q := nightly(loc)
evening := time.Date(tt.y, tt.m, tt.d, 23, 0, 0, 0, loc)
end, in := q.window(evening)
if want := time.Date(tt.y, tt.m, tt.d+1, 7, 0, 0, 0, loc); !in || !end.Equal(want) {
t.Errorf("window(%s) = %s, %v; want the window ending %s", evening, end, in, want)
}
// The night before, which runs into the gap, is in its window too.
early := time.Date(tt.y, tt.m, tt.d, 3, 0, 0, 0, loc)
if _, in := q.window(early); !in {
t.Errorf("%s is not in the window", early)
}
// A window ending at the skipped midnight ends when the clocks
// show 01:00, the first instant after the gap, not at 23:00
// the evening before; one starting then starts at 01:00.
toMidnight := &Quiet{Start: Clock{22, 0}, End: Clock{0, 0}, Days: allDays, Location: loc}
lateEvening := time.Date(tt.y, tt.m, tt.d-1, 23, 30, 0, 0, loc)
end, in = toMidnight.window(lateEvening)
if want := time.Date(tt.y, tt.m, tt.d, 1, 0, 0, 0, loc); !in || !end.Equal(want) {
t.Errorf("window(%s) = %s, %v; want the window ending %s", lateEvening, end, in, want)
}
fromMidnight := &Quiet{Start: Clock{0, 0}, End: Clock{6, 0}, Days: allDays, Location: loc}
gapEnd := time.Date(tt.y, tt.m, tt.d, 1, 0, 0, 0, loc)
if _, in := fromMidnight.window(gapEnd.Add(-time.Second)); in {
t.Errorf("%s, before the gap ends, is in a window starting at the skipped midnight", gapEnd.Add(-time.Second))
}
if _, in := fromMidnight.window(gapEnd); !in {
t.Errorf("%s is not in a window starting at the skipped midnight", gapEnd)
}
})
}
}
func TestWallTime(t *testing.T) {
loc := london(t)
tests := []struct {
y int
m time.Month
d int
c Clock
want time.Time
}{
{2026, time.November, 30, Clock{22, 0}, time.Date(2026, 11, 30, 22, 0, 0, 0, loc)},
{2026, time.November, 31, Clock{7, 0}, time.Date(2026, 12, 1, 7, 0, 0, 0, loc)},
// 01:30 on the night clocks go forward does not exist in London.
{2026, time.March, 29, Clock{1, 30}, time.Date(2026, 3, 29, 1, 0, 0, 0, time.UTC)},
// 01:30 on the night they go back exists twice; time.Date's
// choice, the second, stands.
{2026, time.October, 25, Clock{1, 30}, time.Date(2026, 10, 25, 1, 30, 0, 0, time.UTC)},
}
for _, tt := range tests {
if got := wallTime(tt.y, tt.m, tt.d, tt.c, loc); !got.Equal(tt.want) {
t.Errorf("wallTime(%d-%02d-%02d %02d:%02d) = %s, want %s", tt.y, tt.m, tt.d, tt.c.Hour, tt.c.Minute, got, tt.want)
}
}
}
// sleepUntil advances the bubble's clock to t.
func sleepUntil(t time.Time) {
time.Sleep(time.Until(t))
synctest.Wait()
}
// During quiet hours a priority 3 message is held, a priority 5 message
// prints at once, and the held one prints on an overnight digest when the
// window ends, on the night the clocks go forward too.
func TestQuietHoursHoldForTheMorning(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 3, 28, 21, 0, 0, 0, loc))
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.Quiet = nightly(loc)
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
sleepUntil(time.Date(2026, 3, 28, 23, 0, 0, 0, loc))
held := f.publish(Message{Title: "backup finished", RawPriority: 3})
sleepUntil(time.Date(2026, 3, 28, 23, 30, 0, 0, loc))
urgent := f.publish(Message{Title: "grafana is DOWN", RawPriority: 5})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{urgent.ID}) {
t.Fatalf("printed %v during quiet hours, want only the urgent %v", got, urgent.ID)
}
if st := s.Status(); st.Held != 1 || st.Digested != 1 {
t.Errorf("status %+v", st)
}
// 07:00 BST is 06:00 UTC.
end := time.Date(2026, 3, 29, 7, 0, 0, 0, loc)
sleepUntil(end.Add(-time.Second))
if len(h.digestList()) != 0 {
t.Fatal("the digest printed before the window ended")
}
sleepUntil(end.Add(time.Second))
ds := h.digestList()
if len(ds) != 1 {
t.Fatalf("%d digests at the end of the window, want 1", len(ds))
}
if d := ds[0]; !d.Overnight || d.Count != 1 || d.Rows[0].ID != held.ID {
t.Errorf("digest %+v", d)
}
after := f.publish(Message{Title: "morning", RawPriority: 3})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{urgent.ID, after.ID}) {
t.Errorf("printed %v after the window", got)
}
})
}
// With action drop, messages below the window's priority are left out.
func TestQuietHoursDrop(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 11, 30, 23, 0, 0, 0, loc))
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.Quiet = nightly(loc)
o.Quiet.Drop = true
o.Quiet.MinPriority = 4
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
f.publish(Message{Title: "dropped", RawPriority: 3})
high := f.publish(Message{Title: "high", RawPriority: 4})
sleepUntil(time.Date(2026, 12, 1, 8, 0, 0, 0, loc))
if got := h.printed(); !slices.Equal(got, []string{high.ID}) {
t.Errorf("printed %v, want only %v", got, high.ID)
}
if ds := h.digestList(); len(ds) != 0 {
t.Errorf("digests %+v, want none", ds)
}
if st := s.Status(); st.Held != 0 || st.Digested != 0 {
t.Errorf("status %+v", st)
}
})
}
// Messages held overnight are saved with the state, so a restart during
// the night still prints them in the morning.
func TestQuietHoursHeldSurviveRestart(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
loc := london(t)
sleepUntil(time.Date(2026, 11, 30, 23, 0, 0, 0, loc))
dir := t.TempDir()
f := newFakeServer()
o := testOptions(f, dir)
o.Quiet = nightly(loc)
_, stop := start(t, o, &recorder{})
synctest.Wait()
held := f.publish(Message{Title: "held", RawPriority: 2, SequenceID: "nightly-backup"})
synctest.Wait()
stop()
sleepUntil(time.Date(2026, 12, 1, 2, 0, 0, 0, loc))
h := &recorder{}
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
if st := s.Status(); st.Held != 1 {
t.Errorf("status %+v after the restart", st)
}
update := f.publish(Message{Title: "held again", RawPriority: 2, SequenceID: "nightly-backup"})
sleepUntil(time.Date(2026, 12, 1, 7, 0, 1, 0, loc))
ds := h.digestList()
if len(ds) != 1 || ds[0].Count != 2 || ds[0].Rows[0].ID != held.ID || ds[0].Rows[1].ID != update.ID {
t.Fatalf("digests %+v", ds)
}
if ds[0].Rows[0].Updated || !ds[0].Rows[1].Updated {
t.Errorf("rows %+v: want the second marked as an update", ds[0].Rows)
}
})
}
+172
View File
@@ -0,0 +1,172 @@
package ntfy
import (
"strings"
"time"
"unicode/utf8"
)
// MaxDigestRows is how many held messages a digest lists; it counts the
// rest.
const MaxDigestRows = 50
// maxRowText is the most bytes of a title or a first line a digest row
// keeps.
const maxRowText = 256
// budget is the paper budget: at most limit receipts in any window. It
// keeps the times of the last limit receipts.
type budget struct {
limit int
window time.Duration
prints []time.Time
}
// room reports whether a receipt may print at now.
func (b *budget) room(now time.Time) bool {
b.forget(now)
return len(b.prints) < b.limit
}
// next returns when the budget next has room, or now if it has.
func (b *budget) next(now time.Time) time.Time {
if b.room(now) {
return now
}
return b.prints[0].Add(b.window)
}
// spend records a receipt printed at now.
func (b *budget) spend(now time.Time) {
b.forget(now)
b.prints = append(b.prints, now)
if extra := len(b.prints) - b.limit; extra > 0 {
b.prints = b.prints[extra:]
}
}
// forget drops the receipts older than the window. A receipt dated after
// now, as after the clock was set back, counts as printed now.
func (b *budget) forget(now time.Time) {
i := 0
for i < len(b.prints) && !now.Before(b.prints[i].Add(b.window)) {
i++
}
b.prints = b.prints[i:]
for j, t := range b.prints {
if t.After(now) {
b.prints[j] = now
}
}
}
// DigestRow is a held message, as a digest lists it.
type DigestRow struct {
ID string `json:"id"`
// Time is when the message was published, in Unix seconds.
Time int64 `json:"time"`
Topic string `json:"topic,omitempty"`
Title string `json:"title,omitempty"`
Tags []string `json:"tags,omitempty"`
// FirstLine is the first line of the message's text, kept when it has
// no title, and Markdown is set when that text is markdown.
FirstLine string `json:"first_line,omitempty"`
Markdown bool `json:"markdown,omitempty"`
Priority int `json:"priority,omitempty"`
// Updated is set when the message replaces one printed before.
Updated bool `json:"updated,omitempty"`
}
// Digest is the messages held back, printed on one receipt.
type Digest struct {
// Overnight is set when quiet hours held any of the messages.
Overnight bool
// Rows are the first MaxDigestRows messages held, in the order they
// arrived.
Rows []DigestRow
// Count is how many messages were held, the rows included.
Count int
// Since is when the first message was held, and Until when the digest
// was made.
Since, Until time.Time
}
// held are the messages held for the next digest. It is saved with the
// subscription's state.
type held struct {
Rows []DigestRow `json:"rows"`
Count int `json:"count"`
Overnight bool `json:"overnight,omitempty"`
// Since is when the first message was held, in Unix seconds.
Since int64 `json:"since"`
}
// add holds m, and reports whether it got a row; overnight says that
// quiet hours held it.
func (h *held) add(m Message, updated, overnight bool, now time.Time) bool {
if h.Count == 0 {
h.Since = now.Unix()
}
h.Count++
h.Overnight = h.Overnight || overnight
if len(h.Rows) >= MaxDigestRows {
return false
}
row := DigestRow{
ID: m.ID,
Time: m.Time,
Topic: m.Topic,
Title: cutText(m.Title),
Tags: m.Tags,
Priority: m.Priority(),
Updated: updated,
}
if strings.TrimSpace(row.Title) == "" {
row.FirstLine = cutText(firstLine(m.Message))
row.Markdown = strings.EqualFold(m.ContentType, ContentTypeMarkdown)
}
h.Rows = append(h.Rows, row)
return true
}
// digest returns the held messages as a digest made at now.
func (h *held) digest(now time.Time) Digest {
return Digest{
Overnight: h.Overnight,
Rows: h.Rows,
Count: h.Count,
Since: time.Unix(h.Since, 0),
Until: now,
}
}
// firstLine returns the first line of s that is not blank.
func firstLine(s string) string {
for line := range strings.Lines(s) {
if line = strings.TrimSpace(line); line != "" {
return line
}
}
return ""
}
// cutText returns s cut to maxRowText bytes, on a whole character.
func cutText(s string) string {
if len(s) <= maxRowText {
return s
}
end := maxRowText
for end > 0 && !utf8.RuneStart(s[end]) {
end--
}
return s[:end]
}
+88
View File
@@ -0,0 +1,88 @@
package ntfy
import (
"fmt"
"strings"
"testing"
"time"
)
// The budget allows limit receipts in any window, not limit per refill: a
// sixth receipt waits until the first is a whole window old.
func TestBudget(t *testing.T) {
t0 := time.Date(2026, 11, 30, 21, 0, 0, 0, time.UTC)
b := budget{limit: 5, window: 10 * time.Minute}
for i := range 5 {
now := t0.Add(time.Duration(i) * time.Minute)
if !b.room(now) {
t.Fatalf("no room for receipt %d", i+1)
}
b.spend(now)
}
at := t0.Add(5 * time.Minute)
if b.room(at) {
t.Fatal("room for a sixth receipt within the window")
}
if next := b.next(at); !next.Equal(t0.Add(10 * time.Minute)) {
t.Errorf("next = %s, want when the first receipt is 10 minutes old", next)
}
if !b.room(t0.Add(10 * time.Minute)) {
t.Error("no room once the first receipt left the window")
}
// A receipt dated in the future, as after the clock went back, counts
// as printed now rather than blocking for longer than a window.
b = budget{limit: 1, window: time.Minute, prints: []time.Time{t0.Add(time.Hour)}}
if b.room(t0) {
t.Error("room with a receipt just counted")
}
if !b.room(t0.Add(time.Minute)) {
t.Error("a receipt dated in the future blocked for more than a window")
}
}
func TestRing(t *testing.T) {
var items []string
for i := range ringSize + 10 {
items = append(items, fmt.Sprint(i))
}
r := newRing(items)
if r.has("9") || !r.has("10") || !r.has(fmt.Sprint(ringSize+9)) {
t.Error("the ring kept the wrong items")
}
if got := r.list(); len(got) != ringSize || got[0] != "10" {
t.Errorf("list has %d items from %q", len(got), got[0])
}
// An item added twice stays until both copies are forgotten.
r = newRing([]string{"a", "a"})
for i := range ringSize - 1 {
r.add(fmt.Sprint(i))
}
if !r.has("a") {
t.Error("forgot a while one copy is left")
}
r.add("x")
if r.has("a") {
t.Error("remembers a after both copies left")
}
}
func TestHeldRows(t *testing.T) {
now := time.Date(2026, 11, 30, 21, 5, 0, 0, time.UTC)
var h held
h.add(Message{ID: "a", Time: now.Unix(), Title: strings.Repeat("é", 200), Tags: []string{"warning"}, RawPriority: 4}, false, false, now)
h.add(Message{ID: "b", Message: "\n \nfirst line\nsecond"}, true, true, now.Add(time.Minute))
if h.Count != 2 || !h.Overnight || h.Since != now.Unix() {
t.Errorf("held %+v", h)
}
if row := h.Rows[0]; len(row.Title) > maxRowText || !strings.HasPrefix(row.Title, "é") || row.FirstLine != "" || row.Priority != 4 {
t.Errorf("row %+v", row)
}
if row := h.Rows[1]; row.FirstLine != "first line" || !row.Updated || row.Priority != 3 {
t.Errorf("row %+v", row)
}
d := h.digest(now.Add(9 * time.Minute))
if d.Count != 2 || !d.Since.Equal(now) || !d.Until.Equal(now.Add(9*time.Minute)) || len(d.Rows) != 2 {
t.Errorf("digest %+v", d)
}
}
+76
View File
@@ -0,0 +1,76 @@
package ntfy
import (
"context"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// A redirect is never followed: not to plain http, which would send the
// token in the clear, and not to another host or port, such as the
// printer's raw port, which would print the request. The connection fails
// with an error that says so.
func TestRedirectsAreNotFollowed(t *testing.T) {
// The raw listener stands for any other address, the printer's port
// 9100 among them; it counts the connections it gets.
raw, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer raw.Close()
var dialed atomic.Int64
go func() {
for {
c, err := raw.Accept()
if err != nil {
return
}
dialed.Add(1)
_ = c.Close()
}
}()
for _, target := range []string{"http://" + raw.Addr().String() + "/x", "https://" + raw.Addr().String() + "/x"} {
t.Run(strings.SplitN(target, ":", 2)[0], func(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target, http.StatusFound)
}))
defer srv.Close()
o := Options{
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, Token: "tk_secret",
MinPriority: 1, MaxBacklog: time.Hour, RateLimit: 5, RateWindow: time.Minute, BypassPriority: 5,
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json",
Transport: srv.Client().Transport,
}
s, err := New(o)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = s.Run(ctx, &recorder{})
}()
deadline := time.Now().Add(10 * time.Second)
for s.Status().LastError == "" && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
cancel()
<-done
if st := s.Status(); st.State != StateBackoff || !strings.Contains(st.LastError, "HTTP 302: the server redirects") {
t.Errorf("status %+v, want a backoff after the 302", st)
}
if n := dialed.Load(); n != 0 {
t.Errorf("the redirect target got %d connections", n)
}
})
}
}
+381
View File
@@ -0,0 +1,381 @@
package ntfy
import (
"context"
"fmt"
"slices"
"testing"
"testing/synctest"
"time"
)
// A flood larger than the 512 IDs kept at least, inside the overlap a
// reconnect replays, still prints once: every message a replay can send
// again is remembered. Once the cursor has moved on, the state keeps the
// last 512 only.
func TestFloodInTheOverlapPrintsOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
for i := range 600 {
f.publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 5})
}
synctest.Wait()
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
if n := len(f.streams()); n != 2 {
t.Fatalf("%d stream requests, want a reconnect", n)
}
ids := h.printed()
slices.Sort(ids)
if len(ids) != 600 || len(slices.Compact(slices.Clone(ids))) != 600 {
t.Errorf("%d cards for 600 messages", len(ids))
}
if st := s.Status(); st.Printed != 600 {
t.Errorf("status %+v", st)
}
time.Sleep(10 * time.Minute)
synctest.Wait()
if st, err := loadState(o.StateFile); err != nil || len(st.Seen) != ringSize {
t.Errorf("state keeps %d IDs once the flood is out of reach, want %d (%v)", len(st.Seen), ringSize, err)
}
})
}
// A flood larger than the IDs the subscription keeps still prints once:
// when it forgets IDs a replay could send again, the next replay starts
// after them.
func TestFloodPastTheLimitPrintsOnce(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
s, err := New(o)
if err != nil {
t.Fatal(err)
}
s.seenLimit = 600
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { defer close(done); _ = s.Run(ctx, h) }()
defer func() { cancel(); <-done }()
synctest.Wait()
for i := range 700 {
f.publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 5})
}
synctest.Wait()
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
if n := len(f.streams()); n != 2 {
t.Fatalf("%d stream requests, want a reconnect", n)
}
if got := h.printed(); len(got) != 700 {
t.Errorf("%d cards for 700 messages", len(got))
}
after := f.publish(Message{Title: "after the flood", RawPriority: 5})
synctest.Wait()
if got := h.printed(); len(got) != 701 || got[700] != after.ID {
t.Errorf("%d cards; the message after the flood did not print once", len(got))
}
})
}
// After a first start, a reconnect does not reach back before it: a
// message published shortly before the start never prints.
func TestFirstStartFloor(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
before := f.publish(Message{Title: "a minute before the start"})
time.Sleep(time.Minute)
h := &recorder{}
o := testOptions(f, t.TempDir())
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
started := time.Now().Unix()
time.Sleep(20 * time.Second)
f.drop()
time.Sleep(10 * time.Second)
synctest.Wait()
streams := f.streams()
if since, ok := sinceOf(t, streams[len(streams)-1]); !ok || since != started {
t.Errorf("since = %d, %v; want the start, %d", since, ok, started)
}
if got := h.printed(); slices.Contains(got, before.ID) {
t.Errorf("printed %v, a message from before the first start", got)
}
})
}
// max_backlog is measured by the server's clock: with the host's clock ten
// hours behind it, a ten-hour outage still replays only the last hour.
func TestBacklogUsesTheServerClock(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew = 10 * time.Hour
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
// The subscription last ran ten hours ago by the server's clock.
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// max_backlog follows the stream's clock, the open event's time or else
// the answer's Date: with the host's clock hours ahead of or behind the
// server's, the host's clock never decides what a replay leaves out, and
// the floor never lands in the server's future. The credentials check
// fails here, which changes nothing, since it never tells the clock.
func TestBacklogFollowsTheStreamClock(t *testing.T) {
for _, tt := range []struct {
name string
skew time.Duration
noDate bool
}{
{"host 3 hours ahead", -3 * time.Hour, false},
{"host 10 hours behind", 10 * time.Hour, false},
{"host 10 hours behind, no Date", 10 * time.Hour, true},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew, f.authFails, f.noDate = tt.skew, true, tt.noDate
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
if err := saveState(o.StateFile, state{Cursor: serverNow() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: serverNow() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the message published during the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > serverNow() {
t.Errorf("floor %d is in the server's future, now %d (%v)", st.Floor, serverNow(), err)
}
})
})
}
}
// A keepalive's time is not taken for the server's clock: it may have
// waited in the connection while the subscription paused.
func TestKeepaliveDoesNotSetTheClock(t *testing.T) {
f := newFakeServer()
s, err := New(testOptions(f, t.TempDir()))
if err != nil {
t.Fatal(err)
}
r := s.start(&recorder{})
r.conn = &conn{since: true}
now := time.Now()
r.message(context.Background(), Message{ID: "k", Event: EventKeepalive, Time: now.Unix() - 7200}, now, now)
if r.conn.clockKnown || r.conn.checked {
t.Errorf("a keepalive set the clock: %+v", r.conn)
}
r.message(context.Background(), Message{ID: "o", Event: EventOpen, Time: now.Unix() + 60}, now, now)
if !r.conn.clockKnown || r.conn.serverTime != now.Unix()+60 || !r.conn.checked {
t.Errorf("the open event did not set the clock: %+v", r.conn)
}
}
// MaxBacklog is measured from the connection's own clock and the time
// passed since it read it, never from a clock learned before: a stale one,
// as after the host's clock was stepped, neither loses messages nor
// prints old ones. The credentials check's Date here disagrees with the
// stream by hours.
func TestBacklogIgnoresAnEarlierClock(t *testing.T) {
for _, tt := range []struct {
name string
authSkew time.Duration
}{
{"earlier clock ahead", 9 * time.Hour},
{"earlier clock behind", -3 * time.Hour},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.authSkew = tt.authSkew
o := testOptions(f, t.TempDir())
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: time.Now().Unix() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if since, ok := sinceOf(t, f.streams()[0]); !ok || since != time.Now().Unix()-2*3600-120 {
t.Errorf("since = %d, %v; want the cursor less the slack, unclamped", since, ok)
}
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the message published during the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > time.Now().Unix() {
t.Errorf("floor %d is in the server's future (%v)", st.Floor, err)
}
})
})
}
}
// ntfy's open event tells the clock, not the answer's Date, which a proxy
// in front of ntfy may write from a clock of its own: with the proxy hours
// off, the backlog is still exact, nothing new is left out and the floor
// is never in ntfy's future.
func TestBacklogPrefersTheOpenEvent(t *testing.T) {
for _, tt := range []struct {
name string
dateSkew time.Duration
}{
{"proxy 2 hours ahead", 2 * time.Hour},
{"proxy 3 hours behind", -3 * time.Hour},
} {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.dateSkew = tt.dateSkew
o := testOptions(f, t.TempDir())
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
recent := f.publish(Message{Title: "half an hour ago", Time: time.Now().Unix() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Fatalf("printed %v, want only %v", got, recent.ID)
}
live := f.publish(Message{Title: "live"})
synctest.Wait()
time.Sleep(10 * time.Minute)
f.drop()
synctest.Wait()
during := f.publish(Message{Title: "published while the stream was down"})
time.Sleep(10 * time.Second)
synctest.Wait()
if got := h.printed(); !slices.Contains(got, live.ID) || !slices.Contains(got, during.ID) {
t.Errorf("printed %v, want the live message and the one from the outage", got)
}
stop()
if st, err := loadState(o.StateFile); err != nil || st.Floor > time.Now().Unix() {
t.Errorf("floor %d is in ntfy's future (%v)", st.Floor, err)
}
})
})
}
}
// The stream answer's Date alone tells the clock when the open event
// carries no time.
func TestBacklogFromTheDate(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.skew, f.openNoTime = 10*time.Hour, true
o := testOptions(f, t.TempDir())
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
t.Fatal(err)
}
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
recent := f.publish(Message{Title: "half an hour ago", Time: serverNow() - 1800})
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) || slices.Contains(got, old.ID) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// Only a message that got a row on a digest counts as printed: one held
// past the 50 rows is only counted, so a later message of its sequence is
// not marked as an update.
func TestHeldPastTheRowsIsNotPrinted(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.RateLimit = 1
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
f.publish(Message{Title: "takes the budget"})
for i := range MaxDigestRows + 1 {
f.publish(Message{Title: fmt.Sprintf("held %d", i), SequenceID: fmt.Sprintf("seq-%d", i)})
}
time.Sleep(o.RateWindow + time.Second)
synctest.Wait()
if ds := h.digestList(); len(ds) != 1 || ds[0].Count != MaxDigestRows+1 {
t.Fatalf("digests %+v", ds)
}
time.Sleep(o.RateWindow)
f.publish(Message{Title: "update of a row", SequenceID: "seq-0"})
time.Sleep(o.RateWindow)
f.publish(Message{Title: "update of a counted one", SequenceID: fmt.Sprintf("seq-%d", MaxDigestRows)})
synctest.Wait()
cards := h.cardList()
if len(cards) != 3 {
t.Fatalf("%d cards, want 3", len(cards))
}
if !cards[1].updated || cards[2].updated {
t.Errorf("updated = %v and %v; want only the update of a row marked", cards[1].updated, cards[2].updated)
}
})
}
+229
View File
@@ -0,0 +1,229 @@
package ntfy
import (
"context"
"fmt"
"math/rand/v2"
"net/http"
"slices"
"sync"
"testing"
"testing/synctest"
"time"
)
// soakHandler records what it prints and refuses a share of the calls, as
// a full print queue does.
type soakHandler struct {
recorder
rngMu sync.Mutex
rng *rand.Rand
failRate float64
digestAt []time.Time
}
func (h *soakHandler) refuse() bool {
h.rngMu.Lock()
defer h.rngMu.Unlock()
return h.rng.Float64() < h.failRate
}
func (h *soakHandler) Message(ctx context.Context, m Message, updated bool) error {
if h.refuse() {
return errBusy
}
return h.recorder.Message(ctx, m, updated)
}
func (h *soakHandler) Digest(ctx context.Context, d Digest) error {
if h.refuse() {
return errBusy
}
h.mu.Lock()
h.digestAt = append(h.digestAt, time.Now())
h.mu.Unlock()
return h.recorder.Digest(ctx, d)
}
func (h *soakHandler) setFailRate(r float64) {
h.rngMu.Lock()
defer h.rngMu.Unlock()
h.failRate = r
}
// TestSoak runs a subscription for 24 hours of the bubble's clock against
// a server that drops, stalls, refuses and rate limits it, with floods,
// repeats and updates, a handler that is sometimes full, quiet hours and a
// restart halfway. Then:
// - no message prints twice, on a card or a digest;
// - every message the subscription may read is printed or held, none
// lost;
// - no more than rate_limit receipts below the bypass priority print in
// any rate_window;
// - in quiet hours only urgent messages print, and no digest;
// - a card is marked updated exactly when its sequence printed before;
// - no goroutine is left running once Run returns: synctest.Test fails
// the test if one is.
func TestSoak(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
rng := rand.New(rand.NewPCG(20261130, 4))
dir := t.TempDir()
f := newFakeServer()
h := &soakHandler{rng: rand.New(rand.NewPCG(7, 7)), failRate: 0.05}
o := testOptions(f, dir)
o.MinPriority = 2
o.Quiet = &Quiet{Start: Clock{22, 0}, End: Clock{7, 0}, Days: allDays, Location: time.UTC, MinPriority: 5}
s, stop := start(t, o, h)
begin := time.Now().UTC()
end := begin.Add(24 * time.Hour)
restarted := false
var published []Message
publish := func(m Message) {
published = append(published, f.publish(m))
}
for time.Now().Before(end) {
time.Sleep(time.Duration(10+rng.IntN(590)) * time.Second)
switch r := rng.IntN(100); {
case r < 65:
m := Message{Title: fmt.Sprintf("message %d", len(published)), RawPriority: 1 + rng.IntN(5)}
if len(published) > 0 && rng.IntN(5) == 0 {
m.SequenceID = published[rng.IntN(len(published))].Sequence()
}
publish(m)
case r < 70:
// A same-second repeat of the newest message.
if len(published) > 0 {
f.publish(published[len(published)-1])
}
case r < 75:
for i := range 20 {
publish(Message{Title: fmt.Sprintf("flood %d", i), RawPriority: 2 + rng.IntN(4)})
}
case r < 80:
f.drop()
case r < 83:
f.stall()
case r < 86:
f.answerNext(fakeAnswer{status: http.StatusTooManyRequests, retryAfter: "30"})
f.drop()
case r < 87:
f.answerNext(fakeAnswer{status: http.StatusUnauthorized})
f.drop()
case r < 90:
f.answerNext(fakeAnswer{status: http.StatusBadGateway}, fakeAnswer{status: http.StatusServiceUnavailable})
f.drop()
}
if !restarted && time.Since(begin) > 13*time.Hour {
restarted = true
stop()
time.Sleep(10 * time.Minute)
s, stop = start(t, o, h)
}
}
// Let the last digest print after the quiet hours, with a handler
// that takes everything.
h.setFailRate(0)
sleepUntil(time.Date(end.Year(), end.Month(), end.Day(), 8, 0, 0, 0, time.UTC))
if st := s.Status(); st.Held != 0 {
t.Errorf("%d messages still held at 08:00", st.Held)
}
stop()
synctest.Wait()
cards := h.cardList()
digests := h.digestList()
if len(cards) == 0 || len(digests) == 0 {
t.Fatalf("%d cards and %d digests: the soak exercised too little", len(cards), len(digests))
}
t.Logf("%d messages published, %d cards, %d digests, %d server requests",
len(published), len(cards), len(digests), len(f.streams()))
// Every message the subscription may read, once.
want := make(map[string]Message)
for _, m := range published {
if m.Priority() >= o.MinPriority {
want[m.ID] = m
}
}
got := make(map[string]int)
total := len(cards)
for _, c := range cards {
got[c.m.ID]++
}
for _, d := range digests {
total += d.Count
for _, row := range d.Rows {
got[row.ID]++
}
}
for id, n := range got {
if n > 1 {
t.Errorf("%s printed %d times", id, n)
}
if _, ok := want[id]; !ok {
t.Errorf("%s printed, but the subscription should not have read it", id)
}
}
if total != len(want) {
t.Errorf("%d messages printed or held, want %d", total, len(want))
}
// The paper budget and the quiet hours.
var receipts []time.Time
for _, c := range cards {
_, quiet := o.Quiet.window(c.at)
if c.m.Priority() < o.BypassPriority {
receipts = append(receipts, c.at)
if quiet {
t.Errorf("%s, priority %d, printed in quiet hours at %s", c.m.ID, c.m.Priority(), c.at)
}
}
}
for _, at := range h.digestAt {
if _, quiet := o.Quiet.window(at); quiet {
t.Errorf("a digest printed in quiet hours at %s", at)
}
receipts = append(receipts, at)
}
slices.SortFunc(receipts, func(a, b time.Time) int { return a.Compare(b) })
for i := o.RateLimit; i < len(receipts); i++ {
if receipts[i].Sub(receipts[i-o.RateLimit]) < o.RateWindow {
t.Errorf("receipts %d to %d printed within %s", i-o.RateLimit, i, receipts[i].Sub(receipts[i-o.RateLimit]))
}
}
// Updates. The server sends messages in the order they were
// published, and a replay only repeats ones already dealt with, so
// the subscription first meets each message in that order. While it
// remembers every sequence, a message is an update exactly when an
// earlier one of its sequence printed, on a card or a digest row; a
// message only counted on a digest does not count.
updated := make(map[string]bool)
for _, c := range cards {
updated[c.m.ID] = c.updated
}
for _, d := range digests {
for _, row := range d.Rows {
updated[row.ID] = row.Updated
}
}
if len(want) < ringSize {
seen := make(map[string]bool)
printed := make(map[string]bool)
for _, m := range published {
if _, ok := want[m.ID]; !ok || seen[m.ID] {
continue
}
seen[m.ID] = true
if got, ok := updated[m.ID]; ok && got != printed[m.Sequence()] {
t.Errorf("%s of sequence %s marked updated=%v, want %v", m.ID, m.Sequence(), got, printed[m.Sequence()])
}
if _, ok := updated[m.ID]; ok {
printed[m.Sequence()] = true
}
}
}
})
}
+262
View File
@@ -0,0 +1,262 @@
package ntfy
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"time"
)
// ringSize is how many printed sequences a subscription remembers, and how
// many message IDs it keeps at least.
const ringSize = 512
// maxSeen caps the message IDs a subscription keeps, so that a flood
// cannot grow its state without bound.
const maxSeen = 20000
// stateVersion is the version of the state file's format.
const stateVersion = 1
// state is what a subscription keeps across restarts.
type state struct {
Version int `json:"version"`
// Cursor is the newest ntfy server time the subscription has dealt
// with, in Unix seconds; 0 when it has none.
Cursor int64 `json:"cursor"`
// Floor is the earliest server time a replay may start at, in Unix
// seconds: where a first start began, or where max_backlog last cut a
// replay short.
Floor int64 `json:"floor,omitempty"`
// Seen are the messages dealt with that a replay could send again,
// and at least the last ringSize, oldest first.
Seen []seenID `json:"seen"`
// Printed are the sequences of the last messages printed, on a card or
// a digest, oldest first.
Printed []string `json:"printed"`
// Prints are the times of the receipts in the paper budget, in Unix
// seconds.
Prints []int64 `json:"prints,omitempty"`
// Held are the messages waiting for the next digest.
Held *held `json:"held,omitempty"`
}
// loadState reads the state file at path. A file that does not exist
// gives an empty state. A file that cannot be read or parsed also gives an
// empty state, with the error saying why, for the caller to warn about.
func loadState(path string) (state, error) {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return state{}, nil
}
if err != nil {
return state{}, err
}
var st state
if err := json.Unmarshal(data, &st); err != nil {
return state{}, fmt.Errorf("parsing %s: %w", path, err)
}
if st.Version != stateVersion {
return state{}, fmt.Errorf("%s has version %d, want %d", path, st.Version, stateVersion)
}
if st.Held != nil && len(st.Held.Rows) > MaxDigestRows {
st.Held.Rows = st.Held.Rows[:MaxDigestRows]
}
return st, nil
}
// saveState writes st to path atomically: to a temporary file in the same
// directory, synced to disk, then renamed over path. A crash leaves the
// old file or the new one, never part of either.
func saveState(path string, st state) error {
st.Version = stateVersion
data, err := json.Marshal(st)
if err != nil {
return err
}
dir := filepath.Dir(path)
// CreateTemp makes the file readable by its owner only: held messages
// carry titles.
f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
tmp := f.Name()
_, err = f.Write(data)
if err == nil {
err = f.Sync()
}
if closeErr := f.Close(); err == nil {
err = closeErr
}
if err == nil {
err = os.Rename(tmp, path)
}
if err != nil {
_ = os.Remove(tmp)
return err
}
syncDir(dir)
return nil
}
// syncDir makes a rename in dir durable. Windows cannot open a directory
// to sync it, and its renames need no such step.
func syncDir(dir string) {
if runtime.GOOS == "windows" {
return
}
d, err := os.Open(dir)
if err != nil {
return
}
_ = d.Sync()
_ = d.Close()
}
// seenID is a message dealt with: its ID and its server time.
type seenID struct {
ID string `json:"id"`
Time int64 `json:"time"`
}
// seenSet holds the IDs of the messages dealt with, so that a message a
// replay sends again is dropped. It keeps the messages a replay could
// send, those dated at or after where a replay can start, and at least
// the last ringSize, up to limit in all.
type seenSet struct {
items []seenID
counts map[string]int
limit int
}
// newSeenSet returns a set of at most limit items holding items, oldest
// first.
func newSeenSet(items []seenID, limit int) *seenSet {
s := &seenSet{counts: make(map[string]int), limit: limit}
for _, it := range items {
s.add(it.ID, it.Time)
}
return s
}
// add records the message id of server time t. When the set is full, it
// forgets the oldest, and returns the latest server time among them, for
// the caller to keep a replay from sending them again; otherwise 0.
func (s *seenSet) add(id string, t int64) int64 {
s.items = append(s.items, seenID{ID: id, Time: t})
s.counts[id]++
extra := len(s.items) - s.limit
if extra <= 0 {
return 0
}
var latest int64
for _, it := range s.items[:extra] {
latest = max(latest, it.Time)
}
s.drop(s.items[:extra])
s.items = s.items[extra:]
return latest
}
// has reports whether id was dealt with.
func (s *seenSet) has(id string) bool {
return s.counts[id] > 0
}
// prune forgets the messages dated before start, the earliest time a
// replay can start at, apart from the last ringSize.
func (s *seenSet) prune(start int64) {
keepFrom := len(s.items) - ringSize
kept := s.items[:0]
for i, it := range s.items {
if i >= keepFrom || it.Time >= start {
kept = append(kept, it)
continue
}
s.drop([]seenID{it})
}
clear(s.items[len(kept):])
s.items = kept
}
func (s *seenSet) drop(items []seenID) {
for _, it := range items {
if s.counts[it.ID]--; s.counts[it.ID] <= 0 {
delete(s.counts, it.ID)
}
}
}
// list returns the items, oldest first.
func (s *seenSet) list() []seenID {
return append([]seenID(nil), s.items...)
}
// ring remembers the last ringSize strings added to it.
type ring struct {
items []string
counts map[string]int
}
// newRing returns a ring holding items, oldest first; only the last
// ringSize are kept.
func newRing(items []string) *ring {
r := &ring{counts: make(map[string]int)}
for _, s := range items {
r.add(s)
}
return r
}
// add remembers s, forgetting the oldest item when the ring is full. An
// item may be added more than once.
func (r *ring) add(s string) {
if len(r.items) == ringSize {
oldest := r.items[0]
r.items = r.items[1:]
if r.counts[oldest]--; r.counts[oldest] == 0 {
delete(r.counts, oldest)
}
}
r.items = append(r.items, s)
r.counts[s]++
}
// has reports whether s is remembered.
func (r *ring) has(s string) bool {
return r.counts[s] > 0
}
// list returns the items, oldest first.
func (r *ring) list() []string {
return append([]string(nil), r.items...)
}
// unixTimes returns ts in Unix seconds.
func unixTimes(ts []time.Time) []int64 {
out := make([]int64, len(ts))
for i, t := range ts {
out[i] = t.Unix()
}
return out
}
// fromUnix returns ts, in Unix seconds, as times.
func fromUnix(ts []int64) []time.Time {
out := make([]time.Time, len(ts))
for i, t := range ts {
out[i] = time.Unix(t, 0)
}
return out
}
+63
View File
@@ -0,0 +1,63 @@
package ntfy
import (
"sync"
"time"
)
// States of a subscription, as Status reports them.
const (
// StateConnecting is a subscription opening its connection.
StateConnecting = "connecting"
// StateConnected is a subscription reading its stream.
StateConnected = "connected"
// StateBackoff is a subscription waiting to reconnect after a failure.
StateBackoff = "backoff"
// StateUnauthorized is a subscription whose credentials the server
// refused; it tries again every five minutes.
StateUnauthorized = "unauthorized"
)
// Status is a snapshot of a subscription, for health checks. It holds no
// credentials and nothing a message says.
type Status struct {
Name string
State string
// ConnectedSince is when the current connection opened; zero when
// there is none.
ConnectedSince time.Time
// LastMessageAt is when the last message arrived; zero when none has.
LastMessageAt time.Time
// Printed is how many messages printed on their own card, Digested how
// many were held for a digest, and Held how many wait for the next one.
Printed int
Digested int
Held int
// LastError says why the last connection failed; "" once one opens.
LastError string
}
// status is a Status shared between the subscription and its readers.
type status struct {
mu sync.Mutex
s Status
}
func (st *status) get() Status {
st.mu.Lock()
defer st.mu.Unlock()
return st.s
}
func (st *status) update(fn func(*Status)) {
st.mu.Lock()
defer st.mu.Unlock()
fn(&st.s)
}
+970
View File
@@ -0,0 +1,970 @@
package ntfy
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"math/rand/v2"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// Timing of a subscription.
const (
// stallGrace is added to twice the keepalive interval to give the time
// a connection may stay silent before it counts as stalled.
stallGrace = 15 * time.Second
// stableAfter is how long a connection must have lasted for the next
// reconnect to start the backoff from its first step.
stableAfter = 2 * time.Minute
// unauthorizedRetry is how often a subscription whose credentials were
// refused tries again.
unauthorizedRetry = 5 * time.Minute
// cursorSlack is how far before its cursor a subscription asks the
// server to start. ntfy dates a message when it arrives, before an
// attachment is stored, so a message can reach subscribers after
// others dated later; the slack catches it after a reconnect, and the
// seen IDs drop the repeats.
cursorSlack = 2 * time.Minute
// maxRetryAfter caps the wait a 429 answer asks for.
maxRetryAfter = time.Hour
// firstPrintRetry and maxPrintRetry bound the wait before a message,
// or a digest, the handler could not take is offered again.
firstPrintRetry = time.Second
maxPrintRetry = 30 * time.Second
// saveEvery is the least time between two writes of the state file.
saveEvery = time.Second
// maxWait is the longest the loop sleeps before it looks at its
// deadlines again, so that a change to the wall clock is noticed.
maxWait = time.Minute
// authTimeout bounds the credentials check at startup.
authTimeout = 30 * time.Second
)
// Limits of the stream.
const (
// maxLine is the longest line read from the stream; a longer one is
// skipped.
maxLine = 1 << 20
// userAgent is sent with every request.
userAgent = "uberbringer"
)
// defaultBackoff are the waits before successive reconnects, each with
// ±20% jitter; the last one repeats.
var defaultBackoff = []time.Duration{
5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second, time.Minute, 2 * time.Minute,
}
// errStalled ends a connection that sent nothing for too long.
var errStalled = errors.New("stalled")
// Options configure a Subscriber.
type Options struct {
// Name names the subscription in its status and its log lines.
Name string
// Server is the ntfy server's base URL, e.g. https://ntfy.sh.
Server string
// Topics are the topics read, on one connection.
Topics []string
// Token is an access token, sent as a bearer token. User and Password
// are sent with basic authentication instead. With neither, requests
// carry no credentials.
Token string
User, Password string
// MinPriority is the lowest priority read, 1-5; the server filters by
// it.
MinPriority int
// MaxBacklog is how old, by the server's clock, a missed message may
// be and still print after a restart or an outage. The replay is asked
// for in full; its older messages are left out as they arrive, once the
// connection tells the server's clock: the open event's time, or else
// the answer's Date.
MaxBacklog time.Duration
// RateLimit receipts print per RateWindow at most. Messages over it
// are held and print on one digest once there is room.
RateLimit int
RateWindow time.Duration
// BypassPriority is the lowest priority that prints at once, outside
// the rate limit.
BypassPriority int
// Keepalive is the server's keepalive interval.
Keepalive time.Duration
// Quiet are the quiet hours; nil means none.
Quiet *Quiet
// SkipUpdates leaves out a message that replaces one printed before,
// which is otherwise handed over marked as an update.
SkipUpdates bool
// StateFile is where the subscription keeps its state.
StateFile string
// Transport sends the requests. Nil means a transport with dial, TLS
// handshake and response header timeouts and no overall timeout,
// since the response is a stream.
Transport http.RoundTripper
// Logger logs the subscription's events, never what a message says.
Logger *slog.Logger
// Report receives faults that need attention, such as a state file
// that cannot be written, once each.
Report func(error)
}
// Handler prints what a subscription delivers. It is called from the
// subscription's own goroutine, one call at a time.
type Handler interface {
// Message prints m. updated is set when an earlier message of its
// sequence printed. An error means it was not printed: the subscription
// stops reading and offers it again, after 1 second, then after twice
// as long each time, up to 30 seconds.
Message(ctx context.Context, m Message, updated bool) error
// Digest prints the messages held back on one receipt. An error is
// retried as for Message, while the subscription goes on reading.
Digest(ctx context.Context, d Digest) error
}
// Subscriber reads the messages of an ntfy server's topics as they are
// published and hands them to a Handler. It reconnects after failures,
// resumes from where it stopped, drops repeats, keeps to a paper budget and
// holds messages during quiet hours.
type Subscriber struct {
o Options
streamURL string
authURL string
client *http.Client
ownedIdle func()
backoff []time.Duration
seenLimit int
logger *slog.Logger
status status
}
// New returns a subscriber with options o.
func New(o Options) (*Subscriber, error) {
u, err := url.Parse(o.Server)
switch {
case o.Name == "":
return nil, errors.New("ntfy: a subscription needs a name")
case err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https"):
return nil, fmt.Errorf("ntfy %s: the server is not an http or https URL", o.Name)
case len(o.Topics) == 0:
return nil, fmt.Errorf("ntfy %s: no topics", o.Name)
case o.RateLimit < 1 || o.RateWindow <= 0 || o.Keepalive <= 0 || o.MaxBacklog <= 0:
return nil, fmt.Errorf("ntfy %s: rate limit, rate window, keepalive and backlog must be positive", o.Name)
case o.StateFile == "":
return nil, fmt.Errorf("ntfy %s: no state file", o.Name)
}
if o.Logger == nil {
o.Logger = slog.New(slog.DiscardHandler)
}
if o.Report == nil {
o.Report = func(error) {}
}
base := strings.TrimRight(u.String(), "/") + "/" + strings.Join(o.Topics, ",")
s := &Subscriber{
o: o,
streamURL: base + "/json",
authURL: base + "/auth",
backoff: defaultBackoff,
seenLimit: maxSeen,
logger: o.Logger.With("subscription", o.Name),
ownedIdle: func() {},
}
transport := o.Transport
if transport == nil {
t := newTransport()
transport, s.ownedIdle = t, t.CloseIdleConnections
}
s.client = &http.Client{Transport: transport, CheckRedirect: refuseRedirect}
s.status.s = Status{Name: o.Name, State: StateConnecting}
return s, nil
}
// refuseRedirect makes the client return a redirect as the answer instead
// of following it. A redirect would carry the credentials to wherever it
// points, over plain http or to another host or port, and the stream read
// there would print; a 3xx is a failed connection instead.
func refuseRedirect(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
// newTransport returns a transport whose connection and header waits are
// bounded and whose body reads are not, for a stream that stays open.
func newTransport() *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
IdleConnTimeout: 90 * time.Second,
MaxIdleConns: 2,
}
}
// Status returns a snapshot of the subscription.
func (s *Subscriber) Status() Status {
return s.status.get()
}
// Run reads the subscription until ctx is cancelled, then saves its state
// and returns nil. Failures to connect or to print are retried, never
// returned.
func (s *Subscriber) Run(ctx context.Context, h Handler) error {
r := s.start(h)
defer r.stop()
r.checkAuth(ctx)
r.loop(ctx)
return nil
}
// run is one Run of a subscriber: its state and its connection. Only the
// goroutine that called Run uses it.
type run struct {
s *Subscriber
h Handler
o *Options
log *slog.Logger
cursor int64
floor int64
seen *seenSet
printed *ring
budget budget
held held
conn *conn
connectedAt time.Time
attempt int
reconnectAt time.Time
stallAt time.Time
// pending is the message the handler did not take, offered again at
// retryAt; nothing more is read until it is taken.
pending *Message
retryAt time.Time
retryDelay time.Duration
// digestAt is when a digest the handler did not take is offered again.
digestAt time.Time
digestDelay time.Duration
dirty bool
savedAt time.Time
saveFailed bool
}
// start loads the state and returns the run.
func (s *Subscriber) start(h Handler) *run {
st, err := loadState(s.o.StateFile)
if err != nil {
s.logger.Warn("ntfy state file unreadable; starting without state", "err", err)
st = state{}
}
r := &run{
s: s,
h: h,
o: &s.o,
log: s.logger,
cursor: st.Cursor,
floor: st.Floor,
seen: newSeenSet(st.Seen, s.seenLimit),
printed: newRing(st.Printed),
budget: budget{limit: s.o.RateLimit, window: s.o.RateWindow, prints: fromUnix(st.Prints)},
}
if st.Held != nil {
r.held = *st.Held
}
s.status.update(func(st *Status) { st.Held = r.held.Count })
return r
}
// stop closes the connection and saves the state.
func (r *run) stop() {
r.closeConn()
if r.dirty {
r.save(time.Now())
}
r.s.ownedIdle()
}
// loop runs the subscription until ctx is cancelled: it reads the stream,
// connects and reconnects, retries prints, prints digests and saves the
// state, each when it is due.
func (r *run) loop(ctx context.Context) {
timer := time.NewTimer(maxWait)
defer timer.Stop()
for {
now := time.Now()
r.due(ctx, now)
if ctx.Err() != nil {
return
}
timer.Reset(min(max(r.wake(now).Sub(now), 0), maxWait))
var events <-chan event
if r.conn != nil && r.pending == nil {
events = r.conn.events
}
select {
case <-ctx.Done():
return
case ev := <-events:
r.event(ctx, ev, time.Now())
case <-timer.C:
}
}
}
// due does what is due at now.
func (r *run) due(ctx context.Context, now time.Time) {
if r.pending != nil && !now.Before(r.retryAt) {
m := *r.pending
if !r.deliver(ctx, m, now) {
r.wait(m, now)
} else {
r.dealt(m)
r.pending = nil
if r.conn != nil {
r.stallAt = now.Add(r.stall())
}
}
}
r.flush(ctx, now)
if r.conn == nil && !now.Before(r.reconnectAt) && ctx.Err() == nil {
r.connect(ctx, now)
}
if r.conn != nil && r.pending == nil && !now.Before(r.stallAt) {
r.closeConn()
r.reconnect(event{err: errStalled}, now)
}
if r.dirty && !now.Before(r.savedAt.Add(saveEvery)) {
r.save(now)
}
}
// wake returns the next time something is due after now.
func (r *run) wake(now time.Time) time.Time {
next := now.Add(maxWait)
earlier := func(t time.Time) {
if t.Before(next) {
next = t
}
}
switch {
case r.pending != nil:
earlier(r.retryAt)
case r.conn != nil:
earlier(r.stallAt)
}
if r.conn == nil {
earlier(r.reconnectAt)
}
if at, ok := r.flushAt(now); ok {
earlier(at)
}
if r.dirty {
earlier(r.savedAt.Add(saveEvery))
}
return next
}
// stall is how long a connection may stay silent.
func (r *run) stall() time.Duration {
return 2*r.o.Keepalive + stallGrace
}
// event acts on what the connection's reader sent.
func (r *run) event(ctx context.Context, ev event, now time.Time) {
r.stallAt = now.Add(r.stall())
switch {
case ev.opened:
r.connectedAt = now
r.s.status.update(func(st *Status) {
st.State, st.ConnectedSince, st.LastError = StateConnected, now, ""
})
r.log.Info("ntfy connected")
// The answer's Date may come from a proxy in front of ntfy, whose
// clock is not the one ntfy dates messages by; it stands in only
// when the stream's first line does not tell ntfy's own.
r.conn.date, r.conn.dateRead = ev.date, ev.at
case ev.skipped != "":
r.log.Warn("ntfy line skipped", "reason", ev.skipped)
case ev.msg != nil:
r.message(ctx, *ev.msg, ev.at, now)
case ev.end:
r.closeConn()
r.reconnect(ev, now)
}
}
// message deals with one object of the stream, which its reader read at
// readAt.
func (r *run) message(ctx context.Context, m Message, readAt, now time.Time) {
switch m.Event {
case EventOpen:
// The open event comes first, as soon as the stream opens, so its
// time is ntfy's clock, read live; a keepalive may have waited in
// the connection while the subscription paused, so its time is not.
if !r.conn.clockKnown && m.Time > 0 {
r.conn.setClock(m.Time, readAt)
}
r.learnClock(now)
// Without since, the server replays nothing, so the time it opened
// at is where a reconnect resumes, and no replay may reach before
// it. With since, the replay follows the open event, so its time
// says nothing yet.
if !r.conn.since && r.cursor == 0 && m.Time > 0 {
r.cursor, r.floor, r.dirty = m.Time, m.Time, true
}
return
case EventKeepalive:
r.advance(m.Time)
return
}
r.learnClock(now)
if m.Time > 0 && m.Time < r.conn.oldest {
r.log.Debug("ntfy message older than max_backlog skipped", "ntfy_id", m.ID)
return
}
if m.ID != "" && r.seen.has(m.ID) {
r.log.Debug("ntfy message repeated", "ntfy_id", m.ID)
r.advance(m.Time)
return
}
if m.Printable() {
r.s.status.update(func(st *Status) { st.LastMessageAt = now })
}
if !r.deliver(ctx, m, now) {
r.wait(m, now)
return
}
r.dealt(m)
}
// deliver prints m, holds it for a digest or leaves it out, and reports
// whether it is dealt with: false when the handler did not take it.
func (r *run) deliver(ctx context.Context, m Message, now time.Time) bool {
priority := m.Priority()
if !m.Printable() || priority < r.o.MinPriority {
r.log.Debug("ntfy event skipped", "ntfy_id", m.ID, "event", m.Event)
return true
}
sequence := m.Sequence()
updated := r.printed.has(sequence)
if updated && r.o.SkipUpdates {
r.log.Debug("ntfy update skipped", "ntfy_id", m.ID)
return true
}
_, quiet := r.o.Quiet.window(now)
if quiet && priority < r.o.Quiet.MinPriority {
if r.o.Quiet.Drop {
r.log.Debug("ntfy message dropped in quiet hours", "ntfy_id", m.ID)
return true
}
r.hold(m, updated, true, now)
return true
}
if priority < r.o.BypassPriority && (!r.budget.room(now) || (r.held.Count > 0 && !quiet)) {
r.hold(m, updated, false, now)
return true
}
if err := r.h.Message(ctx, m, updated); err != nil {
if r.pending == nil {
r.log.Warn("ntfy message waits to print", "ntfy_id", m.ID, "err", err)
}
return false
}
if priority < r.o.BypassPriority {
r.budget.spend(now)
}
r.printed.add(sequence)
r.s.status.update(func(st *Status) { st.Printed++ })
return true
}
// hold keeps m for the next digest. Only a message that gets a row counts
// as printed; one past the rows is only counted on the digest.
func (r *run) hold(m Message, updated, overnight bool, now time.Time) {
if r.held.add(m, updated, overnight, now) {
r.printed.add(m.Sequence())
}
r.log.Debug("ntfy message held", "ntfy_id", m.ID, "quiet_hours", overnight)
r.s.status.update(func(st *Status) { st.Digested++; st.Held = r.held.Count })
}
// wait keeps m to offer it again later, waiting longer each time.
func (r *run) wait(m Message, now time.Time) {
if r.pending == nil {
r.retryDelay = firstPrintRetry
} else {
r.retryDelay = min(2*r.retryDelay, maxPrintRetry)
}
r.pending = &m
r.retryAt = now.Add(r.retryDelay)
}
// dealt records m as dealt with, so that it is never handled again. When
// the seen IDs are full and forget messages a replay could still send,
// the floor rises past them, so that no replay sends them again.
func (r *run) dealt(m Message) {
if m.ID != "" {
if forgot := r.seen.add(m.ID, m.Time); forgot > 0 && forgot >= r.replayStart() {
r.floor = max(r.floor, forgot+1)
}
}
r.advance(m.Time)
r.dirty = true
}
// advance moves the cursor forward to t, a server time.
func (r *run) advance(t int64) {
if t > r.cursor {
r.cursor, r.dirty = t, true
}
}
// learnClock settles the connection's clock once a line has come: ntfy's
// own, from the open event, or else the answer's Date, and applies
// MaxBacklog with it.
func (r *run) learnClock(now time.Time) {
c := r.conn
if !c.clockKnown && !c.date.IsZero() {
c.setClock(c.date.Unix(), c.dateRead)
}
r.checkBacklog(now)
}
// checkBacklog applies MaxBacklog to the connection once it has told the
// server's clock: the replay's messages older than MaxBacklog are left out
// as they arrive, and the floor rises to that time, so that they stay out.
func (r *run) checkBacklog(now time.Time) {
c := r.conn
if c == nil || c.checked || !c.clockKnown {
return
}
// The time since the server's clock was read comes from the
// monotonic clock, so a step of the host's clock cannot move it.
serverNow := c.serverTime + int64(now.Sub(c.serverRead)/time.Second)
c.checked, c.oldest = true, serverNow-int64(r.o.MaxBacklog/time.Second)
if c.oldest > r.floor {
r.floor, r.dirty = c.oldest, true
}
}
// replayStart is the earliest server time a replay can start at.
func (r *run) replayStart() int64 {
return max(r.cursor-int64(cursorSlack/time.Second), r.floor)
}
// flushAt returns when the held messages may print, if any are held.
func (r *run) flushAt(now time.Time) (time.Time, bool) {
if r.held.Count == 0 || r.pending != nil {
return time.Time{}, false
}
at := r.budget.next(now)
if end, quiet := r.o.Quiet.window(now); quiet {
at = end
}
if at.Before(r.digestAt) {
at = r.digestAt
}
return at, true
}
// flush prints the held messages on one digest when they may print.
func (r *run) flush(ctx context.Context, now time.Time) {
at, ok := r.flushAt(now)
if !ok || now.Before(at) {
return
}
if _, quiet := r.o.Quiet.window(now); quiet || !r.budget.room(now) {
return
}
if err := r.h.Digest(ctx, r.held.digest(now)); err != nil {
if r.digestAt.IsZero() {
r.digestDelay = firstPrintRetry
r.log.Warn("ntfy digest waits to print", "held", r.held.Count, "err", err)
} else {
r.digestDelay = min(2*r.digestDelay, maxPrintRetry)
}
r.digestAt = now.Add(r.digestDelay)
return
}
r.log.Debug("ntfy digest printed", "held", r.held.Count, "overnight", r.held.Overnight)
r.budget.spend(now)
r.held, r.digestAt, r.dirty = held{}, time.Time{}, true
r.s.status.update(func(st *Status) { st.Held = 0 })
}
// since returns the since parameter of the next connection: the cursor
// less the slack, but not before the floor. With no cursor there is none,
// so that only new messages are read. MaxBacklog is not applied here: the
// host's clock may be off, or may have been stepped since the server last
// told its own, so the connection applies it from the server's clock as
// it tells it (checkBacklog).
func (r *run) since() (int64, bool) {
if r.cursor == 0 {
return 0, false
}
return r.replayStart(), true
}
// request returns a GET request for rawURL with the subscription's
// credentials.
func (r *run) request(ctx context.Context, rawURL string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
switch {
case r.o.Token != "":
req.Header.Set("Authorization", "Bearer "+r.o.Token)
case r.o.User != "":
req.SetBasicAuth(r.o.User, r.o.Password)
}
return req, nil
}
// checkAuth asks the server whether the credentials may read the topics,
// so that refused credentials show at startup. Only a refusal counts:
// anything else is left to the connection to find out.
func (r *run) checkAuth(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, authTimeout)
defer cancel()
req, err := r.request(ctx, r.s.authURL)
if err != nil {
return
}
resp, err := r.s.client.Do(req)
if err != nil {
r.log.Debug("ntfy credentials check failed", "err", describe(err))
return
}
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
r.reconnect(event{end: true, status: resp.StatusCode}, time.Now())
}
}
// connect opens a connection, read by its own goroutine.
func (r *run) connect(ctx context.Context, now time.Time) {
query := url.Values{}
since, hasSince := r.since()
if hasSince {
query.Set("since", strconv.FormatInt(since, 10))
}
if r.o.MinPriority > 1 {
var ps []string
for p := r.o.MinPriority; p <= PriorityMax; p++ {
ps = append(ps, strconv.Itoa(p))
}
query.Set("priority", strings.Join(ps, ","))
}
rawURL := r.s.streamURL
if len(query) > 0 {
rawURL += "?" + query.Encode()
}
cctx, cancel := context.WithCancel(ctx)
req, err := r.request(cctx, rawURL)
if err != nil {
cancel()
r.reconnect(event{end: true, err: err}, now)
return
}
c := &conn{cancel: cancel, events: make(chan event), done: make(chan struct{}), since: hasSince}
go c.read(cctx, r.s.client, req)
r.conn = c
r.stallAt = now.Add(r.stall())
r.s.status.update(func(st *Status) { st.State = StateConnecting })
}
// closeConn closes the connection, if there is one, and waits for its
// reader to stop.
func (r *run) closeConn() {
if r.conn == nil {
return
}
r.conn.cancel()
<-r.conn.done
r.conn = nil
}
// reconnect sets when to connect again after the connection ended as ev
// says: Retry-After for a 429, every five minutes for refused credentials,
// and the backoff otherwise, from its first step after a stable
// connection.
func (r *run) reconnect(ev event, now time.Time) {
if !r.connectedAt.IsZero() && now.Sub(r.connectedAt) >= stableAfter {
r.attempt = 0
}
r.connectedAt = time.Time{}
state, why := StateBackoff, ""
var wait time.Duration
switch {
case ev.status == http.StatusUnauthorized || ev.status == http.StatusForbidden:
state, wait = StateUnauthorized, unauthorizedRetry
why = fmt.Sprintf("HTTP %d: the server refused the credentials", ev.status)
if ev.status == http.StatusForbidden {
why = "HTTP 403: the credentials may not read the topics"
}
case ev.status == http.StatusTooManyRequests:
why, wait = "HTTP 429: too many requests", r.nextBackoff()
if ev.retryAfter > 0 {
wait = ev.retryAfter
}
case ev.status >= 300 && ev.status < 400:
why = fmt.Sprintf("HTTP %d: the server redirects, and redirects are not followed; set server to the address it redirects to", ev.status)
wait = r.nextBackoff()
case ev.status != 0:
why, wait = fmt.Sprintf("HTTP %d", ev.status), r.nextBackoff()
case errors.Is(ev.err, errStalled):
why, wait = fmt.Sprintf("no data for %s", r.stall()), r.nextBackoff()
case ev.err != nil && !errors.Is(ev.err, io.EOF):
why, wait = describe(ev.err), r.nextBackoff()
default:
why, wait = "the server closed the stream", r.nextBackoff()
}
r.reconnectAt = now.Add(wait)
r.s.status.update(func(st *Status) {
st.State, st.ConnectedSince, st.LastError = state, time.Time{}, why
})
if state == StateUnauthorized {
r.log.Warn("ntfy credentials refused", "err", why, "retry_in", wait)
return
}
r.log.Warn("ntfy connection lost", "err", why, "retry_in", wait.Round(time.Millisecond))
}
// nextBackoff returns the wait before the next reconnect, with jitter.
func (r *run) nextBackoff() time.Duration {
d := r.s.backoff[min(r.attempt, len(r.s.backoff)-1)]
r.attempt++
return time.Duration(float64(d) * (0.8 + 0.4*rand.Float64()))
}
// save writes the state. The first failure is logged and reported; later
// ones are retried quietly until a write succeeds.
func (r *run) save(now time.Time) {
r.seen.prune(r.replayStart())
st := state{
Cursor: r.cursor,
Floor: r.floor,
Seen: r.seen.list(),
Printed: r.printed.list(),
Prints: unixTimes(r.budget.prints),
}
if r.held.Count > 0 {
h := r.held
st.Held = &h
}
r.savedAt = now
if err := saveState(r.o.StateFile, st); err != nil {
if !r.saveFailed {
r.log.Error("ntfy state not saved", "err", err)
r.o.Report(fmt.Errorf("saving state: %w", err))
}
r.saveFailed = true
return
}
if r.saveFailed {
r.log.Info("ntfy state saved again")
}
r.saveFailed, r.dirty = false, false
}
// describe says what went wrong with a request, without its URL, which
// names the topics.
func describe(err error) string {
var urlErr *url.Error
if errors.As(err, &urlErr) {
err = urlErr.Err
}
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return "the connection closed"
}
return err.Error()
}
// parseRetryAfter reads a Retry-After header, seconds or an HTTP date, as
// a wait from now, capped at maxRetryAfter; 0 when there is none.
func parseRetryAfter(h string, now time.Time) time.Duration {
h = strings.TrimSpace(h)
if h == "" {
return 0
}
var d time.Duration
if secs, err := strconv.Atoi(h); err == nil {
d = time.Duration(secs) * time.Second
} else if t, err := http.ParseTime(h); err == nil {
d = t.Sub(now)
}
return min(max(d, 0), maxRetryAfter)
}
// event is what a connection's reader sends the loop.
type event struct {
// opened is set when the server answered 200, and date is the
// answer's Date, if it had one.
opened bool
date time.Time
// at is when the reader got the answer or read the line, which can be
// well before the loop takes it.
at time.Time
// msg is an object read from the stream.
msg *Message
// skipped says why a line was skipped.
skipped string
// end is set when the connection ended: with the answer's status and
// Retry-After when it was not 200, or with err.
end bool
status int
retryAfter time.Duration
err error
}
// conn is one connection to the stream.
type conn struct {
cancel context.CancelFunc
events chan event
done chan struct{}
// since is set when the request asked for messages since a time.
since bool
// serverTime is the server's clock, in Unix seconds, as the connection
// told it, read at serverRead; clockKnown is set once it has. Each
// connection learns it afresh, so the host's clock never stands in
// for it.
serverTime int64
serverRead time.Time
clockKnown bool
// date is the answer's Date, read at dateRead, which tells the clock
// only when the stream does not.
date time.Time
dateRead time.Time
// checked is set once MaxBacklog applies to the connection, and oldest
// is then the earliest server time of a message it lets through.
checked bool
oldest int64
}
// setClock records the server's clock, serverTime, read at readAt.
func (c *conn) setClock(serverTime int64, readAt time.Time) {
if serverTime > 0 {
c.serverTime, c.serverRead, c.clockKnown = serverTime, readAt, true
}
}
// read sends the request and the stream's lines to the loop as events,
// until the stream ends or ctx is cancelled.
func (c *conn) read(ctx context.Context, client *http.Client, req *http.Request) {
defer close(c.done)
resp, err := client.Do(req)
if err != nil {
c.send(ctx, event{end: true, err: err})
return
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
c.send(ctx, event{end: true, status: resp.StatusCode,
retryAfter: parseRetryAfter(resp.Header.Get("Retry-After"), time.Now())})
return
}
opened := event{opened: true, at: time.Now()}
if date, err := http.ParseTime(resp.Header.Get("Date")); err == nil {
opened.date = date
}
if !c.send(ctx, opened) {
return
}
br := bufio.NewReaderSize(resp.Body, 64<<10)
for {
line, tooLong, err := readLine(br)
switch {
case tooLong:
if !c.send(ctx, event{skipped: "longer than 1 MiB"}) {
return
}
case len(bytes.TrimSpace(line)) > 0:
var m Message
ev := event{msg: &m, at: time.Now()}
if jsonErr := json.Unmarshal(line, &m); jsonErr != nil {
ev = event{skipped: "not a JSON message"}
}
if !c.send(ctx, ev) {
return
}
}
if err != nil {
c.send(ctx, event{end: true, err: err})
return
}
}
}
// send hands ev to the loop, unless ctx is cancelled first.
func (c *conn) send(ctx context.Context, ev event) bool {
select {
case c.events <- ev:
return true
case <-ctx.Done():
return false
}
}
// readLine reads one line. A line longer than maxLine is read to its end
// and dropped, and reported as too long.
func readLine(br *bufio.Reader) (line []byte, tooLong bool, err error) {
for {
chunk, err := br.ReadSlice('\n')
if !tooLong {
if len(line)+len(chunk) > maxLine {
tooLong, line = true, nil
} else {
line = append(line, chunk...)
}
}
if !errors.Is(err, bufio.ErrBufferFull) {
return line, tooLong, err
}
}
}
+747
View File
@@ -0,0 +1,747 @@
package ntfy
import (
"encoding/base64"
"fmt"
"net/http"
"os"
"slices"
"strconv"
"strings"
"testing"
"testing/synctest"
"time"
)
// sinceOf returns the since parameter of a stream request, and whether it
// has one.
func sinceOf(t *testing.T, r *http.Request) (int64, bool) {
t.Helper()
s := r.URL.Query().Get("since")
if s == "" {
return 0, false
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
t.Fatalf("since %q: %v", s, err)
}
return n, true
}
// A first start asks for no since, so only new messages print; the
// request names the topics and carries the token and a generic user agent.
func TestFirstStartSendsNoSince(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.publish(Message{Title: "old"})
h := &recorder{}
o := testOptions(f, t.TempDir())
o.Topics = []string{"alerts", "backups"}
s, stop := start(t, o, h)
defer stop()
synctest.Wait()
streams := f.streams()
if len(streams) != 1 {
t.Fatalf("%d stream requests, want 1", len(streams))
}
r := streams[0]
if r.URL.Path != "/alerts,backups/json" {
t.Errorf("path %q, want /alerts,backups/json", r.URL.Path)
}
if _, ok := sinceOf(t, r); ok || r.URL.RawQuery != "" {
t.Errorf("query %q, want none", r.URL.RawQuery)
}
if got := r.Header.Get("Authorization"); got != "Bearer tk_testtoken" {
t.Errorf("Authorization %q", got)
}
if got := r.Header.Get("User-Agent"); got != "uberbringer" {
t.Errorf("User-Agent %q", got)
}
if got := h.printed(); len(got) != 0 {
t.Errorf("printed %v, want nothing from before the start", got)
}
if st := s.Status(); st.State != StateConnected || st.ConnectedSince.IsZero() || st.Name != "home" {
t.Errorf("status %+v", st)
}
m := f.publish(Message{Title: "new", RawPriority: 4})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{m.ID}) {
t.Errorf("printed %v, want %v", got, []string{m.ID})
}
if st := s.Status(); st.Printed != 1 || st.LastMessageAt.IsZero() {
t.Errorf("status %+v", st)
}
})
}
func TestBasicAuthAndPriorityFilter(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
o := testOptions(f, t.TempDir())
o.Token, o.User, o.Password = "", "printer", "s3cret"
o.MinPriority = 3
_, stop := start(t, o, &recorder{})
defer stop()
synctest.Wait()
r := f.streams()[0]
if user, pass, ok := r.BasicAuth(); !ok || user != "printer" || pass != "s3cret" {
t.Errorf("basic auth %q %q %v", user, pass, ok)
}
if got := r.URL.Query().Get("priority"); got != "3,4,5" {
t.Errorf("priority %q, want 3,4,5", got)
}
})
}
// After the stream ends, the reconnect asks for the messages since the
// cursor, less the slack, and the repeats it gets are dropped.
func TestReconnectResumesFromCursor(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
_, stop := start(t, testOptions(f, t.TempDir()), h)
defer stop()
synctest.Wait()
time.Sleep(10 * time.Minute)
first := f.publish(Message{Title: "one"})
synctest.Wait()
f.drop()
synctest.Wait()
missed := f.publish(Message{Title: "missed while away"})
time.Sleep(7 * time.Second) // the first backoff step is 5 s ± 20%
synctest.Wait()
streams := f.streams()
if len(streams) != 2 {
t.Fatalf("%d stream requests, want 2", len(streams))
}
// The cursor is the first message's time: no keepalive came after it.
since, ok := sinceOf(t, streams[1])
if want := first.Time - int64(cursorSlack/time.Second); !ok || since != want {
t.Errorf("since = %d, %v; want the cursor less the slack, %d", since, ok, want)
}
if got, want := h.printed(), []string{first.ID, missed.ID}; !slices.Equal(got, want) {
t.Errorf("printed %v, want %v once each", got, want)
}
})
}
// Two messages in the same second, one of them sent twice as ntfy 2.31+
// can, and the overlap a reconnect replays, print once each, also after the
// state is loaded from disk.
func TestDuplicatesAreDropped(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
dir := t.TempDir()
f := newFakeServer()
h := &recorder{}
o := testOptions(f, dir)
_, stop := start(t, o, h)
synctest.Wait()
a := f.publish(Message{Title: "a"})
b := f.publish(Message{Title: "b"})
f.publish(a)
synctest.Wait()
if got, want := h.printed(), []string{a.ID, b.ID}; !slices.Equal(got, want) {
t.Fatalf("printed %v, want %v", got, want)
}
f.drop()
time.Sleep(time.Minute)
synctest.Wait()
if got := h.printed(); len(got) != 2 {
t.Fatalf("printed %v after the reconnect replayed the overlap", got)
}
stop()
h2 := &recorder{}
_, stop = start(t, o, h2)
defer stop()
synctest.Wait()
c := f.publish(Message{Title: "c"})
synctest.Wait()
if got := h2.printed(); !slices.Equal(got, []string{c.ID}) {
t.Errorf("after a restart printed %v, want only %v", got, c.ID)
}
})
}
// A cursor older than MaxBacklog still asks for the whole replay from the
// cursor; only the messages older than MaxBacklog by ntfy's clock are left
// out as they arrive.
func TestStaleCursorReplaysUnclamped(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
dir := t.TempDir()
f := newFakeServer()
o := testOptions(f, dir)
old := f.publish(Message{Title: "three hours ago"})
if err := saveState(o.StateFile, state{Cursor: old.Time}); err != nil {
t.Fatal(err)
}
time.Sleep(3 * time.Hour)
recent := f.publish(Message{Title: "half an hour ago"})
time.Sleep(30 * time.Minute)
h := &recorder{}
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
// The request is not clamped; the connection leaves out what is
// older than the backlog, and the floor keeps it out.
if since, ok := sinceOf(t, f.streams()[0]); !ok || since != old.Time-int64(cursorSlack/time.Second) {
t.Errorf("since = %d, %v; want the cursor less the slack", since, ok)
}
if st, _ := loadState(o.StateFile); st.Floor != 0 && st.Floor < time.Now().Add(-o.MaxBacklog).Unix() {
t.Errorf("floor %d below the backlog", st.Floor)
}
if got := h.printed(); !slices.Equal(got, []string{recent.ID}) {
t.Errorf("printed %v, want only %v", got, recent.ID)
}
})
}
// A start that leaves out messages for their age saves the floor at once,
// so a restart soon after, before any keepalive, with a longer backlog,
// still leaves them out.
func TestBacklogFloorIsSaved(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
o := testOptions(f, t.TempDir())
o.MaxBacklog = 2 * time.Minute
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix()}); err != nil {
t.Fatal(err)
}
time.Sleep(time.Second)
old := f.publish(Message{Title: "published while stopped"})
time.Sleep(3 * time.Minute)
h := &recorder{}
_, stop := start(t, o, h)
synctest.Wait()
stop()
if got := h.printed(); len(got) != 0 {
t.Fatalf("printed %v, a message older than the backlog", got)
}
st, err := loadState(o.StateFile)
if err != nil {
t.Fatal(err)
}
if st.Floor <= old.Time {
t.Errorf("floor %d, want it past the message left out, %d", st.Floor, old.Time)
}
o.MaxBacklog = time.Hour
h2 := &recorder{}
_, stop2 := start(t, o, h2)
defer stop2()
synctest.Wait()
if got := h2.printed(); len(got) != 0 {
t.Errorf("after a restart with a longer backlog, printed %v", got)
}
})
}
// A connection that sends nothing for twice the keepalive plus 15 s is
// closed and opened again.
func TestStallReconnects(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
defer stop()
synctest.Wait()
time.Sleep(time.Minute) // a keepalive arrives at 45 s
synctest.Wait()
f.stall()
stalledAt := time.Now()
// The last line was the keepalive at 45 s, so the stall is noticed
// at 45 s + 105 s, 90 s after the stall began.
time.Sleep(89 * time.Second)
synctest.Wait()
if f.open() != 1 || len(f.streams()) != 1 {
t.Fatalf("reconnected %s after the stall, too early", time.Since(stalledAt))
}
time.Sleep(2 * time.Second)
synctest.Wait()
if f.open() != 0 {
t.Fatal("the stalled connection is still open")
}
if st := s.Status(); st.State != StateBackoff || !strings.Contains(st.LastError, "no data for 1m45s") {
t.Errorf("status %+v", st)
}
time.Sleep(7 * time.Second)
synctest.Wait()
if len(f.streams()) != 2 || f.open() != 1 {
t.Errorf("%d requests, %d open; want a second connection", len(f.streams()), f.open())
}
})
}
// Failed connections wait 5, 10, 20, 30, 60 and then 120 s, each ± 20%;
// after a connection that lasted two minutes the next wait is 5 s again.
func TestBackoff(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
var fails []fakeAnswer
for range 8 {
fails = append(fails, fakeAnswer{status: http.StatusBadGateway})
}
f.answerNext(fails...)
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
defer stop()
steps := []time.Duration{5, 10, 20, 30, 60, 120, 120, 120}
for i, step := range steps {
synctest.Wait()
times := f.streamTimes()
prev := times[len(times)-1]
step *= time.Second
low, high := step*8/10, step*12/10
time.Sleep(time.Until(prev.Add(low - time.Millisecond)))
synctest.Wait()
if got := len(f.streamTimes()); got != len(times) {
t.Fatalf("attempt %d came before %s", i+2, low)
}
time.Sleep(time.Until(prev.Add(high + time.Millisecond)))
synctest.Wait()
if got := len(f.streamTimes()); got != len(times)+1 {
t.Fatalf("attempt %d did not come by %s", i+2, high)
}
}
synctest.Wait()
if st := s.Status(); st.State != StateConnected {
t.Fatalf("status %+v after the failures", st)
}
time.Sleep(3 * time.Minute)
f.drop()
synctest.Wait()
n := len(f.streams())
time.Sleep(6100 * time.Millisecond)
synctest.Wait()
if len(f.streams()) != n+1 {
t.Error("after a stable connection the backoff did not start again at 5 s")
}
})
}
// A 429 waits as long as Retry-After says.
func TestTooManyRequestsHonoursRetryAfter(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.answerNext(fakeAnswer{status: http.StatusTooManyRequests, retryAfter: "300"})
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
defer stop()
synctest.Wait()
if st := s.Status(); st.State != StateBackoff || !strings.Contains(st.LastError, "429") {
t.Errorf("status %+v", st)
}
time.Sleep(299 * time.Second)
synctest.Wait()
if len(f.streams()) != 1 {
t.Fatal("reconnected before Retry-After")
}
time.Sleep(2 * time.Second)
synctest.Wait()
if len(f.streams()) != 2 {
t.Fatal("did not reconnect after Retry-After")
}
})
}
func TestParseRetryAfter(t *testing.T) {
now := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
tests := map[string]time.Duration{
"": 0,
"120": 2 * time.Minute,
" 7 ": 7 * time.Second,
"-5": 0,
"86400": time.Hour,
"Mon, 30 Nov 2026 12:01:30 GMT": 90 * time.Second,
"Mon, 30 Nov 2026 11:00:00 GMT": 0,
"soon": 0,
}
for h, want := range tests {
if got := parseRetryAfter(h, now); got != want {
t.Errorf("parseRetryAfter(%q) = %s, want %s", h, got, want)
}
}
}
// Refused credentials show at startup through the credentials check: the
// state is unauthorized, and the next try is five minutes later.
func TestUnauthorized(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
f.setAuth(http.StatusUnauthorized)
s, stop := start(t, testOptions(f, t.TempDir()), &recorder{})
defer stop()
synctest.Wait()
if st := s.Status(); st.State != StateUnauthorized || !strings.Contains(st.LastError, "HTTP 401") {
t.Errorf("status %+v", st)
}
if strings.Contains(s.Status().LastError, "tk_testtoken") {
t.Error("the status shows the token")
}
if n := len(f.streams()); n != 0 {
t.Fatalf("%d stream requests before the retry", n)
}
// The stream refuses too, so the state stays unauthorized.
f.answerNext(fakeAnswer{status: http.StatusForbidden})
time.Sleep(5*time.Minute + time.Second)
synctest.Wait()
if n := len(f.streams()); n != 1 {
t.Fatalf("%d stream requests five minutes later, want 1", n)
}
if st := s.Status(); st.State != StateUnauthorized || !strings.Contains(st.LastError, "403") {
t.Errorf("status %+v", st)
}
time.Sleep(5*time.Minute + time.Second)
synctest.Wait()
if st := s.Status(); st.State != StateConnected || st.LastError != "" {
t.Errorf("status %+v once the stream accepts the credentials", st)
}
})
}
// While the handler cannot take a message, nothing more is read and the
// cursor stays before it; the message is offered again after 1, 2, 4 ...
// seconds and prints once the handler takes it.
func TestFullQueueHoldsTheCursor(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
dir := t.TempDir()
f := newFakeServer()
h := &recorder{}
o := testOptions(f, dir)
_, stop := start(t, o, h)
synctest.Wait()
time.Sleep(10 * time.Minute)
synctest.Wait()
h.failNext(4)
a := f.publish(Message{Title: "a"})
time.Sleep(time.Second)
b := f.publish(Message{Title: "b"})
synctest.Wait()
time.Sleep(2 * time.Second) // a failed at 0 s and 1 s; next try at 3 s
synctest.Wait()
st, err := loadState(o.StateFile)
if err != nil {
t.Fatal(err)
}
if st.Cursor >= a.Time {
t.Errorf("cursor %d moved to the unprinted message's time %d", st.Cursor, a.Time)
}
if got := h.printed(); len(got) != 0 {
t.Fatalf("printed %v while the queue was full", got)
}
time.Sleep(12 * time.Second) // tries at 3 s and 7 s fail; 15 s takes it
synctest.Wait()
if got, want := h.printed(), []string{a.ID, b.ID}; !slices.Equal(got, want) {
t.Fatalf("printed %v, want %v", got, want)
}
stop()
if st, _ := loadState(o.StateFile); st.Cursor < b.Time {
t.Errorf("cursor %d, want at least %d once both printed", st.Cursor, b.Time)
}
})
}
// The state file survives a restart; a damaged file counts as no state,
// with a warning.
func TestStateFile(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
dir := t.TempDir()
f := newFakeServer()
o := testOptions(f, dir)
_, stop := start(t, o, &recorder{})
synctest.Wait()
m := f.publish(Message{Title: "a", SequenceID: "s1"})
synctest.Wait()
stop()
st, err := loadState(o.StateFile)
if err != nil {
t.Fatal(err)
}
if st.Version != stateVersion || st.Cursor != m.Time || !slices.Contains(st.Seen, seenID{ID: m.ID, Time: m.Time}) ||
!slices.Contains(st.Printed, "s1") || len(st.Prints) != 1 {
t.Errorf("state %+v", st)
}
if info, err := os.Stat(o.StateFile); err == nil && info.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' {
t.Errorf("state file mode %v, want owner only", info.Mode().Perm())
}
for name, data := range map[string]string{
"partial": `{"version":1,"cursor":12`,
"not JSON": "\x00\x01",
"other version": `{"version":2,"cursor":1}`,
} {
if err := os.WriteFile(o.StateFile, []byte(data), 0o600); err != nil {
t.Fatal(err)
}
var logs logBuffer
o.Logger = debugLogger(&logs)
f2 := newFakeServer()
o.Transport = f2
_, stop := start(t, o, &recorder{})
synctest.Wait()
stop()
if !strings.Contains(logs.String(), "ntfy state file unreadable; starting without state") {
t.Errorf("%s: no warning in %q", name, logs.String())
}
if _, ok := sinceOf(t, f2.streams()[0]); ok {
t.Errorf("%s: asked for since, want a fresh start", name)
}
}
})
}
// The state file is written at most once a second.
func TestStateWritesAreThrottled(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
o := testOptions(f, t.TempDir())
o.RateLimit = 100
_, stop := start(t, o, &recorder{})
defer stop()
synctest.Wait()
info := func() time.Time {
fi, err := os.Stat(o.StateFile)
if err != nil {
return time.Time{}
}
return fi.ModTime()
}
f.publish(Message{Title: "a"})
synctest.Wait()
st1, _ := loadState(o.StateFile)
f.publish(Message{Title: "b"})
synctest.Wait()
st2, _ := loadState(o.StateFile)
if len(st2.Seen) != len(st1.Seen) {
t.Errorf("the state was written twice within a second: %d then %d seen", len(st1.Seen), len(st2.Seen))
}
time.Sleep(time.Second)
synctest.Wait()
if st3, _ := loadState(o.StateFile); len(st3.Seen) != 2 || info().IsZero() {
t.Errorf("after a second the state has %d seen, want 2", len(st3.Seen))
}
})
}
// Events other than messages, and base64 bodies, print nothing but move
// the cursor.
func TestNonMessagesSkipped(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
_, stop := start(t, o, h)
synctest.Wait()
f.publish(Message{Event: EventMessageDelete, SequenceID: "x"})
f.publish(Message{Event: EventPollRequest})
last := f.publish(Message{Message: base64.StdEncoding.EncodeToString([]byte{0, 1}), Encoding: "base64"})
synctest.Wait()
stop()
if got := h.printed(); len(got) != 0 {
t.Errorf("printed %v", got)
}
if st, _ := loadState(o.StateFile); st.Cursor != last.Time || len(st.Seen) != 3 {
t.Errorf("state %+v", st)
}
})
}
// A line longer than 1 MiB, and one that is not JSON, are skipped with a
// warning; the stream goes on.
func TestBadLinesSkipped(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
var logs logBuffer
o := testOptions(f, t.TempDir())
o.Logger = debugLogger(&logs)
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
f.publish(Message{Title: strings.Repeat("x", maxLine)})
ok := f.publish(Message{Title: "fine"})
synctest.Wait()
if got := h.printed(); !slices.Equal(got, []string{ok.ID}) {
t.Errorf("printed %v, want only %v", got, ok.ID)
}
if !strings.Contains(logs.String(), "longer than 1 MiB") {
t.Errorf("no warning in %q", logs.String())
}
})
}
// Over the budget, messages are held and print on one digest when there is
// room; priority 5 always prints.
func TestRateLimitDigest(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
s, stop := start(t, testOptions(f, t.TempDir()), h)
defer stop()
synctest.Wait()
var ids []string
for i := range 8 {
ids = append(ids, f.publish(Message{Title: fmt.Sprintf("m%d", i), RawPriority: 4}).ID)
time.Sleep(10 * time.Second)
}
urgent := f.publish(Message{Title: "urgent", RawPriority: 5})
synctest.Wait()
if got, want := h.printed(), append(slices.Clone(ids[:5]), urgent.ID); !slices.Equal(got, want) {
t.Fatalf("printed %v, want the first five and the urgent one, %v", got, want)
}
if st := s.Status(); st.Digested != 3 || st.Held != 3 || st.Printed != 6 {
t.Errorf("status %+v", st)
}
// The first card printed at 0 s, so the window has room at 10 min.
time.Sleep(10*time.Minute - 80*time.Second - time.Second)
synctest.Wait()
if len(h.digestList()) != 0 {
t.Fatal("the digest printed before the budget had room")
}
time.Sleep(2 * time.Second)
synctest.Wait()
ds := h.digestList()
if len(ds) != 1 {
t.Fatalf("%d digests, want 1", len(ds))
}
d := ds[0]
if d.Overnight || d.Count != 3 || len(d.Rows) != 3 || d.Rows[0].ID != ids[5] || d.Rows[2].Title != "m7" {
t.Errorf("digest %+v", d)
}
if st := s.Status(); st.Held != 0 {
t.Errorf("status %+v after the digest", st)
}
})
}
// A digest lists 50 messages and counts the rest.
func TestDigestCapsRows(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.RateLimit = 1
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
for i := range 61 {
f.publish(Message{Message: fmt.Sprintf("line %d\nsecond line", i)})
}
time.Sleep(o.RateWindow)
synctest.Wait()
ds := h.digestList()
if len(ds) != 1 || ds[0].Count != 60 || len(ds[0].Rows) != MaxDigestRows {
t.Fatalf("digests %+v", ds)
}
if row := ds[0].Rows[0]; row.FirstLine != "line 1" || row.Title != "" {
t.Errorf("row %+v, want the first line of a message without a title", row)
}
})
}
// A message of a sequence printed before is handed over as an update; the
// first message of a sequence its publisher named prints plain; with
// SkipUpdates an update is left out.
func TestUpdates(t *testing.T) {
for _, skip := range []bool{false, true} {
t.Run(fmt.Sprintf("skip=%v", skip), func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
h := &recorder{}
o := testOptions(f, t.TempDir())
o.SkipUpdates = skip
_, stop := start(t, o, h)
defer stop()
synctest.Wait()
first := f.publish(Message{Title: "download"})
update := f.publish(Message{Title: "download done", SequenceID: first.ID})
named := f.publish(Message{Title: "backup started", SequenceID: "backup-42"})
namedUpdate := f.publish(Message{Title: "backup done", SequenceID: "backup-42"})
synctest.Wait()
want := map[string]bool{first.ID: false, update.ID: true, named.ID: false, namedUpdate.ID: true}
var got []string
for _, c := range h.cardList() {
got = append(got, c.m.ID)
if c.updated != want[c.m.ID] {
t.Errorf("%s updated = %v", c.m.Title, c.updated)
}
}
wantIDs := []string{first.ID, update.ID, named.ID, namedUpdate.ID}
if skip {
wantIDs = []string{first.ID, named.ID}
}
if !slices.Equal(got, wantIDs) {
t.Errorf("printed %v, want %v", got, wantIDs)
}
})
})
}
}
// No log line carries what a message says, nor the token.
func TestLogsCarryNoText(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
f := newFakeServer()
var logs logBuffer
h := &recorder{}
o := testOptions(f, t.TempDir())
o.Topics = []string{"secret-topic"}
o.Logger = debugLogger(&logs)
o.RateLimit = 1
o.Quiet = &Quiet{Start: Clock{0, 0}, End: Clock{0, 30}, Days: allDays, Location: time.UTC, MinPriority: 5}
_, stop := start(t, o, h)
synctest.Wait()
secret := []string{"SecretTitle", "SecretBody", "SecretTag", "SecretLabel", "secret-topic"}
h.failNext(1)
for p := 1; p <= 5; p++ {
f.publish(Message{Topic: "secret-topic", Title: "SecretTitle", Message: "SecretBody", Tags: []string{"SecretTag"},
RawPriority: p, Actions: []Action{{Action: "view", Label: "SecretLabel", URL: "https://x/SecretTitle"}}})
}
time.Sleep(time.Hour)
f.publish(Message{Topic: "secret-topic", Title: "SecretTitle", Message: "SecretBody"})
f.publish(Message{Topic: "secret-topic", Title: "SecretTitle", Message: "SecretBody"})
f.answerNext(fakeAnswer{status: http.StatusBadGateway}, fakeAnswer{status: http.StatusUnauthorized})
f.stall()
time.Sleep(10 * time.Minute)
synctest.Wait()
stop()
out := logs.String()
for _, want := range []string{"ntfy connection lost", "ntfy credentials refused", "ntfy message held", "ntfy digest printed", "ntfy message waits to print"} {
if !strings.Contains(out, want) {
t.Errorf("the log lacks %q, so the test did not reach it", want)
}
}
if out == "" {
t.Fatal("nothing was logged")
}
for _, s := range append(secret, "tk_testtoken", "SecretTitle") {
if strings.Contains(out, s) {
t.Errorf("the log holds %q:\n%s", s, out)
}
}
})
}
// allDays are the seven days of the week.
var allDays = []time.Weekday{time.Sunday, time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday, time.Saturday}
+5 -4
View File
@@ -66,7 +66,8 @@ type Status struct {
// State is where the job is in its lifecycle. // State is where the job is in its lifecycle.
State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"` State State `json:"status" jsonschema:"enum=queued,enum=printing,enum=done,enum=failed"`
// Source says where the job came from: print for POST /api/v1/print, // Source says where the job came from: print for POST /api/v1/print,
// or module:<name> for a module route, e.g. module:ntfy. // module:<name> for a module route, e.g. module:ntfy, or
// ntfy:<subscription> for an ntfy subscription in the config.
Source string `json:"source,omitempty"` Source string `json:"source,omitempty"`
// Error says why a failed job failed. // Error says why a failed job failed.
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
@@ -111,12 +112,12 @@ type Options struct {
// Meta says where a job came from. It is kept with the job's status and // Meta says where a job came from. It is kept with the job's status and
// logged with it; it never holds what the job prints. // logged with it; it never holds what the job prints.
type Meta struct { type Meta struct {
// Source is the kind of client that sent the job, e.g. print or // Source is the kind of client that sent the job, e.g. print,
// module:ntfy. // module:ntfy or ntfy:home.
Source string Source string
// Ref identifies the job at its source, e.g. the ID of the request // Ref identifies the job at its source, e.g. the ID of the request
// that sent it. // that sent it, or of the ntfy message.
Ref string Ref string
} }
+12 -4
View File
@@ -75,10 +75,15 @@ func TestRenderCompat(t *testing.T) {
var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex from the current renderer") var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex from the current renderer")
// paperReceipts are jobs whose printed result was checked on the TM-T88IV, // paperReceipts are jobs whose printed result was checked on the TM-T88IV,
// with the file their bytes are pinned in and, for a job with an image // with the file their bytes are pinned in, for a job with an image URL the
// URL, the image it was printed with. The bytes are rendered for a TM-T88 // image it was printed with, and the blank lines it fed before its cut.
// in CP437 with the default options. // The bytes are rendered for a TM-T88 in CP437 with the default options
var paperReceipts = []struct{ job, hex, image string }{ // otherwise. ntfy-cutfeed's topic is replaced by a name of the same
// length.
var paperReceipts = []struct {
job, hex, image string
cutFeed int
}{
{job: filepath.Join("..", "..", "..", "examples", "blocks.json"), hex: filepath.Join("testdata", "paper", "blocks.hex")}, {job: filepath.Join("..", "..", "..", "examples", "blocks.json"), hex: filepath.Join("testdata", "paper", "blocks.hex")},
{job: filepath.Join("testdata", "paper", "note.json"), hex: filepath.Join("testdata", "paper", "note.hex")}, {job: filepath.Join("testdata", "paper", "note.json"), hex: filepath.Join("testdata", "paper", "note.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-high.json"), hex: filepath.Join("testdata", "paper", "ntfy-high.hex"), {job: filepath.Join("testdata", "paper", "ntfy-high.json"), hex: filepath.Join("testdata", "paper", "ntfy-high.hex"),
@@ -86,6 +91,8 @@ var paperReceipts = []struct{ job, hex, image string }{
{job: filepath.Join("testdata", "paper", "ntfy-urgent.json"), hex: filepath.Join("testdata", "paper", "ntfy-urgent.hex")}, {job: filepath.Join("testdata", "paper", "ntfy-urgent.json"), hex: filepath.Join("testdata", "paper", "ntfy-urgent.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-default.json"), hex: filepath.Join("testdata", "paper", "ntfy-default.hex")}, {job: filepath.Join("testdata", "paper", "ntfy-default.json"), hex: filepath.Join("testdata", "paper", "ntfy-default.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-min.json"), hex: filepath.Join("testdata", "paper", "ntfy-min.hex")}, {job: filepath.Join("testdata", "paper", "ntfy-min.json"), hex: filepath.Join("testdata", "paper", "ntfy-min.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-digest.json"), hex: filepath.Join("testdata", "paper", "ntfy-digest.hex")},
{job: filepath.Join("testdata", "paper", "ntfy-cutfeed.json"), hex: filepath.Join("testdata", "paper", "ntfy-cutfeed.hex"), cutFeed: 3},
} }
// TestPaperReceipts fails when the bytes of a receipt checked on paper // TestPaperReceipts fails when the bytes of a receipt checked on paper
@@ -110,6 +117,7 @@ func TestPaperReceipts(t *testing.T) {
MaxPixels: 25_000_000, MaxPixels: 25_000_000,
MaxHeight: 4000, MaxHeight: 4000,
MaxLines: 2000, MaxLines: 2000,
CutFeed: receiptFile.cutFeed,
}, fetcher) }, fetcher)
got, err := r.Render(context.Background(), readJob(t, receiptFile.job)) got, err := r.Render(context.Background(), readJob(t, receiptFile.job))
if err != nil { if err != nil {
+79
View File
@@ -0,0 +1,79 @@
package receipt_test
import (
"bytes"
"context"
"errors"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
)
// cutFeedRenderer is a TM-T20 renderer that feeds feed lines before each
// cut and fails a job over maxLines.
func cutFeedRenderer(t *testing.T, feed, maxLines int) *receipt.Renderer {
t.Helper()
return receipt.NewRenderer(receipt.Options{
Profile: tmT20(t), CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000,
MaxLines: maxLines, CutFeed: feed,
}, &fakeFetcher{})
}
// CutFeed feeds blank lines before every cut: the one added at the end of
// each copy and an explicit cut element alike. Zero feeds nothing.
func TestRenderCutFeed(t *testing.T) {
job := receipt.Job{Copies: 2, Elements: []receipt.Element{
{Type: "text", Text: "first"},
{Type: "cut", Mode: "full"},
{Type: "text", Text: "second"},
}}
feedThenPartial := append([]byte{0x1B, 'd', 3}, partialCut...)
feedThenFull := []byte{0x1B, 'd', 3, 0x1D, 0x56, 65, 0}
out, err := cutFeedRenderer(t, 3, 0).Render(context.Background(), job)
if err != nil {
t.Fatal(err)
}
if n := bytes.Count(out, feedThenPartial); n != 2 {
t.Errorf("%d fed partial cuts, want one per copy", n)
}
if n := bytes.Count(out, feedThenFull); n != 2 {
t.Errorf("%d fed full cuts, want one per copy", n)
}
if !bytes.HasSuffix(out, feedThenPartial) {
t.Errorf("the receipt ends % X, want the feed and the cut", out[max(len(out)-8, 0):])
}
out, err = cutFeedRenderer(t, 0, 0).Render(context.Background(), job)
if err != nil {
t.Fatal(err)
}
if bytes.Contains(out, []byte{0x1B, 'd'}) || !bytes.HasSuffix(out, partialCut) {
t.Errorf("CutFeed 0 fed paper: % X", out[max(len(out)-8, 0):])
}
}
// The preview shows the fed lines as blank lines before the cut, and they
// count toward the line limit.
func TestPreviewAndLimitCountCutFeed(t *testing.T) {
job := receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "one line"}}}
p, err := cutFeedRenderer(t, 3, 0).Preview(context.Background(), job)
if err != nil {
t.Fatal(err)
}
var kinds []string
for _, l := range p.Lines {
kinds = append(kinds, l.Kind+":"+l.Text)
}
if len(p.Lines) != 5 || p.Lines[0].Text != "one line" || p.Lines[1].Text != "" || p.Lines[3].Text != "" ||
p.Lines[4].Kind != escpos.LineCut {
t.Errorf("preview lines %q, want the text, three blank lines and the cut", kinds)
}
_, err = cutFeedRenderer(t, 3, 3).Render(context.Background(), job)
var limit *receipt.LineLimitError
if !errors.As(err, &limit) || limit.Lines != 4 {
t.Errorf("err = %v, want 4 lines over the limit of 3", err)
}
}
+19 -2
View File
@@ -46,6 +46,11 @@ type Options struct {
// (ESC 3) used while a box prints, to close the gaps in its vertical // (ESC 3) used while a box prints, to close the gaps in its vertical
// borders. Zero keeps the printer's default spacing. // borders. Zero keeps the printer's default spacing.
BoxLineSpacing int 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 // LineLimitError is returned for a job that would print more lines than
@@ -124,6 +129,7 @@ func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, er
profile: r.options.Profile, profile: r.options.Profile,
codePage: r.options.CodePage, codePage: r.options.CodePage,
lineSpacing: r.options.BoxLineSpacing, lineSpacing: r.options.BoxLineSpacing,
cutFeed: r.options.CutFeed,
} }
unknown := make(map[int]int) unknown := make(map[int]int)
for i, el := range job.Elements { for i, el := range job.Elements {
@@ -137,7 +143,7 @@ func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, er
} }
p.endLine() p.endLine()
if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut { if last := job.Elements[len(job.Elements)-1]; last.Type != TypeCut {
body.Cut(escpos.CutPartial, 0) p.cut(escpos.CutPartial)
} }
lines := p.lines * job.copies() lines := p.lines * job.copies()
if limit := r.options.MaxLines; limit > 0 && lines > limit { if limit := r.options.MaxLines; limit > 0 && lines > limit {
@@ -239,6 +245,7 @@ type printer struct {
profile escpos.Profile profile escpos.Profile
codePage escpos.CodePage codePage escpos.CodePage
lineSpacing int lineSpacing int
cutFeed int
x int x int
// lines counts printed lines: text lines, fed lines, and one for each // lines counts printed lines: text lines, fed lines, and one for each
@@ -314,13 +321,23 @@ func (p *printer) element(el Element, img *image.Paletted) error {
return err return err
} }
p.endLine() p.endLine()
p.b.Cut(mode, 0) p.cut(mode)
default: default:
return fmt.Errorf("unknown type %q", el.Type) return fmt.Errorf("unknown type %q", el.Type)
} }
return nil 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 // 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 // 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, // wider than the paper. The width is worked out as if the data were bytes,
+6
View File
@@ -0,0 +1,6 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac4201b4501437574
206665656420746573741b450020c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4bf0ab320546872656520626c616e6b206c696e6573206265666f
726520746865206375742e202020202020b30ac0c4c4c4c4c4206e7466792d70
617065722d746f70696320fa203330204e6f762031353a303220c4c4d90a1b45
001b2d001d42001d21001b4d001b64031d564200
+16
View File
@@ -0,0 +1,16 @@
{
"elements": [
{
"type": "box",
"children": [
{
"type": "text",
"text": "Three blank lines before the cut."
}
],
"title": "Cut feed test",
"title_bold": true,
"footer": "ntfy-paper-topic · 30 Nov 15:02"
}
]
}
+6
View File
@@ -0,0 +1,6 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac4201b45014f7665
726e6967687420fa20312068656c641b450020c4c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4bf0ab32031343a35372051756965742074687265652020202020
2020202020202020202020202020202020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4
c4c4c4c4c4c4c4c4c4c4c4c4c42031343a35372d31353a303220c4c4d90a1b45
001b2d001d42001d21001b4d001d564200
+16
View File
@@ -0,0 +1,16 @@
{
"elements": [
{
"type": "box",
"children": [
{
"type": "text",
"text": "14:57 Quiet three"
}
],
"title": "Overnight · 1 held",
"title_bold": true,
"footer": "14:57-15:02"
}
]
}
+6 -2
View File
@@ -29,8 +29,12 @@ AmbientCapabilities=
NoNewPrivileges=true NoNewPrivileges=true
# ── Sandboxing ──────────────────────────────────────────────────────────────── # ── Sandboxing ────────────────────────────────────────────────────────────────
# The daemon only reads its config and the system CA bundle; it writes no # The daemon reads its config and the system CA bundle, writes only the state
# files and opens no devices, so the whole file system is read-only to it. # 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).
StateDirectory=uberbringer
StateDirectoryMode=0700
ProtectSystem=strict ProtectSystem=strict
ProtectHome=true ProtectHome=true
PrivateTmp=true PrivateTmp=true