Every digest went to the print queue under the fixed reference "digest", so after a crash the queue could not tell a digest it had queued from a new one. Once queued jobs survive a restart, a crash in the second between queueing a digest and saving the subscription's state would print it twice; the same window exists today for a digest that printed in that second. A digest now gets a reference of its own when it is made, "digest_" and a TypeID, and is saved with it in the subscription's state, apart from the held messages. It is offered to the queue only once that save has succeeded, and dropped once the queue takes it; while the state file cannot be written, digests wait. A restart with a saved digest offers that digest again first, with the same rows and reference, and the queue's duplicate check answers with the earlier job while it holds it. Messages held after a digest is made wait for the next one, also while quiet hours delay the saved digest after a restart: added to a digest the queue already holds, they would never print. The digest is submitted as unique, like a card. A digest can cost one more state save, two fsyncs. The reference shows in the log lines and Sentry reports where "digest" did. This completes stage 1c of docs/plans/job-store.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1076 lines
32 KiB
Go
1076 lines
32 KiB
Go
package ntfy
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"math/rand/v2"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"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
|
|
|
|
// cursorSaveEvery is the least time between two writes when only the
|
|
// cursor has moved, as each keepalive moves it. A saved cursor that is
|
|
// behind costs only a longer replay after a crash, and the saved IDs
|
|
// drop the messages it sends again.
|
|
cursorSaveEvery = 10 * time.Minute
|
|
|
|
// 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")
|
|
|
|
// errStateNotSaved holds back a digest whose state could not be saved.
|
|
var errStateNotSaved = errors.New("the subscription's state could not be saved")
|
|
|
|
// 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
|
|
|
|
// Sync flushes a written state file to disk, and then its directory
|
|
// where the system allows. Nil means (*os.File).Sync.
|
|
Sync func(*os.File) error
|
|
|
|
// 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
|
|
|
|
// Queued reports whether the print queue already holds the card of m:
|
|
// one queued before a restart that lost the subscription's record of
|
|
// it. Such a message is not held for a digest, where it would print
|
|
// again.
|
|
Queued(m Message) bool
|
|
}
|
|
|
|
// 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) {}
|
|
}
|
|
if o.Sync == nil {
|
|
o.Sync = (*os.File).Sync
|
|
}
|
|
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
|
|
|
|
// digest is the digest made from held messages that the handler has
|
|
// not taken yet; messages held meanwhile wait for the next one.
|
|
// digestUnsaved is set until the state holding it has been saved, and
|
|
// it is not offered before.
|
|
digest *madeDigest
|
|
digestUnsaved bool
|
|
|
|
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 means the state changed in a way a restart must see, and is
|
|
// written within saveEvery; cursorMoved means only the cursor moved,
|
|
// and is written within cursorSaveEvery.
|
|
dirty bool
|
|
cursorMoved 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
|
|
}
|
|
r.digest = st.Digest
|
|
s.status.update(func(st *Status) { st.Held = r.waiting() })
|
|
return r
|
|
}
|
|
|
|
// stop closes the connection and saves the state.
|
|
func (r *run) stop() {
|
|
r.closeConn()
|
|
if r.dirty || r.cursorMoved {
|
|
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 at, ok := r.saveAt(); ok && !now.Before(at) {
|
|
r.save(now)
|
|
}
|
|
}
|
|
|
|
// saveAt returns when the state is next due to be written, if it changed.
|
|
func (r *run) saveAt() (time.Time, bool) {
|
|
switch {
|
|
case r.dirty:
|
|
return r.savedAt.Add(saveEvery), true
|
|
case r.cursorMoved:
|
|
return r.savedAt.Add(cursorSaveEvery), true
|
|
}
|
|
return time.Time{}, false
|
|
}
|
|
|
|
// 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 at, ok := r.saveAt(); ok {
|
|
earlier(at)
|
|
}
|
|
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
|
|
}
|
|
if !r.queued(m) {
|
|
r.hold(m, updated, true, now)
|
|
}
|
|
return true
|
|
}
|
|
if priority < r.o.BypassPriority && (!r.budget.room(now) || (r.waiting() > 0 && !quiet)) {
|
|
if !r.queued(m) {
|
|
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
|
|
}
|
|
|
|
// queued reports whether the print queue already holds m's card, queued
|
|
// before a restart that lost the save of m. m then counts as printed and
|
|
// is not held, since a digest row would print it again; a message that is
|
|
// not held reaches the queue, whose own check answers it.
|
|
func (r *run) queued(m Message) bool {
|
|
if m.ID == "" || !r.h.Queued(m) {
|
|
return false
|
|
}
|
|
r.printed.add(m.Sequence())
|
|
r.log.Debug("ntfy message already queued", "ntfy_id", m.ID)
|
|
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.waiting() })
|
|
}
|
|
|
|
// waiting returns how many held messages wait to print: those of the
|
|
// digest made and those held after it.
|
|
func (r *run) waiting() int {
|
|
n := r.held.Count
|
|
if r.digest != nil {
|
|
n += r.digest.Count
|
|
}
|
|
return n
|
|
}
|
|
|
|
// 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. The first move
|
|
// from 0 is written like any change a restart must see: a saved cursor of
|
|
// 0 is a first start, which replays nothing.
|
|
func (r *run) advance(t int64) {
|
|
if t > r.cursor {
|
|
if r.cursor == 0 {
|
|
r.dirty = true
|
|
}
|
|
r.cursor, r.cursorMoved = 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 wait.
|
|
func (r *run) flushAt(now time.Time) (time.Time, bool) {
|
|
if r.waiting() == 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. A
|
|
// digest offered again keeps its rows and reference. A new one is made
|
|
// from the messages held, under a new reference, and offered only once it
|
|
// is saved: should the daemon stop before the handler's success is saved,
|
|
// the next start offers the same digest again, which the print queue
|
|
// knows by its reference if it holds the job.
|
|
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 r.digest == nil {
|
|
d := r.held.makeDigest(now)
|
|
r.digest, r.held, r.digestUnsaved = &d, held{}, true
|
|
}
|
|
d := r.digest
|
|
if r.digestUnsaved {
|
|
if r.save(now); r.saveFailed {
|
|
r.digestWaits(now, errStateNotSaved)
|
|
return
|
|
}
|
|
r.digestUnsaved = false
|
|
}
|
|
if err := r.h.Digest(ctx, d.digest()); err != nil {
|
|
r.digestWaits(now, err)
|
|
return
|
|
}
|
|
r.log.Debug("ntfy digest printed", "ref", d.Ref, "held", d.Count, "overnight", d.Overnight)
|
|
r.budget.spend(now)
|
|
r.digest, r.digestAt, r.dirty = nil, time.Time{}, true
|
|
r.s.status.update(func(st *Status) { st.Held = r.waiting() })
|
|
}
|
|
|
|
// digestWaits offers the digest again later, after 1 second, then after
|
|
// twice as long each time, up to 30 seconds.
|
|
func (r *run) digestWaits(now time.Time, err error) {
|
|
if r.digestAt.IsZero() {
|
|
r.digestDelay = firstPrintRetry
|
|
r.log.Warn("ntfy digest waits to print", "ref", r.digest.Ref, "held", r.digest.Count, "err", err)
|
|
} else {
|
|
r.digestDelay = min(2*r.digestDelay, maxPrintRetry)
|
|
}
|
|
r.digestAt = now.Add(r.digestDelay)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
if r.digest != nil {
|
|
d := *r.digest
|
|
st.Digest = &d
|
|
}
|
|
r.savedAt = now
|
|
if err := saveState(r.o.StateFile, st, r.o.Sync); 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, r.cursorMoved = false, 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
|
|
}
|
|
}
|
|
}
|