| 1 | package docs |
| 2 | |
| 3 | // Live push, slice 1b: the stream carries the update bytes |
| 4 | // (docs/superpowers/specs/2026-11-26-live-push-design.md §3.1, §3.4, §5; |
| 5 | // plan docs/superpowers/plans/2026-11-26-live-push.md). Behind |
| 6 | // $DOCS_LIVE_PUSH: off, a `push=1` stream is exactly today's, and so is |
| 7 | // every POST. |
| 8 | // |
| 9 | // What lives here: |
| 10 | // - pushRegistry: the open push streams (id -> session binding and |
| 11 | // document) and, per document, who posted each recent seq (seq -> |
| 12 | // stream, counter, SHA-256 of the bytes), recorded inside the POST's |
| 13 | // transaction (§3.4); |
| 14 | // - pushFrames: the rows after a stream's cursor as hello/push/own/update |
| 15 | // frames (§3.1), through an optional per-document frame cache; |
| 16 | // - lateAnswers: the per-session pacing of §5. |
| 17 | |
| 18 | import ( |
| 19 | "context" |
| 20 | "crypto/rand" |
| 21 | "crypto/sha256" |
| 22 | "encoding/base64" |
| 23 | "encoding/hex" |
| 24 | "net/http" |
| 25 | "strconv" |
| 26 | "strings" |
| 27 | "sync" |
| 28 | "sync/atomic" |
| 29 | "time" |
| 30 | ) |
| 31 | |
| 32 | const ( |
| 33 | pushMaxRowBytes = 32 << 10 // a larger row goes by fetch (update) |
| 34 | pushMaxBehindRow = 256 // further behind than this: one update |
| 35 | pushMaxBehind = 512 << 10 // or than this many bytes |
| 36 | pushOriginsKept = 64 // seq -> origin entries per document |
| 37 | pushFrameCached = 64 // rows per document in the frame cache |
| 38 | ) |
| 39 | |
| 40 | // ParseLivePush reads $DOCS_LIVE_PUSH: on/off (also 1/0, true/false); |
| 41 | // unset is off. Anything else is a startup refusal. |
| 42 | func ParseLivePush(v string) (bool, error) { return parseOnOff("DOCS_LIVE_PUSH", v) } |
| 43 | |
| 44 | // sessionBinding identifies the session a request presents: a hash of the |
| 45 | // session cookie authentication reads, exactly as it reads it (the first |
| 46 | // cookie with the configured name, rastrillo sessions' CookieName: the |
| 47 | // __Host- form on an https origin), or, failing that, its Authorization |
| 48 | // header. Home and the native apps' approved sessions use the same cookie. |
| 49 | // A stream id is bound to it, so a Docs-Stream header from another session |
| 50 | // is ignored (§3.4). Cookies appended after it change nothing (#175 finding |
| 51 | // 1). Empty means nothing to bind to: that stream never gets `own`. |
| 52 | func (h *handlers) sessionBinding(r *http.Request) string { |
| 53 | name := "rastrillo_session" |
| 54 | if strings.HasPrefix(h.origin, "https://") { |
| 55 | name = "__Host-rastrillo_session" |
| 56 | } |
| 57 | sum := sha256.New() |
| 58 | if c, err := r.Cookie(name); err == nil { |
| 59 | sum.Write([]byte(name + "=" + c.Value)) |
| 60 | } else if a := r.Header.Get("Authorization"); a != "" { |
| 61 | sum.Write([]byte(a)) |
| 62 | } else { |
| 63 | return "" |
| 64 | } |
| 65 | return hex.EncodeToString(sum.Sum(nil)) |
| 66 | } |
| 67 | |
| 68 | func newStreamID() string { |
| 69 | b := make([]byte, 16) |
| 70 | if _, err := rand.Read(b); err != nil { |
| 71 | panic("docs: stream id: " + err.Error()) |
| 72 | } |
| 73 | return base64.RawURLEncoding.EncodeToString(b) |
| 74 | } |
| 75 | |
| 76 | type pushStream struct { |
| 77 | session string |
| 78 | docID int64 |
| 79 | } |
| 80 | |
| 81 | type pushOrigin struct { |
| 82 | stream string |
| 83 | counter string |
| 84 | hash [32]byte |
| 85 | } |
| 86 | |
| 87 | // postOrigin is what a POST's Docs-Stream header resolved to. |
| 88 | type postOrigin struct { |
| 89 | stream string |
| 90 | counter string |
| 91 | } |
| 92 | |
| 93 | type postOriginKey struct{} |
| 94 | |
| 95 | type pushRegistry struct { |
| 96 | mu sync.Mutex |
| 97 | streams map[string]pushStream |
| 98 | origins map[int64]map[int64]pushOrigin |
| 99 | frames map[int64]*frameCache |
| 100 | } |
| 101 | |
| 102 | func newPushRegistry() *pushRegistry { |
| 103 | return &pushRegistry{streams: map[string]pushStream{}, origins: map[int64]map[int64]pushOrigin{}, frames: map[int64]*frameCache{}} |
| 104 | } |
| 105 | |
| 106 | func (p *pushRegistry) open(id string, s pushStream) { |
| 107 | p.mu.Lock() |
| 108 | p.streams[id] = s |
| 109 | p.mu.Unlock() |
| 110 | } |
| 111 | |
| 112 | func (p *pushRegistry) close(id string) { |
| 113 | p.mu.Lock() |
| 114 | delete(p.streams, id) |
| 115 | p.mu.Unlock() |
| 116 | } |
| 117 | |
| 118 | // origin resolves a Docs-Stream header ("<stream id>.<counter>") on a POST |
| 119 | // to docID: only a stream open on that document, bound to the same |
| 120 | // session. Anything else is ignored, as if the header were absent. |
| 121 | func (p *pushRegistry) origin(r *http.Request, docID int64, session string) (postOrigin, bool) { |
| 122 | header := r.Header.Get("Docs-Stream") |
| 123 | id, counter, ok := strings.Cut(header, ".") |
| 124 | if !ok || id == "" || len(id) > 64 || counter == "" || len(counter) > 20 { |
| 125 | return postOrigin{}, false |
| 126 | } |
| 127 | if _, err := strconv.ParseUint(counter, 10, 64); err != nil { |
| 128 | return postOrigin{}, false |
| 129 | } |
| 130 | p.mu.Lock() |
| 131 | s, open := p.streams[id] |
| 132 | p.mu.Unlock() |
| 133 | if !open || s.docID != docID || session == "" || s.session != session { |
| 134 | return postOrigin{}, false |
| 135 | } |
| 136 | return postOrigin{stream: id, counter: counter}, true |
| 137 | } |
| 138 | |
| 139 | // record notes who posted seq. Called inside the POST's transaction, before |
| 140 | // commit, so a stream that reads the row always finds it (rows become |
| 141 | // visible only at commit). A rolled-back transaction leaves an entry for a |
| 142 | // seq that a later row may reuse; the hash keeps that from matching. |
| 143 | func (p *pushRegistry) record(docID, seq int64, o postOrigin, update []byte) { |
| 144 | h := sha256.Sum256(update) |
| 145 | p.mu.Lock() |
| 146 | defer p.mu.Unlock() |
| 147 | m := p.origins[docID] |
| 148 | if m == nil { |
| 149 | m = map[int64]pushOrigin{} |
| 150 | p.origins[docID] = m |
| 151 | } |
| 152 | m[seq] = pushOrigin{stream: o.stream, counter: o.counter, hash: h} |
| 153 | for k := range m { |
| 154 | if k <= seq-pushOriginsKept { |
| 155 | delete(m, k) |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | func (p *pushRegistry) lookup(docID, seq int64) (pushOrigin, bool) { |
| 161 | p.mu.Lock() |
| 162 | defer p.mu.Unlock() |
| 163 | o, ok := p.origins[docID][seq] |
| 164 | return o, ok |
| 165 | } |
| 166 | |
| 167 | // frameCache keeps recent rows of one document, opened, so W streams |
| 168 | // woken by one POST read and unseal it once rather than W times (§4.2's |
| 169 | // fan-out). Measured in slice 1b (TestLivePushFanoutProbe, 5 typists and |
| 170 | // 5 watchers in one document): row reads fall ~79% (6,000 to ~1,270 for |
| 171 | // 600 uploads) and the frames are identical (TestPushFrameCacheIsTransparent); |
| 172 | // process CPU did not move beyond noise, so something else dominates a |
| 173 | // flush. Kept on for the reads it saves SQLite. Rows are immutable once committed, so a cached row never |
| 174 | // goes stale; the cache is bounded per document and dropped with the |
| 175 | // document's last stream. |
| 176 | type frameCache struct { |
| 177 | mu sync.Mutex |
| 178 | rows map[int64][]byte |
| 179 | refs int |
| 180 | } |
| 181 | |
| 182 | func (p *pushRegistry) cacheFor(docID int64) *frameCache { |
| 183 | p.mu.Lock() |
| 184 | defer p.mu.Unlock() |
| 185 | c := p.frames[docID] |
| 186 | if c == nil { |
| 187 | c = &frameCache{rows: map[int64][]byte{}} |
| 188 | p.frames[docID] = c |
| 189 | } |
| 190 | c.refs++ |
| 191 | return c |
| 192 | } |
| 193 | |
| 194 | func (p *pushRegistry) releaseCache(docID int64) { |
| 195 | p.mu.Lock() |
| 196 | defer p.mu.Unlock() |
| 197 | if c := p.frames[docID]; c != nil { |
| 198 | c.refs-- |
| 199 | if c.refs <= 0 { |
| 200 | delete(p.frames, docID) |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | func (c *frameCache) get(seq int64) ([]byte, bool) { |
| 206 | c.mu.Lock() |
| 207 | defer c.mu.Unlock() |
| 208 | b, ok := c.rows[seq] |
| 209 | return b, ok |
| 210 | } |
| 211 | |
| 212 | func (c *frameCache) put(seq int64, b []byte) { |
| 213 | c.mu.Lock() |
| 214 | defer c.mu.Unlock() |
| 215 | c.rows[seq] = b |
| 216 | for k := range c.rows { |
| 217 | if k <= seq-pushFrameCached { |
| 218 | delete(c.rows, k) |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // pushRow is one row for a stream: its bytes, or why it has none. |
| 224 | type pushRow struct { |
| 225 | seq int64 |
| 226 | bytes []byte |
| 227 | unusable bool // could not be opened |
| 228 | tooLarge bool // over pushMaxRowBytes: goes as update, never loaded |
| 229 | } |
| 230 | |
| 231 | // pushSealSlack is how much longer a stored (sealed) row may be than its |
| 232 | // update: the length check before loading is on the stored bytes. |
| 233 | const pushSealSlack = 256 |
| 234 | |
| 235 | // rowsAfter returns doc's rows after sent, in seq order, and the log's |
| 236 | // current seq. far reports a stream more than pushMaxBehindRow rows or |
| 237 | // pushMaxBehind bytes behind: no rows are returned and none was read. The |
| 238 | // decision is made from the rows' count and stored lengths before any |
| 239 | // row's bytes are read or opened, and a row too large to push is never |
| 240 | // loaded (#175 finding 2). The rest come through cache when it holds them |
| 241 | // all, otherwise with updatesGet's query and opening (§3.1). |
| 242 | func (h *handlers) rowsAfter(ctx context.Context, doc *Document, sent int64, cache *frameCache) (rows []pushRow, current int64, far bool, err error) { |
| 243 | db := h.store.db.WithContext(ctx) |
| 244 | if err = db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Select("COALESCE(MAX(seq), 0)").Scan(¤t).Error; err != nil { |
| 245 | return nil, 0, false, err |
| 246 | } |
| 247 | if current <= sent { |
| 248 | return nil, current, false, nil |
| 249 | } |
| 250 | if current-sent > pushMaxBehindRow { |
| 251 | return nil, current, true, nil |
| 252 | } |
| 253 | if cache != nil { |
| 254 | rows = make([]pushRow, 0, current-sent) |
| 255 | total := 0 |
| 256 | for seq := sent + 1; seq <= current; seq++ { |
| 257 | b, ok := cache.get(seq) |
| 258 | if !ok { |
| 259 | rows = nil |
| 260 | break |
| 261 | } |
| 262 | total += len(b) |
| 263 | rows = append(rows, pushRow{seq: seq, bytes: b}) |
| 264 | } |
| 265 | if rows != nil { |
| 266 | if total > pushMaxBehind { |
| 267 | return nil, current, true, nil |
| 268 | } |
| 269 | h.pushStats.cacheHits.Add(int64(len(rows))) |
| 270 | return rows, current, false, nil |
| 271 | } |
| 272 | } |
| 273 | var lengths []struct { |
| 274 | Seq int64 |
| 275 | N int64 |
| 276 | } |
| 277 | if err = db.Model(&DocUpdate{}).Select("seq, LENGTH(update_bin) AS n"). |
| 278 | Where("doc_id = ? AND seq > ? AND seq <= ?", doc.ID, sent, current). |
| 279 | Order("seq ASC").Scan(&lengths).Error; err != nil { |
| 280 | return nil, 0, false, err |
| 281 | } |
| 282 | var total int64 |
| 283 | var small []int64 |
| 284 | for _, l := range lengths { |
| 285 | if l.N <= pushMaxRowBytes+pushSealSlack { |
| 286 | total += l.N |
| 287 | small = append(small, l.Seq) |
| 288 | } |
| 289 | } |
| 290 | if total > pushMaxBehind+int64(len(small))*pushSealSlack { |
| 291 | return nil, current, true, nil |
| 292 | } |
| 293 | loaded := map[int64][]byte{} |
| 294 | unusable := map[int64]bool{} |
| 295 | if len(small) > 0 { |
| 296 | var updates []DocUpdate |
| 297 | if err = db.Where("doc_id = ? AND seq IN ?", doc.ID, small).Find(&updates).Error; err != nil { |
| 298 | return nil, 0, false, err |
| 299 | } |
| 300 | h.pushStats.rowReads.Add(int64(len(updates))) |
| 301 | for i := range updates { |
| 302 | u := &updates[i] |
| 303 | if err := h.store.openContentUpdate(doc.GUID, u); err != nil { |
| 304 | unusable[u.Seq] = true |
| 305 | continue |
| 306 | } |
| 307 | loaded[u.Seq] = u.UpdateBin |
| 308 | if cache != nil && len(u.UpdateBin) <= pushMaxRowBytes { |
| 309 | cache.put(u.Seq, u.UpdateBin) |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | rows = make([]pushRow, 0, len(lengths)) |
| 314 | for _, l := range lengths { |
| 315 | b, ok := loaded[l.Seq] |
| 316 | switch { |
| 317 | case ok && len(b) <= pushMaxRowBytes: |
| 318 | rows = append(rows, pushRow{seq: l.Seq, bytes: b}) |
| 319 | case ok: |
| 320 | rows = append(rows, pushRow{seq: l.Seq, tooLarge: true}) |
| 321 | case unusable[l.Seq]: |
| 322 | rows = append(rows, pushRow{seq: l.Seq, unusable: true}) |
| 323 | default: |
| 324 | rows = append(rows, pushRow{seq: l.Seq, tooLarge: true}) |
| 325 | } |
| 326 | } |
| 327 | return rows, current, false, nil |
| 328 | } |
| 329 | |
| 330 | // pushFrames renders rows as frames for stream id (§3.1): own for an update |
| 331 | // this stream posted (matched by stream id and the bytes' hash), update |
| 332 | // for a row too large or unreadable, push otherwise. Too far behind (more |
| 333 | // than pushMaxBehindRow rows or pushMaxBehind bytes) is one update for the |
| 334 | // log's current seq. It returns the text to write in one flush and the new |
| 335 | // cursor. |
| 336 | func (h *handlers) pushFrames(docID int64, id string, rows []pushRow, current, sent int64, far bool) (string, int64) { |
| 337 | if far { |
| 338 | return "event: update\ndata: " + strconv.FormatInt(current, 10) + "\n\n", current |
| 339 | } |
| 340 | if len(rows) == 0 { |
| 341 | return "", sent |
| 342 | } |
| 343 | last := rows[len(rows)-1].seq |
| 344 | var b strings.Builder |
| 345 | for _, r := range rows { |
| 346 | seq := strconv.FormatInt(r.seq, 10) |
| 347 | switch o, ok := h.pushRegistry.lookup(docID, r.seq); { |
| 348 | case r.unusable || r.tooLarge || len(r.bytes) > pushMaxRowBytes: |
| 349 | // The client fetches from its cursor, which brings this row and |
| 350 | // everything after it: one update for the current seq ends the |
| 351 | // flush, rather than an update per remaining row. |
| 352 | b.WriteString("event: update\ndata: " + strconv.FormatInt(current, 10) + "\n\n") |
| 353 | return b.String(), current |
| 354 | case ok && o.stream == id && o.hash == sha256.Sum256(r.bytes): |
| 355 | b.WriteString("id: " + seq + "." + pushTag(r.seq, r.bytes) + "\nevent: own\ndata: " + seq + " " + o.counter + "\n\n") |
| 356 | default: |
| 357 | b.WriteString("id: " + seq + "." + pushTag(r.seq, r.bytes) + "\nevent: push\ndata: " + seq + " ") |
| 358 | b.WriteString(base64.StdEncoding.EncodeToString(r.bytes)) |
| 359 | b.WriteString("\n\n") |
| 360 | } |
| 361 | } |
| 362 | return b.String(), last |
| 363 | } |
| 364 | |
| 365 | // lateAnswers paces a person who posts too fast to one document (§5): |
| 366 | // over lateLimit updates in a second, the next answer waits, before the |
| 367 | // POST takes the document's lock or the writer, for at most lateMaxWait, |
| 368 | // ended by the request's cancellation or the process draining. At most |
| 369 | // lateMaxWaiting answers per person wait; beyond that, 503 with |
| 370 | // Retry-After: 1 (never a 4xx: the web save queue drops a 4xx batch). Keyed |
| 371 | // on the authenticated actor, never on request bytes (#175 finding 1: a |
| 372 | // key from cookies let appended cookies make a new key per request). |
| 373 | type lateAnswers struct { |
| 374 | mu sync.Mutex |
| 375 | recent map[lateKey][]time.Time |
| 376 | waiting map[string]int |
| 377 | now func() time.Time |
| 378 | limit int // lateLimit; the fan-out probe raises it (its typists share a session) |
| 379 | } |
| 380 | |
| 381 | type lateKey struct { |
| 382 | session string |
| 383 | docID int64 |
| 384 | } |
| 385 | |
| 386 | const ( |
| 387 | lateLimit = 30 |
| 388 | lateWindow = time.Second |
| 389 | lateMaxWait = time.Second |
| 390 | lateMaxWaiting = 2 |
| 391 | ) |
| 392 | |
| 393 | func newLateAnswers() *lateAnswers { |
| 394 | return &lateAnswers{recent: map[lateKey][]time.Time{}, waiting: map[string]int{}, now: time.Now, limit: lateLimit} |
| 395 | } |
| 396 | |
| 397 | // admit returns once the POST may proceed (true), or false when it should |
| 398 | // be answered 503 (too many waiting) or was cancelled or drained while |
| 399 | // waiting. |
| 400 | func (l *lateAnswers) admit(ctx context.Context, draining <-chan struct{}, session string, docID int64) (ok bool, busy bool) { |
| 401 | if session == "" { |
| 402 | return true, false |
| 403 | } |
| 404 | key := lateKey{session, docID} |
| 405 | l.mu.Lock() |
| 406 | now := l.now() |
| 407 | times := l.recent[key] |
| 408 | cut := 0 |
| 409 | for cut < len(times) && now.Sub(times[cut]) >= lateWindow { |
| 410 | cut++ |
| 411 | } |
| 412 | times = times[cut:] |
| 413 | var wait time.Duration |
| 414 | if len(times) >= l.limit { |
| 415 | wait = min(times[len(times)-l.limit].Add(lateWindow).Sub(now), lateMaxWait) |
| 416 | } |
| 417 | if wait > 0 { |
| 418 | if l.waiting[session] >= lateMaxWaiting { |
| 419 | l.recent[key] = times |
| 420 | l.mu.Unlock() |
| 421 | return false, true |
| 422 | } |
| 423 | l.waiting[session]++ |
| 424 | } |
| 425 | l.recent[key] = append(times, now.Add(wait)) |
| 426 | if len(l.recent) > 4096 { |
| 427 | // Bounded: forget sessions idle for a window. |
| 428 | for k, ts := range l.recent { |
| 429 | if len(ts) == 0 || now.Sub(ts[len(ts)-1]) > lateWindow { |
| 430 | delete(l.recent, k) |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | l.mu.Unlock() |
| 435 | if wait <= 0 { |
| 436 | return true, false |
| 437 | } |
| 438 | defer func() { |
| 439 | l.mu.Lock() |
| 440 | l.waiting[session]-- |
| 441 | if l.waiting[session] <= 0 { |
| 442 | delete(l.waiting, session) |
| 443 | } |
| 444 | l.mu.Unlock() |
| 445 | }() |
| 446 | t := time.NewTimer(wait) |
| 447 | defer t.Stop() |
| 448 | select { |
| 449 | case <-t.C: |
| 450 | return true, false |
| 451 | case <-ctx.Done(): |
| 452 | return false, false |
| 453 | case <-draining: |
| 454 | return false, false |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | // pushStats count what push streams did (tests and the fan-out probe). |
| 459 | type pushStats struct { |
| 460 | rowReads, cacheHits, frames atomic.Int64 |
| 461 | } |
| 462 | |
| 463 | // pushTag is a row's short digest: 16 hex digits of SHA-256 over its seq |
| 464 | // and its bytes. Push and own frames carry it in their id (<seq>.<tag>), |
| 465 | // fetches in Docs-Seq-Tag, and a resume names the tag of its cursor's row, |
| 466 | // so the server can tell a cursor into a log that has since been rewound |
| 467 | // and rewritten (a restore that the epoch did not catch) from one into this |
| 468 | // log (#175 finding 3). |
| 469 | func pushTag(seq int64, b []byte) string { |
| 470 | h := sha256.New() |
| 471 | var n [8]byte |
| 472 | for i := 0; i < 8; i++ { |
| 473 | n[i] = byte(seq >> (56 - 8*i)) |
| 474 | } |
| 475 | h.Write(n[:]) |
| 476 | h.Write(b) |
| 477 | return hex.EncodeToString(h.Sum(nil))[:16] |
| 478 | } |
| 479 | |
| 480 | // cursorMatches reports whether row seq of doc is the row tag was taken |
| 481 | // from: the resume check (#175 finding 3). A missing row does not match. |
| 482 | func (h *handlers) cursorMatches(ctx context.Context, doc *Document, seq int64, tag string) (bool, error) { |
| 483 | var rows []DocUpdate |
| 484 | if err := h.store.db.WithContext(ctx).Where("doc_id = ? AND seq = ?", doc.ID, seq).Limit(1).Find(&rows).Error; err != nil { |
| 485 | return false, err |
| 486 | } |
| 487 | if len(rows) == 0 { |
| 488 | return false, nil |
| 489 | } |
| 490 | if err := h.store.openContentUpdate(doc.GUID, &rows[0]); err != nil { |
| 491 | return false, err |
| 492 | } |
| 493 | return pushTag(seq, rows[0].UpdateBin) == tag, nil |
| 494 | } |
| 495 | |