Add ntfy subscriptions with digests, quiet hours and a cut feed
[[ntfy.subscriptions]] tables make the daemon subscribe to ntfy topics itself and print each message as a notification card, so the phone's ntfy app is the only client. Each subscription is one ntfy.Subscriber in the daemon's errgroup: one event loop owns its state, and one goroutine per connection reads the JSON stream. internal/app hands its messages to modules.FromNtfy, Card, Validate and Submit with the source ntfy:<name> and the message's ID as ref, so ntfy never imports modules. The cursor is ntfy server time, never an ID. ntfy sends open before the replay, so only keepalives and messages dealt with move it, and a reconnect asks for two minutes before it, since a message is dated before its attachment is stored. The IDs of the messages a replay could send again are kept, at least the last 512 and 20,000 at most, so a flood in the overlap never reprints; when the cap forgets IDs a replay could send, the floor rises past them. A saved floor bounds replays: a first start sets it to the open event's time, and max_backlog (default 1h, at most 12h), measured by the server's clock as each connection tells it (its open event, else its Date, then the monotonic clock), never the host's, so replays are requested unclamped and filtered as they arrive, raises it when it clamps, so what it left out stays out. The state, with the held messages and the receipt times, is written atomically at most once a second and at shutdown. Redirects are never followed, so credentials never go to another address or over plain http. A stalled stream reconnects after twice the keepalive plus 15 s, failures back off 5 to 120 s with jitter, a 429 waits for Retry-After, and refused credentials, checked at startup through /auth, show as unauthorized and retry every 5 minutes. A full print queue pauses reading and retries the message from 1 s to 30 s, and the cursor moves past it only once it is queued. The paper budget is a strict window: at most rate_limit receipts (5) in any rate_window (10m), digests included; the rest are held and print on one digest card once there is room, and outside quiet hours bypass_priority (5) and above print at once. Quiet hours hold everything below their min_priority for one Overnight digest when the window ends, or drop it; windows cross midnight and keep their times of day when clocks change, also where the change skips midnight or a window's end. A message whose sequence printed before, on a card or a digest row, is marked (updated), or skipped with ntfy.format.updates = "skip"; the first of a sequence its publisher named prints plain. /healthz lists the subscriptions without changing how its status code is decided, and no credential, topic or message text reaches it, the logs or a config error. Subscriptions come from the file only, with strict keys and per-entry defaults; credentials are optional, at most one kind. ntfy.state_dir is required with a subscription: the unit gains StateDirectory=uberbringer, install.sh writes the path into a new config, and the Docker image sets it for a volume and runs as the fixed user 10001. README explains how to lock a self-hosted ntfy server down so that only your publishers can print. Breaking: printer.cut_feed (default 3) feeds blank lines before every cut, so the last line no longer sits right at the cut. They count toward format.max_lines once per copy, so a job within 3 lines a copy of the limit now fails. The renderer's option is 0 unless set, so the pinned receipts keep their bytes. testing/synctest drives the subscriber on a virtual clock, including a 24-hour soak with floods, repeats, refusals, a full queue, quiet hours and a restart that fails on any leaked goroutine; it replaces a 24-hour run on hardware. Tests over real sockets cover net/http's goroutines and redirects to plain http and to another port. Checked on the TM-T88IV against a live ntfy server: a phone message, quiet hours with priorities 3 and 5 and the Overnight digest, a stale cursor, a 30-minute outage with an update, a wrong token, and the three-line cut feed. The digest and the cut-feed card are pinned in TestPaperReceipts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1335ed0687
commit
fb76284129
52 files changed
+6464
-390
No files matched your search
@@ -0,0 +1,266 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/ntfy"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// weekdays are the config's day names.
|
||||
var weekdays = map[string]time.Weekday{
|
||||
"sun": time.Sunday, "mon": time.Monday, "tue": time.Tuesday, "wed": time.Wednesday,
|
||||
"thu": time.Thursday, "fri": time.Friday, "sat": time.Saturday,
|
||||
}
|
||||
|
||||
// newSubscribers returns a subscriber for each [[ntfy.subscriptions]]
|
||||
// table. It reads the credential files and makes sure the state directory
|
||||
// can be written, so that a mistake in either stops the daemon at startup.
|
||||
func newSubscribers(cfg *config.Config, logger *slog.Logger) ([]*ntfy.Subscriber, error) {
|
||||
subs := cfg.Ntfy.Subscriptions
|
||||
if len(subs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
dir := cfg.Ntfy.StateDir
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("config ntfy.state_dir: %w", err)
|
||||
}
|
||||
probe, err := os.CreateTemp(dir, ".write-check-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config ntfy.state_dir: %s cannot be written: %w", dir, err)
|
||||
}
|
||||
_ = probe.Close()
|
||||
_ = os.Remove(probe.Name())
|
||||
|
||||
subscribers := make([]*ntfy.Subscriber, 0, len(subs))
|
||||
for i, sc := range subs {
|
||||
at := fmt.Sprintf("config ntfy.subscriptions[%d]", i)
|
||||
o := ntfy.Options{
|
||||
Name: sc.Name,
|
||||
Server: sc.Server,
|
||||
Topics: sc.Topics,
|
||||
Token: sc.Token,
|
||||
User: sc.User,
|
||||
MinPriority: sc.MinPriority,
|
||||
MaxBacklog: sc.MaxBacklog,
|
||||
RateLimit: sc.RateLimit,
|
||||
RateWindow: sc.RateWindow,
|
||||
BypassPriority: sc.BypassPriority,
|
||||
Keepalive: sc.Keepalive,
|
||||
SkipUpdates: cfg.Ntfy.Format.Updates == "skip",
|
||||
StateFile: filepath.Join(dir, "ntfy-"+sc.Name+".json"),
|
||||
Logger: logger,
|
||||
Report: func(err error) { reportNtfy(sc.Name, "", err) },
|
||||
}
|
||||
if sc.TokenFile != "" {
|
||||
if o.Token, err = readSecret(sc.TokenFile, sc.Name, logger); err != nil {
|
||||
return nil, fmt.Errorf("%s.token_file: %w", at, err)
|
||||
}
|
||||
}
|
||||
if sc.PasswordFile != "" {
|
||||
if o.Password, err = readSecret(sc.PasswordFile, sc.Name, logger); err != nil {
|
||||
return nil, fmt.Errorf("%s.password_file: %w", at, err)
|
||||
}
|
||||
}
|
||||
if sc.Quiet != nil {
|
||||
if o.Quiet, err = quietHours(*sc.Quiet, cfg.Format.Timezone); err != nil {
|
||||
return nil, fmt.Errorf("%s.quiet: %w", at, err)
|
||||
}
|
||||
}
|
||||
sub, err := ntfy.New(o)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", at, err)
|
||||
}
|
||||
subscribers = append(subscribers, sub)
|
||||
}
|
||||
return subscribers, nil
|
||||
}
|
||||
|
||||
// readSecret reads a token or password from the file at path: its whole
|
||||
// content, without the spaces and line breaks around it. A file that the
|
||||
// group or others may read is logged as a warning, on systems with Unix
|
||||
// permissions.
|
||||
func readSecret(path, subscription string, logger *slog.Logger) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if info, err := os.Stat(path); err == nil && runtime.GOOS != "windows" && info.Mode().Perm()&0o077 != 0 {
|
||||
logger.Warn("ntfy credentials file can be read by others; make it 0600",
|
||||
"subscription", subscription, "file", path, "mode", fmt.Sprintf("%#o", info.Mode().Perm()))
|
||||
}
|
||||
secret := strings.TrimSpace(string(data))
|
||||
if secret == "" {
|
||||
return "", fmt.Errorf("%s is empty", path)
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
// quietHours turns the config's quiet hours into the subscriber's. The
|
||||
// zone defaults to formatZone.
|
||||
func quietHours(q config.NtfyQuiet, formatZone string) (*ntfy.Quiet, error) {
|
||||
start, err := time.Parse("15:04", q.Start)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start: %w", err)
|
||||
}
|
||||
end, err := time.Parse("15:04", q.End)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("end: %w", err)
|
||||
}
|
||||
zone := q.Timezone
|
||||
if zone == "" {
|
||||
zone = formatZone
|
||||
}
|
||||
loc, err := time.LoadLocation(zone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("timezone: %w", err)
|
||||
}
|
||||
quiet := &ntfy.Quiet{
|
||||
Start: ntfy.Clock{Hour: start.Hour(), Minute: start.Minute()},
|
||||
End: ntfy.Clock{Hour: end.Hour(), Minute: end.Minute()},
|
||||
Location: loc,
|
||||
MinPriority: q.MinPriority,
|
||||
Drop: q.Action == "drop",
|
||||
}
|
||||
for _, day := range q.Days {
|
||||
quiet.Days = append(quiet.Days, weekdays[day])
|
||||
}
|
||||
return quiet, nil
|
||||
}
|
||||
|
||||
// ntfySubmitter is the print queue as a subscription uses it.
|
||||
type ntfySubmitter interface {
|
||||
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
|
||||
}
|
||||
|
||||
// ntfyPrinter prints what a subscription delivers: each message as a
|
||||
// card, and held messages as a digest, through the print queue. Jobs carry
|
||||
// the source ntfy:<name> and the message's ID, or "digest".
|
||||
type ntfyPrinter struct {
|
||||
name string
|
||||
jobs ntfySubmitter
|
||||
env func() modules.Env
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// digestRef is the reference of a digest's job.
|
||||
const digestRef = "digest"
|
||||
|
||||
// Message prints m as a card, marked "(updated)" when updated. A full
|
||||
// queue is returned, for the subscription to offer m again.
|
||||
func (p *ntfyPrinter) Message(_ context.Context, m ntfy.Message, updated bool) error {
|
||||
n, err := modules.FromNtfy(m)
|
||||
if err != nil {
|
||||
p.logger.Debug("ntfy message has nothing to print", "subscription", p.name, "ntfy_id", m.ID)
|
||||
return nil
|
||||
}
|
||||
n.Updated = updated
|
||||
env := p.env()
|
||||
job, err := modules.Card(n, env.Card, env)
|
||||
p.reportFallback(m.ID, err)
|
||||
return p.submit(job, m.ID)
|
||||
}
|
||||
|
||||
// Digest prints the held messages on one receipt.
|
||||
func (p *ntfyPrinter) Digest(_ context.Context, d ntfy.Digest) error {
|
||||
env := p.env()
|
||||
job, err := modules.DigestCard(d, env.Card, env)
|
||||
p.reportFallback(digestRef, err)
|
||||
return p.submit(job, digestRef)
|
||||
}
|
||||
|
||||
// submit validates job and queues it. Card and DigestCard return valid
|
||||
// jobs, so a job that fails validation is a bug: it is logged and
|
||||
// reported, and dropped rather than retried.
|
||||
func (p *ntfyPrinter) submit(job receipt.Job, ref string) error {
|
||||
if err := job.Validate(); err != nil {
|
||||
problems := 1
|
||||
var ve *receipt.ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
problems = len(ve.Problems)
|
||||
}
|
||||
p.logger.Error("ntfy receipt is invalid", "subscription", p.name, "ref", ref, "problems", problems)
|
||||
reportNtfy(p.name, ref, fmt.Errorf("the receipt failed validation with %d problems", problems))
|
||||
return nil
|
||||
}
|
||||
status, err := p.jobs.Submit(job, printqueue.Meta{Source: "ntfy:" + p.name, Ref: ref})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.logger.Info("ntfy receipt queued", "subscription", p.name, "ref", ref, "job_id", status.ID.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
// reportFallback logs and reports a card that fell back to the plain
|
||||
// receipt, which still prints. The error never quotes the message.
|
||||
func (p *ntfyPrinter) reportFallback(ref string, err error) {
|
||||
var fallbackErr *modules.FallbackError
|
||||
if !errors.As(err, &fallbackErr) {
|
||||
return
|
||||
}
|
||||
attrs := []any{"subscription", p.name, "ref", ref, "err", fallbackErr.Error()}
|
||||
if fallbackErr.Stack != "" {
|
||||
attrs = append(attrs, "stack", fallbackErr.Stack)
|
||||
}
|
||||
p.logger.Error("ntfy card printed its fallback receipt", attrs...)
|
||||
reportNtfy(p.name, ref, fallbackErr)
|
||||
}
|
||||
|
||||
// reportNtfy sends a subscription's fault to Sentry, tagged with the
|
||||
// subscription and the message's ID, if there is one.
|
||||
func reportNtfy(name, ref string, err error) {
|
||||
hub := sentry.CurrentHub().Clone()
|
||||
hub.Scope().SetTag("subscription", name)
|
||||
if ref != "" {
|
||||
hub.Scope().SetTag("ref", ref)
|
||||
}
|
||||
hub.CaptureException(fmt.Errorf("ntfy %s: %w", name, err))
|
||||
}
|
||||
|
||||
// ntfyHealth returns the subscriptions' states for /healthz, or nil when
|
||||
// there are none.
|
||||
func ntfyHealth(subs []*ntfy.Subscriber) func() []server.NtfyHealth {
|
||||
if len(subs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return func() []server.NtfyHealth {
|
||||
out := make([]server.NtfyHealth, len(subs))
|
||||
for i, sub := range subs {
|
||||
st := sub.Status()
|
||||
out[i] = server.NtfyHealth{
|
||||
Name: st.Name,
|
||||
State: st.State,
|
||||
ConnectedSince: timePtr(st.ConnectedSince),
|
||||
LastMessageAt: timePtr(st.LastMessageAt),
|
||||
Printed: st.Printed,
|
||||
Digested: st.Digested,
|
||||
Held: st.Held,
|
||||
LastError: st.LastError,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
// timePtr returns t in UTC, or nil for the zero time.
|
||||
func timePtr(t time.Time) *time.Time {
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
t = t.UTC().Truncate(time.Second)
|
||||
return &t
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/modules"
|
||||
"uberbringer/internal/pkg/ntfy"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// TestServeWithSubscription runs the daemon with a subscription to a fake
|
||||
// ntfy server: a message on the stream prints, /healthz lists the
|
||||
// subscription as connected without changing its status code, and the
|
||||
// state is saved at shutdown.
|
||||
func TestServeWithSubscription(t *testing.T) {
|
||||
printer := startFakePrinter(t)
|
||||
var auth sync.Map
|
||||
ntfyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
auth.Store(r.URL.Path, r.Header.Get("Authorization"))
|
||||
if strings.HasSuffix(r.URL.Path, "/auth") {
|
||||
fmt.Fprint(w, `{"success":true}`)
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
fmt.Fprintf(w, "{\"id\":\"open1\",\"time\":%d,\"event\":\"open\",\"topic\":\"alerts\"}\n", now)
|
||||
fmt.Fprintf(w, "{\"id\":\"msg1\",\"time\":%d,\"event\":\"message\",\"topic\":\"alerts\",\"title\":\"Grüße vom Abo\",\"priority\":4}\n", now)
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done()
|
||||
}))
|
||||
defer ntfyServer.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
tokenFile := filepath.Join(dir, "ntfy.token")
|
||||
if err := os.WriteFile(tokenFile, []byte("tk_fromfile\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const secret = "end-to-end-secret-end-to-end-secret!"
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
body := fmt.Sprintf(`
|
||||
[api]
|
||||
secret = %q
|
||||
[printer]
|
||||
address = "127.0.0.1"
|
||||
port = %d
|
||||
[log]
|
||||
level = "error"
|
||||
[ntfy]
|
||||
state_dir = %q
|
||||
[[ntfy.subscriptions]]
|
||||
name = "home"
|
||||
server = %q
|
||||
allow_insecure = true
|
||||
topics = ["alerts"]
|
||||
token_file = %q
|
||||
`, secret, printer.addr.Port, filepath.Join(dir, "state"), ntfyServer.URL, tokenFile)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen) }()
|
||||
|
||||
waitFor(t, func() bool {
|
||||
// "Grüße" in CP437: ü is 0x81, ß is 0xE1.
|
||||
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e vom Abo"))
|
||||
})
|
||||
if got, _ := auth.Load("/alerts/json"); got != "Bearer tk_fromfile" {
|
||||
t.Errorf("Authorization %q, want the token from the file", got)
|
||||
}
|
||||
|
||||
var health struct {
|
||||
Status string
|
||||
Ntfy []struct {
|
||||
Name, State string
|
||||
Printed int
|
||||
}
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
resp, err := http.Get("http://" + ln.Addr().String() + "/healthz")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_ = json.NewDecoder(resp.Body).Decode(&health)
|
||||
return len(health.Ntfy) == 1 && health.Ntfy[0].Printed == 1
|
||||
})
|
||||
if n := health.Ntfy[0]; n.Name != "home" || n.State != "connected" {
|
||||
t.Errorf("ntfy health %+v", n)
|
||||
}
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-served:
|
||||
if err != nil {
|
||||
t.Fatalf("serve returned %v after shutdown", err)
|
||||
}
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("serve did not shut down")
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, "state", "ntfy-home.json"))
|
||||
if err != nil || !bytes.Contains(data, []byte(`"msg1"`)) {
|
||||
t.Errorf("state file %s, %v; want it to remember msg1", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The daemon refuses to start with a credentials file it cannot read, or
|
||||
// one that is empty.
|
||||
func TestNewSubscribersErrors(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
empty := filepath.Join(dir, "empty")
|
||||
if err := os.WriteFile(empty, []byte(" \n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := config.Default()
|
||||
cfg.Ntfy.StateDir = filepath.Join(dir, "state")
|
||||
sub := config.DefaultSubscription()
|
||||
sub.Name, sub.Server, sub.Topics = "home", "https://ntfy.sh", []string{"alerts"}
|
||||
for _, tt := range []struct {
|
||||
file, want string
|
||||
}{
|
||||
{filepath.Join(dir, "missing"), "ntfy.subscriptions[0].token_file"},
|
||||
{empty, "is empty"},
|
||||
} {
|
||||
sub.TokenFile = tt.file
|
||||
cfg.Ntfy.Subscriptions = []config.NtfySubscription{sub}
|
||||
if _, err := newSubscribers(&cfg, slog.New(slog.DiscardHandler)); err == nil || !strings.Contains(err.Error(), tt.want) {
|
||||
t.Errorf("token_file %s: err = %v, want %q", tt.file, err, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A credentials file others may read is accepted with a warning.
|
||||
func TestReadSecretWarnsAboutPermissions(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Windows has no Unix permissions")
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "token")
|
||||
if err := os.WriteFile(path, []byte("tk_secret\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logs bytes.Buffer
|
||||
got, err := readSecret(path, "home", slog.New(slog.NewTextHandler(&logs, nil)))
|
||||
if err != nil || got != "tk_secret" {
|
||||
t.Fatalf("readSecret = %q, %v", got, err)
|
||||
}
|
||||
if out := logs.String(); !strings.Contains(out, "can be read by others") || strings.Contains(out, "tk_secret") {
|
||||
t.Errorf("log %q, want a warning without the secret", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuietHours(t *testing.T) {
|
||||
q, err := quietHours(config.NtfyQuiet{Start: "22:30", End: "06:45", Days: []string{"fri", "sat"},
|
||||
MinPriority: 4, Action: "drop"}, "Europe/London")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if q.Start != (ntfy.Clock{Hour: 22, Minute: 30}) || q.End != (ntfy.Clock{Hour: 6, Minute: 45}) ||
|
||||
q.Location.String() != "Europe/London" || q.MinPriority != 4 || !q.Drop ||
|
||||
len(q.Days) != 2 || q.Days[0] != time.Friday || q.Days[1] != time.Saturday {
|
||||
t.Errorf("quiet %+v", q)
|
||||
}
|
||||
q, err = quietHours(config.DefaultQuiet(), "UTC")
|
||||
if err != nil || q.Location != time.UTC || q.Drop || len(q.Days) != 7 {
|
||||
t.Errorf("quiet %+v, %v", q, err)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeQueue records the jobs submitted to it, or refuses them.
|
||||
type fakeQueue struct {
|
||||
jobs []receipt.Job
|
||||
metas []printqueue.Meta
|
||||
err error
|
||||
}
|
||||
|
||||
func (q *fakeQueue) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error) {
|
||||
if q.err != nil {
|
||||
return printqueue.Status{}, q.err
|
||||
}
|
||||
q.jobs = append(q.jobs, job)
|
||||
q.metas = append(q.metas, meta)
|
||||
return printqueue.Status{}, nil
|
||||
}
|
||||
|
||||
func testEnv() modules.Env {
|
||||
return modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
|
||||
}
|
||||
|
||||
// The handler prints a message as a card with its source and ID, marks an
|
||||
// update, prints a digest, skips what has nothing to print, and hands a
|
||||
// full queue back for a retry. Its log lines carry no text.
|
||||
func TestNtfyPrinter(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
q := &fakeQueue{}
|
||||
p := &ntfyPrinter{name: "home", jobs: q, env: testEnv, logger: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))}
|
||||
ctx := context.Background()
|
||||
|
||||
m := ntfy.Message{ID: "msg1", Event: "message", Topic: "alerts", Title: "Disk almost full", Message: "SecretBody"}
|
||||
if err := p.Message(ctx, m, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.Message(ctx, ntfy.Message{ID: "b64", Event: "message", Message: "AAE=", Encoding: "base64"}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.Digest(ctx, ntfy.Digest{Rows: []ntfy.DigestRow{{ID: "x", Title: "SecretRow"}}, Count: 1, Until: testEnv().Now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(q.jobs) != 2 {
|
||||
t.Fatalf("%d jobs, want the card and the digest", len(q.jobs))
|
||||
}
|
||||
if q.metas[0] != (printqueue.Meta{Source: "ntfy:home", Ref: "msg1"}) || q.metas[1] != (printqueue.Meta{Source: "ntfy:home", Ref: "digest"}) {
|
||||
t.Errorf("metas %+v", q.metas)
|
||||
}
|
||||
if title := q.jobs[0].Elements[0].Title; title != "Disk almost full (updated)" {
|
||||
t.Errorf("card title %q, want the update marked", title)
|
||||
}
|
||||
|
||||
q.err = printqueue.ErrQueueFull
|
||||
if err := p.Message(ctx, m, false); !errors.Is(err, printqueue.ErrQueueFull) {
|
||||
t.Errorf("err = %v, want the full queue back", err)
|
||||
}
|
||||
|
||||
p.reportFallback("msg1", &modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"})
|
||||
p.reportFallback("msg2", nil)
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, "ntfy card printed its fallback receipt") || !strings.Contains(out, "ref=msg1") ||
|
||||
!strings.Contains(out, "goroutine 1") || strings.Contains(out, "msg2") {
|
||||
t.Errorf("log %q, want the fallback logged with the ID", out)
|
||||
}
|
||||
for _, secret := range []string{"Disk almost full", "SecretBody", "SecretRow"} {
|
||||
if strings.Contains(out, secret) {
|
||||
t.Errorf("the log holds %q", secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func TestPreviewCommandReadsStdin(t *testing.T) {
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := " ── stdin ──\n - - - - - - - partial cut - - - - - - - -\n"; out.String() != want {
|
||||
if want := " ── stdin ──\n\n\n\n - - - - - - - partial cut - - - - - - - -\n"; out.String() != want {
|
||||
t.Errorf("output = %q, want %q", out.String(), want)
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ func TestPreviewCommandErrors(t *testing.T) {
|
||||
{"unknown field", `{"elements":[{"type":"rule","colour":"red"}]}`, "", `unknown field "colour"`},
|
||||
{"invalid", `{"elements":[{"type":"box"},{"type":"kv"}]}`, "",
|
||||
"invalid job:\n elements[0] (box): text or children is required\n elements[1] (kv): pairs: at least one pair is required"},
|
||||
{"too many lines", `{"elements":[{"type":"feed","lines":20}]}`, "[format]\nmax_lines = 10\n", "receipt would print 20 lines, limit is 10"},
|
||||
{"too many lines", `{"elements":[{"type":"feed","lines":20}]}`, "[format]\nmax_lines = 10\n", "receipt would print 23 lines, limit is 10"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -129,6 +129,7 @@ func TestPreviewCommandModule(t *testing.T) {
|
||||
"│ [ ] Milk │\n" +
|
||||
"│ [√] Eggs │\n" +
|
||||
"└───────────────────────────── kitchen ──┘\n" +
|
||||
"\n\n\n" +
|
||||
" - - - - - - - partial cut - - - - - - - -\n"
|
||||
if out.String() != want || errOut.Len() != 0 {
|
||||
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
|
||||
@@ -159,6 +160,7 @@ func TestPreviewCommandNtfy(t *testing.T) {
|
||||
"║ Tags: nas01 ║",
|
||||
"╚══════════════ backups · 29 Nov 21:04 ══╝",
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
"", "", "",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
{"compact, with markers", "[format]\ntimezone = \"UTC\"\n[ntfy.format]\nstyle = \"compact\"\n" +
|
||||
@@ -167,6 +169,7 @@ func TestPreviewCommandNtfy(t *testing.T) {
|
||||
"/!\\ Backup FAILED on nas01",
|
||||
"Job nightly-offsite exited with code 2",
|
||||
"after 3h12m. Last good run: 2 days ago.",
|
||||
"", "", "",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
}
|
||||
|
||||
@@ -71,6 +71,11 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
}
|
||||
defer flushSentry()
|
||||
|
||||
subscribers, err := newSubscribers(cfg, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fetcher := safehttp.New(safehttp.Options{
|
||||
Timeout: cfg.Images.Timeout,
|
||||
MaxBytes: cfg.Images.MaxBytes,
|
||||
@@ -113,6 +118,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
Previewer: renderer,
|
||||
Modules: registry,
|
||||
ModuleEnv: env,
|
||||
Ntfy: ntfyHealth(subscribers),
|
||||
}, logger)
|
||||
|
||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||
@@ -130,6 +136,10 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
|
||||
group, groupCtx := errgroup.WithContext(ctx)
|
||||
group.Go(func() error { return queue.Run(groupCtx) })
|
||||
group.Go(func() error { return srv.Serve(groupCtx, ln) })
|
||||
for _, sub := range subscribers {
|
||||
handler := &ntfyPrinter{name: sub.Status().Name, jobs: queue, env: env, logger: logger}
|
||||
group.Go(func() error { return sub.Run(groupCtx, handler) })
|
||||
}
|
||||
err = group.Wait()
|
||||
logger.Info("shutdown complete")
|
||||
return err
|
||||
@@ -157,6 +167,7 @@ func rendererOptions(cfg *config.Config) (receipt.Options, error) {
|
||||
MaxHeight: cfg.Images.MaxHeight,
|
||||
MaxLines: cfg.Format.MaxLines,
|
||||
BoxLineSpacing: cfg.Printer.BoxLineSpacing,
|
||||
CutFeed: cfg.Printer.CutFeed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -183,12 +183,43 @@ type printerHealth struct {
|
||||
// healthResponse is the body of GET /healthz.
|
||||
type healthResponse struct {
|
||||
// Status is ok, degraded when the printer is not ready, or unavailable
|
||||
// when it is unreachable or did not answer in time.
|
||||
// when it is unreachable or did not answer in time. It depends on the
|
||||
// printer alone.
|
||||
Status string `json:"status" jsonschema:"enum=ok,enum=degraded,enum=unavailable"`
|
||||
// Printer is the printer's state.
|
||||
Printer printerHealth `json:"printer"`
|
||||
// Queue is the print queue's state.
|
||||
Queue queueHealth `json:"queue"`
|
||||
// Ntfy is the state of each ntfy subscription, in the order of the
|
||||
// config; absent when none is configured.
|
||||
Ntfy []NtfyHealth `json:"ntfy,omitempty"`
|
||||
}
|
||||
|
||||
// NtfyHealth is the state of an ntfy subscription. It holds no
|
||||
// credentials and nothing a message says.
|
||||
type NtfyHealth struct {
|
||||
// Name is the subscription's name from the config.
|
||||
Name string `json:"name"`
|
||||
// State is connecting, connected, backoff while it waits to reconnect
|
||||
// after a failure, or unauthorized when the server refused its
|
||||
// credentials; it then tries again every five minutes.
|
||||
State string `json:"state" jsonschema:"enum=connecting,enum=connected,enum=backoff,enum=unauthorized"`
|
||||
// ConnectedSince is when the current connection opened; absent while
|
||||
// there is none.
|
||||
ConnectedSince *time.Time `json:"connected_since,omitempty"`
|
||||
// LastMessageAt is when the last message arrived; absent until one
|
||||
// has.
|
||||
LastMessageAt *time.Time `json:"last_message_at,omitempty"`
|
||||
// Printed is how many messages printed on a card of their own since
|
||||
// the daemon started.
|
||||
Printed int `json:"printed"`
|
||||
// Digested is how many messages were held for a digest since the
|
||||
// daemon started: over the rate limit, or in quiet hours.
|
||||
Digested int `json:"digested"`
|
||||
// Held is how many messages wait for the next digest.
|
||||
Held int `json:"held"`
|
||||
// LastError says why the last connection failed; empty once one opens.
|
||||
LastError string `json:"last_error"`
|
||||
}
|
||||
|
||||
// queueHealth is the queue part of the /healthz response.
|
||||
@@ -205,6 +236,9 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
|
||||
|
||||
var resp healthResponse
|
||||
resp.Queue.Pending = s.jobs.Pending()
|
||||
if s.ntfy != nil {
|
||||
resp.Ntfy = s.ntfy()
|
||||
}
|
||||
httpStatus := fiber.StatusOK
|
||||
|
||||
st, err := s.settledPrinterStatus(ctx)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
gotoken "go/token"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// /healthz lists the subscriptions, and its status code still follows the
|
||||
// printer alone: a subscription that is down turns nothing to 503, and
|
||||
// one that is up turns nothing to 200.
|
||||
func TestHealthListsSubscriptions(t *testing.T) {
|
||||
since := time.Date(2026, 11, 29, 20, 58, 1, 0, time.UTC)
|
||||
last := time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC)
|
||||
subs := []NtfyHealth{
|
||||
{Name: "home", State: "connected", ConnectedSince: &since, LastMessageAt: &last, Printed: 12, Digested: 2, Held: 1},
|
||||
{Name: "work", State: "unauthorized", LastError: "HTTP 401: the server refused the credentials"},
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
printer *fakePrinter
|
||||
want int
|
||||
}{
|
||||
{"printer ready", &fakePrinter{statuses: []escpos.Status{{Online: true}}}, http.StatusOK},
|
||||
{"printer unreachable", &fakePrinter{err: errors.New("connection refused")}, http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, tt.printer)
|
||||
s.ntfy = func() []NtfyHealth { return subs }
|
||||
resp, body := send(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status %d, want %d", resp.StatusCode, tt.want)
|
||||
}
|
||||
var got healthResponse
|
||||
if err := json.Unmarshal(body, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Ntfy, subs) {
|
||||
t.Errorf("ntfy = %+v, want %+v", got.Ntfy, subs)
|
||||
}
|
||||
for _, want := range []string{`"name":"home","state":"connected","connected_since":"2026-11-29T20:58:01Z"`,
|
||||
`"printed":12,"digested":2,"held":1,"last_error":""`, `"name":"work","state":"unauthorized","printed":0`} {
|
||||
if !strings.Contains(string(body), want) {
|
||||
t.Errorf("body %s lacks %s", body, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{statuses: []escpos.Status{{Online: true}}})
|
||||
_, body := send(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
if strings.Contains(string(body), `"ntfy"`) {
|
||||
t.Errorf("body %s lists ntfy without subscriptions", body)
|
||||
}
|
||||
}
|
||||
|
||||
// The state enum of a subscription lists exactly the ntfy package's
|
||||
// states.
|
||||
func TestNtfyStateEnumListsEveryState(t *testing.T) {
|
||||
file, err := parser.ParseFile(gotoken.NewFileSet(), "../../../pkg/ntfy/status.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var states []string
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
spec, ok := n.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
for i, name := range spec.Names {
|
||||
if !strings.HasPrefix(name.Name, "State") || i >= len(spec.Values) {
|
||||
continue
|
||||
}
|
||||
if lit, ok := spec.Values[i].(*ast.BasicLit); ok && lit.Kind == gotoken.STRING {
|
||||
v, _ := strconv.Unquote(lit.Value)
|
||||
states = append(states, v)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
slices.Sort(states)
|
||||
if enum := enumOf(t, reflect.TypeFor[NtfyHealth](), "State"); len(states) == 0 || !slices.Equal(states, enum) {
|
||||
t.Errorf("NtfyHealth.State enum %v, ntfy State constants %v", enum, states)
|
||||
}
|
||||
}
|
||||
@@ -167,10 +167,12 @@ func Routes() []Route {
|
||||
Method: http.MethodGet,
|
||||
Path: "/healthz",
|
||||
OperationID: "getHealth",
|
||||
Summary: "Printer and queue health",
|
||||
Summary: "Printer, queue and subscription health",
|
||||
Description: "Reads the printer's real-time status. A printer that looks not ready is read again " +
|
||||
"750 ms later, and only a problem that is still there gives 503. A printer that does not " +
|
||||
"answer status requests is reported as status unknown with 200.",
|
||||
"answer status requests is reported as status unknown with 200. The ntfy subscriptions, " +
|
||||
"when any are configured, are listed with their state; the status code depends on the " +
|
||||
"printer alone.",
|
||||
Tag: "health",
|
||||
NoStore: true,
|
||||
Responses: []Response{
|
||||
|
||||
@@ -58,6 +58,10 @@ type Deps struct {
|
||||
// ModuleEnv returns what a module may know when it builds a job: the
|
||||
// time now, and the zone and layout times print in.
|
||||
ModuleEnv func() modules.Env
|
||||
|
||||
// Ntfy returns the state of each ntfy subscription for /healthz. Nil
|
||||
// when none is configured.
|
||||
Ntfy func() []NtfyHealth
|
||||
}
|
||||
|
||||
// Info describes the running build for the index route.
|
||||
@@ -114,6 +118,7 @@ type Server struct {
|
||||
previewer Previewer
|
||||
modules Modules
|
||||
moduleEnv func() modules.Env
|
||||
ntfy func() []NtfyHealth
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
@@ -139,6 +144,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
|
||||
previewer: deps.Previewer,
|
||||
modules: deps.Modules,
|
||||
moduleEnv: deps.ModuleEnv,
|
||||
ntfy: deps.Ntfy,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
|
||||
@@ -10,4 +10,7 @@ Used ................................. 94%
|
||||
Inverted <b>not a tag</b> ?
|
||||
[image 384 dots: logo.png]
|
||||
[qr: https://example.com]
|
||||
|
||||
|
||||
|
||||
- - - - - - - partial cut - - - - - - - -
|
||||
+380
-19
@@ -8,8 +8,10 @@ import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -34,6 +36,9 @@ const MinSecretLength = 32
|
||||
// takes.
|
||||
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].
|
||||
const (
|
||||
LogFormatText = "text"
|
||||
@@ -106,6 +111,10 @@ type PrinterConfig struct {
|
||||
// keeps the printer's default 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"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout"`
|
||||
|
||||
@@ -129,27 +138,152 @@ type FormatConfig struct {
|
||||
TimeLayout string `mapstructure:"time_layout"`
|
||||
}
|
||||
|
||||
// Values of NtfyFormatConfig's settings.
|
||||
// Values of the ntfy settings.
|
||||
var (
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
NtfyQRModes = []string{"all", "first", "none"}
|
||||
NtfyStyles = []string{"auto", "box", "compact"}
|
||||
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
|
||||
// most characters in a marker.
|
||||
// Limits of the ntfy settings.
|
||||
const (
|
||||
// MaxNtfyLines is the largest ntfy.format.max_lines.
|
||||
MaxNtfyLines = 400
|
||||
MaxMarker = 16
|
||||
|
||||
// MaxMarker is the most characters in a marker.
|
||||
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
|
||||
// modules.
|
||||
// modules and from the subscriptions.
|
||||
type NtfyConfig struct {
|
||||
Format NtfyFormatConfig `mapstructure:"format"`
|
||||
|
||||
// Markers override the markers printed for tags, by tag: an empty
|
||||
// marker hides the tag.
|
||||
Markers map[string]string `mapstructure:"markers"`
|
||||
|
||||
// StateDir is the directory each subscription keeps its state in: its
|
||||
// cursor, the IDs it has seen and the messages it holds. Required when
|
||||
// a subscription is configured.
|
||||
StateDir string `mapstructure:"state_dir"`
|
||||
|
||||
// Subscriptions are the ntfy servers and topics whose messages print.
|
||||
// They come from the file only: a list of tables has no environment
|
||||
// variable.
|
||||
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.
|
||||
@@ -169,6 +303,11 @@ type NtfyFormatConfig struct {
|
||||
|
||||
// Markdown lays out markdown messages.
|
||||
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.
|
||||
@@ -237,6 +376,7 @@ func Default() Config {
|
||||
// printer makes it break words at the right edge.
|
||||
Model: "tm-t88",
|
||||
CodePage: "cp437",
|
||||
CutFeed: 3,
|
||||
DialTimeout: 5 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
Retries: 3,
|
||||
@@ -254,6 +394,7 @@ func Default() Config {
|
||||
QR: "all",
|
||||
Images: true,
|
||||
Markdown: true,
|
||||
Updates: "print",
|
||||
},
|
||||
},
|
||||
Queue: QueueConfig{
|
||||
@@ -293,7 +434,7 @@ func Load(path string) (*Config, error) {
|
||||
var envSet []string
|
||||
bound := map[string]bool{PathEnvVar: true}
|
||||
for _, key := range slices.Sorted(maps.Keys(keys)) {
|
||||
if keys[key] == section {
|
||||
if kind := keys[key]; kind != setting && kind != tableSetting {
|
||||
continue
|
||||
}
|
||||
name := envVar(key)
|
||||
@@ -340,13 +481,7 @@ func Load(path string) (*Config, error) {
|
||||
|
||||
var cfg Config
|
||||
err := v.Unmarshal(&cfg,
|
||||
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
|
||||
durations(),
|
||||
stringToList(),
|
||||
stringToTable(),
|
||||
refuseFractions(),
|
||||
stringToNumberOrFlag(),
|
||||
)),
|
||||
viper.DecodeHook(decodeHooks()),
|
||||
// Values are taken as written, apart from the strings that hooks
|
||||
// above parse: environment variables are strings.
|
||||
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
|
||||
@@ -417,14 +552,21 @@ func readFile(path string) (map[string]any, error) {
|
||||
return table, nil
|
||||
}
|
||||
|
||||
// keyKind tells a setting from a section that holds settings, and from a
|
||||
// table setting, whose keys are the user's own.
|
||||
// keyKind tells a setting from a section that holds settings, from a
|
||||
// table setting, whose keys are the user's own, and from a list of tables.
|
||||
type keyKind int
|
||||
|
||||
const (
|
||||
setting keyKind = iota + 1
|
||||
section
|
||||
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
|
||||
@@ -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
|
||||
// giving way to it; the table settings default to empty.
|
||||
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:
|
||||
v.SetDefault(key, field.Interface())
|
||||
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
|
||||
// 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
|
||||
@@ -485,7 +658,7 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
kind = 0
|
||||
}
|
||||
switch {
|
||||
case isTable && kind == section:
|
||||
case isTable && (kind == section || kind == listSection):
|
||||
u, c := checkKeys(sub, path, key, keys)
|
||||
unknown = append(unknown, u...)
|
||||
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)
|
||||
unknown = append(unknown, u...)
|
||||
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:
|
||||
unknown = append(unknown, path)
|
||||
}
|
||||
@@ -501,6 +678,38 @@ func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyK
|
||||
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
|
||||
// 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
|
||||
@@ -530,6 +739,50 @@ func displayKey(name string) string {
|
||||
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
|
||||
// is refused, since the decoder would read it as nanoseconds.
|
||||
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.BoxLineSpacing >= 0 && p.BoxLineSpacing <= 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.Retries >= 0, "printer.retries must not be negative")
|
||||
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,
|
||||
"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.History >= 0, "queue.history must not be negative")
|
||||
@@ -732,6 +988,111 @@ func (c *Config) Validate() error {
|
||||
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
|
||||
// formats: two times that differ in every field format differently. A
|
||||
// layout with none of Go's reference values, such as "HH:MM", prints
|
||||
|
||||
@@ -53,8 +53,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
|
||||
if cfg.Images.AllowPrivateNetworks {
|
||||
t.Error("private networks must be blocked by default")
|
||||
}
|
||||
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 {
|
||||
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing)
|
||||
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 || cfg.Printer.CutFeed != 3 {
|
||||
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" {
|
||||
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",
|
||||
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",
|
||||
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 ||
|
||||
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.Printer.CutFeed != def.Printer.CutFeed ||
|
||||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout ||
|
||||
cfg.Ntfy.Format != def.Ntfy.Format || len(cfg.Ntfy.Markers) != 0 {
|
||||
cfg.Ntfy.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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNtfy(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -409,6 +422,7 @@ max_lines = 400
|
||||
qr = "first"
|
||||
images = false
|
||||
markdown = false
|
||||
updates = "skip"
|
||||
[ntfy.markers]
|
||||
backup = "[B]"
|
||||
skull = ""
|
||||
@@ -417,7 +431,7 @@ skull = ""
|
||||
if err != nil {
|
||||
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 {
|
||||
t.Errorf("format %+v, want %+v", cfg.Ntfy.Format, want)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ func (c *Config) Value(key string) (string, error) {
|
||||
if v.Kind() == reflect.Struct {
|
||||
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) {
|
||||
case time.Duration:
|
||||
return value.String(), nil
|
||||
|
||||
@@ -20,10 +20,10 @@ import (
|
||||
|
||||
// TestNtfyBuildsThePaperJobs checks that the ntfy module still builds the
|
||||
// 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
|
||||
// a host at UTC-6 with the default card options.
|
||||
// the receipt package pins: the messages in testdata/paper, built on a
|
||||
// host at UTC-6 with the default card options.
|
||||
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) {
|
||||
body, err := os.ReadFile(filepath.Join("testdata", "paper", "ntfy-"+name+".json"))
|
||||
if err != nil {
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -83,12 +83,7 @@ func decodeNtfy(body []byte) (ntfy.Message, error) {
|
||||
// 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.
|
||||
func FromNtfy(m ntfy.Message) (Notice, error) {
|
||||
switch m.Event {
|
||||
case "", ntfy.EventMessage:
|
||||
default:
|
||||
return Notice{}, ErrSkip
|
||||
}
|
||||
if strings.EqualFold(m.Encoding, ntfy.EncodingBase64) {
|
||||
if !m.Printable() {
|
||||
return Notice{}, ErrSkip
|
||||
}
|
||||
n := Notice{
|
||||
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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 - - - - - - - -
|
||||
@@ -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}
|
||||
@@ -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}))
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
// Package ntfy holds the wire types of ntfy (https://ntfy.sh), the
|
||||
// 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
|
||||
|
||||
import "strings"
|
||||
|
||||
// Event types of a Message.
|
||||
const (
|
||||
EventOpen = "open"
|
||||
@@ -74,6 +78,25 @@ func (m Message) Priority() int {
|
||||
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
|
||||
// actions send a request with Method, Headers and Body; broadcast actions
|
||||
// send an Android intent with Extras; copy actions copy Value to the
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}
|
||||
@@ -66,7 +66,8 @@ type Status struct {
|
||||
// State is where the job is in its lifecycle.
|
||||
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,
|
||||
// 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"`
|
||||
// Error says why a failed job failed.
|
||||
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
|
||||
// logged with it; it never holds what the job prints.
|
||||
type Meta struct {
|
||||
// Source is the kind of client that sent the job, e.g. print or
|
||||
// module:ntfy.
|
||||
// Source is the kind of client that sent the job, e.g. print,
|
||||
// module:ntfy or ntfy:home.
|
||||
Source string
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
|
||||
@@ -75,10 +75,15 @@ func TestRenderCompat(t *testing.T) {
|
||||
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,
|
||||
// with the file their bytes are pinned in and, for a job with an image
|
||||
// URL, the image it was printed with. The bytes are rendered for a TM-T88
|
||||
// in CP437 with the default options.
|
||||
var paperReceipts = []struct{ job, hex, image string }{
|
||||
// with the file their bytes are pinned in, for a job with an image URL the
|
||||
// image it was printed with, and the blank lines it fed before its cut.
|
||||
// The bytes are rendered for a TM-T88 in CP437 with the default options
|
||||
// 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("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"),
|
||||
@@ -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-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-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
|
||||
@@ -110,6 +117,7 @@ func TestPaperReceipts(t *testing.T) {
|
||||
MaxPixels: 25_000_000,
|
||||
MaxHeight: 4000,
|
||||
MaxLines: 2000,
|
||||
CutFeed: receiptFile.cutFeed,
|
||||
}, fetcher)
|
||||
got, err := r.Render(context.Background(), readJob(t, receiptFile.job))
|
||||
if err != nil {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,11 @@ type Options struct {
|
||||
// (ESC 3) used while a box prints, to close the gaps in its vertical
|
||||
// borders. Zero keeps the printer's default spacing.
|
||||
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
|
||||
@@ -124,6 +129,7 @@ func (r *Renderer) render(job Job, images map[int]*image.Paletted) (rendered, er
|
||||
profile: r.options.Profile,
|
||||
codePage: r.options.CodePage,
|
||||
lineSpacing: r.options.BoxLineSpacing,
|
||||
cutFeed: r.options.CutFeed,
|
||||
}
|
||||
unknown := make(map[int]int)
|
||||
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()
|
||||
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()
|
||||
if limit := r.options.MaxLines; limit > 0 && lines > limit {
|
||||
@@ -239,6 +245,7 @@ type printer struct {
|
||||
profile escpos.Profile
|
||||
codePage escpos.CodePage
|
||||
lineSpacing int
|
||||
cutFeed int
|
||||
x int
|
||||
|
||||
// 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
|
||||
}
|
||||
p.endLine()
|
||||
p.b.Cut(mode, 0)
|
||||
p.cut(mode)
|
||||
default:
|
||||
return fmt.Errorf("unknown type %q", el.Type)
|
||||
}
|
||||
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
|
||||
// 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,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
1b401b74001b61001b4d001d21001b45001b2d001d4200dac4201b4501437574
|
||||
206665656420746573741b450020c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
|
||||
c4c4c4c4c4c4bf0ab320546872656520626c616e6b206c696e6573206265666f
|
||||
726520746865206375742e202020202020b30ac0c4c4c4c4c4206e7466792d70
|
||||
617065722d746f70696320fa203330204e6f762031353a303220c4c4d90a1b45
|
||||
001b2d001d42001d21001b4d001b64031d564200
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
1b401b74001b61001b4d001d21001b45001b2d001d4200dac4201b45014f7665
|
||||
726e6967687420fa20312068656c641b450020c4c4c4c4c4c4c4c4c4c4c4c4c4
|
||||
c4c4c4c4c4c4bf0ab32031343a35372051756965742074687265652020202020
|
||||
2020202020202020202020202020202020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4
|
||||
c4c4c4c4c4c4c4c4c4c4c4c4c42031343a35372d31353a303220c4c4d90a1b45
|
||||
001b2d001d42001d21001b4d001d564200
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user