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>
271 lines
6.9 KiB
Go
271 lines
6.9 KiB
Go
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"`
|
|
|
|
// Digest is the digest made and not yet taken by the handler, kept
|
|
// apart from the messages held after it.
|
|
Digest *madeDigest `json:"digest,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]
|
|
}
|
|
if st.Digest != nil && len(st.Digest.Rows) > MaxDigestRows {
|
|
st.Digest.Rows = st.Digest.Rows[:MaxDigestRows]
|
|
}
|
|
return st, nil
|
|
}
|
|
|
|
// saveState writes st to path atomically: to a temporary file in the same
|
|
// directory, flushed to disk with sync, then renamed over path, and the
|
|
// directory flushed after the rename. A crash leaves the old file or the
|
|
// new one, never part of either.
|
|
func saveState(path string, st state, sync func(*os.File) error) 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 = sync(f)
|
|
}
|
|
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, sync)
|
|
return nil
|
|
}
|
|
|
|
// syncDir makes a rename in dir durable by flushing dir with sync. Windows
|
|
// cannot open a directory to sync it, and its renames need no such step.
|
|
func syncDir(dir string, sync func(*os.File) error) {
|
|
if runtime.GOOS == "windows" {
|
|
return
|
|
}
|
|
d, err := os.Open(dir)
|
|
if err != nil {
|
|
return
|
|
}
|
|
_ = sync(d)
|
|
_ = 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
|
|
}
|