live_test.go204 lines, 5.9 KB
| 1 | package live |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/fiston-user/murmur/internal/platform/testdb" |
| 14 | ) |
| 15 | |
| 16 | func like(id int64) Event { |
| 17 | return Event{ID: id, Kind: "like", Data: []byte(`{"actor":"bob","post_id":7}`)} |
| 18 | } |
| 19 | |
| 20 | // open is how many streams the hub holds for a user. |
| 21 | func (h *Hub) open(user int64) int { |
| 22 | h.mu.Lock() |
| 23 | defer h.mu.Unlock() |
| 24 | return len(h.streams[user]) |
| 25 | } |
| 26 | |
| 27 | // An event goes to every stream its user has open, and to nobody else. |
| 28 | func TestDeliver(t *testing.T) { |
| 29 | h := NewHub() |
| 30 | phone, laptop, other := h.Register(1), h.Register(1), h.Register(2) |
| 31 | h.Deliver(1, like(5)) |
| 32 | for _, c := range []chan Event{phone, laptop} { |
| 33 | if got := <-c; got.ID != 5 { |
| 34 | t.Fatalf("got event %d, want 5", got.ID) |
| 35 | } |
| 36 | } |
| 37 | if len(other) != 0 { |
| 38 | t.Fatal("user 2 got an event that was for user 1") |
| 39 | } |
| 40 | h.Unregister(1, phone) |
| 41 | h.Unregister(1, laptop) |
| 42 | h.Deliver(1, like(6)) // nobody is there, and that's fine |
| 43 | if h.open(1) != 0 || h.open(2) != 1 { |
| 44 | t.Fatalf("streams left: %d for user 1, %d for user 2, want 0 and 1", h.open(1), h.open(2)) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // A stream that nobody reads fills up, and then the hub lets go of it. |
| 49 | // The stream next to it, which is read, never notices. |
| 50 | func TestSlowStreamIsDropped(t *testing.T) { |
| 51 | h := NewHub() |
| 52 | slow, fast := h.Register(1), h.Register(1) |
| 53 | for i := range int64(buffer + 1) { |
| 54 | h.Deliver(1, like(i+1)) |
| 55 | if got := <-fast; got.ID != i+1 { |
| 56 | t.Fatalf("the fast stream got event %d, want %d", got.ID, i+1) |
| 57 | } |
| 58 | } |
| 59 | n := 0 |
| 60 | for range slow { // the channel was closed, so this loop ends |
| 61 | n++ |
| 62 | } |
| 63 | if n != buffer || h.open(1) != 1 || h.dropped != 1 { |
| 64 | t.Fatalf("the slow stream held %d events, %d streams are left, %d dropped: want %d, 1 and 1", |
| 65 | n, h.open(1), h.dropped, buffer) |
| 66 | } |
| 67 | h.Unregister(1, slow) // its handler still says goodbye, and nothing breaks |
| 68 | } |
| 69 | |
| 70 | // Streams come and go while events are delivered: the race detector watches the hub. |
| 71 | func TestHubCrowd(t *testing.T) { |
| 72 | h := NewHub() |
| 73 | var crowd sync.WaitGroup |
| 74 | for user := range int64(50) { |
| 75 | crowd.Go(func() { |
| 76 | for range 100 { |
| 77 | c := h.Register(user) |
| 78 | h.Deliver(user, like(1)) |
| 79 | h.Deliver((user+1)%50, like(2)) |
| 80 | h.Unregister(user, c) |
| 81 | } |
| 82 | }) |
| 83 | } |
| 84 | crowd.Wait() |
| 85 | if len(h.streams) != 0 { |
| 86 | t.Fatalf("%d users still have streams, want none", len(h.streams)) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | // server is a real HTTP server with Stream behind it. left gets a value every time |
| 91 | // a stream's handler returns. |
| 92 | func server(t *testing.T, h *Handler) (url string, left chan struct{}) { |
| 93 | left = make(chan struct{}, 8) |
| 94 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 95 | h.Stream(w, r) |
| 96 | left <- struct{}{} |
| 97 | })) |
| 98 | t.Cleanup(srv.Close) |
| 99 | return srv.URL, left |
| 100 | } |
| 101 | |
| 102 | // connect opens a stream and reads up to the first comment, so the stream is registered. |
| 103 | func connect(t *testing.T, ctx context.Context, url, lastID string) *bufio.Scanner { |
| 104 | t.Helper() |
| 105 | req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 106 | if lastID != "" { |
| 107 | req.Header.Set("Last-Event-ID", lastID) |
| 108 | } |
| 109 | res, err := http.DefaultClient.Do(req) |
| 110 | if err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | t.Cleanup(func() { res.Body.Close() }) |
| 114 | if got := res.Header.Get("Content-Type"); got != "text/event-stream" { |
| 115 | t.Fatalf("Content-Type is %q", got) |
| 116 | } |
| 117 | lines := bufio.NewScanner(res.Body) |
| 118 | next(t, lines, ": connected", "") |
| 119 | return lines |
| 120 | } |
| 121 | |
| 122 | // next reads the lines we expect, one after the other. |
| 123 | func next(t *testing.T, lines *bufio.Scanner, want ...string) { |
| 124 | t.Helper() |
| 125 | for _, w := range want { |
| 126 | if !lines.Scan() || lines.Text() != w { |
| 127 | t.Fatalf("the stream said %q, want %q", lines.Text(), w) |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // An event travels down the stream as lines of text, and a client that leaves gives its place back. |
| 133 | func TestStream(t *testing.T) { |
| 134 | hub := NewHub() |
| 135 | h := &Handler{Hub: hub, User: func(context.Context) int64 { return 1 }} |
| 136 | url, left := server(t, h) |
| 137 | ctx, hangUp := context.WithCancel(context.Background()) |
| 138 | lines := connect(t, ctx, url, "") |
| 139 | |
| 140 | hub.Deliver(1, like(5)) |
| 141 | hub.Deliver(1, Event{Kind: "post", Data: []byte(`{"post_id":7}`)}) |
| 142 | next(t, lines, "id: 5", "event: like", `data: {"actor":"bob","post_id":7}`, "", |
| 143 | "event: post", `data: {"post_id":7}`, "") |
| 144 | |
| 145 | hangUp() |
| 146 | <-left |
| 147 | if hub.open(1) != 0 { |
| 148 | t.Fatal("the client left, and its stream is still in the hub") |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // A client that says what it saw last gets what it missed first, and nothing twice. |
| 153 | func TestStreamCatchesUp(t *testing.T) { |
| 154 | hub := NewHub() |
| 155 | h := &Handler{Hub: hub, User: func(context.Context) int64 { return 1 }} |
| 156 | h.Missed = func(_ context.Context, user, after int64) ([]Event, error) { |
| 157 | if user != 1 || after != 5 { |
| 158 | return nil, fmt.Errorf("asked for user %d after %d", user, after) |
| 159 | } |
| 160 | hub.Deliver(1, like(7)) // event 7 happens right now: it's in the answer, and in the buffer |
| 161 | return []Event{like(6), like(7)}, nil |
| 162 | } |
| 163 | url, _ := server(t, h) |
| 164 | lines := connect(t, context.Background(), url, "5") |
| 165 | |
| 166 | hub.Deliver(1, like(8)) |
| 167 | var ids []string |
| 168 | for len(ids) < 3 && lines.Scan() { |
| 169 | if id, ok := strings.CutPrefix(lines.Text(), "id: "); ok { |
| 170 | ids = append(ids, id) |
| 171 | } |
| 172 | } |
| 173 | if got := strings.Join(ids, " "); got != "6 7 8" { |
| 174 | t.Fatalf("the stream sent events %s, want 6 7 8", got) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // Two servers, one Redis: what is published reaches the streams on both. |
| 179 | // And a hub that starts to listen lets go of whoever was connected before. |
| 180 | func TestSubscribe(t *testing.T) { |
| 181 | rdb := testdb.Redis(t) |
| 182 | ctx, stop := context.WithCancel(context.Background()) |
| 183 | defer stop() |
| 184 | a, b := NewHub(), NewHub() |
| 185 | early := []chan Event{a.Register(1), b.Register(1)} |
| 186 | go a.Subscribe(ctx, rdb) |
| 187 | go b.Subscribe(ctx, rdb) |
| 188 | for _, c := range early { |
| 189 | if _, open := <-c; open { |
| 190 | t.Fatal("a stream from before the hub listened got an event") |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | onA, onB := a.Register(1), b.Register(1) |
| 195 | if err := Publish(ctx, rdb, 1, like(5)); err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | for _, c := range []chan Event{onA, onB} { |
| 199 | got := <-c |
| 200 | if got.ID != 5 || got.Kind != "like" || string(got.Data) != string(like(5).Data) { |
| 201 | t.Fatalf("got %+v", got) |
| 202 | } |
| 203 | } |
| 204 | } |