| 1 | // live.go is the transport a browser edits a deck over: the update log |
| 2 | // by cursor, one new update in, an advisory stream out, and a heartbeat |
| 3 | // saying who is in the deck. |
| 4 | // |
| 5 | // It is Docs' live-sync design adopted whole (its internal/docs/{ |
| 6 | // handlers.go, stream.go}), with one addition and one difference. |
| 7 | // |
| 8 | // The addition is presence, which is NOT document state (spec §3.3): it |
| 9 | // lives in the hub's memory, never in the log, and is gone when this |
| 10 | // process is. |
| 11 | // |
| 12 | // The difference is framing. Docs concatenates updates, because a Yjs |
| 13 | // update is self-delimiting and its client feeds the whole blob to one |
| 14 | // decoder. Slides frames each one as a 4-byte big-endian length then |
| 15 | // the bytes, so the client can hand them to the core one at a time and |
| 16 | // so a fixture can compare a frame against the update that produced it |
| 17 | // (the plan's live-sync wire). Concatenation would make both of those |
| 18 | // "decode and hope". |
| 19 | // |
| 20 | // What never travels on the stream is bytes. The stream says "there is |
| 21 | // content through seq N" and the client fetches it through the endpoint |
| 22 | // it already used at mount — one code path from stored update to a |
| 23 | // browser's Y.Doc rather than two that can drift, and no base64 tax on |
| 24 | // every keystroke batch. |
| 25 | package slides |
| 26 | |
| 27 | import ( |
| 28 | "compress/gzip" |
| 29 | "context" |
| 30 | "encoding/binary" |
| 31 | "encoding/json" |
| 32 | "errors" |
| 33 | "fmt" |
| 34 | "io" |
| 35 | "net/http" |
| 36 | "strconv" |
| 37 | "strings" |
| 38 | "time" |
| 39 | |
| 40 | "gorm.io/gorm" |
| 41 | |
| 42 | "amadan.net/rastrillo/rastrillo" |
| 43 | |
| 44 | "amadan.net/oficina/slides/internal/slides/core" |
| 45 | "amadan.net/oficina/slides/internal/slides/deck" |
| 46 | "amadan.net/oficina/slides/internal/slides/live" |
| 47 | ) |
| 48 | |
| 49 | // maxUpdateBytes is the cap on one posted update (the plan's 1 MiB). |
| 50 | // Generous for a keystroke batch and for a pasted slide; small enough |
| 51 | // that a client cannot make this instance hold an arbitrary amount of |
| 52 | // memory by opening one connection. core/src/scene.rs and |
| 53 | // fixtures/scenes.mjs hold it too, as MAX_UPDATE_BYTES: a batch with a |
| 54 | // scene op whose update would be larger is refused there, so no deck |
| 55 | // holds a scene an editor could not save again. Change the three |
| 56 | // together. |
| 57 | const maxUpdateBytes = 1 << 20 |
| 58 | |
| 59 | // maxPresenceBytes is the cap on one heartbeat body. A heartbeat is |
| 60 | // four short strings; anything approaching this is not one. |
| 61 | const maxPresenceBytes = 4 << 10 |
| 62 | |
| 63 | // maxPresenceField bounds each string the client supplies. Ids in this |
| 64 | // app are twelve characters (decks.go's newID) and a client id is a |
| 65 | // browser's own random string, so 128 is roomy — and a cap of some kind |
| 66 | // is required, because these strings are held in memory for the life of |
| 67 | // a heartbeat by a request that only had to be signed in. |
| 68 | const maxPresenceField = 128 |
| 69 | |
| 70 | // errUpdateRefused is the core looking at the bytes a client posted and |
| 71 | // saying no: malformed wire bytes, or bytes that trapped the module and |
| 72 | // were contained. It is the client's problem, so it is a 422 and an |
| 73 | // Info-level log — accepting arbitrary input over HTTP and occasionally |
| 74 | // being sent nonsense is the ordinary case, not an incident. |
| 75 | // |
| 76 | // Everything else out of appendUpdate — a database failure, a replay of |
| 77 | // this deck's own history going wrong, a rebuild that itself failed — |
| 78 | // is a 500, because the client did not cause it and an operator needs |
| 79 | // to see it. |
| 80 | var errUpdateRefused = errors.New("slides: the core refused this update") |
| 81 | |
| 82 | // --- GET /d/{sqid}/updates --- |
| 83 | |
| 84 | // updatesGet serves the deck's log from a cursor: `application/octet- |
| 85 | // stream`, each update framed as a 4-byte big-endian length then the |
| 86 | // bytes, in seq order. |
| 87 | // |
| 88 | // `Slides-Seq` is the highest seq in the BODY, or the cursor itself |
| 89 | // when the body is empty — derived from the bytes in hand and never |
| 90 | // from a second MAX(seq) query. The difference matters: a separate |
| 91 | // query can see an update this response does not carry, and the client |
| 92 | // would then record a cursor for bytes it never received and never ask |
| 93 | // for them again. |
| 94 | // |
| 95 | // `Slides-Snapshot: <seq>` says the first frame is a snapshot rather |
| 96 | // than a log row. A client that does not care can ignore it — a |
| 97 | // snapshot is a Yjs update like any other and applying it is correct |
| 98 | // either way — and one that does can tell "here is the deck" from "here |
| 99 | // is what changed". |
| 100 | func (a *app) updatesGet(w http.ResponseWriter, r *http.Request) { |
| 101 | u, ok := a.viewer(w, r) |
| 102 | if !ok { |
| 103 | return |
| 104 | } |
| 105 | d, ok := a.deckFor(w, r, u) |
| 106 | if !ok { |
| 107 | return |
| 108 | } |
| 109 | since, ok := parseSince(w, r) |
| 110 | if !ok { |
| 111 | return |
| 112 | } |
| 113 | |
| 114 | updates, highest, snapshotSeq, err := a.readUpdates(r.Context(), d, since) |
| 115 | if err != nil { |
| 116 | a.fail(w, r, "read a deck's log", err) |
| 117 | return |
| 118 | } |
| 119 | |
| 120 | w.Header().Set("Content-Type", "application/octet-stream") |
| 121 | w.Header().Set("Cache-Control", "no-store") |
| 122 | w.Header().Set("Slides-Seq", strconv.FormatInt(highest, 10)) |
| 123 | if snapshotSeq > 0 { |
| 124 | w.Header().Set("Slides-Snapshot", strconv.FormatInt(snapshotSeq, 10)) |
| 125 | } |
| 126 | |
| 127 | var length [4]byte |
| 128 | for _, u := range updates { |
| 129 | binary.BigEndian.PutUint32(length[:], uint32(len(u))) |
| 130 | if _, err := w.Write(length[:]); err != nil { |
| 131 | // The client went away mid-response. Logged rather than |
| 132 | // surfaced: the status line is already on the wire. |
| 133 | a.logger.Error("slides: write the update log", "deck", d.Sqid, "err", err) |
| 134 | return |
| 135 | } |
| 136 | if _, err := w.Write(u); err != nil { |
| 137 | a.logger.Error("slides: write the update log", "deck", d.Sqid, "err", err) |
| 138 | return |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // readUpdates is what a cursor is owed: the frames to send, the highest |
| 144 | // seq they carry, and the seq of the snapshot when one of them is one. |
| 145 | // |
| 146 | // The snapshot is only ever offered at since=0. A client mid-session |
| 147 | // holds a prefix of the log and needs the tail after it; handing it a |
| 148 | // whole-document update instead would be correct (Yjs would merge it) |
| 149 | // and wasteful on every single fetch. At since=0 it is the opposite: a |
| 150 | // deck with two thousand updates behind it would otherwise send all two |
| 151 | // thousand to every tab that opens it. |
| 152 | func (a *app) readUpdates(ctx context.Context, d Deck, since int64) (frames [][]byte, highest, snapshotSeq int64, err error) { |
| 153 | highest = since |
| 154 | tail := since |
| 155 | |
| 156 | if since == 0 { |
| 157 | // An accelerator, never the source of truth (snapshot.go): a |
| 158 | // lookup that fails serves the plain log rather than failing a |
| 159 | // request the log alone can still answer. |
| 160 | snap, err := a.latestSnapshot(ctx, d.ID) |
| 161 | if err != nil { |
| 162 | a.logger.Error("slides: load a deck's newest snapshot, serving the plain log instead", |
| 163 | "deck", d.Sqid, "err", err) |
| 164 | } else if snap != nil && snap.Seq > since { |
| 165 | frames = append(frames, snap.Bytes) |
| 166 | snapshotSeq = snap.Seq |
| 167 | tail = snap.Seq |
| 168 | highest = snap.Seq |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | var updates []DeckUpdate |
| 173 | if err := a.db.G.WithContext(ctx). |
| 174 | Where("deck_id = ? AND seq > ?", d.ID, tail). |
| 175 | Order("seq").Find(&updates).Error; err != nil { |
| 176 | return nil, 0, 0, fmt.Errorf("slides: read deck %s log from %d: %w", d.Sqid, tail, err) |
| 177 | } |
| 178 | for _, u := range updates { |
| 179 | frames = append(frames, u.Bytes) |
| 180 | if u.Seq > highest { |
| 181 | highest = u.Seq |
| 182 | } |
| 183 | } |
| 184 | return frames, highest, snapshotSeq, nil |
| 185 | } |
| 186 | |
| 187 | // parseSince reads the ?since= cursor: the highest seq the client |
| 188 | // already holds, so the answer carries only what came after it. Absent |
| 189 | // means 0, which asks for the whole deck — what a tab wants at mount. |
| 190 | // |
| 191 | // A malformed or negative value is a 400 rather than a silent 0. |
| 192 | // Treating "banana" as "send everything" would answer an expensive |
| 193 | // question nobody asked and hide a client bug behind a response that |
| 194 | // looks fine. |
| 195 | func parseSince(w http.ResponseWriter, r *http.Request) (int64, bool) { |
| 196 | raw := r.URL.Query().Get("since") |
| 197 | if raw == "" { |
| 198 | return 0, true |
| 199 | } |
| 200 | since, err := strconv.ParseInt(raw, 10, 64) |
| 201 | if err != nil || since < 0 { |
| 202 | http.Error(w, rastrillo.T(r, "slides.live.error.badsince"), http.StatusBadRequest) |
| 203 | return 0, false |
| 204 | } |
| 205 | return since, true |
| 206 | } |
| 207 | |
| 208 | // --- POST /d/{sqid}/updates --- |
| 209 | |
| 210 | var ( |
| 211 | errUpdateTooLarge = errors.New("slides: posted update is larger than maxUpdateBytes") |
| 212 | errUpdateEncoding = errors.New("slides: posted update has an unsupported Content-Encoding") |
| 213 | errUpdateCorrupt = errors.New("slides: posted update is not valid gzip") |
| 214 | ) |
| 215 | |
| 216 | // readPostedUpdate reads a posted update, gunzipping a body sent with |
| 217 | // Content-Encoding: gzip. The editor compresses a large save so that more |
| 218 | // of them fit a keepalive request's 64KiB, the one kind WebKit still sends |
| 219 | // while a link the page opened is loading (fixtures/save-queue.mjs, Docs |
| 220 | // #94). body is already under http.MaxBytesReader, which bounds what is |
| 221 | // read off the wire; the decompressed bytes are bounded by maxUpdateBytes |
| 222 | // again, so a small body cannot expand into a large one. Anything but gzip |
| 223 | // or none is refused rather than stored as if it were an update. |
| 224 | func readPostedUpdate(body io.Reader, encoding string) ([]byte, error) { |
| 225 | switch strings.ToLower(strings.TrimSpace(encoding)) { |
| 226 | case "", "identity": |
| 227 | return io.ReadAll(body) |
| 228 | case "gzip": |
| 229 | default: |
| 230 | return nil, errUpdateEncoding |
| 231 | } |
| 232 | var tooBig *http.MaxBytesError |
| 233 | zr, err := gzip.NewReader(body) |
| 234 | if err != nil { |
| 235 | if errors.As(err, &tooBig) { |
| 236 | return nil, err |
| 237 | } |
| 238 | return nil, fmt.Errorf("%w: %v", errUpdateCorrupt, err) |
| 239 | } |
| 240 | update, err := io.ReadAll(io.LimitReader(zr, maxUpdateBytes+1)) |
| 241 | if err != nil { |
| 242 | if errors.As(err, &tooBig) { |
| 243 | return nil, err |
| 244 | } |
| 245 | return nil, fmt.Errorf("%w: %v", errUpdateCorrupt, err) |
| 246 | } |
| 247 | if len(update) > maxUpdateBytes { |
| 248 | return nil, errUpdateTooLarge |
| 249 | } |
| 250 | return update, nil |
| 251 | } |
| 252 | |
| 253 | // updatesPost takes one Yjs update from a browser, applies it through |
| 254 | // the core, stores it and answers 204 with the seq it landed at. |
| 255 | // |
| 256 | // The body is wrapped in MaxBytesReader before anything reads it, so an |
| 257 | // oversized update is refused before it is buffered into memory at all, |
| 258 | // never after. |
| 259 | func (a *app) updatesPost(w http.ResponseWriter, r *http.Request) { |
| 260 | u, ok := a.viewer(w, r) |
| 261 | if !ok { |
| 262 | return |
| 263 | } |
| 264 | d, ok := a.deckFor(w, r, u) |
| 265 | if !ok { |
| 266 | return |
| 267 | } |
| 268 | |
| 269 | r.Body = http.MaxBytesReader(w, r.Body, maxUpdateBytes) |
| 270 | update, err := readPostedUpdate(r.Body, r.Header.Get("Content-Encoding")) |
| 271 | if err != nil { |
| 272 | var tooBig *http.MaxBytesError |
| 273 | switch { |
| 274 | case errors.As(err, &tooBig), errors.Is(err, errUpdateTooLarge): |
| 275 | http.Error(w, rastrillo.T(r, "slides.live.error.toolarge"), http.StatusRequestEntityTooLarge) |
| 276 | case errors.Is(err, errUpdateEncoding): |
| 277 | http.Error(w, rastrillo.T(r, "slides.live.error.invalid"), http.StatusUnsupportedMediaType) |
| 278 | case errors.Is(err, errUpdateCorrupt): |
| 279 | // 400, not the 422 an update the core refuses gets: the body |
| 280 | // is not even gzip. Docs answers the same (Claude Fable on |
| 281 | // Docs #94, round 2). |
| 282 | a.logger.Info("slides: refuse a posted update", "deck", d.Sqid, "err", err) |
| 283 | http.Error(w, rastrillo.T(r, "slides.live.error.invalid"), http.StatusBadRequest) |
| 284 | default: |
| 285 | a.fail(w, r, "read a posted update", err) |
| 286 | } |
| 287 | return |
| 288 | } |
| 289 | |
| 290 | seq, err := a.appendUpdate(r.Context(), &d, actorFor(u), update, a.deckGuard(r.Context(), u, d)) |
| 291 | if err != nil { |
| 292 | if a.guardRefused(w, r, err) { |
| 293 | return |
| 294 | } |
| 295 | if errors.Is(err, errUpdateRefused) { |
| 296 | a.logger.Info("slides: refuse a posted update", "deck", d.Sqid, "err", err) |
| 297 | http.Error(w, rastrillo.T(r, "slides.live.error.invalid"), http.StatusUnprocessableEntity) |
| 298 | return |
| 299 | } |
| 300 | if errors.Is(err, errDeckBusy) { |
| 301 | // Two retries both lost: real contention rather than a |
| 302 | // race worth spinning on. The client's own queue reposts, |
| 303 | // and Yjs makes a duplicate harmless. |
| 304 | http.Error(w, rastrillo.T(r, "slides.live.error.busy"), http.StatusConflict) |
| 305 | return |
| 306 | } |
| 307 | a.fail(w, r, "apply a posted update", err) |
| 308 | return |
| 309 | } |
| 310 | |
| 311 | // The header before the broadcast, both only on success: an |
| 312 | // announced seq must be one a reader can actually fetch back. |
| 313 | w.Header().Set("Slides-Seq", strconv.FormatInt(seq, 10)) |
| 314 | w.WriteHeader(http.StatusNoContent) |
| 315 | } |
| 316 | |
| 317 | // appendUpdate is the second write path into a document, beside |
| 318 | // applyOps, and it takes the same lock the same way: open the deck, |
| 319 | // apply the update to the handle, insert the log row at Seq+1 and bump |
| 320 | // the row's seq in ONE transaction whose `WHERE id = ? AND seq = ?` is |
| 321 | // the optimistic lock. One retry on errDeckBusy from a freshly opened |
| 322 | // document, for editDeck's reason — the batch applied nothing, so |
| 323 | // replaying it against the state that beat us is correct. |
| 324 | // |
| 325 | // It exists rather than being folded into applyOps because the two |
| 326 | // differ in exactly one line and in what a failure of that line MEANS. |
| 327 | // applyOps hands the core a batch this app wrote, so a refusal is a bug |
| 328 | // here; appendUpdate hands it bytes off the wire, so a refusal is the |
| 329 | // ordinary case and has to come back distinguishable (errUpdateRefused) |
| 330 | // rather than as a 500. |
| 331 | // |
| 332 | // The one line is previewUpdate, and it does more than apply: it reads |
| 333 | // the deck back and parses it BEFORE anything is stored. Bytes off the |
| 334 | // wire can put any shape at any key, and a shape the typed reader |
| 335 | // cannot hold would otherwise be committed to the log and then fail |
| 336 | // every openDeck after it — the viewer, the editor, every slide, every |
| 337 | // asset, and both write paths, for good. The view itself tolerates |
| 338 | // the shapes it can (core/src/view.rs); this is the gate for whatever |
| 339 | // it cannot, and it stands whether or not the view is clever. |
| 340 | // |
| 341 | // d is a pointer because its Seq is updated in place on success and |
| 342 | // re-read on a conflict, exactly as editDeck does. |
| 343 | // |
| 344 | // g is the team-mode write guard, run inside commitUpdate's transaction; |
| 345 | // nil outside team mode. |
| 346 | func (a *app) appendUpdate(ctx context.Context, d *Deck, actor string, update []byte, g writeGuard) (int64, error) { |
| 347 | var lastErr error |
| 348 | for attempt := 0; attempt < 2; attempt++ { |
| 349 | h, before, err := a.openDeck(ctx, *d) |
| 350 | if err != nil { |
| 351 | return 0, err |
| 352 | } |
| 353 | view, err := a.previewUpdate(ctx, h, d, update) |
| 354 | if err != nil { |
| 355 | h.Close(ctx) |
| 356 | return 0, err |
| 357 | } |
| 358 | if err := sceneRefusal(before, view); err != nil { |
| 359 | h.Close(ctx) |
| 360 | return 0, fmt.Errorf("%w: %w", errUpdateRefused, err) |
| 361 | } |
| 362 | updates, err := a.stampSceneAuthors(ctx, h, d, before, view, actor, update) |
| 363 | if err != nil { |
| 364 | h.Close(ctx) |
| 365 | return 0, err |
| 366 | } |
| 367 | seq, err := a.commitUpdate(ctx, d, actor, updates, g) |
| 368 | if err == nil { |
| 369 | // After the commit, in this order and for the same reasons |
| 370 | // applyOps has: nobody is told about a seq a rolled-back |
| 371 | // transaction never wrote, and the snapshot is taken from |
| 372 | // a handle that holds exactly what the row now claims — |
| 373 | // d.Seq, which is past seq when a stamp followed it. |
| 374 | a.live.PublishSeq(d.Sqid, d.Seq) |
| 375 | a.mirrorMeta(ctx, d, view, d.Seq) |
| 376 | a.maybeSnapshot(ctx, *d, h, d.Seq) |
| 377 | h.Close(ctx) |
| 378 | return seq, nil |
| 379 | } |
| 380 | h.Close(ctx) |
| 381 | |
| 382 | lastErr = err |
| 383 | if !errors.Is(err, errDeckBusy) { |
| 384 | return 0, err |
| 385 | } |
| 386 | // Re-read the row: our copy's Seq is what just lost. |
| 387 | if err := a.db.G.WithContext(ctx).First(d, d.ID).Error; err != nil { |
| 388 | return 0, fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| 389 | } |
| 390 | } |
| 391 | return 0, lastErr |
| 392 | } |
| 393 | |
| 394 | // previewUpdate applies the posted bytes to a freshly opened handle and |
| 395 | // reads the deck they produce, outside any transaction: the handle is |
| 396 | // per-attempt and discarded on any failure, so nothing here has to be |
| 397 | // undone. All three refusals are errUpdateRefused — the core would not |
| 398 | // take the bytes, or it took them and the text they leave is outside |
| 399 | // the schema, or the deck they make cannot be read — because all three |
| 400 | // are the client's problem and none has touched the log. Anything else |
| 401 | // is a 500 for the reasons the variable's own comment gives. |
| 402 | // |
| 403 | // The check comes BEFORE the parse and is the stronger of the two |
| 404 | // (codex 3). The view is a projection, and a tolerant one: it drops a |
| 405 | // formatting attribute it does not know and reads the words around it, |
| 406 | // so an update carrying `unknown_mark` on a run parses perfectly. The |
| 407 | // editor does not read the projection. It binds y-prosemirror to the |
| 408 | // shared text itself, and y-prosemirror 1.3.7 answers a mark its schema |
| 409 | // lacks by deleting the whole XmlText — the words, not the mark. So the |
| 410 | // gate has to look at the document, not at what the document projects |
| 411 | // to: core.Handle.Check walks every text fragment and refuses anything |
| 412 | // the §2.6 vocabulary does not define. The parse stays for what it was |
| 413 | // always for — a shape the typed reader cannot hold at all. |
| 414 | // |
| 415 | // The view comes back so mirrorMeta can use it rather than reading the |
| 416 | // deck out of the module a second time on every keystroke batch. |
| 417 | func (a *app) previewUpdate(ctx context.Context, h *core.Handle, d *Deck, update []byte) (*deck.Deck, error) { |
| 418 | if err := h.Apply(ctx, update); err != nil { |
| 419 | if core.Rejected(err) || core.Recovered(err) { |
| 420 | return nil, fmt.Errorf("%w: %w", errUpdateRefused, err) |
| 421 | } |
| 422 | // A rebuild that itself failed, or a full retained log: |
| 423 | // neither is the client's doing, and the second means this |
| 424 | // deck needs a snapshot before it can take anything else. |
| 425 | return nil, fmt.Errorf("slides: apply a posted update to deck %s: %w", d.Sqid, err) |
| 426 | } |
| 427 | if err := h.Check(ctx); err != nil { |
| 428 | if core.Rejected(err) || core.Recovered(err) { |
| 429 | return nil, fmt.Errorf("%w: the text it leaves is outside the schema: %w", errUpdateRefused, err) |
| 430 | } |
| 431 | return nil, fmt.Errorf("slides: check a posted update to deck %s: %w", d.Sqid, err) |
| 432 | } |
| 433 | raw, err := h.JSON(ctx) |
| 434 | if err != nil { |
| 435 | return nil, fmt.Errorf("slides: read deck %s after a posted update: %w", d.Sqid, err) |
| 436 | } |
| 437 | view, err := deck.Parse(raw) |
| 438 | if err != nil { |
| 439 | return nil, fmt.Errorf("%w: the deck it produces cannot be read: %w", errUpdateRefused, err) |
| 440 | } |
| 441 | return view, nil |
| 442 | } |
| 443 | |
| 444 | // stampSceneAuthors is the posted update, then — when it left a scene |
| 445 | // with an author the server did not give it (scene_writes.go) — the |
| 446 | // update that puts that right, applied to h after it. before is the |
| 447 | // deck as h held it before the posted update, view as it holds it now. |
| 448 | func (a *app) stampSceneAuthors(ctx context.Context, h *core.Handle, d *Deck, before, view *deck.Deck, actor string, update []byte) ([][]byte, error) { |
| 449 | ops, err := sceneAuthorOps(before, view, actor) |
| 450 | if err != nil || ops == nil { |
| 451 | return [][]byte{update}, err |
| 452 | } |
| 453 | stamp, err := h.Ops(ctx, ops) |
| 454 | if err != nil { |
| 455 | return nil, fmt.Errorf("slides: stamp scene authors on deck %s: %w", d.Sqid, err) |
| 456 | } |
| 457 | return [][]byte{update, stamp}, nil |
| 458 | } |
| 459 | |
| 460 | // commitUpdate is appendUpdate's one attempt at the database: applyOps' |
| 461 | // transaction with the updates already applied and checked by |
| 462 | // previewUpdate, so the transaction holds SQLite's single writer for a |
| 463 | // few statements and no guest calls. The updates take the seqs after |
| 464 | // d.Seq in order; the answer is the first, the one the poster sent, and |
| 465 | // d.Seq is left at the last. |
| 466 | // |
| 467 | // The poster adopts the answer as its cursor only when it is the next |
| 468 | // row it expected (live-updates.mjs, noteOwnSeq), so a stamp after it |
| 469 | // is fetched like anybody else's update when the seq is published. |
| 470 | func (a *app) commitUpdate(ctx context.Context, d *Deck, actor string, updates [][]byte, g writeGuard) (int64, error) { |
| 471 | first := d.Seq + 1 |
| 472 | err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 473 | return g.run(func() error { return commitUpdateTx(tx, d, actor, updates, first) }) |
| 474 | }) |
| 475 | if err != nil { |
| 476 | return 0, err |
| 477 | } |
| 478 | d.Seq = first + int64(len(updates)) - 1 |
| 479 | return first, nil |
| 480 | } |
| 481 | |
| 482 | // commitUpdateTx is commitUpdate's transaction body. |
| 483 | func commitUpdateTx(tx *gorm.DB, d *Deck, actor string, updates [][]byte, first int64) error { |
| 484 | next := first - 1 |
| 485 | for _, update := range updates { |
| 486 | next++ |
| 487 | if err := tx.Create(&DeckUpdate{ |
| 488 | DeckID: d.ID, |
| 489 | Seq: next, |
| 490 | Actor: actor, |
| 491 | Bytes: update, |
| 492 | CreatedAt: time.Now().UTC(), |
| 493 | }).Error; err != nil { |
| 494 | if errors.Is(err, gorm.ErrDuplicatedKey) { |
| 495 | // Somebody else's update is already at this seq: the |
| 496 | // lost race, reported as the lost race. |
| 497 | return errDeckBusy |
| 498 | } |
| 499 | return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // Only the seq here. The row's title and theme follow the |
| 504 | // document too, but that is mirrorMeta's job AFTER the commit: |
| 505 | // it costs a read of the whole deck out of the wasm module, |
| 506 | // and metaRowUpdates' own comment says why that must not |
| 507 | // happen inside this transaction — it would hold SQLite's |
| 508 | // single writer for the length of a guest call on the path of |
| 509 | // every keystroke batch in the app. |
| 510 | res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| 511 | Updates(map[string]any{"seq": next}) |
| 512 | if res.Error != nil { |
| 513 | return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| 514 | } |
| 515 | if res.RowsAffected != 1 { |
| 516 | return errDeckBusy |
| 517 | } |
| 518 | return nil |
| 519 | } |
| 520 | |
| 521 | // mirrorMeta makes the deck row follow the document's meta after an |
| 522 | // update posted over the wire: the editor's Deck section writes |
| 523 | // meta.title and meta.theme this way, and the deck list, the settings |
| 524 | // form and every link's label read the row. |
| 525 | // |
| 526 | // It runs after the commit, deliberately, and it is the one place the |
| 527 | // wire path differs from the API's. metaRowUpdates can read a BATCH — |
| 528 | // it knows the ops — and so folds the row write into applyOps' own |
| 529 | // transaction. An update is bytes, not ops, so the only way to know |
| 530 | // what it did is to read the document back; previewUpdate already did, |
| 531 | // before the transaction, and v is that reading. Nothing here calls |
| 532 | // into the wasm module or holds SQLite's single writer for longer than |
| 533 | // one UPDATE. |
| 534 | // |
| 535 | // What that costs is honest: the row can be a moment behind the |
| 536 | // document, and a failure leaves it behind until the next update. Both |
| 537 | // are fine for what the row is — a label and a filter — and neither is |
| 538 | // data loss: the document is committed either way. |
| 539 | // |
| 540 | // seq is the seq this update landed at, and it is the guard: the write |
| 541 | // only lands while the row is still at it. Two updates racing would |
| 542 | // otherwise let the older one's read win, and the list would show a |
| 543 | // title nobody typed last. |
| 544 | func (a *app) mirrorMeta(ctx context.Context, d *Deck, v *deck.Deck, seq int64) { |
| 545 | changes := metaRowChanges(v, *d) |
| 546 | if len(changes) == 0 { |
| 547 | return |
| 548 | } |
| 549 | res := a.db.G.WithContext(ctx).Model(&Deck{}). |
| 550 | Where("id = ? AND seq = ?", d.ID, seq).Updates(changes) |
| 551 | if res.Error != nil { |
| 552 | a.logger.Error("slides: mirror a deck's meta onto its row", "deck", d.Sqid, "err", res.Error) |
| 553 | return |
| 554 | } |
| 555 | if res.RowsAffected != 1 { |
| 556 | return |
| 557 | } |
| 558 | if title, ok := changes["title"].(string); ok { |
| 559 | d.Title = title |
| 560 | } |
| 561 | if theme, ok := changes["theme"].(string); ok { |
| 562 | d.Theme = theme |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | // metaRowChanges is the row's share of a document's meta: the columns |
| 567 | // that differ from what the row already holds, and nothing else — nil |
| 568 | // when nothing does, which is the answer for the vast majority of |
| 569 | // updates and the one that saves the write. |
| 570 | // |
| 571 | // An empty title is not a title: the document may legitimately have |
| 572 | // none, and blanking the row would leave a deck with no name anywhere |
| 573 | // a name is read. A theme the row cannot use is left out for |
| 574 | // metaRowUpdates' reason — the core takes any string, the row is what |
| 575 | // themes a render. |
| 576 | func metaRowChanges(v *deck.Deck, d Deck) map[string]any { |
| 577 | changes := map[string]any{} |
| 578 | if v.Meta.Title != "" && v.Meta.Title != d.Title { |
| 579 | changes["title"] = v.Meta.Title |
| 580 | } |
| 581 | if validTheme(v.Meta.Theme) && v.Meta.Theme != d.Theme { |
| 582 | changes["theme"] = v.Meta.Theme |
| 583 | } |
| 584 | if len(changes) == 0 { |
| 585 | return nil |
| 586 | } |
| 587 | return changes |
| 588 | } |
| 589 | |
| 590 | // --- GET /d/{sqid}/stream --- |
| 591 | |
| 592 | // deckStream is the deck's SSE feed: `event: update` carrying a seq and |
| 593 | // no bytes, `event: presence` carrying the whole set as JSON, a comment |
| 594 | // ping in between, and one of each on connect. |
| 595 | // |
| 596 | // The timings are presentation.go's, shared rather than restated |
| 597 | // (streamHeartbeat, streamWriteDeadline, streamTTL): the reasons are |
| 598 | // the same reasons, and two apps' worth of streams in one binary |
| 599 | // behaving differently would be a surprise nobody asked for. |
| 600 | // |
| 601 | // The connect events are load-bearing rather than an optimisation. The |
| 602 | // update one heals a tab whose cursor legitimately failed to advance |
| 603 | // and covers the gap between the page rendering and this stream |
| 604 | // opening; the presence one tells a tab who is already here, rather |
| 605 | // than leaving it to find out as each of them happens to move. |
| 606 | func (a *app) deckStream(w http.ResponseWriter, r *http.Request) { |
| 607 | u, ok := a.viewer(w, r) |
| 608 | if !ok { |
| 609 | return |
| 610 | } |
| 611 | d, ok := a.deckFor(w, r, u) |
| 612 | if !ok { |
| 613 | return |
| 614 | } |
| 615 | fl, ok := w.(http.Flusher) |
| 616 | if !ok { |
| 617 | a.fail(w, r, "stream: the ResponseWriter does not flush", nil) |
| 618 | return |
| 619 | } |
| 620 | if a.stopping() { |
| 621 | drained(w) |
| 622 | return |
| 623 | } |
| 624 | |
| 625 | // Subscribe BEFORE re-reading the seq, never after (Docs' note): an |
| 626 | // update committing between the two must produce a redundant |
| 627 | // notification, which costs one empty fetch, where the other order |
| 628 | // would let it fall into the gap and leave the tab looking current |
| 629 | // and being stale until somebody typed. |
| 630 | ch, stop := a.live.Subscribe(d.Sqid) |
| 631 | defer stop() |
| 632 | |
| 633 | var current Deck |
| 634 | if err := a.db.G.WithContext(r.Context()).Take(¤t, d.ID).Error; err != nil { |
| 635 | a.fail(w, r, "read a deck for the stream", err) |
| 636 | return |
| 637 | } |
| 638 | |
| 639 | rc := http.NewResponseController(w) |
| 640 | w.Header().Set("Content-Type", "text/event-stream") |
| 641 | w.Header().Set("Cache-Control", "no-store") |
| 642 | w.WriteHeader(http.StatusOK) |
| 643 | fl.Flush() |
| 644 | |
| 645 | // Team mode: the stream stands on the viewer's standing, so it is |
| 646 | // re-decided before every delivery and again when a Member lease |
| 647 | // runs out (teamStreamAccess), and ends on a definite "no". A silent |
| 648 | // stream cannot outlive a removal. While standing cannot be read the |
| 649 | // stream is HELD: open, delivering nothing but comment pings, re-asking |
| 650 | // at streamHoldRetry (the roster's RetryAfter), and caught up (the current seq and presence) |
| 651 | // the moment standing returns — so a Home blip neither leaks an |
| 652 | // update nor strands a tab on a failed reconnect (Fable #33, note 1). |
| 653 | // Outside team mode renewC is nil, never ready, and nothing here runs. |
| 654 | var renew *time.Timer |
| 655 | var renewC <-chan time.Time |
| 656 | defer func() { |
| 657 | if renew != nil { |
| 658 | renew.Stop() |
| 659 | } |
| 660 | }() |
| 661 | held := false |
| 662 | stillReaches := func() bool { |
| 663 | if a.team == nil { |
| 664 | return true |
| 665 | } |
| 666 | decision, next := a.teamStreamAccess(r, d.ID) |
| 667 | switch decision { |
| 668 | case streamEnds: |
| 669 | return false |
| 670 | case streamHolds: |
| 671 | held, next = true, streamHoldRetry |
| 672 | default: |
| 673 | held = false |
| 674 | } |
| 675 | switch { |
| 676 | case next <= 0: |
| 677 | renewC = nil |
| 678 | case renew == nil: |
| 679 | renew = time.NewTimer(next) |
| 680 | renewC = renew.C |
| 681 | default: |
| 682 | renew.Reset(next) |
| 683 | renewC = renew.C |
| 684 | } |
| 685 | return true |
| 686 | } |
| 687 | |
| 688 | // send is every byte's one exit: deadline armed, bytes, flush. The |
| 689 | // deadline error is ignored deliberately — a ResponseWriter that |
| 690 | // cannot set deadlines still streams, unbounded — while a write |
| 691 | // error ends the handler, because it means the client is gone. |
| 692 | send := func(text string) bool { |
| 693 | _ = rc.SetWriteDeadline(time.Now().Add(streamWriteDeadline)) |
| 694 | if _, err := io.WriteString(w, text); err != nil { |
| 695 | return false |
| 696 | } |
| 697 | fl.Flush() |
| 698 | return true |
| 699 | } |
| 700 | seqText := func(seq int64) string { |
| 701 | return "event: update\ndata: " + strconv.FormatInt(seq, 10) + "\n\n" |
| 702 | } |
| 703 | presenceText := func(set live.PresenceSet) (string, bool) { |
| 704 | // A nil set must go out as `[]`, not `null`: the client reads |
| 705 | // this as "everybody here", and null is a different sentence. |
| 706 | if set == nil { |
| 707 | set = live.PresenceSet{} |
| 708 | } |
| 709 | body, err := json.Marshal(set) |
| 710 | if err != nil { |
| 711 | a.logger.Error("slides: encode presence", "deck", d.Sqid, "err", err) |
| 712 | return "", false |
| 713 | } |
| 714 | return "event: presence\ndata: " + string(body) + "\n\n", true |
| 715 | } |
| 716 | // catchUp is what a held stream owes when standing returns: what the |
| 717 | // connect events say, read afresh. |
| 718 | catchUp := func() bool { |
| 719 | var now Deck |
| 720 | if err := a.db.G.WithContext(r.Context()).Take(&now, d.ID).Error; err != nil { |
| 721 | return false |
| 722 | } |
| 723 | presence, ok := presenceText(a.live.Snapshot(d.Sqid)) |
| 724 | return ok && send(seqText(now.Seq)) && send(presence) |
| 725 | } |
| 726 | // write re-decides (team mode) and then sends; while held only a |
| 727 | // comment carries, since it says nothing about the deck. |
| 728 | write := func(text string) bool { |
| 729 | wasHeld := held |
| 730 | if !stillReaches() { |
| 731 | return false |
| 732 | } |
| 733 | if held { |
| 734 | return !strings.HasPrefix(text, ":") || send(text) |
| 735 | } |
| 736 | if wasHeld && !catchUp() { |
| 737 | return false |
| 738 | } |
| 739 | return send(text) |
| 740 | } |
| 741 | seqEvent := func(seq int64) bool { return write(seqText(seq)) } |
| 742 | presenceEvent := func(set live.PresenceSet) bool { |
| 743 | text, ok := presenceText(set) |
| 744 | return ok && write(text) |
| 745 | } |
| 746 | |
| 747 | if !seqEvent(current.Seq) { |
| 748 | return |
| 749 | } |
| 750 | if !presenceEvent(a.live.Snapshot(d.Sqid)) { |
| 751 | return |
| 752 | } |
| 753 | |
| 754 | heartbeat := time.NewTimer(streamHeartbeat) |
| 755 | defer heartbeat.Stop() |
| 756 | ttl := time.NewTimer(streamTTL) |
| 757 | defer ttl.Stop() |
| 758 | |
| 759 | for { |
| 760 | select { |
| 761 | case <-r.Context().Done(): |
| 762 | // The client went away. |
| 763 | return |
| 764 | case <-a.draining.done(): |
| 765 | // The process is stopping, which never cancels a request's |
| 766 | // context: this is what lets the graceful shutdown finish |
| 767 | // instead of waiting out its deadline on an open editor |
| 768 | // (drain.go). |
| 769 | return |
| 770 | case <-ttl.C: |
| 771 | // A clean close: the browser reopens if it still wants one, |
| 772 | // and a tab nobody is looking at does not. |
| 773 | return |
| 774 | case e, ok := <-ch: |
| 775 | if !ok { |
| 776 | // Dropped for falling behind. Ending the response is |
| 777 | // the right answer: EventSource reconnects, and the |
| 778 | // connect events make it right again immediately. |
| 779 | return |
| 780 | } |
| 781 | sent := false |
| 782 | if e.Presence != nil { |
| 783 | sent = presenceEvent(*e.Presence) |
| 784 | } else { |
| 785 | sent = seqEvent(e.Seq) |
| 786 | } |
| 787 | if !sent { |
| 788 | return |
| 789 | } |
| 790 | heartbeat.Reset(streamHeartbeat) |
| 791 | case <-heartbeat.C: |
| 792 | if !write(": ping\n\n") { |
| 793 | return |
| 794 | } |
| 795 | heartbeat.Reset(streamHeartbeat) |
| 796 | case <-renewC: |
| 797 | // The Member lease this stream stood on is up, or a held |
| 798 | // stream's retry is due: renewed, still held, or ended. |
| 799 | wasHeld := held |
| 800 | if !stillReaches() { |
| 801 | return |
| 802 | } |
| 803 | if wasHeld && !held && !catchUp() { |
| 804 | return |
| 805 | } |
| 806 | } |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | // --- POST /d/{sqid}/presence --- |
| 811 | |
| 812 | // deckPresence is one tab saying "I am here, on this slide, in this |
| 813 | // block". The client posts every twenty seconds and on every change |
| 814 | // (spec §3.3); two missed beats and the hub's sweeper drops it. |
| 815 | // |
| 816 | // Name and Colour are stamped from the users row and are NOT read from |
| 817 | // the body. Anything else would let anybody signed in appear in a deck |
| 818 | // wearing a colleague's name, which is the whole value of presence |
| 819 | // inverted. |
| 820 | // |
| 821 | // Nothing here is persisted. Presence is not document state: it never |
| 822 | // reaches the update log, it is never snapshotted, and it is gone when |
| 823 | // this process is. |
| 824 | func (a *app) deckPresence(w http.ResponseWriter, r *http.Request) { |
| 825 | u, ok := a.viewer(w, r) |
| 826 | if !ok { |
| 827 | return |
| 828 | } |
| 829 | d, ok := a.deckFor(w, r, u) |
| 830 | if !ok { |
| 831 | return |
| 832 | } |
| 833 | |
| 834 | r.Body = http.MaxBytesReader(w, r.Body, maxPresenceBytes) |
| 835 | var body struct { |
| 836 | Client string `json:"client"` |
| 837 | Slide string `json:"slide"` |
| 838 | Block string `json:"block"` |
| 839 | } |
| 840 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil { |
| 841 | var tooBig *http.MaxBytesError |
| 842 | if errors.As(err, &tooBig) { |
| 843 | http.Error(w, rastrillo.T(r, "slides.live.error.toolarge"), http.StatusRequestEntityTooLarge) |
| 844 | return |
| 845 | } |
| 846 | liveInvalid(w, r) |
| 847 | return |
| 848 | } |
| 849 | // A heartbeat with no client to key on would be filed under the |
| 850 | // empty string, where every tab in the deck would overwrite every |
| 851 | // other. Refused rather than guessed at. |
| 852 | if body.Client == "" || len(body.Client) > maxPresenceField || |
| 853 | len(body.Slide) > maxPresenceField || len(body.Block) > maxPresenceField { |
| 854 | liveInvalid(w, r) |
| 855 | return |
| 856 | } |
| 857 | |
| 858 | name := u.viewerLabel() |
| 859 | a.live.PublishPresence(d.Sqid, live.Presence{ |
| 860 | Client: body.Client, |
| 861 | Name: name, |
| 862 | Colour: u.Colour, |
| 863 | Slide: body.Slide, |
| 864 | Block: body.Block, |
| 865 | At: time.Now().UTC(), |
| 866 | }) |
| 867 | w.WriteHeader(http.StatusNoContent) |
| 868 | } |
| 869 | |
| 870 | // liveInvalid is the 422 a JSON caller on this surface gets: a body |
| 871 | // shaped like every other JSON error this app writes, so a client has |
| 872 | // one shape to read rather than two. The binary update endpoint answers |
| 873 | // the same status as plain text, because its caller is posting bytes |
| 874 | // and has no JSON decoder in the path at all. |
| 875 | func liveInvalid(w http.ResponseWriter, r *http.Request) { |
| 876 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 877 | w.WriteHeader(http.StatusUnprocessableEntity) |
| 878 | _ = json.NewEncoder(w).Encode(map[string]string{ |
| 879 | "error": "invalid", |
| 880 | "message": rastrillo.T(r, "slides.live.error.invalid"), |
| 881 | }) |
| 882 | } |
| 883 | |