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})) }