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 } // syncFile flushes a file, or a directory, to disk. It is a variable so // that tests, which write state files thousands of times, can skip the // flush; on a disk that is slow to sync, each one costs tens of // milliseconds. var syncFile = (*os.File).Sync // 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 = syncFile(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) 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 } _ = syncFile(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 }