oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1package slides
2
3import (
4 "bufio"
5 "context"
6 "strconv"
7
8 "amadan.net/oficina/home/roster"
9 "amadan.net/oficina/slides/internal/slides/present"
10 "errors"
11 "io"
12 "net/http"
13 "net/http/httptest"
14 "net/url"
15 "strings"
16 "testing"
17 "time"
18)
19
20// openStream opens path on a real server with the jar's cookies and
21// reads up to and including its connect events (the deck stream sends
22// two, update and presence; a presentation's one), so the handler is
23// known to be past its checks, subscribed, and waiting.
24func (f *teamFixture) openStream(t *testing.T, path string, withCookies bool) *bufio.Reader {
25 t.Helper()
26 srv := httptest.NewServer(f.mux)
27 t.Cleanup(srv.Close)
28 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
29 t.Cleanup(cancel)
30 req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil)
31 if err != nil {
32 t.Fatal(err)
33 }
34 // The instance's own host: rastrillo serves the origin it resolved.
35 req.Host = strings.TrimPrefix(homeTestOrigin, "https://")
36 if withCookies {
37 for _, c := range f.jar {
38 req.AddCookie(c)
39 }
40 }
41 resp, err := http.DefaultClient.Do(req)
42 if err != nil {
43 t.Fatal(err)
44 }
45 t.Cleanup(func() { resp.Body.Close() })
46 if resp.StatusCode != http.StatusOK {
47 t.Fatalf("stream %s = %d", path, resp.StatusCode)
48 }
49 br := bufio.NewReader(resp.Body)
50 events := 1
51 if strings.HasPrefix(path, "/d/") {
52 events = 2
53 }
54 for events > 0 {
55 line, err := br.ReadString('\n')
56 if err != nil {
57 t.Fatalf("stream ended before its connect events: %v", err)
58 }
59 if line == "\n" {
60 events--
61 }
62 }
63 return br
64}
65
66// endsWithin reports whether the stream's body ends within d, reading
67// whatever it sends meanwhile.
68func endsWithin(br *bufio.Reader, d time.Duration) (string, bool) {
69 done := make(chan error, 1)
70 var got strings.Builder
71 go func() {
72 _, err := io.Copy(&got, br)
73 done <- err
74 }()
75 select {
76 case err := <-done:
77 return got.String(), err == nil || errors.Is(err, io.EOF)
78 case <-time.After(d):
79 return got.String(), false
80 }
81}
82
83// Renewal: at the lease the stream asks again, and while the roster still
84// says Member it carries on, and still delivers.
85func TestTeamDeckStreamRenewsWhileStillAMember(t *testing.T) {
86 f := newTeamFixture(t)
87 colleague := f.member(teamSubject('b'), "member")
88 plan := f.deck(colleague, "Team plan", rungTeam)
89 f.member(teamSubject('a'), "member")
90 f.clock.Step(59 * time.Second)
91 f.dir.SetDown(true)
92 if err := f.a.team.Refresh(context.Background()); err == nil {
93 t.Fatal("refresh succeeded with the directory down")
94 }
95 f.dir.SetDown(false)
96 br := f.openStream(t, deckPath(plan)+"/stream", true)
97 f.clock.Step(6 * time.Second) // past the lease and the backoff
98 time.Sleep(1500 * time.Millisecond) // past the stream's lease timer
99 if got := f.do("POST", deckPath(plan)+"/updates", string(f.update(plan, "Still here")), "application/octet-stream", homeTestOrigin); got.Code != http.StatusNoContent {
100 t.Fatalf("member write = %d", got.Code)
101 }
102 line := make(chan string, 1)
103 go func() {
104 for {
105 l, err := br.ReadString('\n')
106 if err != nil {
107 line <- "EOF"
108 return
109 }
110 if strings.HasPrefix(l, "event: update") {
111 line <- l
112 return
113 }
114 }
115 }()
116 select {
117 case got := <-line:
118 if got == "EOF" {
119 t.Fatal("the renewed stream ended")
120 }
121 case <-time.After(5 * time.Second):
122 t.Fatal("the renewed stream delivered nothing")
123 }
124}
125
126// Removal reaches a deck stream at its next delivery: a write by
127// somebody else after the removal ends the removed member's stream
128// rather than telling them about it.
129func TestTeamDeckStreamEndsOnRemoval(t *testing.T) {
130 f := newTeamFixture(t)
131 colleague := f.member(teamSubject('b'), "member")
132 plan := f.deck(colleague, "Team plan", rungTeam)
133 f.member(teamSubject('a'), "member")
134 br := f.openStream(t, deckPath(plan)+"/stream", true)
135 f.dir.Set(teamSubject('a'), "")
136 f.refreshed()
137 if err := f.a.editDeck(context.Background(), &plan, actorFor(colleague), mustOps(t, "After"), nil, nil); err != nil {
138 t.Fatal(err)
139 }
140 if got, ended := endsWithin(br, 5*time.Second); !ended || strings.Contains(got, "event: update") {
141 t.Fatalf("a removed member's stream = %q (ended %v), want it ended with nothing delivered", got, ended)
142 }
143}
144
145func mustOps(t *testing.T, title string) []byte {
146 t.Helper()
147 b, err := opsJSON([]op{{"op": "set_meta", "title": title, "theme": defaultTheme}})
148 if err != nil {
149 t.Fatal(err)
150 }
151 return b
152}
153
154// startTalk has the jar's person present d and returns the session sqid.
155func (f *teamFixture) startTalk(t *testing.T, d Deck) string {
156 t.Helper()
157 got := f.post(deckPath(d)+"/present", nil)
158 if got.Code != http.StatusSeeOther {
159 t.Fatalf("present = %d %s", got.Code, got.Body.String())
160 }
161 loc, _ := url.Parse(got.Header().Get("Location"))
162 return strings.Split(strings.TrimPrefix(loc.Path, "/p/"), "/")[0]
163}
164
165// A presentation stands on its presenter's reach. Removed, the projector
166// is told the talk is over and the row is ended; with their standing
167// unknown, the projector gets a retryable 503 and the talk is left
168// running.
169func TestTeamPresentationStandsOnThePresenter(t *testing.T) {
170 f := newTeamFixture(t)
171 colleague := f.member(teamSubject('b'), "member")
172 plan := f.deck(colleague, "Team plan", rungTeam)
173 f.member(teamSubject('a'), "member")
174 session := f.startTalk(t, plan)
175 f.jar = map[string]*http.Cookie{} // the projector has no session
176 if got := f.get("/p/" + session); got.Code != 200 {
177 t.Fatalf("projector = %d", got.Code)
178 }
179
180 f.expired()
181 if got := f.get("/p/" + session); got.Code != http.StatusServiceUnavailable {
182 t.Fatalf("projector with the presenter's standing unknown = %d, want 503", got.Code)
183 }
184 var p Presentation
185 f.d.G.Where("sqid = ?", session).Take(&p)
186 if p.EndedAt != nil {
187 t.Fatal("an unknown standing ended the talk")
188 }
189
190 f.dir.Set(teamSubject('a'), "")
191 f.renewed()
192 if got := f.get("/p/" + session); got.Code != http.StatusGone {
193 t.Fatalf("projector after the presenter's removal = %d, want 410", got.Code)
194 }
195 f.d.G.Where("sqid = ?", session).Take(&p)
196 if p.EndedAt == nil {
197 t.Fatal("the removed presenter's talk was not ended")
198 }
199}
200
201// lines feeds a stream's lines to a channel, closed when the body ends.
202func lines(br *bufio.Reader) <-chan string {
203 ch := make(chan string, 64)
204 go func() {
205 defer close(ch)
206 for {
207 l, err := br.ReadString('\n')
208 if err != nil {
209 return
210 }
211 ch <- l
212 }
213 }()
214 return ch
215}
216
217// within reads ch for d: the first line containing want (found), or
218// whether the stream ended, with every line seen.
219func within(ch <-chan string, want string, d time.Duration) (seen string, found, ended bool) {
220 deadline := time.After(d)
221 for {
222 select {
223 case l, ok := <-ch:
224 if !ok {
225 return seen, false, true
226 }
227 seen += l
228 if want != "" && strings.Contains(l, want) {
229 return seen, true, false
230 }
231 case <-deadline:
232 return seen, false, false
233 }
234 }
235}
236
237// shortHold makes a held stream re-ask every 100 ms instead of the
238// roster's 5 s.
239func shortHold(t *testing.T) {
240 streamHoldRetry = 100 * time.Millisecond
241 t.Cleanup(func() { streamHoldRetry = roster.RetryAfter })
242}
243
244// A deck stream whose Member lease runs out while the roster cannot be
245// read is held, not ended (Fable #33, note 1): it stays open and delivers
246// nothing about the deck, and the moment standing returns it is caught
247// up with the deck's current seq.
248func TestTeamDeckStreamHoldsWhileStandingIsUnknown(t *testing.T) {
249 shortHold(t)
250 f := newTeamFixture(t)
251 colleague := f.member(teamSubject('b'), "member")
252 plan := f.deck(colleague, "Team plan", rungTeam)
253 f.member(teamSubject('a'), "member")
254 f.dir.SetDown(true)
255 f.clock.Step(59 * time.Second)
256 feed := lines(f.openStream(t, deckPath(plan)+"/stream", true))
257 f.clock.Step(2 * time.Second)
258 time.Sleep(1500 * time.Millisecond) // past the stream's lease timer: held
259 if err := f.a.editDeck(context.Background(), &plan, actorFor(colleague), mustOps(t, "While held"), nil, nil); err != nil {
260 t.Fatal(err)
261 }
262 if seen, found, ended := within(feed, "event:", time.Second); found || ended {
263 t.Fatalf("a held deck stream delivered or ended: %q (ended %v)", seen, ended)
264 }
265 f.dir.SetDown(false)
266 f.refreshed()
267 seen, found, _ := within(feed, "data: "+strconv.FormatInt(plan.Seq, 10), 3*time.Second)
268 if !found || !strings.Contains(seen, "event: update") {
269 t.Fatalf("the held stream was not caught up to seq %d: %q", plan.Seq, seen)
270 }
271}
272
273// A projector stream whose presenter's lease runs out while the roster
274// cannot be read is held, delivering nothing; when it can be read again
275// the projector gets the talk's current state, never what was published
276// while held.
277func TestTeamPresentationStreamHoldsWhileThePresenterIsUnknown(t *testing.T) {
278 shortHold(t)
279 f := newTeamFixture(t)
280 colleague := f.member(teamSubject('b'), "member")
281 plan := f.deck(colleague, "Team plan", rungTeam)
282 f.member(teamSubject('a'), "member")
283 session := f.startTalk(t, plan)
284 f.dir.SetDown(true)
285 f.clock.Step(59 * time.Second)
286 feed := lines(f.openStream(t, "/p/"+session+"/stream", false))
287 f.clock.Step(2 * time.Second)
288 time.Sleep(1500 * time.Millisecond)
289 f.a.hub.Publish(session, present.Event{Slide: 9})
290 if seen, found, ended := within(feed, "event:", time.Second); found || ended {
291 t.Fatalf("a held projector stream delivered or ended: %q (ended %v)", seen, ended)
292 }
293 f.dir.SetDown(false)
294 f.refreshed()
295 seen, found, _ := within(feed, "event: slide", 3*time.Second)
296 if !found {
297 t.Fatalf("the held projector was not caught up: %q", seen)
298 }
299 if rest, _, _ := within(feed, "", 200*time.Millisecond); strings.Contains(seen+rest, `"slide":9`) {
300 t.Fatal("a held projector was sent what was published while it was held")
301 }
302}
303
304// A projector that connects while its presenter's standing is unknown is
305// not refused (an EventSource answered 503 fails for good): it is held,
306// and served once the roster can be read. The page itself is still the
307// retryable 503; a removed presenter's stream is the 410.
308func TestTeamProjectorConnectsWhileThePresenterIsUnknown(t *testing.T) {
309 shortHold(t)
310 f := newTeamFixture(t)
311 colleague := f.member(teamSubject('b'), "member")
312 plan := f.deck(colleague, "Team plan", rungTeam)
313 f.member(teamSubject('a'), "member")
314 session := f.startTalk(t, plan)
315 f.expired()
316 srv := httptest.NewServer(f.mux)
317 t.Cleanup(srv.Close)
318 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
319 t.Cleanup(cancel)
320 req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/p/"+session+"/stream", nil)
321 req.Host = strings.TrimPrefix(homeTestOrigin, "https://")
322 resp, err := http.DefaultClient.Do(req)
323 if err != nil {
324 t.Fatal(err)
325 }
326 t.Cleanup(func() { resp.Body.Close() })
327 if resp.StatusCode != http.StatusOK {
328 t.Fatalf("projector stream under Unknown = %d, want a held 200", resp.StatusCode)
329 }
330 feed := lines(bufio.NewReader(resp.Body))
331 if seen, found, ended := within(feed, "event:", 500*time.Millisecond); found || ended {
332 t.Fatalf("a held projector delivered or ended: %q", seen)
333 }
334 f.dir.SetDown(false)
335 f.refreshed()
336 if seen, found, _ := within(feed, "event: slide", 3*time.Second); !found {
337 t.Fatalf("the projector was not served once the roster returned: %q", seen)
338 }
339 f.dir.Set(teamSubject('a'), "")
340 f.refreshed()
341 r2, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/p/"+session+"/stream", nil)
342 r2.Host = req.Host
343 gone, err := http.DefaultClient.Do(r2)
344 if err != nil {
345 t.Fatal(err)
346 }
347 gone.Body.Close()
348 if gone.StatusCode != http.StatusGone {
349 t.Fatalf("projector stream for a removed presenter = %d, want 410", gone.StatusCode)
350 }
351}
352