| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/home/roster" |
| 12 | "amadan.net/rastrillo/rastrillo" |
| 13 | ) |
| 14 | |
| 15 | // The stream's timings. Lifted from rastrillo's own SSE handler |
| 16 | // (jobs/events.go), and each one is carried for its own reason rather |
| 17 | // than by imitation — see the notes on each. |
| 18 | const ( |
| 19 | // defaultStreamWriteDeadline is the per-write idle deadline, |
| 20 | // re-armed before every event and every heartbeat through |
| 21 | // http.NewResponseController. This is what lets a stream coexist |
| 22 | // with rastrillo serve's zero WriteTimeout default: a total |
| 23 | // response deadline would cut a healthy long-lived stream off |
| 24 | // alongside the stalled ones, so the framework leaves WriteTimeout |
| 25 | // off and expects a streaming handler to bound its own writes. |
| 26 | defaultStreamWriteDeadline = 30 * time.Second |
| 27 | |
| 28 | // defaultStreamHeartbeat is the comment-ping cadence on a quiet |
| 29 | // stream. It keeps intermediaries from timing out a connection |
| 30 | // that looks idle, and — more importantly here — it is what makes |
| 31 | // the write deadline above ever fire: without a periodic write, a |
| 32 | // client that has gone away without closing is discovered at the |
| 33 | // next real edit, which may be never. |
| 34 | defaultStreamHeartbeat = 15 * time.Second |
| 35 | |
| 36 | // defaultStreamTTL bounds any one connection. The client reopens |
| 37 | // (see fixtures/live-updates.mjs), so this costs a browser nothing |
| 38 | // and is half of the hibernation story the design spec's §6 |
| 39 | // describes: platform hibernation is default-on, and a document |
| 40 | // left open on Friday must not pin its instance awake all weekend. |
| 41 | // No timer here exists outside a live connection, so nothing in |
| 42 | // this file is a ticker that dies at hibernation. |
| 43 | defaultStreamTTL = 5 * time.Minute |
| 44 | |
| 45 | // pushLeaseLead ends a team-mode push stream this long before its |
| 46 | // lease, so `bye lease` is written while the lease still admits it. |
| 47 | pushLeaseLead = 2 * time.Second |
| 48 | ) |
| 49 | |
| 50 | // stream serves GET /d/{sqid}/stream: a Server-Sent Events feed that |
| 51 | // says "this document has content through seq N" and nothing else. |
| 52 | // The bytes themselves are fetched by the client through |
| 53 | // GET /d/{sqid}/updates?since=N — the same binary endpoint it already |
| 54 | // used at mount, through the same replay path. |
| 55 | // |
| 56 | // Keeping document bytes off this stream is deliberate, and mirrors |
| 57 | // the reasoning in rastrillo's own SSE handler for keeping HTML off |
| 58 | // its one ("SSE never carries HTML, so the one rendering path |
| 59 | // stays"). Two consequences here: there is exactly one code path that |
| 60 | // turns stored updates into a browser's Y.Doc, rather than two that |
| 61 | // can drift; and SSE's text-only framing costs nothing, where putting |
| 62 | // opaque binary Yjs updates on it would have meant base64 and about a |
| 63 | // third more bytes on every keystroke batch. |
| 64 | // |
| 65 | // Reader-scoped through getDocumentForUpdates, so a stranger gets the |
| 66 | // same 404 the update routes give — never a 403, which would confirm |
| 67 | // the document exists. |
| 68 | func (h *handlers) stream(w http.ResponseWriter, r *http.Request) { |
| 69 | doc, ok := h.getDocumentForUpdates(w, r) |
| 70 | if !ok { |
| 71 | return |
| 72 | } |
| 73 | // A process that is shutting down opens no new stream (hub.drain). |
| 74 | select { |
| 75 | case <-h.hub.draining(): |
| 76 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 77 | return |
| 78 | default: |
| 79 | } |
| 80 | |
| 81 | fl, ok := w.(http.Flusher) |
| 82 | if !ok { |
| 83 | h.logger.Error("docs: stream: ResponseWriter does not flush", "sqid", doc.Sqid) |
| 84 | http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus()) |
| 85 | return |
| 86 | } |
| 87 | |
| 88 | // Subscribe BEFORE reading the current seq, never after. An update |
| 89 | // committing between the two must produce a redundant |
| 90 | // notification, which costs one empty fetch; the other order would |
| 91 | // let it fall into the gap and produce nothing at all, and the tab |
| 92 | // would sit there current-looking and stale until the next edit. |
| 93 | ch, stop := h.hub.subscribe(doc.ID) |
| 94 | defer stop() |
| 95 | |
| 96 | // A push stream (push.go; the live-push spec's §3.1) only when the |
| 97 | // server's switch is on. Otherwise push=1 is ignored and this stream is |
| 98 | // exactly today's. |
| 99 | push := h.livePush && r.URL.Query().Get("push") == "1" |
| 100 | |
| 101 | var guard *teamStreamGuard |
| 102 | var leaseTimer *time.Timer |
| 103 | var leaseDeadline <-chan time.Time |
| 104 | if h.store.team != nil { |
| 105 | a, ok := r.Context().Value(accessContextKey{}).(*requestAccess) |
| 106 | if !ok || a == nil || a.runtime != h.store.team { |
| 107 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 108 | return |
| 109 | } |
| 110 | // A Member's stream rests on a lease and never opens without its |
| 111 | // deadline (#175 finding 4: a lost TryLock here used to open it |
| 112 | // with none). A zero lease or Unknown standing is asked again; a |
| 113 | // Member with no lease left after that is refused (503, retried). |
| 114 | lease := h.store.team.lease(a) |
| 115 | if lease <= 0 && a.Subject() != "" && a.state() != roster.NotMember { |
| 116 | fresh, left := h.store.team.freshLease(r.Context(), requestIdentity{Actor: a.actor, HomeSubject: a.Subject()}) |
| 117 | if fresh != nil && fresh.state() == roster.Member { |
| 118 | if left <= 0 { |
| 119 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 120 | return |
| 121 | } |
| 122 | a, lease = fresh, left |
| 123 | } |
| 124 | } |
| 125 | guard = &teamStreamGuard{store: h.store, access: a, request: r, docID: doc.ID} |
| 126 | if lease > 0 { |
| 127 | guard.deadline = time.Now().Add(lease) |
| 128 | guard.role = a.Role() |
| 129 | } |
| 130 | if _, ok := guard.check(); !ok { |
| 131 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 132 | return |
| 133 | } |
| 134 | if !guard.deadline.IsZero() { |
| 135 | remaining := guard.remaining() |
| 136 | if remaining <= 0 { |
| 137 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 138 | return |
| 139 | } |
| 140 | if push { |
| 141 | // Early enough that `bye lease` can still be written. |
| 142 | remaining = max(remaining-h.leaseLead(), 0) |
| 143 | } |
| 144 | leaseTimer = time.NewTimer(remaining) |
| 145 | defer leaseTimer.Stop() |
| 146 | leaseDeadline = leaseTimer.C |
| 147 | } |
| 148 | } |
| 149 | seqContext := r.Context() |
| 150 | if guard != nil { |
| 151 | var cancel context.CancelFunc |
| 152 | seqContext, cancel = context.WithTimeout(seqContext, min(guard.remaining(), defaultStreamWriteDeadline)) |
| 153 | defer cancel() |
| 154 | } |
| 155 | current, err := h.store.currentSeq(seqContext, doc.ID) |
| 156 | if err != nil { |
| 157 | h.logger.Error("docs: stream: read current seq", "sqid", doc.Sqid, "err", err) |
| 158 | http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus()) |
| 159 | return |
| 160 | } |
| 161 | // Where a push stream starts: Last-Event-ID (EventSource sends it on its |
| 162 | // own reconnects) wins over since; garbage in either is a 400, as |
| 163 | // parseSince answers. With neither, it starts at the current seq. |
| 164 | // A cursor may name its row's tag (<seq>.<tag> in Last-Event-ID, or |
| 165 | // since=<seq> with a Docs-Seq-Tag request header), which the stream |
| 166 | // checks below. Never in the query string: access logs keep it, and the |
| 167 | // tag is an unkeyed digest of the row (#175 approval, finding 6). |
| 168 | start, resume, tag := current, false, "" |
| 169 | if push { |
| 170 | raw, rawTag := r.Header.Get("Last-Event-ID"), "" |
| 171 | if raw != "" { |
| 172 | // Only Last-Event-ID carries <seq>.<tag>: it is a header, and it |
| 173 | // is what EventSource sends back from a frame's id. |
| 174 | raw, rawTag, _ = strings.Cut(raw, ".") |
| 175 | } else { |
| 176 | // since is a plain seq, as parseSince reads it: since=<seq>.<tag> |
| 177 | // would put the tag back in the query string, and is a 400. |
| 178 | raw = r.URL.Query().Get("since") |
| 179 | tag = r.Header.Get("Docs-Seq-Tag") |
| 180 | } |
| 181 | if raw != "" { |
| 182 | n, err := strconv.ParseInt(raw, 10, 64) |
| 183 | if err != nil || n < 0 { |
| 184 | http.Error(w, rastrillo.T(r, "docs.error.badsince"), http.StatusBadRequest) |
| 185 | return |
| 186 | } |
| 187 | if rawTag != "" { |
| 188 | tag = rawTag |
| 189 | } |
| 190 | start, resume = n, true |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | rc := http.NewResponseController(w) |
| 195 | if guard != nil { |
| 196 | limit, ok := guard.check() |
| 197 | if !ok || rc.SetWriteDeadline(time.Now().Add(limit)) != nil { |
| 198 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 199 | return |
| 200 | } |
| 201 | } |
| 202 | w.Header().Set("Content-Type", "text/event-stream") |
| 203 | w.Header().Set("Cache-Control", "no-store") |
| 204 | w.WriteHeader(http.StatusOK) |
| 205 | fl.Flush() |
| 206 | |
| 207 | // write is every byte's one exit: deadline armed, then the bytes, |
| 208 | // then the flush. The deadline error is ignored deliberately — a |
| 209 | // ResponseWriter that cannot set deadlines still streams, just |
| 210 | // unbounded — while a write error ends the handler, because it |
| 211 | // means the client is gone. |
| 212 | write := func(text string) bool { |
| 213 | // Team streams already revalidate through their original bounded lease. |
| 214 | if guard == nil && !h.nativeStreamAllowed(r, doc.Sqid) { |
| 215 | return false |
| 216 | } |
| 217 | limit := defaultStreamWriteDeadline |
| 218 | if guard != nil { |
| 219 | var ok bool |
| 220 | limit, ok = guard.check() |
| 221 | if !ok { |
| 222 | return false |
| 223 | } |
| 224 | } |
| 225 | if err := rc.SetWriteDeadline(time.Now().Add(limit)); err != nil && guard != nil { |
| 226 | return false |
| 227 | } |
| 228 | if _, err := io.WriteString(w, text); err != nil { |
| 229 | return false |
| 230 | } |
| 231 | fl.Flush() |
| 232 | return true |
| 233 | } |
| 234 | event := func(seq int64) bool { |
| 235 | return write("event: update\ndata: " + strconv.FormatInt(seq, 10) + "\n\n") |
| 236 | } |
| 237 | |
| 238 | // A push stream: hello first (stream id, the log's current seq, the log |
| 239 | // epoch), registered with its session for Docs-Stream (§3.4). |
| 240 | var ( |
| 241 | streamID string |
| 242 | sent = start |
| 243 | cache *frameCache |
| 244 | ) |
| 245 | flushFrames := func() bool { return true } |
| 246 | if push { |
| 247 | streamID = newStreamID() |
| 248 | h.pushRegistry.open(streamID, pushStream{session: h.sessionBinding(r), docID: doc.ID}) |
| 249 | defer h.pushRegistry.close(streamID) |
| 250 | if h.pushFrameCache { |
| 251 | cache = h.pushRegistry.cacheFor(doc.ID) |
| 252 | defer h.pushRegistry.releaseCache(doc.ID) |
| 253 | } |
| 254 | flushFrames = func() bool { |
| 255 | rows, current, far, err := h.rowsAfter(r.Context(), doc, sent, cache) |
| 256 | if err != nil { |
| 257 | h.logger.Error("docs: stream: read rows", "sqid", doc.Sqid, "err", err) |
| 258 | return false |
| 259 | } |
| 260 | text, next := h.pushFrames(doc.ID, streamID, rows, current, sent, far) |
| 261 | if text == "" { |
| 262 | return true |
| 263 | } |
| 264 | if !write(text) { |
| 265 | return false |
| 266 | } |
| 267 | h.pushStats.frames.Add(1) |
| 268 | sent = next |
| 269 | return true |
| 270 | } |
| 271 | if !write("event: hello\ndata: " + streamID + " " + strconv.FormatInt(current, 10) + " " + h.store.logEpoch + "\n\n") { |
| 272 | return |
| 273 | } |
| 274 | } |
| 275 | bye := func(reason string) { |
| 276 | if push { |
| 277 | write("event: bye\ndata: " + reason + "\n\n") |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | if push && resume { |
| 282 | // A cursor this log cannot vouch for resyncs from the start rather |
| 283 | // than resume (#175 findings 3 and 5): one ahead of the log, or one |
| 284 | // whose row's tag does not match the row this log holds at that seq |
| 285 | // (a restore the epoch did not catch, then rewritten past it). |
| 286 | if start > current || (tag != "" && start > 0 && !h.cursorHeld(r, doc, start, tag)) { |
| 287 | write("event: resync\ndata: " + strconv.FormatInt(current, 10) + "\n\n") |
| 288 | return |
| 289 | } |
| 290 | // What the client missed since its cursor arrives as frames: the |
| 291 | // connect-time fetch goes away. |
| 292 | if !flushFrames() { |
| 293 | return |
| 294 | } |
| 295 | } else if !event(current) { |
| 296 | // The connect-time event is load-bearing, not an optimisation. It |
| 297 | // is what heals a tab whose cursor legitimately failed to advance |
| 298 | // (a POST whose seq was not cursor+1, design D3), and it covers |
| 299 | // the gap between the page rendering server-side and this stream |
| 300 | // opening. Sending the current seq unconditionally costs a client |
| 301 | // that is already current exactly one empty ?since= fetch. A push |
| 302 | // stream opened without a cursor keeps it, after hello. |
| 303 | return |
| 304 | } |
| 305 | |
| 306 | heartbeat := time.NewTimer(h.heartbeatInterval()) |
| 307 | defer heartbeat.Stop() |
| 308 | ttl := time.NewTimer(h.ttlInterval()) |
| 309 | defer ttl.Stop() |
| 310 | |
| 311 | for { |
| 312 | select { |
| 313 | case <-leaseDeadline: |
| 314 | bye("lease") |
| 315 | return |
| 316 | case <-r.Context().Done(): |
| 317 | // The client went away. |
| 318 | return |
| 319 | case <-h.hub.draining(): |
| 320 | // The process is shutting down, which never cancels a |
| 321 | // request's context: this is what lets the graceful shutdown |
| 322 | // finish instead of waiting out its deadline on an open |
| 323 | // stream (hub.drain). |
| 324 | bye("drain") |
| 325 | return |
| 326 | case <-ttl.C: |
| 327 | // A clean close, not an error: the client reopens if it |
| 328 | // still wants one, and a parked tab does not. |
| 329 | bye("ttl") |
| 330 | return |
| 331 | case seq := <-ch: |
| 332 | if push { |
| 333 | if !flushFrames() { |
| 334 | return |
| 335 | } |
| 336 | } else if !event(seq) { |
| 337 | return |
| 338 | } |
| 339 | heartbeat.Reset(h.heartbeatInterval()) |
| 340 | case <-heartbeat.C: |
| 341 | // The heartbeat is a timer inside a live connection, so it may |
| 342 | // also sweep idle warm handles (warm.go, rule 7). |
| 343 | h.store.warm.sweep(r.Context()) |
| 344 | if !write(": ping\n\n") { |
| 345 | return |
| 346 | } |
| 347 | heartbeat.Reset(h.heartbeatInterval()) |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | // heartbeatInterval and ttlInterval read the handler's own overrides, |
| 353 | // falling back to the constants above. The overrides exist for |
| 354 | // stream_test.go, whose whole subject is behaviour over time: the |
| 355 | // production values are right for a browser and useless for a test |
| 356 | // suite, and the alternative — a test that waits five minutes to |
| 357 | // prove a five-minute TTL — is not a test anyone runs. |
| 358 | func (h *handlers) heartbeatInterval() time.Duration { |
| 359 | if h.streamHeartbeat > 0 { |
| 360 | return h.streamHeartbeat |
| 361 | } |
| 362 | return defaultStreamHeartbeat |
| 363 | } |
| 364 | |
| 365 | // leaseLead is pushLeaseLead, or the tests' override (a lead longer than |
| 366 | // the lease ends the stream with `bye lease` at once). |
| 367 | func (h *handlers) leaseLead() time.Duration { |
| 368 | if h.pushLeaseLead > 0 { |
| 369 | return h.pushLeaseLead |
| 370 | } |
| 371 | return pushLeaseLead |
| 372 | } |
| 373 | |
| 374 | func (h *handlers) ttlInterval() time.Duration { |
| 375 | if h.streamTTL > 0 { |
| 376 | return h.streamTTL |
| 377 | } |
| 378 | return defaultStreamTTL |
| 379 | } |
| 380 | |
| 381 | // cursorHeld is cursorMatches for a stream; a read error counts as not |
| 382 | // held, which resyncs (the safe direction). |
| 383 | func (h *handlers) cursorHeld(r *http.Request, doc *Document, seq int64, tag string) bool { |
| 384 | ok, err := h.cursorMatches(r.Context(), doc, seq, tag) |
| 385 | if err != nil { |
| 386 | h.logger.Error("docs: stream: check cursor", "sqid", doc.Sqid, "err", err) |
| 387 | } |
| 388 | return ok |
| 389 | } |
| 390 | |