| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/home/roster" |
| 17 | "amadan.net/oficina/slides/internal/slides/present" |
| 18 | ) |
| 19 | |
| 20 | // presentingApp is an app with one deck and one Positional session on |
| 21 | // it, written straight into the database, whose remote token is token. |
| 22 | // The deck has no document yet, which is an empty talk: these tests are |
| 23 | // about who may write and in what order, not where a press lands. |
| 24 | func presentingApp(t *testing.T, token string) (*http.ServeMux, *app, Presentation) { |
| 25 | t.Helper() |
| 26 | mux, a, err := New(testDB(t), Config{KeymailServers: testKeymailServers, Env: EnvDevelopment, Origin: "http://localhost:8091", Logger: quietLogger()}) |
| 27 | if err != nil { |
| 28 | t.Fatalf("New: %v", err) |
| 29 | } |
| 30 | t.Cleanup(func() { a.Close() }) |
| 31 | d := Deck{Sqid: "presentdk2", Title: "Talk", OwnerID: 1, Rung: "private"} |
| 32 | if err := a.db.G.Create(&d).Error; err != nil { |
| 33 | t.Fatalf("create a deck: %v", err) |
| 34 | } |
| 35 | p := Presentation{ |
| 36 | Sqid: "presentss2", DeckID: d.ID, Actor: "person:1", Code: "ABCDEF", |
| 37 | RemoteTokenHash: hashRemoteToken(token), StartedAt: time.Now().UTC(), |
| 38 | Positional: true, Mode: "core", Seq: 3, |
| 39 | } |
| 40 | if err := a.db.G.Create(&p).Error; err != nil { |
| 41 | t.Fatalf("create a presentation: %v", err) |
| 42 | } |
| 43 | return mux, a, p |
| 44 | } |
| 45 | |
| 46 | // pressRequestWith is a press as the phone posts it. |
| 47 | func pressRequestWith(token, op string) *http.Request { |
| 48 | form := url.Values{"op": {op}, "t": {token}, "press": {rand.Text()}} |
| 49 | r := httptest.NewRequest(http.MethodPost, "/p/presentss2/command", strings.NewReader(form.Encode())) |
| 50 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 51 | return r |
| 52 | } |
| 53 | |
| 54 | // TestATokenReplacedMidPressDrivesNothing: a press is let in on the |
| 55 | // row its request resolved, the phone is re-paired before its |
| 56 | // transaction runs, and the press must then move nothing. The |
| 57 | // credential is checked again against the row the transaction reads. |
| 58 | func TestATokenReplacedMidPressDrivesNothing(t *testing.T) { |
| 59 | const token = "the-phone-token-the-presenter-paired-first" |
| 60 | _, a, p := presentingApp(t, token) |
| 61 | |
| 62 | // The same press path untouched works, so the refusal below is the |
| 63 | // replaced token and nothing else. |
| 64 | if _, err := a.applyPress(pressRequestWith(token, "next"), p, pressCommand{Op: "next", Press: rand.Text()}, ""); err != nil { |
| 65 | t.Fatalf("a press with the paired token: %v", err) |
| 66 | } |
| 67 | |
| 68 | r := pressRequestWith(token, "next") |
| 69 | if drives, _, _ := a.mayDrive(httptest.NewRecorder(), r, p, token); !drives { |
| 70 | t.Fatal("the paired token was not let in") |
| 71 | } |
| 72 | // Re-paired between the request being let in and its write. |
| 73 | if err := a.db.G.Model(&Presentation{}).Where("id = ?", p.ID). |
| 74 | Update("remote_token_hash", hashRemoteToken("a-new-phone-token")).Error; err != nil { |
| 75 | t.Fatalf("re-pair: %v", err) |
| 76 | } |
| 77 | _, err := a.applyPress(r, p, pressCommand{Op: "next", Press: rand.Text()}, "") |
| 78 | if !errors.Is(err, errNotDriver) { |
| 79 | t.Errorf("a press whose token was replaced mid-flight: err %v, want errNotDriver", err) |
| 80 | } |
| 81 | |
| 82 | var now Presentation |
| 83 | if err := a.db.G.Take(&now, p.ID).Error; err != nil { |
| 84 | t.Fatalf("reread the session: %v", err) |
| 85 | } |
| 86 | if now.Seq != 4 { |
| 87 | t.Errorf("after one press and one refused one the session is at seq %d, want 4", now.Seq) |
| 88 | } |
| 89 | var kept int64 |
| 90 | if err := a.db.G.Model(&PresentationPress{}).Where("presentation_id = ?", p.ID).Count(&kept).Error; err != nil { |
| 91 | t.Fatalf("count press ids: %v", err) |
| 92 | } |
| 93 | if kept != 1 { |
| 94 | t.Errorf("the refused press left %d press ids, want only the first press's 1", kept) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // TestAStreamNeverGoesBackToAnOlderPress forces the interleaving two |
| 99 | // presses can make: A commits first (seq 4), then B (seq 5), but B's |
| 100 | // goroutine publishes before A's. The stream must leave its page at B, |
| 101 | // never on A's older position. |
| 102 | func TestAStreamNeverGoesBackToAnOlderPress(t *testing.T) { |
| 103 | mux, a, p := presentingApp(t, "token") |
| 104 | srv := httptest.NewServer(mux) |
| 105 | defer srv.Close() |
| 106 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 107 | defer cancel() |
| 108 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/p/"+p.Sqid+"/stream", nil) |
| 109 | if err != nil { |
| 110 | t.Fatal(err) |
| 111 | } |
| 112 | resp, err := http.DefaultClient.Do(req) |
| 113 | if err != nil { |
| 114 | t.Fatalf("open the stream: %v", err) |
| 115 | } |
| 116 | defer resp.Body.Close() |
| 117 | events := bufio.NewReader(resp.Body) |
| 118 | if e := readSlideEvent(t, events); e.Seq != 3 { |
| 119 | t.Fatalf("the connect event is %+v, want seq 3", e) |
| 120 | } |
| 121 | |
| 122 | // Both committed, in order: the row holds B. |
| 123 | a2 := p |
| 124 | a2.SlideID, a2.Seq = "after-a", 4 |
| 125 | b := p |
| 126 | b.SlideID, b.Seq = "after-b", 5 |
| 127 | if err := a.db.G.Model(&Presentation{}).Where("id = ?", p.ID). |
| 128 | Updates(map[string]any{"slide_id": b.SlideID, "seq": b.Seq}).Error; err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | // Published the other way round, then an end to fence the stream. |
| 132 | a.hub.Publish(p.Sqid, eventFor(b)) |
| 133 | a.hub.Publish(p.Sqid, eventFor(a2)) |
| 134 | a.hub.Publish(p.Sqid, present.Event{Ended: true}) |
| 135 | |
| 136 | var last present.Event |
| 137 | for { |
| 138 | e := readSlideEvent(t, events) |
| 139 | if e.Ended { |
| 140 | break |
| 141 | } |
| 142 | last = e |
| 143 | } |
| 144 | if last.Seq != 5 || last.SlideID != "after-b" { |
| 145 | t.Errorf("the stream left its page at %+v, want B's position (after-b, seq 5)", last) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // readSlideEvent reads the stream until its next `slide` event. |
| 150 | func readSlideEvent(t *testing.T, r *bufio.Reader) present.Event { |
| 151 | t.Helper() |
| 152 | var name string |
| 153 | for { |
| 154 | line, err := r.ReadString('\n') |
| 155 | if err != nil { |
| 156 | t.Fatalf("read the stream: %v", err) |
| 157 | } |
| 158 | line = strings.TrimRight(line, "\r\n") |
| 159 | switch { |
| 160 | case strings.HasPrefix(line, "event: "): |
| 161 | name = strings.TrimPrefix(line, "event: ") |
| 162 | case strings.HasPrefix(line, "data: ") && name == "slide": |
| 163 | var e present.Event |
| 164 | if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &e); err != nil { |
| 165 | t.Fatalf("the stream's event: %v", err) |
| 166 | } |
| 167 | return e |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // TestAHeldStreamNeverGoesBackToAnOlderPress is the same interleaving |
| 173 | // meeting a held projector (team mode, the presenter's standing |
| 174 | // unknown): A commits (seq 4), B commits (seq 5), and the hold ends on |
| 175 | // the arrival of A's late event. The catch-up writes the row, B, and A |
| 176 | // must not be written after it; nor may B's own event, arriving last, |
| 177 | // be lost. The page never goes back, and ends at B. |
| 178 | // |
| 179 | // The test orders itself against the stream, not a clock: streamTrace |
| 180 | // says when the stream enters its hold and what ended it. The hold's |
| 181 | // retry is an hour, so only A's event can end it, and the test insists |
| 182 | // that it did. |
| 183 | func TestAHeldStreamNeverGoesBackToAnOlderPress(t *testing.T) { |
| 184 | trace := make(chan string, 16) |
| 185 | streamTrace = func(state string) { |
| 186 | select { |
| 187 | case trace <- state: |
| 188 | default: |
| 189 | } |
| 190 | } |
| 191 | streamHoldRetry = time.Hour |
| 192 | t.Cleanup(func() { streamTrace, streamHoldRetry = nil, roster.RetryAfter }) |
| 193 | waitFor := func(want string) { |
| 194 | t.Helper() |
| 195 | deadline := time.After(10 * time.Second) |
| 196 | for { |
| 197 | select { |
| 198 | case got := <-trace: |
| 199 | if got == want { |
| 200 | return |
| 201 | } |
| 202 | t.Fatalf("the stream said %q, waiting for %q", got, want) |
| 203 | case <-deadline: |
| 204 | t.Fatalf("the stream never said %q", want) |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | f := newTeamFixture(t) |
| 210 | colleague := f.member(teamSubject('b'), "member") |
| 211 | plan := f.deck(colleague, "Team plan", rungTeam) |
| 212 | f.member(teamSubject('a'), "member") |
| 213 | session := f.startTalk(t, plan) |
| 214 | var p Presentation |
| 215 | if err := f.d.G.Where("sqid = ?", session).Take(&p).Error; err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | f.dir.SetDown(true) |
| 219 | f.clock.Step(59 * time.Second) |
| 220 | feed := lines(f.openStream(t, "/p/"+session+"/stream", false)) |
| 221 | f.clock.Step(2 * time.Second) |
| 222 | waitFor("held") // the stream's lease ran out with the roster down |
| 223 | |
| 224 | // Both committed, in order: the row holds B. |
| 225 | a2, b := p, p |
| 226 | a2.SlideID, a2.Seq = "after-a", 4 |
| 227 | b.SlideID, b.Seq = "after-b", 5 |
| 228 | if err := f.d.G.Model(&Presentation{}).Where("id = ?", p.ID). |
| 229 | Updates(map[string]any{"slide_id": b.SlideID, "seq": b.Seq}).Error; err != nil { |
| 230 | t.Fatal(err) |
| 231 | } |
| 232 | // Standing returns; A's event arrives first, then B's, then an end |
| 233 | // to fence the stream. |
| 234 | f.dir.SetDown(false) |
| 235 | f.refreshed() |
| 236 | f.a.hub.Publish(session, eventFor(a2)) |
| 237 | waitFor("caught up by an event") // A's arrival ended the hold |
| 238 | f.a.hub.Publish(session, eventFor(b)) |
| 239 | f.a.hub.Publish(session, present.Event{Ended: true}) |
| 240 | |
| 241 | // A position from the start: every event before the fence has one. |
| 242 | last := present.Event{Position: &present.Position{}} |
| 243 | var written []int64 |
| 244 | deadline := time.After(4 * time.Second) |
| 245 | for { |
| 246 | select { |
| 247 | case l, ok := <-feed: |
| 248 | if !ok { |
| 249 | t.Fatalf("the stream ended before its fence; wrote seqs %v", written) |
| 250 | } |
| 251 | data, isData := strings.CutPrefix(strings.TrimRight(l, "\n"), "data: ") |
| 252 | if !isData { |
| 253 | continue |
| 254 | } |
| 255 | var e present.Event |
| 256 | if err := json.Unmarshal([]byte(data), &e); err != nil { |
| 257 | t.Fatalf("the stream's event %q: %v", data, err) |
| 258 | } |
| 259 | if e.Ended { |
| 260 | if last.Seq != 5 || last.SlideID != "after-b" { |
| 261 | t.Errorf("the held stream left its page at %+v (wrote seqs %v), want B's position (after-b, seq 5)", last, written) |
| 262 | } |
| 263 | return |
| 264 | } |
| 265 | if e.Seq < last.Seq { |
| 266 | t.Errorf("the held stream went back from seq %d to %d (wrote seqs %v)", last.Seq, e.Seq, append(written, e.Seq)) |
| 267 | } |
| 268 | written = append(written, e.Seq) |
| 269 | last = e |
| 270 | case <-deadline: |
| 271 | t.Fatalf("no fence within 4s; wrote seqs %v", written) |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |