| 1 | package docs |
| 2 | |
| 3 | // Live push, slice 1b (push.go, logepoch.go, stream.go; the live-push |
| 4 | // spec's §3.1, §3.4, §5, §8 and the tests it lists in §9.1–§9.2). |
| 5 | |
| 6 | import ( |
| 7 | "bufio" |
| 8 | "bytes" |
| 9 | "context" |
| 10 | "encoding/base64" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "os" |
| 17 | "path/filepath" |
| 18 | "sort" |
| 19 | "strconv" |
| 20 | "strings" |
| 21 | "sync" |
| 22 | "sync/atomic" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/oficina/home/roster" |
| 27 | "amadan.net/rastrillo/rastrillo/sessions" |
| 28 | "github.com/carlosframework/docs/internal/core" |
| 29 | ) |
| 30 | |
| 31 | type pushFixture struct { |
| 32 | t *testing.T |
| 33 | app *App |
| 34 | srv *httptest.Server |
| 35 | owner int64 |
| 36 | doc *Document |
| 37 | ctx context.Context |
| 38 | // cookies is one signed-in session of owner@example.com: the stream and |
| 39 | // the POSTs present the same session, as one tab does. |
| 40 | cookies []*http.Cookie |
| 41 | // host, when set, is the Host every request names (team mode's bridge). |
| 42 | host string |
| 43 | } |
| 44 | |
| 45 | func newPushFixture(t *testing.T, cfg Config) *pushFixture { |
| 46 | t.Helper() |
| 47 | app, err := NewForTestWith(t, cfg) |
| 48 | if err != nil { |
| 49 | t.Fatalf("NewForTestWith: %v", err) |
| 50 | } |
| 51 | ctx := context.Background() |
| 52 | owner := app.TestPerson(t, "owner@example.com") |
| 53 | doc, err := app.Store().Create(ctx, owner, "Push") |
| 54 | if err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | srv := httptest.NewServer(app.Handler()) |
| 58 | t.Cleanup(srv.Close) |
| 59 | f := &pushFixture{t: t, app: app, srv: srv, owner: owner, doc: doc, ctx: ctx} |
| 60 | f.cookies = f.session("owner@example.com") |
| 61 | return f |
| 62 | } |
| 63 | |
| 64 | // session signs address in once and returns its cookies. |
| 65 | func (f *pushFixture) session(address string) []*http.Cookie { |
| 66 | return f.app.TestRequest(f.t, address, http.MethodGet, "/", nil).Cookies() |
| 67 | } |
| 68 | |
| 69 | // update is a valid update adding one paragraph from its own Yjs client. |
| 70 | func (f *pushFixture) update(k int, text string) []byte { |
| 71 | f.t.Helper() |
| 72 | u, err := f.app.core.InitialUpdate(f.ctx, f.doc.GUID, uint64(500000+k), []core.InitialBlock{{Text: text}}) |
| 73 | if err != nil { |
| 74 | f.t.Fatal(err) |
| 75 | } |
| 76 | return u |
| 77 | } |
| 78 | |
| 79 | // post POSTs update with cookies and an optional Docs-Stream header, and |
| 80 | // returns the status and Docs-Seq. |
| 81 | func (f *pushFixture) post(cookies []*http.Cookie, update []byte, docsStream string) (int, int64) { |
| 82 | f.t.Helper() |
| 83 | req, _ := http.NewRequest(http.MethodPost, f.srv.URL+"/d/"+f.doc.Sqid+"/updates", bytes.NewReader(update)) |
| 84 | req.Header.Set("Content-Type", "application/octet-stream") |
| 85 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 86 | if docsStream != "" { |
| 87 | req.Header.Set("Docs-Stream", docsStream) |
| 88 | } |
| 89 | for _, c := range cookies { |
| 90 | req.AddCookie(c) |
| 91 | } |
| 92 | res, err := f.srv.Client().Do(req) |
| 93 | if err != nil { |
| 94 | f.t.Fatal(err) |
| 95 | } |
| 96 | io.Copy(io.Discard, res.Body) |
| 97 | res.Body.Close() |
| 98 | seq, _ := strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64) |
| 99 | return res.StatusCode, seq |
| 100 | } |
| 101 | |
| 102 | type frame struct{ id, tag, event, data string } |
| 103 | |
| 104 | // testStream is an open stream with a frame reader. |
| 105 | type testStream struct { |
| 106 | res *http.Response |
| 107 | frames chan frame |
| 108 | done chan struct{} |
| 109 | } |
| 110 | |
| 111 | func (f *pushFixture) open(cookies []*http.Cookie, query string, header map[string]string) *testStream { |
| 112 | f.t.Helper() |
| 113 | req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream"+query, nil) |
| 114 | if f.host != "" { |
| 115 | req.Host = f.host |
| 116 | } |
| 117 | for k, v := range header { |
| 118 | req.Header.Set(k, v) |
| 119 | } |
| 120 | for _, c := range cookies { |
| 121 | req.AddCookie(c) |
| 122 | } |
| 123 | res, err := f.srv.Client().Do(req) |
| 124 | if err != nil { |
| 125 | f.t.Fatal(err) |
| 126 | } |
| 127 | if res.StatusCode != 200 { |
| 128 | res.Body.Close() |
| 129 | f.t.Fatalf("stream %s: %d", query, res.StatusCode) |
| 130 | } |
| 131 | s := &testStream{res: res, frames: make(chan frame, 1024), done: make(chan struct{})} |
| 132 | f.t.Cleanup(func() { res.Body.Close() }) |
| 133 | go func() { |
| 134 | defer close(s.done) |
| 135 | r := bufio.NewReaderSize(res.Body, 1<<20) |
| 136 | var fr frame |
| 137 | for { |
| 138 | line, err := r.ReadString('\n') |
| 139 | if err != nil { |
| 140 | return |
| 141 | } |
| 142 | line = strings.TrimRight(line, "\r\n") |
| 143 | switch { |
| 144 | case strings.HasPrefix(line, ":"): |
| 145 | case strings.HasPrefix(line, "id: "): |
| 146 | fr.id, fr.tag, _ = strings.Cut(line[4:], ".") |
| 147 | case strings.HasPrefix(line, "event: "): |
| 148 | fr.event = line[7:] |
| 149 | case strings.HasPrefix(line, "data: "): |
| 150 | fr.data = line[6:] |
| 151 | case line == "": |
| 152 | if fr.event != "" { |
| 153 | s.frames <- fr |
| 154 | } |
| 155 | fr = frame{} |
| 156 | } |
| 157 | } |
| 158 | }() |
| 159 | return s |
| 160 | } |
| 161 | |
| 162 | func (s *testStream) next(t *testing.T) frame { |
| 163 | t.Helper() |
| 164 | select { |
| 165 | case fr := <-s.frames: |
| 166 | return fr |
| 167 | case <-s.done: |
| 168 | select { |
| 169 | case fr := <-s.frames: |
| 170 | return fr |
| 171 | default: |
| 172 | } |
| 173 | t.Fatal("the stream ended") |
| 174 | case <-time.After(5 * time.Second): |
| 175 | t.Fatal("no frame within 5 s") |
| 176 | } |
| 177 | return frame{} |
| 178 | } |
| 179 | |
| 180 | // quiet asserts no frame arrives within d. |
| 181 | func (s *testStream) quiet(t *testing.T, d time.Duration) { |
| 182 | t.Helper() |
| 183 | select { |
| 184 | case fr := <-s.frames: |
| 185 | t.Fatalf("unexpected frame %+v", fr) |
| 186 | case <-time.After(d): |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | // hello reads the hello frame and returns the stream id, seq and epoch. |
| 191 | func (s *testStream) hello(t *testing.T) (string, int64, string) { |
| 192 | t.Helper() |
| 193 | fr := s.next(t) |
| 194 | parts := strings.Fields(fr.data) |
| 195 | if fr.event != "hello" || len(parts) != 3 { |
| 196 | t.Fatalf("first frame %+v, want hello <id> <seq> <epoch>", fr) |
| 197 | } |
| 198 | seq, err := strconv.ParseInt(parts[1], 10, 64) |
| 199 | if err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | return parts[0], seq, parts[2] |
| 203 | } |
| 204 | |
| 205 | func pushOn() Config { return Config{LivePush: true} } |
| 206 | |
| 207 | // §9.1: one POST yields exactly one flushed push frame per watcher, with |
| 208 | // the row's bytes, and `own` for the poster's stream; no update event. |
| 209 | func TestPushOnePOSTOneFramePerWatcher(t *testing.T) { |
| 210 | f := newPushFixture(t, pushOn()) |
| 211 | poster := f.open(f.cookies, "?push=1&since=0", nil) |
| 212 | id, _, _ := poster.hello(t) |
| 213 | var watchers []*testStream |
| 214 | for i := 0; i < 3; i++ { |
| 215 | w := f.open(f.session("owner@example.com"), "?push=1&since=0", nil) |
| 216 | w.hello(t) |
| 217 | watchers = append(watchers, w) |
| 218 | } |
| 219 | u := f.update(1, "hello push") |
| 220 | frames0 := f.app.handlers.pushStats.frames.Load() |
| 221 | code, seq := f.post(f.cookies, u, id+".7") |
| 222 | if code != http.StatusNoContent || seq != 1 { |
| 223 | t.Fatalf("POST: %d, seq %d", code, seq) |
| 224 | } |
| 225 | for i, w := range watchers { |
| 226 | fr := w.next(t) |
| 227 | parts := strings.SplitN(fr.data, " ", 2) |
| 228 | if fr.event != "push" || fr.id != "1" || len(parts) != 2 || parts[0] != "1" { |
| 229 | t.Fatalf("watcher %d: %+v, want push 1", i, fr) |
| 230 | } |
| 231 | got, err := base64.StdEncoding.DecodeString(parts[1]) |
| 232 | if err != nil || !bytes.Equal(got, u) { |
| 233 | t.Fatalf("watcher %d: the frame's bytes are not the update's", i) |
| 234 | } |
| 235 | w.quiet(t, 150*time.Millisecond) |
| 236 | } |
| 237 | if fr := poster.next(t); fr.event != "own" || fr.id != "1" || fr.data != "1 7" { |
| 238 | t.Fatalf("poster: %+v, want own 1 7", fr) |
| 239 | } |
| 240 | poster.quiet(t, 150*time.Millisecond) |
| 241 | if n := f.app.handlers.pushStats.frames.Load() - frames0; n != 4 { |
| 242 | t.Errorf("%d flushes for one POST and four streams, want 4", n) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | // §3.4: `own` only for the stream the header names, from the session that |
| 247 | // opened it, on its document. Anything else is a push. |
| 248 | func TestPushOwnNeedsTheSameSessionAndDocument(t *testing.T) { |
| 249 | f := newPushFixture(t, pushOn()) |
| 250 | poster := f.open(f.cookies, "?push=1&since=0", nil) |
| 251 | id, _, _ := poster.hello(t) |
| 252 | |
| 253 | // Another session of the same person names this stream. |
| 254 | f.post(f.session("owner@example.com"), f.update(1, "other session"), id+".1") |
| 255 | if fr := poster.next(t); fr.event != "push" { |
| 256 | t.Fatalf("another session's header: %+v, want push", fr) |
| 257 | } |
| 258 | // A stream on another document. |
| 259 | other, err := f.app.Store().Create(f.ctx, f.owner, "Other") |
| 260 | if err != nil { |
| 261 | t.Fatal(err) |
| 262 | } |
| 263 | g := *f |
| 264 | g.doc = other |
| 265 | otherStream := g.open(f.cookies, "?push=1&since=0", nil) |
| 266 | otherID, _, _ := otherStream.hello(t) |
| 267 | f.post(f.cookies, f.update(2, "wrong document"), otherID+".1") |
| 268 | if fr := poster.next(t); fr.event != "push" { |
| 269 | t.Fatalf("another document's stream id: %+v, want push", fr) |
| 270 | } |
| 271 | // Malformed and unknown headers. |
| 272 | for i, h := range []string{"nonsense", id + ".x", "unknown.1", id + "."} { |
| 273 | f.post(f.cookies, f.update(3+i, "bad header"), h) |
| 274 | if fr := poster.next(t); fr.event != "push" { |
| 275 | t.Fatalf("header %q: %+v, want push", h, fr) |
| 276 | } |
| 277 | } |
| 278 | // The real thing. |
| 279 | f.post(f.cookies, f.update(9, "mine"), id+".42") |
| 280 | if fr := poster.next(t); fr.event != "own" || !strings.HasSuffix(fr.data, " 42") { |
| 281 | t.Fatalf("own: %+v", fr) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // §3.4: a seq whose origin entry was recorded by a transaction that rolled |
| 286 | // back, then reused by another POST, must not come back as `own`: the |
| 287 | // entry's hash does not match the committed row. |
| 288 | func TestPushOwnIsCheckedAgainstTheRowsBytes(t *testing.T) { |
| 289 | f := newPushFixture(t, pushOn()) |
| 290 | poster := f.open(f.cookies, "?push=1&since=0", nil) |
| 291 | id, _, _ := poster.hello(t) |
| 292 | f.app.handlers.pushRegistry.record(f.doc.ID, 1, postOrigin{stream: id, counter: "5"}, []byte("a rolled-back update")) |
| 293 | f.post(f.session("owner@example.com"), f.update(1, "someone else"), "") |
| 294 | if fr := poster.next(t); fr.event != "push" { |
| 295 | t.Fatalf("%+v, want push: a stale origin entry was believed", fr) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | // §9.1: frames in seq order, gapless, under concurrent POSTs. |
| 300 | func TestPushFramesInSeqOrderUnderConcurrentPOSTs(t *testing.T) { |
| 301 | f := newPushFixture(t, pushOn()) |
| 302 | w := f.open(f.cookies, "?push=1&since=0", nil) |
| 303 | w.hello(t) |
| 304 | const writers, each = 8, 10 |
| 305 | sessions := make([][]*http.Cookie, writers) |
| 306 | for g := range sessions { |
| 307 | address := fmt.Sprintf("writer%d@example.com", g) |
| 308 | f.app.TestPerson(t, address) |
| 309 | if err := f.app.Store().Grant(f.ctx, f.owner, f.doc.Sqid, address, RoleWriter); err != nil { |
| 310 | t.Fatal(err) |
| 311 | } |
| 312 | sessions[g] = f.session(address) |
| 313 | } |
| 314 | var wg sync.WaitGroup |
| 315 | for g := 0; g < writers; g++ { |
| 316 | wg.Add(1) |
| 317 | go func(g int) { |
| 318 | defer wg.Done() |
| 319 | cookies := sessions[g] |
| 320 | for i := 0; i < each; i++ { |
| 321 | if code, _ := f.post(cookies, f.update(g*100+i, fmt.Sprintf("g%di%d", g, i)), ""); code != http.StatusNoContent { |
| 322 | t.Errorf("POST: %d", code) |
| 323 | } |
| 324 | } |
| 325 | }(g) |
| 326 | } |
| 327 | wg.Wait() |
| 328 | var last int64 |
| 329 | for last < writers*each { |
| 330 | fr := w.next(t) |
| 331 | if fr.event != "push" { |
| 332 | t.Fatalf("%+v, want push", fr) |
| 333 | } |
| 334 | seq, _ := strconv.ParseInt(strings.Fields(fr.data)[0], 10, 64) |
| 335 | if seq != last+1 { |
| 336 | t.Fatalf("frame %d after %d: out of order or a gap", seq, last) |
| 337 | } |
| 338 | last = seq |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | // §3.1: resume from since; Last-Event-ID wins over since. |
| 343 | func TestPushResumesFromSinceAndLastEventID(t *testing.T) { |
| 344 | f := newPushFixture(t, pushOn()) |
| 345 | for k := 1; k <= 5; k++ { |
| 346 | f.post(f.cookies, f.update(k, fmt.Sprint("row", k)), "") |
| 347 | } |
| 348 | seqs := func(s *testStream, n int) []string { |
| 349 | var out []string |
| 350 | for i := 0; i < n; i++ { |
| 351 | fr := s.next(t) |
| 352 | if fr.event != "push" { |
| 353 | t.Fatalf("%+v, want push", fr) |
| 354 | } |
| 355 | out = append(out, fr.id) |
| 356 | } |
| 357 | s.quiet(t, 150*time.Millisecond) |
| 358 | return out |
| 359 | } |
| 360 | s := f.open(f.cookies, "?push=1&since=2", nil) |
| 361 | if _, cur, _ := s.hello(t); cur != 5 { |
| 362 | t.Fatalf("hello seq %d, want 5", cur) |
| 363 | } |
| 364 | if got := strings.Join(seqs(s, 3), ","); got != "3,4,5" { |
| 365 | t.Fatalf("since=2 sent %s", got) |
| 366 | } |
| 367 | s = f.open(f.cookies, "?push=1&since=1", map[string]string{"Last-Event-ID": "4"}) |
| 368 | s.hello(t) |
| 369 | if got := strings.Join(seqs(s, 1), ","); got != "5" { |
| 370 | t.Fatalf("Last-Event-ID 4 over since=1 sent %s", got) |
| 371 | } |
| 372 | for _, q := range []string{"?push=1&since=banana", "?push=1&since=-1"} { |
| 373 | req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream"+q, nil) |
| 374 | for _, c := range f.cookies { |
| 375 | req.AddCookie(c) |
| 376 | } |
| 377 | res, err := f.srv.Client().Do(req) |
| 378 | if err != nil { |
| 379 | t.Fatal(err) |
| 380 | } |
| 381 | res.Body.Close() |
| 382 | if res.StatusCode != http.StatusBadRequest { |
| 383 | t.Errorf("%s: %d, want 400", q, res.StatusCode) |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // §3.1: hello first, with the current seq and the log epoch; a push stream |
| 389 | // with no cursor keeps today's connect-time update; fetches carry the |
| 390 | // epoch too. |
| 391 | func TestPushHelloAndTheConnectTimeUpdate(t *testing.T) { |
| 392 | f := newPushFixture(t, pushOn()) |
| 393 | f.post(f.cookies, f.update(1, "one"), "") |
| 394 | s := f.open(f.cookies, "?push=1", nil) |
| 395 | id, seq, epoch := s.hello(t) |
| 396 | if id == "" || seq != 1 || epoch != f.app.store.logEpoch || epoch == "" { |
| 397 | t.Fatalf("hello %q %d %q (log epoch %q)", id, seq, epoch, f.app.store.logEpoch) |
| 398 | } |
| 399 | if fr := s.next(t); fr.event != "update" || fr.data != "1" || fr.id != "" { |
| 400 | t.Fatalf("%+v, want the connect-time update 1 without an id", fr) |
| 401 | } |
| 402 | rec := httptest.NewRecorder() |
| 403 | f.app.Handler().ServeHTTP(rec, f.app.TestRequest(t, "owner@example.com", http.MethodGet, "/d/"+f.doc.Sqid+"/updates?since=0", nil)) |
| 404 | if rec.Header().Get("Docs-Log-Epoch") != epoch { |
| 405 | t.Fatalf("fetch Docs-Log-Epoch %q, want %q", rec.Header().Get("Docs-Log-Epoch"), epoch) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | // §3.1: a row over 32 KiB goes as update (no id), and the cursor moves past |
| 410 | // it; a client more than 256 rows behind gets one update. |
| 411 | func TestPushOversizedAndFarBehindGoByFetch(t *testing.T) { |
| 412 | f := newPushFixture(t, pushOn()) |
| 413 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 414 | s.hello(t) |
| 415 | big := f.update(1, strings.Repeat("x", pushMaxRowBytes+1024)) |
| 416 | if len(big) <= pushMaxRowBytes { |
| 417 | t.Fatalf("test update is only %d bytes", len(big)) |
| 418 | } |
| 419 | f.post(f.cookies, big, "") |
| 420 | if fr := s.next(t); fr.event != "update" || fr.data != "1" || fr.id != "" { |
| 421 | t.Fatalf("%+v, want update 1 with no id", fr) |
| 422 | } |
| 423 | f.post(f.cookies, f.update(2, "small"), "") |
| 424 | if fr := s.next(t); fr.event != "push" || fr.id != "2" { |
| 425 | t.Fatalf("%+v, want push 2 after the update moved the cursor", fr) |
| 426 | } |
| 427 | |
| 428 | g := newPushFixture(t, pushOn()) |
| 429 | for k := 1; k <= pushMaxBehindRow+10; k++ { |
| 430 | g.post(g.cookies, g.update(k, fmt.Sprint("r", k)), "") |
| 431 | } |
| 432 | behind := g.open(g.cookies, "?push=1&since=0", nil) |
| 433 | behind.hello(t) |
| 434 | want := strconv.Itoa(pushMaxBehindRow + 10) |
| 435 | if fr := behind.next(t); fr.event != "update" || fr.data != want { |
| 436 | t.Fatalf("%+v, want one update %s", fr, want) |
| 437 | } |
| 438 | behind.quiet(t, 150*time.Millisecond) |
| 439 | g.post(g.cookies, g.update(9999, "next"), "") |
| 440 | if fr := behind.next(t); fr.event != "push" || fr.id != strconv.Itoa(pushMaxBehindRow+11) { |
| 441 | t.Fatalf("%+v, want the next row as push", fr) |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | // §3.6: bye before the TTL close and on drain. |
| 446 | func TestPushByeOnTTLAndDrain(t *testing.T) { |
| 447 | f := newPushFixture(t, pushOn()) |
| 448 | streamDurations(t, f.app, time.Minute, 300*time.Millisecond) |
| 449 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 450 | s.hello(t) |
| 451 | if fr := s.next(t); fr.event != "bye" || fr.data != "ttl" { |
| 452 | t.Fatalf("%+v, want bye ttl", fr) |
| 453 | } |
| 454 | streamDurations(t, f.app, time.Minute, time.Minute) |
| 455 | d := f.open(f.cookies, "?push=1&since=0", nil) |
| 456 | d.hello(t) |
| 457 | f.app.Drain() |
| 458 | if fr := d.next(t); fr.event != "bye" || fr.data != "drain" { |
| 459 | t.Fatalf("%+v, want bye drain", fr) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | // §3.6: a team-mode push stream says `bye lease` before its lease closes it. |
| 464 | func TestPushByeLeaseInTeamMode(t *testing.T) { |
| 465 | tf := newTeamRouterFixtureWith(t, false, false) |
| 466 | tf.app.handlers.livePush = true |
| 467 | tf.app.store.recordOrigin = tf.app.handlers.pushRegistry.record |
| 468 | tf.app.handlers.pushLeaseLead = 24 * time.Hour // longer than any lease: at once |
| 469 | b := tf.browser() |
| 470 | b.localSignin(t, "alice@example.com") |
| 471 | b.linkProof(t, teamSubject('a'), "alice@example.com") |
| 472 | routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/")) |
| 473 | srv := httptest.NewServer(tf.app.Handler()) |
| 474 | defer srv.Close() |
| 475 | f := &pushFixture{t: t, app: tf.app, srv: srv, doc: tf.own, ctx: context.Background(), host: strings.TrimPrefix(strings.TrimPrefix(bridgeOrigin, "https://"), "http://")} |
| 476 | for _, c := range b.cookies { |
| 477 | f.cookies = append(f.cookies, c) |
| 478 | } |
| 479 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 480 | s.hello(t) |
| 481 | fr := s.next(t) |
| 482 | for fr.event == "push" { // the fixture's own row, resumed from 0 |
| 483 | fr = s.next(t) |
| 484 | } |
| 485 | if fr.event != "bye" || fr.data != "lease" { |
| 486 | t.Fatalf("%+v, want bye lease", fr) |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | // §6 and §9.1: a reader's stream receives frames, and the reader cannot |
| 491 | // post; access revoked between two frames ends the stream. |
| 492 | func TestPushReaderAndRevocation(t *testing.T) { |
| 493 | f := newPushFixture(t, pushOn()) |
| 494 | // Private: a Team document would stay readable to an allowlisted member |
| 495 | // after the grant goes. |
| 496 | f.doc = f.app.TestCreatePrivate(t, f.owner, "Private") |
| 497 | f.app.TestPerson(t, "reader@example.com") |
| 498 | if err := f.app.Store().Grant(f.ctx, f.owner, f.doc.Sqid, "reader@example.com", RoleReader); err != nil { |
| 499 | t.Fatal(err) |
| 500 | } |
| 501 | reader := f.session("reader@example.com") |
| 502 | s := f.open(reader, "?push=1&since=0", nil) |
| 503 | s.hello(t) |
| 504 | f.post(f.cookies, f.update(1, "for the reader"), "") |
| 505 | if fr := s.next(t); fr.event != "push" || fr.id != "1" { |
| 506 | t.Fatalf("reader: %+v, want push 1", fr) |
| 507 | } |
| 508 | if code, _ := f.post(reader, f.update(2, "from the reader"), ""); code != http.StatusNotFound { |
| 509 | t.Fatalf("reader POST: %d, want 404", code) |
| 510 | } |
| 511 | // The owner's stream warms the frame cache, so the reader's would be |
| 512 | // served from it if the check were skipped. |
| 513 | owner := f.open(f.cookies, "?push=1&since=1", nil) |
| 514 | owner.hello(t) |
| 515 | if err := f.app.Store().Revoke(f.ctx, f.owner, f.doc.Sqid, "reader@example.com"); err != nil { |
| 516 | t.Fatal(err) |
| 517 | } |
| 518 | f.post(f.cookies, f.update(3, "after revocation"), "") |
| 519 | if fr := owner.next(t); fr.event != "push" || fr.id != "2" { |
| 520 | t.Fatalf("owner: %+v", fr) |
| 521 | } |
| 522 | s.endsWithoutAFrame(t, "a revoked reader") |
| 523 | } |
| 524 | |
| 525 | // endsWithoutAFrame asserts the stream closes and sends nothing first |
| 526 | // (#175 finding 7: a frame of any kind is a failure, not only push). |
| 527 | func (s *testStream) endsWithoutAFrame(t *testing.T, who string) { |
| 528 | t.Helper() |
| 529 | select { |
| 530 | case fr := <-s.frames: |
| 531 | t.Fatalf("%s's stream sent %+v instead of ending", who, fr) |
| 532 | case <-s.done: |
| 533 | select { |
| 534 | case fr := <-s.frames: |
| 535 | t.Fatalf("%s's stream sent %+v before ending", who, fr) |
| 536 | default: |
| 537 | } |
| 538 | case <-time.After(3 * time.Second): |
| 539 | t.Fatalf("%s's stream stayed open", who) |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // #175 finding 7: a stream ends, sending nothing, when its document is |
| 544 | // deleted, its session signs out, or the document stops being visible to |
| 545 | // the reader; and, in team mode, when the roster drops the member. A short |
| 546 | // heartbeat makes each stream re-check without a new update. |
| 547 | func TestPushStreamsEndWhenAccessEnds(t *testing.T) { |
| 548 | t.Run("delete", func(t *testing.T) { |
| 549 | f := newPushFixture(t, pushOn()) |
| 550 | streamDurations(t, f.app, 50*time.Millisecond, time.Minute) |
| 551 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 552 | s.hello(t) |
| 553 | if err := f.app.Store().Delete(f.ctx, f.owner, f.doc.Sqid); err != nil { |
| 554 | t.Fatal(err) |
| 555 | } |
| 556 | s.endsWithoutAFrame(t, "a deleted document") |
| 557 | }) |
| 558 | t.Run("sign-out", func(t *testing.T) { |
| 559 | f := newPushFixture(t, pushOn()) |
| 560 | streamDurations(t, f.app, 50*time.Millisecond, time.Minute) |
| 561 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 562 | s.hello(t) |
| 563 | req, _ := http.NewRequest(http.MethodPost, f.srv.URL+"/signout", nil) |
| 564 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 565 | req.Header.Set("Origin", f.srv.URL) |
| 566 | for _, c := range f.cookies { |
| 567 | req.AddCookie(c) |
| 568 | } |
| 569 | client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 570 | res, err := client.Do(req) |
| 571 | if err != nil { |
| 572 | t.Fatal(err) |
| 573 | } |
| 574 | res.Body.Close() |
| 575 | if res.StatusCode >= 400 { |
| 576 | t.Fatalf("sign-out: %d", res.StatusCode) |
| 577 | } |
| 578 | s.endsWithoutAFrame(t, "a signed-out session") |
| 579 | }) |
| 580 | t.Run("visibility", func(t *testing.T) { |
| 581 | f := newPushFixture(t, pushOn()) |
| 582 | streamDurations(t, f.app, 50*time.Millisecond, time.Minute) |
| 583 | f.app.TestPerson(t, "member@example.com") |
| 584 | member := f.session("member@example.com") |
| 585 | s := f.open(member, "?push=1&since=0", nil) // a team document: every member reads it |
| 586 | s.hello(t) |
| 587 | if err := f.app.Store().SetVisibility(f.ctx, f.owner, f.doc.Sqid, VisibilityPrivate); err != nil { |
| 588 | t.Fatal(err) |
| 589 | } |
| 590 | s.endsWithoutAFrame(t, "a member of a document made private") |
| 591 | }) |
| 592 | t.Run("roster", func(t *testing.T) { |
| 593 | f, tf := teamPushFixture(t) |
| 594 | streamDurations(t, f.app, 50*time.Millisecond, time.Minute) |
| 595 | s := f.open(f.cookies, "?push=1&since="+strconv.FormatInt(f.currentSeq(), 10), nil) |
| 596 | s.hello(t) |
| 597 | tf.clock.step(roster.RetryAfter) |
| 598 | tf.directory.change([]roster.MemberEntry{{Subject: teamSubject('b'), Role: "member"}, {Subject: teamSubject('c'), Role: "member"}}, false) |
| 599 | if err := tf.app.store.team.cache.Refresh(t.Context()); err != nil { |
| 600 | t.Fatal(err) |
| 601 | } |
| 602 | s.endsWithoutAFrame(t, "a member the roster dropped") |
| 603 | }) |
| 604 | } |
| 605 | |
| 606 | // §7: with the switch on, a client that does not ask for push sees exactly |
| 607 | // today's stream: no hello, update events whose data parses as an Int64 |
| 608 | // (the old native parser's rule), and the POST answers as before. |
| 609 | func TestPushOldClientsAreUnchanged(t *testing.T) { |
| 610 | f := newPushFixture(t, pushOn()) |
| 611 | s := f.open(f.cookies, "", nil) |
| 612 | fr := s.next(t) |
| 613 | if fr.event != "update" || fr.data != "0" || fr.id != "" { |
| 614 | t.Fatalf("first event %+v, want update 0", fr) |
| 615 | } |
| 616 | code, seq := f.post(f.cookies, f.update(1, "old"), "") |
| 617 | if code != http.StatusNoContent || seq != 1 { |
| 618 | t.Fatalf("POST %d %d", code, seq) |
| 619 | } |
| 620 | fr = s.next(t) |
| 621 | if _, err := strconv.ParseInt(fr.data, 10, 64); fr.event != "update" || err != nil || fr.id != "" { |
| 622 | t.Fatalf("%+v, want update with an Int64 data line", fr) |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | // §8: off, push=1 is ignored and Docs-Stream changes nothing. |
| 627 | func TestPushSwitchOff(t *testing.T) { |
| 628 | f := newPushFixture(t, Config{}) |
| 629 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 630 | if fr := s.next(t); fr.event != "update" || fr.data != "0" { |
| 631 | t.Fatalf("%+v, want today's connect-time update", fr) |
| 632 | } |
| 633 | f.post(f.cookies, f.update(1, "x"), "anything.1") |
| 634 | if fr := s.next(t); fr.event != "update" || fr.data != "1" { |
| 635 | t.Fatalf("%+v, want update 1", fr) |
| 636 | } |
| 637 | rec := httptest.NewRecorder() |
| 638 | f.app.Handler().ServeHTTP(rec, f.app.TestRequest(t, "owner@example.com", http.MethodGet, "/d/"+f.doc.Sqid+"/updates?since=0", nil)) |
| 639 | if rec.Header().Get("Docs-Log-Epoch") != "" { |
| 640 | t.Error("Docs-Log-Epoch with the switch off") |
| 641 | } |
| 642 | for _, c := range []struct { |
| 643 | in string |
| 644 | want bool |
| 645 | bad bool |
| 646 | }{{"", false, false}, {"off", false, false}, {"on", true, false}, {"maybe", false, true}} { |
| 647 | got, err := ParseLivePush(c.in) |
| 648 | if got != c.want || (err != nil) != c.bad { |
| 649 | t.Errorf("ParseLivePush(%q) = %v, %v", c.in, got, err) |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | // §5: late answers. Within the limit nothing waits; over it the next answer |
| 655 | // waits (at most a second); a third waiter is busy (503); cancellation and |
| 656 | // drain end a wait. |
| 657 | func TestLateAnswers(t *testing.T) { |
| 658 | l := newLateAnswers() |
| 659 | clock := time.Unix(1000, 0) |
| 660 | var mu sync.Mutex |
| 661 | l.now = func() time.Time { mu.Lock(); defer mu.Unlock(); return clock } |
| 662 | drain := make(chan struct{}) |
| 663 | ctx := context.Background() |
| 664 | for i := 0; i < lateLimit; i++ { |
| 665 | if ok, busy := l.admit(ctx, drain, "s", 1); !ok || busy { |
| 666 | t.Fatalf("POST %d within the limit refused", i) |
| 667 | } |
| 668 | } |
| 669 | if ok, busy := l.admit(ctx, drain, "", 1); !ok || busy { |
| 670 | t.Fatal("an unbound session is not paced") |
| 671 | } |
| 672 | if ok, _ := l.admit(ctx, drain, "s", 2); !ok { |
| 673 | t.Fatal("another document is not paced") |
| 674 | } |
| 675 | start := time.Now() |
| 676 | if ok, busy := l.admit(ctx, drain, "s", 1); !ok || busy { |
| 677 | t.Fatal("the paced POST was refused") |
| 678 | } |
| 679 | if waited := time.Since(start); waited < 900*time.Millisecond || waited > 2*time.Second { |
| 680 | t.Fatalf("waited %v, want about a second", waited) |
| 681 | } |
| 682 | // Two waiting, the third busy. |
| 683 | results := make(chan bool, 2) |
| 684 | cctx, cancel := context.WithCancel(ctx) |
| 685 | for i := 0; i < 2; i++ { |
| 686 | go func() { ok, _ := l.admit(cctx, drain, "s", 1); results <- ok }() |
| 687 | } |
| 688 | time.Sleep(100 * time.Millisecond) |
| 689 | if ok, busy := l.admit(ctx, drain, "s", 1); ok || !busy { |
| 690 | t.Fatalf("third waiter: ok %v busy %v, want busy", ok, busy) |
| 691 | } |
| 692 | cancel() |
| 693 | for i := 0; i < 2; i++ { |
| 694 | if <-results { |
| 695 | t.Fatal("a cancelled wait reported ok") |
| 696 | } |
| 697 | } |
| 698 | go func() { time.Sleep(100 * time.Millisecond); close(drain) }() |
| 699 | if ok, _ := l.admit(ctx, drain, "s", 1); ok { |
| 700 | t.Fatal("a drained wait reported ok") |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | // §5 at the handler: a session posting far over the limit gets 503 with |
| 705 | // Retry-After for what cannot wait, never a 4xx. |
| 706 | func TestLateAnswersAt503(t *testing.T) { |
| 707 | f := newPushFixture(t, pushOn()) |
| 708 | var mu sync.Mutex |
| 709 | codes := map[int]int{} |
| 710 | var wg sync.WaitGroup |
| 711 | u := f.update(1, "same") |
| 712 | for i := 0; i < lateLimit+20; i++ { |
| 713 | wg.Add(1) |
| 714 | go func() { |
| 715 | defer wg.Done() |
| 716 | code, _ := f.post(f.cookies, u, "") |
| 717 | mu.Lock() |
| 718 | codes[code]++ |
| 719 | mu.Unlock() |
| 720 | }() |
| 721 | } |
| 722 | wg.Wait() |
| 723 | for code := range codes { |
| 724 | if code >= 400 && code < 500 { |
| 725 | t.Fatalf("answers %v: a 4xx", codes) |
| 726 | } |
| 727 | } |
| 728 | if codes[http.StatusServiceUnavailable] == 0 { |
| 729 | t.Fatalf("answers %v: nothing was told to wait", codes) |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | // §3.1: the log epoch stays across ordinary restarts, overlapping ones |
| 734 | // included, and rotates when the file beside the database is gone or the |
| 735 | // database is older than the last start (a restore). |
| 736 | func TestLogEpochRotation(t *testing.T) { |
| 737 | dir := t.TempDir() |
| 738 | cfg := Config{DBPath: filepath.Join(dir, "docs.db"), Env: "development"} |
| 739 | start := func() *App { |
| 740 | app, err := New(cfg) |
| 741 | if err != nil { |
| 742 | t.Fatal(err) |
| 743 | } |
| 744 | return app |
| 745 | } |
| 746 | a := start() |
| 747 | e1 := a.store.logEpoch |
| 748 | b := start() // an overlapping generation |
| 749 | if b.store.logEpoch != e1 { |
| 750 | t.Fatal("an overlapping start rotated the epoch") |
| 751 | } |
| 752 | b.Close() |
| 753 | a.Close() |
| 754 | backup := copyDB(t, cfg.DBPath, dir+"/backup") |
| 755 | c := start() |
| 756 | if c.store.logEpoch != e1 { |
| 757 | t.Fatal("an ordinary restart rotated the epoch") |
| 758 | } |
| 759 | c.Close() |
| 760 | os.Remove(cfg.DBPath + ".log-epoch") |
| 761 | d := start() |
| 762 | e2 := d.store.logEpoch |
| 763 | if e2 == e1 { |
| 764 | t.Fatal("a start without the file beside the database kept the epoch") |
| 765 | } |
| 766 | d.Close() |
| 767 | // A restore of the database from before the last start. |
| 768 | restoreDB(t, backup, cfg.DBPath) |
| 769 | e := start() |
| 770 | if e.store.logEpoch == e2 || e.store.logEpoch == e1 { |
| 771 | t.Fatal("a restored database kept an epoch") |
| 772 | } |
| 773 | e.Close() |
| 774 | } |
| 775 | |
| 776 | func copyDB(t *testing.T, from, to string) string { |
| 777 | t.Helper() |
| 778 | for _, suffix := range []string{"", "-wal", "-shm"} { |
| 779 | b, err := os.ReadFile(from + suffix) |
| 780 | if err != nil { |
| 781 | continue |
| 782 | } |
| 783 | if err := os.WriteFile(to+suffix, b, 0600); err != nil { |
| 784 | t.Fatal(err) |
| 785 | } |
| 786 | } |
| 787 | return to |
| 788 | } |
| 789 | |
| 790 | func restoreDB(t *testing.T, from, to string) { |
| 791 | t.Helper() |
| 792 | for _, suffix := range []string{"-wal", "-shm"} { |
| 793 | os.Remove(to + suffix) |
| 794 | } |
| 795 | copyDB(t, from, to) |
| 796 | } |
| 797 | |
| 798 | // §9.2's timing gate: with a round trip injected, the time from POST to the |
| 799 | // bytes in a watcher's hand is at least half a round trip shorter with |
| 800 | // push than with the fetch path (update event, then GET), in the same |
| 801 | // process, best of three medians. Push removes a request, so anything less |
| 802 | // means it is not doing so. Relative only: no absolute threshold. |
| 803 | func TestPushIsFasterThanTheFetchPath(t *testing.T) { |
| 804 | f := newPushFixture(t, pushOn()) |
| 805 | const oneWay = 10 * time.Millisecond |
| 806 | proxy := delayProxy(t, strings.TrimPrefix(f.srv.URL, "http://"), oneWay) |
| 807 | base := "http://" + proxy |
| 808 | client := &http.Client{} |
| 809 | |
| 810 | measure := func(push bool, from int) float64 { |
| 811 | watch := &pushFixture{t: t, app: f.app, srv: &httptest.Server{URL: base}, doc: f.doc, ctx: f.ctx, cookies: f.cookies} |
| 812 | query := "" |
| 813 | if push { |
| 814 | query = "?push=1&since=" + strconv.FormatInt(f.currentSeq(), 10) |
| 815 | } |
| 816 | s := watch.openClient(client, query) |
| 817 | if push { |
| 818 | s.hello(t) |
| 819 | } else { |
| 820 | s.next(t) // connect-time update |
| 821 | } |
| 822 | var times []float64 |
| 823 | for k := from; k < from+15; k++ { |
| 824 | start := time.Now() |
| 825 | code, seq := watch.postWith(client, f.update(k, fmt.Sprint("t", k))) |
| 826 | if code != http.StatusNoContent { |
| 827 | t.Fatalf("POST %d", code) |
| 828 | } |
| 829 | for { |
| 830 | fr := s.next(t) |
| 831 | if push && fr.event == "push" && fr.id == strconv.FormatInt(seq, 10) { |
| 832 | break |
| 833 | } |
| 834 | if !push && fr.event == "update" { |
| 835 | // The fetch path: the GET for the announced rows. |
| 836 | watch.getWith(client, seq-1) |
| 837 | break |
| 838 | } |
| 839 | } |
| 840 | times = append(times, float64(time.Since(start).Microseconds())/1000) |
| 841 | } |
| 842 | s.res.Body.Close() |
| 843 | sort.Float64s(times) |
| 844 | return times[len(times)/2] |
| 845 | } |
| 846 | best := func(push bool, base int) float64 { |
| 847 | b := measure(push, base) |
| 848 | for r := 1; r < 3; r++ { |
| 849 | b = min(b, measure(push, base+r*100)) |
| 850 | } |
| 851 | return b |
| 852 | } |
| 853 | fetch := best(false, 1000) |
| 854 | push := best(true, 2000) |
| 855 | t.Logf("POST -> bytes in hand, 20 ms round trip: fetch path %.1f ms, push %.1f ms", fetch, push) |
| 856 | if push > fetch-float64(oneWay.Milliseconds()) { |
| 857 | t.Fatalf("push (%.1f ms) is not half a round trip faster than the fetch path (%.1f ms)", push, fetch) |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | func (f *pushFixture) currentSeq() int64 { |
| 862 | seq, err := f.app.store.currentSeq(f.ctx, f.doc.ID) |
| 863 | if err != nil { |
| 864 | f.t.Fatal(err) |
| 865 | } |
| 866 | return seq |
| 867 | } |
| 868 | |
| 869 | func (f *pushFixture) openClient(client *http.Client, query string) *testStream { |
| 870 | f.t.Helper() |
| 871 | req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream"+query, nil) |
| 872 | for _, c := range f.cookies { |
| 873 | req.AddCookie(c) |
| 874 | } |
| 875 | res, err := client.Do(req) |
| 876 | if err != nil || res.StatusCode != 200 { |
| 877 | f.t.Fatalf("stream: %v %v", err, res) |
| 878 | } |
| 879 | s := &testStream{res: res, frames: make(chan frame, 1024), done: make(chan struct{})} |
| 880 | go func() { |
| 881 | defer close(s.done) |
| 882 | r := bufio.NewReader(res.Body) |
| 883 | var fr frame |
| 884 | for { |
| 885 | line, err := r.ReadString('\n') |
| 886 | if err != nil { |
| 887 | return |
| 888 | } |
| 889 | line = strings.TrimRight(line, "\r\n") |
| 890 | switch { |
| 891 | case strings.HasPrefix(line, "id: "): |
| 892 | fr.id, fr.tag, _ = strings.Cut(line[4:], ".") |
| 893 | case strings.HasPrefix(line, "event: "): |
| 894 | fr.event = line[7:] |
| 895 | case strings.HasPrefix(line, "data: "): |
| 896 | fr.data = line[6:] |
| 897 | case line == "": |
| 898 | if fr.event != "" { |
| 899 | s.frames <- fr |
| 900 | } |
| 901 | fr = frame{} |
| 902 | } |
| 903 | } |
| 904 | }() |
| 905 | return s |
| 906 | } |
| 907 | |
| 908 | func (f *pushFixture) postWith(client *http.Client, update []byte) (int, int64) { |
| 909 | req, _ := http.NewRequest(http.MethodPost, f.srv.URL+"/d/"+f.doc.Sqid+"/updates", bytes.NewReader(update)) |
| 910 | req.Header.Set("Content-Type", "application/octet-stream") |
| 911 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 912 | for _, c := range f.cookies { |
| 913 | req.AddCookie(c) |
| 914 | } |
| 915 | res, err := client.Do(req) |
| 916 | if err != nil { |
| 917 | f.t.Fatal(err) |
| 918 | } |
| 919 | io.Copy(io.Discard, res.Body) |
| 920 | res.Body.Close() |
| 921 | seq, _ := strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64) |
| 922 | return res.StatusCode, seq |
| 923 | } |
| 924 | |
| 925 | func (f *pushFixture) getWith(client *http.Client, since int64) { |
| 926 | req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/updates?since="+strconv.FormatInt(since, 10), nil) |
| 927 | for _, c := range f.cookies { |
| 928 | req.AddCookie(c) |
| 929 | } |
| 930 | res, err := client.Do(req) |
| 931 | if err != nil { |
| 932 | f.t.Fatal(err) |
| 933 | } |
| 934 | io.Copy(io.Discard, res.Body) |
| 935 | res.Body.Close() |
| 936 | } |
| 937 | |
| 938 | // delayProxy forwards loopback connections to upstream, holding each chunk |
| 939 | // oneWay in each direction, in order. |
| 940 | func delayProxy(t *testing.T, upstream string, oneWay time.Duration) string { |
| 941 | t.Helper() |
| 942 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 943 | if err != nil { |
| 944 | t.Fatal(err) |
| 945 | } |
| 946 | t.Cleanup(func() { l.Close() }) |
| 947 | pump := func(src, dst net.Conn) { |
| 948 | type chunk struct { |
| 949 | b []byte |
| 950 | at time.Time |
| 951 | } |
| 952 | ch := make(chan chunk, 1<<12) |
| 953 | go func() { |
| 954 | for c := range ch { |
| 955 | time.Sleep(time.Until(c.at)) |
| 956 | if _, err := dst.Write(c.b); err != nil { |
| 957 | break |
| 958 | } |
| 959 | } |
| 960 | dst.Close() |
| 961 | for range ch { |
| 962 | } |
| 963 | }() |
| 964 | buf := make([]byte, 32<<10) |
| 965 | for { |
| 966 | n, err := src.Read(buf) |
| 967 | if n > 0 { |
| 968 | ch <- chunk{append([]byte(nil), buf[:n]...), time.Now().Add(oneWay)} |
| 969 | } |
| 970 | if err != nil { |
| 971 | close(ch) |
| 972 | return |
| 973 | } |
| 974 | } |
| 975 | } |
| 976 | go func() { |
| 977 | for { |
| 978 | c, err := l.Accept() |
| 979 | if err != nil { |
| 980 | return |
| 981 | } |
| 982 | u, err := net.Dial("tcp", upstream) |
| 983 | if err != nil { |
| 984 | c.Close() |
| 985 | continue |
| 986 | } |
| 987 | go pump(c, u) |
| 988 | go pump(u, c) |
| 989 | } |
| 990 | }() |
| 991 | return l.Addr().String() |
| 992 | } |
| 993 | |
| 994 | // §3.4: the origin entry is recorded inside the POST's transaction, so even |
| 995 | // with other writers' POSTs waking the poster's stream in between, every |
| 996 | // update the poster sent comes back to it as `own`, never as its own bytes. |
| 997 | func TestPushOwnUnderConcurrentPOSTs(t *testing.T) { |
| 998 | f := newPushFixture(t, pushOn()) |
| 999 | f.app.TestPerson(t, "other@example.com") |
| 1000 | if err := f.app.Store().Grant(f.ctx, f.owner, f.doc.Sqid, "other@example.com", RoleWriter); err != nil { |
| 1001 | t.Fatal(err) |
| 1002 | } |
| 1003 | other := f.session("other@example.com") |
| 1004 | poster := f.open(f.cookies, "?push=1&since=0", nil) |
| 1005 | id, _, _ := poster.hello(t) |
| 1006 | const each = 20 |
| 1007 | mine := map[int64]string{} |
| 1008 | var mu sync.Mutex |
| 1009 | var wg sync.WaitGroup |
| 1010 | wg.Add(2) |
| 1011 | go func() { |
| 1012 | defer wg.Done() |
| 1013 | for i := 0; i < each; i++ { |
| 1014 | _, seq := f.post(f.cookies, f.update(i, fmt.Sprint("mine", i)), fmt.Sprintf("%s.%d", id, i+1)) |
| 1015 | mu.Lock() |
| 1016 | mine[seq] = strconv.Itoa(i + 1) |
| 1017 | mu.Unlock() |
| 1018 | } |
| 1019 | }() |
| 1020 | go func() { |
| 1021 | defer wg.Done() |
| 1022 | for i := 0; i < each; i++ { |
| 1023 | f.post(other, f.update(100+i, fmt.Sprint("theirs", i)), "") |
| 1024 | } |
| 1025 | }() |
| 1026 | wg.Wait() |
| 1027 | for seen := 0; seen < 2*each; seen++ { |
| 1028 | fr := poster.next(t) |
| 1029 | seq, _ := strconv.ParseInt(fr.id, 10, 64) |
| 1030 | counter, isMine := mine[seq] |
| 1031 | switch { |
| 1032 | case isMine && (fr.event != "own" || fr.data != fr.id+" "+counter): |
| 1033 | t.Fatalf("my update %d came back as %+v", seq, fr) |
| 1034 | case !isMine && fr.event != "push": |
| 1035 | t.Fatalf("another writer's update %d came back as %+v", seq, fr) |
| 1036 | } |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | // The frame cache changes nothing a stream sends: the same frames, bytes |
| 1041 | // included, with it on and off; with it on, W streams read each row once. |
| 1042 | func TestPushFrameCacheIsTransparent(t *testing.T) { |
| 1043 | run := func(cache bool) ([]string, int64, int64) { |
| 1044 | f := newPushFixture(t, pushOn()) |
| 1045 | f.app.handlers.pushFrameCache = cache |
| 1046 | var streams []*testStream |
| 1047 | for i := 0; i < 4; i++ { |
| 1048 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 1049 | s.hello(t) |
| 1050 | streams = append(streams, s) |
| 1051 | } |
| 1052 | writer := f.session("owner@example.com") |
| 1053 | for k := 1; k <= 10; k++ { |
| 1054 | f.post(writer, f.update(k, fmt.Sprint("c", k)), "") |
| 1055 | } |
| 1056 | var got []string |
| 1057 | for _, s := range streams { |
| 1058 | for i := 0; i < 10; i++ { |
| 1059 | fr := s.next(t) |
| 1060 | got = append(got, fr.event+" "+fr.id+" "+fr.data) |
| 1061 | } |
| 1062 | } |
| 1063 | st := f.app.handlers.pushStats |
| 1064 | return got, st.rowReads.Load(), st.cacheHits.Load() |
| 1065 | } |
| 1066 | off, offReads, _ := run(false) |
| 1067 | on, onReads, hits := run(true) |
| 1068 | if strings.Join(off, "\n") != strings.Join(on, "\n") { |
| 1069 | t.Fatal("the frame cache changed what streams send") |
| 1070 | } |
| 1071 | if hits == 0 || onReads >= offReads { |
| 1072 | t.Fatalf("cache on: %d row reads and %d hits, against %d reads off", onReads, hits, offReads) |
| 1073 | } |
| 1074 | t.Logf("4 streams x 10 rows: %d row reads without the cache, %d with it (%d hits)", offReads, onReads, hits) |
| 1075 | } |
| 1076 | |
| 1077 | // #175 finding 1: the limiter keys on the authenticated person, not on |
| 1078 | // cookie bytes. One real session posting 45 times at once, each request with |
| 1079 | // an extra rastrillo_session cookie appended (auth reads only the first), |
| 1080 | // must still be paced: some answers 503, none 4xx. And the junk cookie |
| 1081 | // does not change the stream binding: own still arrives. |
| 1082 | func TestLateAnswersIgnoreAppendedCookies(t *testing.T) { |
| 1083 | f := newPushFixture(t, pushOn()) |
| 1084 | poster := f.open(f.cookies, "?push=1&since=0", nil) |
| 1085 | id, _, _ := poster.hello(t) |
| 1086 | u := f.update(1, "same") |
| 1087 | var mu sync.Mutex |
| 1088 | codes := map[int]int{} |
| 1089 | var wg sync.WaitGroup |
| 1090 | for i := 0; i < 45; i++ { |
| 1091 | wg.Add(1) |
| 1092 | go func(i int) { |
| 1093 | defer wg.Done() |
| 1094 | cookies := append(append([]*http.Cookie(nil), f.cookies...), &http.Cookie{Name: "rastrillo_session", Value: fmt.Sprint("junk", i)}) |
| 1095 | code, _ := f.post(cookies, u, "") |
| 1096 | mu.Lock() |
| 1097 | codes[code]++ |
| 1098 | mu.Unlock() |
| 1099 | }(i) |
| 1100 | } |
| 1101 | wg.Wait() |
| 1102 | for code := range codes { |
| 1103 | if code >= 400 && code < 500 { |
| 1104 | t.Fatalf("answers %v: a 4xx", codes) |
| 1105 | } |
| 1106 | } |
| 1107 | if codes[http.StatusServiceUnavailable] == 0 { |
| 1108 | t.Fatalf("answers %v: 45 POSTs at once were not paced (junk cookies made 45 limiter keys)", codes) |
| 1109 | } |
| 1110 | time.Sleep(1100 * time.Millisecond) // out of the window |
| 1111 | junk := append(append([]*http.Cookie(nil), f.cookies...), &http.Cookie{Name: "rastrillo_session", Value: "junk"}) |
| 1112 | f.post(junk, f.update(2, "mine"), id+".9") |
| 1113 | for { |
| 1114 | fr := poster.next(t) |
| 1115 | if fr.event == "own" && strings.HasSuffix(fr.data, " 9") { |
| 1116 | break |
| 1117 | } |
| 1118 | if fr.event == "push" && strings.Contains(fr.data, base64.StdEncoding.EncodeToString(f.update(2, "mine"))) { |
| 1119 | t.Fatal("an appended cookie broke the stream binding: own came back as push") |
| 1120 | } |
| 1121 | } |
| 1122 | } |
| 1123 | |
| 1124 | // #175 finding 2: a stream that will get a single update (too far behind, |
| 1125 | // or rows too large to push) learns so from the rows' lengths, before any |
| 1126 | // row's bytes are read or opened, and the frame cache never keeps a row it |
| 1127 | // could not push. |
| 1128 | func TestPushFarBehindReadsNoBytes(t *testing.T) { |
| 1129 | f := newPushFixture(t, pushOn()) |
| 1130 | for k := 1; k <= 20; k++ { |
| 1131 | f.post(f.cookies, f.update(k, strings.Repeat(fmt.Sprint(k%10), pushMaxRowBytes+1024)), "") |
| 1132 | } |
| 1133 | reads := f.app.handlers.pushStats.rowReads.Load() |
| 1134 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 1135 | s.hello(t) |
| 1136 | if fr := s.next(t); fr.event != "update" || fr.data != "20" { |
| 1137 | t.Fatalf("%+v, want update 20", fr) |
| 1138 | } |
| 1139 | if n := f.app.handlers.pushStats.rowReads.Load() - reads; n != 0 { |
| 1140 | t.Fatalf("%d rows read and opened for a stream that got one update", n) |
| 1141 | } |
| 1142 | f.app.handlers.pushRegistry.mu.Lock() |
| 1143 | for _, c := range f.app.handlers.pushRegistry.frames { |
| 1144 | c.mu.Lock() |
| 1145 | for seq, b := range c.rows { |
| 1146 | if len(b) > pushMaxRowBytes { |
| 1147 | t.Errorf("the frame cache holds row %d (%d bytes)", seq, len(b)) |
| 1148 | } |
| 1149 | } |
| 1150 | c.mu.Unlock() |
| 1151 | } |
| 1152 | f.app.handlers.pushRegistry.mu.Unlock() |
| 1153 | |
| 1154 | g := newPushFixture(t, pushOn()) |
| 1155 | for k := 1; k <= pushMaxBehindRow+44; k++ { |
| 1156 | g.post(g.cookies, g.update(k, fmt.Sprint("r", k)), "") |
| 1157 | } |
| 1158 | reads = g.app.handlers.pushStats.rowReads.Load() |
| 1159 | behind := g.open(g.cookies, "?push=1&since=0", nil) |
| 1160 | behind.hello(t) |
| 1161 | if fr := behind.next(t); fr.event != "update" { |
| 1162 | t.Fatalf("%+v, want update", fr) |
| 1163 | } |
| 1164 | if n := g.app.handlers.pushStats.rowReads.Load() - reads; n != 0 { |
| 1165 | t.Fatalf("%d rows read for a stream %d rows behind", n, pushMaxBehindRow+44) |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | // #175 finding 3: push and own frames carry id <seq>.<tag>, the tag a digest |
| 1170 | // of the row; fetches carry Docs-Seq-Tag. A resume names its cursor's tag, |
| 1171 | // and the server checks it against the row it holds. |
| 1172 | func TestPushFramesCarryTheRowsTag(t *testing.T) { |
| 1173 | f := newPushFixture(t, pushOn()) |
| 1174 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 1175 | s.hello(t) |
| 1176 | u := f.update(1, "tagged") |
| 1177 | f.post(f.cookies, u, "") |
| 1178 | fr := s.next(t) |
| 1179 | if fr.event != "push" || fr.id != "1" || fr.tag != pushTag(1, u) { |
| 1180 | t.Fatalf("%+v, want push 1 with tag %s", fr, pushTag(1, u)) |
| 1181 | } |
| 1182 | rec := httptest.NewRecorder() |
| 1183 | f.app.Handler().ServeHTTP(rec, f.app.TestRequest(t, "owner@example.com", http.MethodGet, "/d/"+f.doc.Sqid+"/updates?since=0", nil)) |
| 1184 | if got := rec.Header().Get("Docs-Seq-Tag"); got != pushTag(1, u) { |
| 1185 | t.Fatalf("Docs-Seq-Tag %q, want %q", got, pushTag(1, u)) |
| 1186 | } |
| 1187 | f.post(f.cookies, f.update(2, "next"), "") |
| 1188 | good := f.open(f.cookies, "?push=1&since=1", map[string]string{"Docs-Seq-Tag": pushTag(1, u)}) |
| 1189 | good.hello(t) |
| 1190 | if fr := good.next(t); fr.event != "push" || fr.id != "2" { |
| 1191 | t.Fatalf("resume with the right tag: %+v", fr) |
| 1192 | } |
| 1193 | viaHeader := f.open(f.cookies, "?push=1", map[string]string{"Last-Event-ID": "1." + pushTag(1, u)}) |
| 1194 | viaHeader.hello(t) |
| 1195 | if fr := viaHeader.next(t); fr.event != "push" || fr.id != "2" { |
| 1196 | t.Fatalf("resume by Last-Event-ID seq.tag: %+v", fr) |
| 1197 | } |
| 1198 | bad := f.open(f.cookies, "?push=1&since=1", map[string]string{"Docs-Seq-Tag": "0000000000000000"}) |
| 1199 | bad.hello(t) |
| 1200 | if fr := bad.next(t); fr.event != "resync" { |
| 1201 | t.Fatalf("resume with a wrong tag: %+v, want resync", fr) |
| 1202 | } |
| 1203 | // Never in the query string, where access logs keep it (#175 approval, |
| 1204 | // finding 6): a tag there is not read. |
| 1205 | query := f.open(f.cookies, "?push=1&since=1&tag=0000000000000000", nil) |
| 1206 | query.hello(t) |
| 1207 | if fr := query.next(t); fr.event != "push" || fr.id != "2" { |
| 1208 | t.Fatalf("a tag in the query string was read: %+v", fr) |
| 1209 | } |
| 1210 | } |
| 1211 | |
| 1212 | // #175 finding 3, the restore it is for: the database and the file beside |
| 1213 | // it copied at seq 3, rows 4 and 5 written (a client holds 5), the copy |
| 1214 | // restored in place (so the epoch is kept), and two different rows written, |
| 1215 | // so the log is back at 5. A client resuming at 5 with row 5's tag must be |
| 1216 | // told to resync; its 4 and 5 are not the log's. |
| 1217 | func TestPushRestoredLogIsDetected(t *testing.T) { |
| 1218 | dir := t.TempDir() |
| 1219 | cfg := Config{DBPath: filepath.Join(dir, "docs.db"), Env: "development", LivePush: true} |
| 1220 | open := func() *pushFixture { |
| 1221 | app, err := New(cfg) |
| 1222 | if err != nil { |
| 1223 | t.Fatal(err) |
| 1224 | } |
| 1225 | t.Cleanup(func() { app.Close() }) |
| 1226 | srv := httptest.NewServer(app.Handler()) |
| 1227 | t.Cleanup(srv.Close) |
| 1228 | f := &pushFixture{t: t, app: app, srv: srv, ctx: context.Background()} |
| 1229 | f.owner = app.TestPerson(t, "owner@example.com") |
| 1230 | docs, err := app.Store().List(f.ctx, f.owner) |
| 1231 | if err != nil { |
| 1232 | t.Fatal(err) |
| 1233 | } |
| 1234 | for _, d := range docs { |
| 1235 | if d.Title == "Restored" { |
| 1236 | f.doc = d |
| 1237 | } |
| 1238 | } |
| 1239 | if f.doc == nil { |
| 1240 | if f.doc, err = app.Store().Create(f.ctx, f.owner, "Restored"); err != nil { |
| 1241 | t.Fatal(err) |
| 1242 | } |
| 1243 | } |
| 1244 | f.cookies = f.session("owner@example.com") |
| 1245 | return f |
| 1246 | } |
| 1247 | f := open() |
| 1248 | for k := 1; k <= 3; k++ { |
| 1249 | f.post(f.cookies, f.update(k, fmt.Sprint("before", k)), "") |
| 1250 | } |
| 1251 | f.app.Close() |
| 1252 | backup := copyDB(t, cfg.DBPath, filepath.Join(dir, "backup.db")) |
| 1253 | sidecar, _ := os.ReadFile(cfg.DBPath + ".log-epoch") |
| 1254 | f = open() |
| 1255 | var held []byte |
| 1256 | for k := 4; k <= 5; k++ { |
| 1257 | held = f.update(k, fmt.Sprint("lost", k)) |
| 1258 | f.post(f.cookies, held, "") |
| 1259 | } |
| 1260 | tag := pushTag(5, held) |
| 1261 | f.app.Close() |
| 1262 | restoreDB(t, backup, cfg.DBPath) |
| 1263 | os.WriteFile(cfg.DBPath+".log-epoch", sidecar, 0600) // a volume snapshot carries it along |
| 1264 | f = open() |
| 1265 | for k := 6; k <= 7; k++ { |
| 1266 | f.post(f.cookies, f.update(k, fmt.Sprint("after", k)), "") |
| 1267 | } |
| 1268 | s := f.open(f.cookies, "?push=1&since=5", map[string]string{"Docs-Seq-Tag": tag}) |
| 1269 | _, seq, _ := s.hello(t) |
| 1270 | if seq != 5 { |
| 1271 | t.Fatalf("the restored log is at %d, want 5 (the case the seq check cannot see)", seq) |
| 1272 | } |
| 1273 | if fr := s.next(t); fr.event != "resync" { |
| 1274 | t.Fatalf("%+v: a client whose 4 and 5 are not the log's was not told to resync", fr) |
| 1275 | } |
| 1276 | } |
| 1277 | |
| 1278 | // #175 finding 5: a cursor ahead of the log is told to resync, not accepted. |
| 1279 | func TestPushCursorAheadOfTheLogResyncs(t *testing.T) { |
| 1280 | f := newPushFixture(t, pushOn()) |
| 1281 | f.post(f.cookies, f.update(1, "one"), "") |
| 1282 | s := f.open(f.cookies, "?push=1&since=99", nil) |
| 1283 | s.hello(t) |
| 1284 | if fr := s.next(t); fr.event != "resync" || fr.data != "1" { |
| 1285 | t.Fatalf("%+v, want resync 1", fr) |
| 1286 | } |
| 1287 | } |
| 1288 | |
| 1289 | // #175 finding 6: two starts close together. The first has bumped the |
| 1290 | // database's boot but not yet rewritten the file beside it when the second |
| 1291 | // reads both: the file is one boot behind, with the same epoch. That is |
| 1292 | // not a restore, and must not rotate. |
| 1293 | func TestLogEpochSurvivesAStartBetweenAnotherStartsTwoWrites(t *testing.T) { |
| 1294 | dir := t.TempDir() |
| 1295 | cfg := Config{DBPath: filepath.Join(dir, "docs.db"), Env: "development"} |
| 1296 | a, err := New(cfg) |
| 1297 | if err != nil { |
| 1298 | t.Fatal(err) |
| 1299 | } |
| 1300 | epoch := a.store.logEpoch |
| 1301 | // The window: another start has saved boot+1 and not yet renamed. |
| 1302 | if err := a.store.db.Exec("UPDATE docs_log_epoch SET boot = boot + 1 WHERE id = 1").Error; err != nil { |
| 1303 | t.Fatal(err) |
| 1304 | } |
| 1305 | b, err := New(cfg) |
| 1306 | if err != nil { |
| 1307 | t.Fatal(err) |
| 1308 | } |
| 1309 | defer b.Close() |
| 1310 | defer a.Close() |
| 1311 | if b.store.logEpoch != epoch { |
| 1312 | t.Fatal("a start between another start's database write and its file write rotated the epoch") |
| 1313 | } |
| 1314 | } |
| 1315 | |
| 1316 | // teamPushFixture is a linked team member (alice) on a team instance with |
| 1317 | // push on: a fixture for the team-mode stream tests. |
| 1318 | func teamPushFixture(t *testing.T) (*pushFixture, *teamRouterFixture) { |
| 1319 | t.Helper() |
| 1320 | tf := newTeamRouterFixtureWith(t, false, false) |
| 1321 | tf.app.handlers.livePush = true |
| 1322 | tf.app.store.recordOrigin = tf.app.handlers.pushRegistry.record |
| 1323 | b := tf.browser() |
| 1324 | b.localSignin(t, "alice@example.com") |
| 1325 | b.linkProof(t, teamSubject('a'), "alice@example.com") |
| 1326 | routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/")) |
| 1327 | srv := httptest.NewServer(tf.app.Handler()) |
| 1328 | t.Cleanup(srv.Close) |
| 1329 | f := &pushFixture{t: t, app: tf.app, srv: srv, doc: tf.own, ctx: context.Background(), host: strings.TrimPrefix(bridgeOrigin, "https://")} |
| 1330 | for _, c := range b.cookies { |
| 1331 | f.cookies = append(f.cookies, c) |
| 1332 | } |
| 1333 | return f, tf |
| 1334 | } |
| 1335 | |
| 1336 | // contendedLease makes the next n lease reads answer 0, as a roster whose |
| 1337 | // TryLock loses does (#175 finding 4). |
| 1338 | func contendedLease(f *pushFixture, n *atomic.Int32) { |
| 1339 | f.app.store.team.leaseRemaining = func(a *requestAccess) time.Duration { |
| 1340 | if n.Add(-1) >= 0 { |
| 1341 | return 0 |
| 1342 | } |
| 1343 | return a.Remaining() |
| 1344 | } |
| 1345 | } |
| 1346 | |
| 1347 | // #175 finding 4: one lease read lost to contention mid-stream does not end |
| 1348 | // the stream; each delivery asks afresh. |
| 1349 | func TestTeamStreamSurvivesAContendedLease(t *testing.T) { |
| 1350 | f, _ := teamPushFixture(t) |
| 1351 | var lost atomic.Int32 |
| 1352 | contendedLease(f, &lost) |
| 1353 | s := f.open(f.cookies, "?push=1&since="+strconv.FormatInt(f.currentSeq(), 10), nil) |
| 1354 | s.hello(t) |
| 1355 | lost.Store(1) |
| 1356 | if code, _ := f.postHost(f.update(1, "after a lost TryLock"), ""); code != http.StatusNoContent { |
| 1357 | t.Fatalf("POST %d", code) |
| 1358 | } |
| 1359 | if fr := s.next(t); fr.event != "push" { |
| 1360 | t.Fatalf("%+v, want the push the contended stream still owes", fr) |
| 1361 | } |
| 1362 | } |
| 1363 | |
| 1364 | // #175 finding 4: a Member's stream never opens without a lease deadline. A |
| 1365 | // lease that stays unreadable is refused (503); one read lost to contention |
| 1366 | // is asked again, and the stream opens on a lease (it says bye lease). |
| 1367 | func TestTeamStreamNeverOpensWithoutALease(t *testing.T) { |
| 1368 | f, _ := teamPushFixture(t) |
| 1369 | var lost atomic.Int32 |
| 1370 | contendedLease(f, &lost) |
| 1371 | lost.Store(1 << 20) |
| 1372 | req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream?push=1&since=0", nil) |
| 1373 | req.Host = f.host |
| 1374 | for _, c := range f.cookies { |
| 1375 | req.AddCookie(c) |
| 1376 | } |
| 1377 | res, err := f.srv.Client().Do(req) |
| 1378 | if err != nil { |
| 1379 | t.Fatal(err) |
| 1380 | } |
| 1381 | res.Body.Close() |
| 1382 | if res.StatusCode != http.StatusServiceUnavailable { |
| 1383 | t.Fatalf("a stream with no readable lease answered %d, want 503", res.StatusCode) |
| 1384 | } |
| 1385 | lost.Store(1) |
| 1386 | f.app.handlers.pushLeaseLead = 24 * time.Hour // a lease timer exists: bye lease at once |
| 1387 | s := f.open(f.cookies, "?push=1&since=0", nil) |
| 1388 | s.hello(t) |
| 1389 | fr := s.next(t) |
| 1390 | for fr.event == "push" { |
| 1391 | fr = s.next(t) |
| 1392 | } |
| 1393 | if fr.event != "bye" || fr.data != "lease" { |
| 1394 | t.Fatalf("%+v, want bye lease: the stream opened without a lease deadline", fr) |
| 1395 | } |
| 1396 | } |
| 1397 | |
| 1398 | // #175 approval finding 1: rastrillo's SQLite transactions are deferred, so |
| 1399 | // a transaction that reads first and writes later fails with |
| 1400 | // SQLITE_BUSY_SNAPSHOT (which busy_timeout does not retry) when another |
| 1401 | // connection commits in between. Two processes starting on one database at |
| 1402 | // once (an overlapped deploy) must both start. |
| 1403 | func TestLogEpochTwoConcurrentStarts(t *testing.T) { |
| 1404 | dir := t.TempDir() |
| 1405 | cfg := Config{DBPath: filepath.Join(dir, "docs.db"), Env: "development"} |
| 1406 | first, err := New(cfg) // migrations applied once |
| 1407 | if err != nil { |
| 1408 | t.Fatal(err) |
| 1409 | } |
| 1410 | first.Close() |
| 1411 | for round := 0; round < 20; round++ { |
| 1412 | var wg sync.WaitGroup |
| 1413 | errs := make(chan error, 2) |
| 1414 | apps := make(chan *App, 2) |
| 1415 | for i := 0; i < 2; i++ { |
| 1416 | wg.Add(1) |
| 1417 | go func() { |
| 1418 | defer wg.Done() |
| 1419 | app, err := New(cfg) |
| 1420 | if err != nil { |
| 1421 | errs <- err |
| 1422 | return |
| 1423 | } |
| 1424 | apps <- app |
| 1425 | }() |
| 1426 | } |
| 1427 | wg.Wait() |
| 1428 | close(errs) |
| 1429 | close(apps) |
| 1430 | for app := range apps { |
| 1431 | app.Close() |
| 1432 | } |
| 1433 | for err := range errs { |
| 1434 | t.Fatalf("round %d: a concurrent start failed: %v", round, err) |
| 1435 | } |
| 1436 | } |
| 1437 | } |
| 1438 | |
| 1439 | // #175 approval note 4: a stream that rests on no lease (a guest's grant) |
| 1440 | // asks the roster nothing per delivery: its standing is the one it opened |
| 1441 | // with, as before, and a roster check that may wait on a refresh is not |
| 1442 | // spent on it. |
| 1443 | func TestTeamGuestStreamAsksTheRosterNothing(t *testing.T) { |
| 1444 | f, tf := teamPushFixture(t) |
| 1445 | tf.clock.step(roster.RetryAfter) |
| 1446 | tf.directory.change([]roster.MemberEntry{{Subject: teamSubject('b'), Role: "member"}, {Subject: teamSubject('c'), Role: "member"}}, false) |
| 1447 | if err := tf.app.store.team.cache.Refresh(t.Context()); err != nil { |
| 1448 | t.Fatal(err) |
| 1449 | } |
| 1450 | f.doc = tf.shared // Bob's, granted to alice, who is no longer a member |
| 1451 | s := f.open(f.cookies, "?push=1&since="+strconv.FormatInt(f.currentSeq(), 10), nil) |
| 1452 | s.hello(t) |
| 1453 | before := f.app.store.team.freshLeases.Load() |
| 1454 | for k := 1; k <= 3; k++ { |
| 1455 | if code, _ := f.postHost(f.update(k, fmt.Sprint("guest", k)), ""); code != http.StatusNoContent { |
| 1456 | t.Fatalf("guest POST %d", code) |
| 1457 | } |
| 1458 | if fr := s.next(t); fr.event != "push" { |
| 1459 | t.Fatalf("%+v, want push", fr) |
| 1460 | } |
| 1461 | } |
| 1462 | if n := f.app.store.team.freshLeases.Load() - before; n != 0 { |
| 1463 | t.Fatalf("a guest's stream asked the roster %d times for three deliveries", n) |
| 1464 | } |
| 1465 | } |
| 1466 | |
| 1467 | // Follow-up to #175: since is a plain seq, as parseSince reads it. A tag |
| 1468 | // there (since=<seq>.<tag>) would put the row's digest back in the query |
| 1469 | // string; it is a 400. Only Last-Event-ID carries <seq>.<tag>. |
| 1470 | func TestPushSinceIsAPlainSeq(t *testing.T) { |
| 1471 | f := newPushFixture(t, pushOn()) |
| 1472 | f.post(f.cookies, f.update(1, "one"), "") |
| 1473 | req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream?push=1&since=1.0000000000000000", nil) |
| 1474 | for _, c := range f.cookies { |
| 1475 | req.AddCookie(c) |
| 1476 | } |
| 1477 | res, err := f.srv.Client().Do(req) |
| 1478 | if err != nil { |
| 1479 | t.Fatal(err) |
| 1480 | } |
| 1481 | res.Body.Close() |
| 1482 | if res.StatusCode != http.StatusBadRequest { |
| 1483 | t.Fatalf("since=<seq>.<tag> answered %d, want 400", res.StatusCode) |
| 1484 | } |
| 1485 | } |
| 1486 | |
| 1487 | // Follow-up to #175: a team stream that opened on no lease ends the moment |
| 1488 | // its standing reads Member. "Never Member without a lease" must not rest |
| 1489 | // on Access.Remaining latching Unknown (a stand-in, or a future roster, |
| 1490 | // may not latch). |
| 1491 | func TestTeamStreamWithoutALeaseEndsIfItsStandingIsMember(t *testing.T) { |
| 1492 | f, tf := teamPushFixture(t) |
| 1493 | req := httptest.NewRequest(http.MethodGet, bridgeOrigin+"/d/"+f.doc.Sqid+"/stream", nil) |
| 1494 | for _, c := range f.cookies { |
| 1495 | req.AddCookie(c) |
| 1496 | } |
| 1497 | team := tf.app.store.team |
| 1498 | session, ok := team.readSession(context.Background(), req) |
| 1499 | if !ok { |
| 1500 | t.Fatal("fixture: no session") |
| 1501 | } |
| 1502 | id, err := team.home.resolver.resolve(sessions.WithSession(req, session)) |
| 1503 | if err != nil { |
| 1504 | t.Fatal(err) |
| 1505 | } |
| 1506 | member := team.resolveAccess(context.Background(), id) |
| 1507 | if member.state() != roster.Member { |
| 1508 | t.Fatalf("fixture: alice is %v, want Member", member.state()) |
| 1509 | } |
| 1510 | g := &teamStreamGuard{store: tf.app.store, access: member, request: req, docID: f.doc.ID} // no deadline |
| 1511 | if _, ok := g.check(); ok { |
| 1512 | t.Fatal("a stream with no lease deadline went on with a Member standing") |
| 1513 | } |
| 1514 | } |
| 1515 | |