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