| 1 | // api.go is the drive surface (spec §7): the JSON an agent speaks to |
| 2 | // build a deck, look at what it made, and put it on a projector. No |
| 3 | // person's browser ever reaches it. |
| 4 | // |
| 5 | // # Why it is mounted outside the chi router |
| 6 | // |
| 7 | // csrf.Protect is app-wide (app.go) and it is right to be: it refuses |
| 8 | // a state-changing request that carries no browser evidence of |
| 9 | // same-origin submission, and "no evidence" is exactly what a |
| 10 | // non-browser client sends — no Sec-Fetch-Site, no Origin, no Referer. |
| 11 | // csrf.SameOrigin's last clause refuses that outright, so every POST |
| 12 | // an agent made through the chi router would be a 403 with an HTML |
| 13 | // body. |
| 14 | // |
| 15 | // So /api/v1 is mounted on the ServeMux ahead of the chi router, with |
| 16 | // its own gate. That is not a hole in the CSRF defence: a browser |
| 17 | // never attaches an `Authorization` header of its own, so a page on |
| 18 | // another origin cannot make a request this surface will authenticate, |
| 19 | // whatever it does with credentials or forms. The capability is the |
| 20 | // header, and CSRF is an attack on ambient credentials. |
| 21 | // |
| 22 | // # What it is |
| 23 | // |
| 24 | // Every answer with a body is JSON, including every error, and every |
| 25 | // error is `{"error": "<identifier>"}` — a fixed English word a |
| 26 | // program branches on, never a translated sentence. Some carry more: |
| 27 | // a refused batch adds `op` and `message`, which is the core's own |
| 28 | // account of which operation it refused and why. |
| 29 | // |
| 30 | // Visibility is the OPERATOR's visibility, evaluated through |
| 31 | // decks.go's visibleDecks like every screen. An agent is exactly as |
| 32 | // powerful as the person who minted its token and never a step more. |
| 33 | package slides |
| 34 | |
| 35 | import ( |
| 36 | "context" |
| 37 | "encoding/json" |
| 38 | "errors" |
| 39 | "fmt" |
| 40 | "io" |
| 41 | "mime" |
| 42 | "net/http" |
| 43 | "regexp" |
| 44 | "strconv" |
| 45 | "strings" |
| 46 | |
| 47 | "github.com/go-chi/chi/v5" |
| 48 | "gorm.io/gorm" |
| 49 | |
| 50 | "amadan.net/oficina/slides/internal/slides/core" |
| 51 | "amadan.net/oficina/slides/internal/slides/deck" |
| 52 | slidehtml "amadan.net/oficina/slides/internal/slides/render" |
| 53 | ) |
| 54 | |
| 55 | // apiPrefix is where the drive surface lives, and what app.go mounts |
| 56 | // on the ServeMux. Versioned from the first day it exists: an agent's |
| 57 | // configuration outlives a deploy, so the day this shape changes there |
| 58 | // has to be somewhere for the old one to keep answering. |
| 59 | const apiPrefix = "/api/v1" |
| 60 | |
| 61 | // The error identifiers. Fixed English words, not catalog keys: this |
| 62 | // is a machine surface, and a caller that branches on the error has to |
| 63 | // see the same string whatever Accept-Language it happened to send. |
| 64 | // The words a PERSON reads about a failure are the API caller's to |
| 65 | // write, from these plus the message a 422 carries. |
| 66 | const ( |
| 67 | errUnauthorized = "unauthorized" |
| 68 | errNotFound = "not_found" |
| 69 | errInvalid = "invalid" |
| 70 | errConflict = "conflict" |
| 71 | errUnsupported = "unsupported_media_type" |
| 72 | errTooLarge = "too_large" |
| 73 | errMethod = "method_not_allowed" |
| 74 | errInternal = "internal" |
| 75 | ) |
| 76 | |
| 77 | // maxAPIBody is the largest request body this surface reads. A mebibyte |
| 78 | // is far more than any batch of operations needs — the biggest thing an |
| 79 | // op carries is a slide's Markdown — and it is the bound that stops an |
| 80 | // unbounded read from being the way to take the process down. A |
| 81 | // picture's bytes come through POST .../assets instead, which reads at |
| 82 | // most maxAssetBytes (agent_assets.go). |
| 83 | const maxAPIBody = 1 << 20 |
| 84 | |
| 85 | // apiRouter is the whole drive surface, gated by the bearer and |
| 86 | // nothing else. |
| 87 | // |
| 88 | // Full paths rather than a mount, because the ServeMux hands the |
| 89 | // request over with its path intact: what is written here is what a |
| 90 | // caller types, which is also what docs/api.md documents. |
| 91 | func (a *app) apiRouter() http.Handler { |
| 92 | r := chi.NewRouter() |
| 93 | r.Use(a.bearerActor) |
| 94 | r.Get(apiPrefix+"/decks", a.apiListDecks) |
| 95 | r.Post(apiPrefix+"/decks", a.apiCreateDeck) |
| 96 | r.Get(apiPrefix+"/decks/{sqid}", a.apiGetDeck) |
| 97 | r.Post(apiPrefix+"/decks/{sqid}/ops", a.apiOps) |
| 98 | // A picture, the bytes as the body (agent_assets.go). |
| 99 | r.Post(apiPrefix+"/decks/{sqid}/assets", a.apiPostAsset) |
| 100 | // A scene's pictures and code (scenestills.go). |
| 101 | r.Put(apiPrefix+"/decks/{sqid}/scenes/{id}/stills/{state}", a.apiPutStill) |
| 102 | r.Put(apiPrefix+"/decks/{sqid}/scenes/{id}/code", a.apiPutSceneCode) |
| 103 | r.Post(apiPrefix+"/decks/{sqid}/scene-bundles", a.apiPostSceneBundle) |
| 104 | // {file} rather than {id}.html: chi can match a static tail inside |
| 105 | // a segment, but the extension is part of what this endpoint means |
| 106 | // — it is the HTML rendering of a slide, and the .svg thumbnail of |
| 107 | // spec §7.2 lands beside it in slice 3 — so the handler reads the |
| 108 | // extension itself and there is one place to add the second one. |
| 109 | r.Get(apiPrefix+"/decks/{sqid}/slides/{file}", a.apiSlide) |
| 110 | r.Post(apiPrefix+"/decks/{sqid}/present", a.apiPresent) |
| 111 | // Exporting (exports.go, spec §4.3). Three endpoints because it is |
| 112 | // a job: start it, watch it, take the file. {id} carries the .pdf |
| 113 | // itself for the same reason {file} does above — chi matches whole |
| 114 | // segments. |
| 115 | r.Post(apiPrefix+"/decks/{sqid}/export", a.apiStartExport) |
| 116 | r.Get(apiPrefix+"/decks/{sqid}/export/{id}", a.apiExportStatus) |
| 117 | // Anything else under the prefix is a 404 in this surface's own |
| 118 | // shape, not chi's plain-text one: a caller parsing JSON should |
| 119 | // never be handed something else because it mistyped a path. |
| 120 | r.NotFound(func(w http.ResponseWriter, r *http.Request) { |
| 121 | apiFail(w, http.StatusNotFound, errNotFound) |
| 122 | }) |
| 123 | r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { |
| 124 | apiFail(w, http.StatusMethodNotAllowed, errMethod) |
| 125 | }) |
| 126 | return r |
| 127 | } |
| 128 | |
| 129 | // --- answering --- |
| 130 | |
| 131 | // writeJSON is every successful answer: the header, the status, the |
| 132 | // body, in that order. |
| 133 | // |
| 134 | // Encoded into a buffer before anything touches the wire, render.go's |
| 135 | // reason: an encoding failure becomes a clean 500 rather than a |
| 136 | // half-written body with a 200 already on it. |
| 137 | func (a *app) writeJSON(w http.ResponseWriter, status int, body any) { |
| 138 | b, err := json.Marshal(body) |
| 139 | if err != nil { |
| 140 | a.logger.Error("slides: encode an API answer", "err", err) |
| 141 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 142 | return |
| 143 | } |
| 144 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 145 | w.WriteHeader(status) |
| 146 | w.Write(b) |
| 147 | } |
| 148 | |
| 149 | // apiFail is every error with nothing more to say than which one it |
| 150 | // is. Hand-encoded rather than through json.Marshal so the error path |
| 151 | // cannot itself fail to encode. |
| 152 | func apiFail(w http.ResponseWriter, status int, id string) { |
| 153 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 154 | w.WriteHeader(status) |
| 155 | fmt.Fprintf(w, "{\"error\":%q}\n", id) |
| 156 | } |
| 157 | |
| 158 | // apiInvalid is the 422 with an account of what was wrong: the message |
| 159 | // as the core (or this file) put it, and the index of the operation it |
| 160 | // belongs to when there is one. op is omitted when the failure is not |
| 161 | // about a particular operation — a missing title, a theme that is not |
| 162 | // one of the six. |
| 163 | func (a *app) apiInvalid(w http.ResponseWriter, message string, op int) { |
| 164 | body := map[string]any{"error": errInvalid, "message": message} |
| 165 | if op >= 0 { |
| 166 | body["op"] = op |
| 167 | } |
| 168 | a.writeJSON(w, http.StatusUnprocessableEntity, body) |
| 169 | } |
| 170 | |
| 171 | // --- reading --- |
| 172 | |
| 173 | // readJSON reads a request body into dst, answering the four refusals |
| 174 | // a JSON surface owes a caller: the wrong media type, a body too big |
| 175 | // to be an edit, bytes that are not the shape the endpoint takes, and |
| 176 | // a body that carries anything after its JSON value. It reports |
| 177 | // whether the caller may carry on. |
| 178 | // |
| 179 | // The last of those is the one a decoder will not raise on its own. |
| 180 | // json.Decoder reads ONE value and stops, so `{...}{...}` — an encoder |
| 181 | // that wrote twice, two batches concatenated by a shell — would have |
| 182 | // applied the first batch and thrown the second away silently. Anything |
| 183 | // but whitespace after the value is a 422, and the caller sends the |
| 184 | // batch it meant. |
| 185 | func (a *app) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool { |
| 186 | ct := r.Header.Get("Content-Type") |
| 187 | if ct != "" { |
| 188 | kind, _, err := mime.ParseMediaType(ct) |
| 189 | if err != nil || kind != "application/json" { |
| 190 | apiFail(w, http.StatusUnsupportedMediaType, errUnsupported) |
| 191 | return false |
| 192 | } |
| 193 | } |
| 194 | r.Body = http.MaxBytesReader(w, r.Body, maxAPIBody) |
| 195 | dec := json.NewDecoder(r.Body) |
| 196 | if err := dec.Decode(dst); err != nil { |
| 197 | var tooBig *http.MaxBytesError |
| 198 | if errors.As(err, &tooBig) { |
| 199 | apiFail(w, http.StatusRequestEntityTooLarge, errTooLarge) |
| 200 | return false |
| 201 | } |
| 202 | a.apiInvalid(w, "the body is not the JSON this endpoint takes: "+err.Error(), -1) |
| 203 | return false |
| 204 | } |
| 205 | // io.EOF, and nothing else, means the value was the whole body. |
| 206 | // Trailing whitespace decodes to EOF too, so `curl -d @file`'s |
| 207 | // newline is not an error. |
| 208 | if err := dec.Decode(new(json.RawMessage)); !errors.Is(err, io.EOF) { |
| 209 | var tooBig *http.MaxBytesError |
| 210 | if errors.As(err, &tooBig) { |
| 211 | apiFail(w, http.StatusRequestEntityTooLarge, errTooLarge) |
| 212 | return false |
| 213 | } |
| 214 | a.apiInvalid(w, "the body carries more than one JSON value", -1) |
| 215 | return false |
| 216 | } |
| 217 | return true |
| 218 | } |
| 219 | |
| 220 | // --- resolving --- |
| 221 | |
| 222 | // apiPrincipal is the resolved bearer, or a 500. Past bearerActor |
| 223 | // there is always one; this exists so a handler reads it in one line |
| 224 | // and a wiring mistake surfaces as an error rather than a zero value |
| 225 | // that would scope every query to user 0. |
| 226 | func (a *app) apiPrincipal(w http.ResponseWriter, r *http.Request) (principal, bool) { |
| 227 | p, ok := principalFrom(r) |
| 228 | if !ok { |
| 229 | a.logger.Error("slides: no principal past the bearer gate", "path", r.URL.Path) |
| 230 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 231 | return principal{}, false |
| 232 | } |
| 233 | return p, true |
| 234 | } |
| 235 | |
| 236 | // apiDeckFor resolves the {sqid} in r to a deck the OPERATOR may read, |
| 237 | // answering 404 itself when there is none — deckFor's rule and |
| 238 | // deckFor's reason, in JSON: a deck that is not yours does not exist, |
| 239 | // so a stranger holding a sqid cannot learn whether it is real. |
| 240 | func (a *app) apiDeckFor(w http.ResponseWriter, r *http.Request, p principal) (Deck, bool) { |
| 241 | var d Deck |
| 242 | err := a.visibleDecks(r.Context(), p.operator). |
| 243 | Where("decks.sqid = ?", chi.URLParam(r, "sqid")).Take(&d).Error |
| 244 | switch { |
| 245 | case err == nil: |
| 246 | return d, true |
| 247 | case errors.Is(err, gorm.ErrRecordNotFound) && a.teamUnknown(p.operator): |
| 248 | // Team mode, the operator's standing unknown: deckFor's |
| 249 | // retryable answer, in JSON. |
| 250 | teamUnavailableJSON(w) |
| 251 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 252 | apiFail(w, http.StatusNotFound, errNotFound) |
| 253 | default: |
| 254 | a.logger.Error("slides: load a deck for the API", "err", err) |
| 255 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 256 | } |
| 257 | return Deck{}, false |
| 258 | } |
| 259 | |
| 260 | // --- GET /api/v1/decks --- |
| 261 | |
| 262 | // apiDeckSummary is one row of the list: everything an agent needs to |
| 263 | // pick a deck without opening it, plus the slide count, which it can |
| 264 | // only know by opening it. |
| 265 | type apiDeckSummary struct { |
| 266 | Sqid string `json:"sqid"` |
| 267 | Title string `json:"title"` |
| 268 | Slides int `json:"slides"` |
| 269 | Rung string `json:"rung"` |
| 270 | UpdatedAt string `json:"updated_at"` |
| 271 | Seq int64 `json:"seq"` |
| 272 | } |
| 273 | |
| 274 | // apiListDecks serves GET /api/v1/decks: every deck the operator may |
| 275 | // open, most recently edited first — the deck list screen's query, |
| 276 | // answered as JSON. |
| 277 | // |
| 278 | // The slide count costs one wasm instance per deck (decks.go's |
| 279 | // slideCount says why), and a deck whose document will not open is |
| 280 | // reported with a count of zero rather than taking the whole list |
| 281 | // down with it. |
| 282 | func (a *app) apiListDecks(w http.ResponseWriter, r *http.Request) { |
| 283 | p, ok := a.apiPrincipal(w, r) |
| 284 | if !ok { |
| 285 | return |
| 286 | } |
| 287 | var rows []Deck |
| 288 | if err := a.visibleDecks(r.Context(), p.operator). |
| 289 | Order("decks.updated_at DESC, decks.id DESC").Find(&rows).Error; err != nil { |
| 290 | a.logger.Error("slides: list decks for the API", "err", err) |
| 291 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 292 | return |
| 293 | } |
| 294 | // Team mode, standing unknown: a JSON list cannot carry the deck |
| 295 | // list's partial notice, and an agent would take a short list for |
| 296 | // the whole one, so it is unavailable rather than short (Fable on |
| 297 | // Docs #100). Asked after listing, of the same Access. |
| 298 | if a.teamPartial(p.operator) { |
| 299 | teamUnavailableJSON(w) |
| 300 | return |
| 301 | } |
| 302 | out := make([]apiDeckSummary, 0, len(rows)) |
| 303 | for _, d := range rows { |
| 304 | slides, _ := a.slideCount(r.Context(), d) |
| 305 | out = append(out, apiDeckSummary{ |
| 306 | Sqid: d.Sqid, |
| 307 | Title: d.Title, |
| 308 | Slides: slides, |
| 309 | Rung: d.Rung, |
| 310 | UpdatedAt: d.UpdatedAt.UTC().Format("2006-01-02T15:04:05Z"), |
| 311 | Seq: d.Seq, |
| 312 | }) |
| 313 | } |
| 314 | a.writeJSON(w, http.StatusOK, map[string]any{"decks": out}) |
| 315 | } |
| 316 | |
| 317 | // --- POST /api/v1/decks --- |
| 318 | |
| 319 | // apiCreateDeck serves POST /api/v1/decks. The deck is the OPERATOR's |
| 320 | // — an agent owns nothing, because an agent can be revoked and a deck |
| 321 | // must outlive that — and its first update is recorded against the |
| 322 | // AGENT, so the history says which program made it. |
| 323 | // |
| 324 | // The opening batch is createDeck's own (decks.go's openingOps): a new |
| 325 | // deck opens on a title slide whichever surface made it, so an agent |
| 326 | // and a person produce the same thing. |
| 327 | func (a *app) apiCreateDeck(w http.ResponseWriter, r *http.Request) { |
| 328 | p, ok := a.apiPrincipal(w, r) |
| 329 | if !ok { |
| 330 | return |
| 331 | } |
| 332 | if !a.teamMemberOnlyJSON(w, p.operator) { |
| 333 | return |
| 334 | } |
| 335 | var body struct { |
| 336 | Title string `json:"title"` |
| 337 | Theme string `json:"theme"` |
| 338 | } |
| 339 | if !a.readJSON(w, r, &body) { |
| 340 | return |
| 341 | } |
| 342 | title := strings.TrimSpace(body.Title) |
| 343 | if title == "" { |
| 344 | a.apiInvalid(w, "title is required", -1) |
| 345 | return |
| 346 | } |
| 347 | theme := body.Theme |
| 348 | if theme == "" { |
| 349 | theme = defaultTheme |
| 350 | } |
| 351 | if !validTheme(theme) { |
| 352 | a.apiInvalid(w, "theme must be one of "+strings.Join(themeIDs, ", "), -1) |
| 353 | return |
| 354 | } |
| 355 | |
| 356 | g := a.memberGuard(r.Context(), p.operator) |
| 357 | d, err := a.createDeckRow(r.Context(), p.operator, title, theme, g) |
| 358 | if guardRefusedJSON(w, err) { |
| 359 | return |
| 360 | } |
| 361 | if err != nil { |
| 362 | a.logger.Error("slides: create a deck for the API", "err", err) |
| 363 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 364 | return |
| 365 | } |
| 366 | ops, err := openingOps(title, theme) |
| 367 | if err != nil { |
| 368 | a.logger.Error("slides: build the opening ops for the API", "err", err) |
| 369 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 370 | return |
| 371 | } |
| 372 | if err := a.editDeck(r.Context(), &d, p.actor(), ops, nil, g); err != nil { |
| 373 | if guardRefusedJSON(w, err) { |
| 374 | return |
| 375 | } |
| 376 | a.logger.Error("slides: write the opening ops for the API", "err", err) |
| 377 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 378 | return |
| 379 | } |
| 380 | a.writeJSON(w, http.StatusCreated, map[string]any{"sqid": d.Sqid}) |
| 381 | } |
| 382 | |
| 383 | // --- GET /api/v1/decks/{sqid} --- |
| 384 | |
| 385 | // apiGetDeck serves the whole document: the core's own view (§2's |
| 386 | // model, core/src/view.rs) with the deck's sqid and seq alongside it. |
| 387 | // |
| 388 | // The seq is the ETag, unquoted nowhere and quoted everywhere, because |
| 389 | // the seq is exactly what an ETag is for: it moves on every write and |
| 390 | // on nothing else, so an agent holding one already has the document. |
| 391 | func (a *app) apiGetDeck(w http.ResponseWriter, r *http.Request) { |
| 392 | p, ok := a.apiPrincipal(w, r) |
| 393 | if !ok { |
| 394 | return |
| 395 | } |
| 396 | d, ok := a.apiDeckFor(w, r, p) |
| 397 | if !ok { |
| 398 | return |
| 399 | } |
| 400 | |
| 401 | etag := strconv.Quote(strconv.FormatInt(d.Seq, 10)) |
| 402 | w.Header().Set("ETag", etag) |
| 403 | if matchesETag(r.Header.Get("If-None-Match"), etag) { |
| 404 | // Before the document is opened, which is the whole point: a |
| 405 | // 304 costs no wasm instance and no log replay. |
| 406 | w.WriteHeader(http.StatusNotModified) |
| 407 | return |
| 408 | } |
| 409 | |
| 410 | h, _, err := a.openDeck(r.Context(), d) |
| 411 | if err != nil { |
| 412 | a.logger.Error("slides: open a deck for the API", "deck", d.Sqid, "err", err) |
| 413 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 414 | return |
| 415 | } |
| 416 | defer h.Close(r.Context()) |
| 417 | raw, err := h.JSON(r.Context()) |
| 418 | if err != nil { |
| 419 | a.logger.Error("slides: read a deck view for the API", "deck", d.Sqid, "err", err) |
| 420 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 421 | return |
| 422 | } |
| 423 | |
| 424 | // Decoded to raw fragments rather than to any: the view carries |
| 425 | // fractional z values and box coordinates, and a round trip |
| 426 | // through map[string]any would reformat every number the core |
| 427 | // wrote. This adds two keys and re-encodes the rest byte for byte. |
| 428 | var view map[string]json.RawMessage |
| 429 | if err := json.Unmarshal(raw, &view); err != nil { |
| 430 | a.logger.Error("slides: the deck view is not a JSON object", "deck", d.Sqid, "err", err) |
| 431 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 432 | return |
| 433 | } |
| 434 | view["sqid"], _ = json.Marshal(d.Sqid) |
| 435 | view["seq"], _ = json.Marshal(d.Seq) |
| 436 | a.writeJSON(w, http.StatusOK, view) |
| 437 | } |
| 438 | |
| 439 | // matchesETag reads an If-None-Match header the way RFC 9110 says to: |
| 440 | // a comma-separated list, `*` matching anything, and a weak validator |
| 441 | // comparing equal to its strong twin (weak comparison is what |
| 442 | // If-None-Match uses). |
| 443 | func matchesETag(header, etag string) bool { |
| 444 | if header == "" { |
| 445 | return false |
| 446 | } |
| 447 | for _, candidate := range strings.Split(header, ",") { |
| 448 | candidate = strings.TrimSpace(candidate) |
| 449 | if candidate == "*" { |
| 450 | return true |
| 451 | } |
| 452 | if strings.TrimPrefix(candidate, "W/") == strings.TrimPrefix(etag, "W/") { |
| 453 | return true |
| 454 | } |
| 455 | } |
| 456 | return false |
| 457 | } |
| 458 | |
| 459 | // --- POST /api/v1/decks/{sqid}/ops --- |
| 460 | |
| 461 | // coreOpIndex finds which operation the core refused. Its messages are |
| 462 | // prefixed "op <i>: " and "op <i> (applying): " (core/src/ops.rs's |
| 463 | // apply_ops), which is the only place that index exists — the batch is |
| 464 | // checked as one thing, so nothing on this side knows it. |
| 465 | var coreOpIndex = regexp.MustCompile(`^op (\d+)\b`) |
| 466 | |
| 467 | // apiOps serves the operation batch (spec §7.2): the one way anything |
| 468 | // in a document changes. |
| 469 | // |
| 470 | // Two things it does that the editor's own path does not: |
| 471 | // |
| 472 | // - It MINTS the ids. The core never draws entropy (decks.go's |
| 473 | // newID), so `add_slide`, `add_block` and `duplicate_slide` each |
| 474 | // need an id supplied by the host — and an agent writing a batch |
| 475 | // should not have to invent twelve base32 characters to add a |
| 476 | // slide. Any it left out are minted here and returned keyed by the |
| 477 | // operation's index, so the next batch can address what this one |
| 478 | // made. Ids the caller DID supply are left exactly as they are. |
| 479 | // - It reports which operation was refused, so a caller can fix that |
| 480 | // one rather than bisecting its own batch. |
| 481 | // |
| 482 | // A refused batch applies nothing — that is the core's guarantee, not |
| 483 | // this handler's (core/src/ops.rs's two-pass check) — and this answers |
| 484 | // 422 with the core's own account of it. |
| 485 | func (a *app) apiOps(w http.ResponseWriter, r *http.Request) { |
| 486 | p, ok := a.apiPrincipal(w, r) |
| 487 | if !ok { |
| 488 | return |
| 489 | } |
| 490 | d, ok := a.apiDeckFor(w, r, p) |
| 491 | if !ok { |
| 492 | return |
| 493 | } |
| 494 | |
| 495 | // Raw fragments, not any: an op carries fractional z values and box |
| 496 | // coordinates the core wrote a contract for, and this handler adds |
| 497 | // keys to an op rather than rewriting it. |
| 498 | var body struct { |
| 499 | Ops []map[string]json.RawMessage `json:"ops"` |
| 500 | } |
| 501 | if !a.readJSON(w, r, &body) { |
| 502 | return |
| 503 | } |
| 504 | if len(body.Ops) == 0 { |
| 505 | a.apiInvalid(w, "ops must be a non-empty list of operations", -1) |
| 506 | return |
| 507 | } |
| 508 | |
| 509 | ids, err := a.applyAgentOps(r.Context(), &d, p.actor(), body.Ops, a.deckGuard(r.Context(), p.operator, d)) |
| 510 | if err != nil { |
| 511 | a.apiOpsFailed(w, d, err) |
| 512 | return |
| 513 | } |
| 514 | a.writeJSON(w, http.StatusOK, map[string]any{"seq": d.Seq, "ids": ids}) |
| 515 | } |
| 516 | |
| 517 | // apiOpsFailed answers a batch the deck refused, for every route that |
| 518 | // applies one (apiOps, agent_assets.go, scenestills.go): the guard's |
| 519 | // answer, a lost race twice over, the core's account of the op it |
| 520 | // refused, or a 500. |
| 521 | func (a *app) apiOpsFailed(w http.ResponseWriter, d Deck, err error) { |
| 522 | switch { |
| 523 | case guardRefusedJSON(w, err): |
| 524 | case errors.Is(err, errDeckBusy): |
| 525 | // Two attempts have already been made; a third would be |
| 526 | // spinning. 409 is the honest answer, and the caller re-reads |
| 527 | // the deck and decides what its batch now means. |
| 528 | apiFail(w, http.StatusConflict, errConflict) |
| 529 | default: |
| 530 | var rejected *core.RejectedError |
| 531 | if errors.As(err, &rejected) { |
| 532 | msg := rejected.Error() |
| 533 | op := -1 |
| 534 | if m := coreOpIndex.FindStringSubmatch(msg); m != nil { |
| 535 | if i, convErr := strconv.Atoi(m[1]); convErr == nil { |
| 536 | op = i |
| 537 | } |
| 538 | } |
| 539 | a.apiInvalid(w, msg, op) |
| 540 | return |
| 541 | } |
| 542 | a.logger.Error("slides: apply an agent's ops", "deck", d.Sqid, "err", err) |
| 543 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | // applyAgentOps mints the batch's missing ids and applies it, with one |
| 548 | // retry on the optimistic lock. |
| 549 | // |
| 550 | // The deck is opened once on the happy path: minting needs the current |
| 551 | // document (how many blocks a slide has, for duplicate_slide), and so |
| 552 | // does applying, so both run against the one handle. A second writer |
| 553 | // landing in between is errDeckBusy, and the second attempt re-reads |
| 554 | // the row and reopens — the ids minted on the first attempt are |
| 555 | // already written into the ops, so it mints nothing new and the caller |
| 556 | // is told the same ids either way. |
| 557 | func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []map[string]json.RawMessage, g writeGuard) (map[string]string, error) { |
| 558 | ids, _, err := a.applyAgentOpsFrom(ctx, d, actor, func(*deck.Deck) ([]map[string]json.RawMessage, error) { return ops, nil }, g) |
| 559 | return ids, err |
| 560 | } |
| 561 | |
| 562 | // applyAgentOpsFrom is applyAgentOps for a batch that depends on the |
| 563 | // document it lands on: build is given the view each attempt opened, so |
| 564 | // whatever it checked is what the write is made against. The optimistic |
| 565 | // lock refuses the write if the deck has moved since that open, and the |
| 566 | // retry builds again from the newer one. An error from build is |
| 567 | // returned as it is, with nothing written. It answers the document as |
| 568 | // the write left it. |
| 569 | func (a *app) applyAgentOpsFrom(ctx context.Context, d *Deck, actor string, build func(*deck.Deck) ([]map[string]json.RawMessage, error), g writeGuard) (map[string]string, *deck.Deck, error) { |
| 570 | var ids map[string]string |
| 571 | var lastErr error |
| 572 | for attempt := 0; attempt < 2; attempt++ { |
| 573 | h, view, err := a.openDeck(ctx, *d) |
| 574 | if err != nil { |
| 575 | return nil, nil, err |
| 576 | } |
| 577 | ops, err := build(view) |
| 578 | if err != nil { |
| 579 | h.Close(ctx) |
| 580 | return nil, nil, err |
| 581 | } |
| 582 | minted, err := mintOpIDs(ops, view) |
| 583 | if err != nil { |
| 584 | h.Close(ctx) |
| 585 | return nil, nil, err |
| 586 | } |
| 587 | if attempt == 0 { |
| 588 | ids = minted |
| 589 | } |
| 590 | encoded, err := json.Marshal(ops) |
| 591 | if err != nil { |
| 592 | h.Close(ctx) |
| 593 | return nil, nil, fmt.Errorf("slides: encode ops: %w", err) |
| 594 | } |
| 595 | after, err := a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops), g) |
| 596 | h.Close(ctx) |
| 597 | if err == nil { |
| 598 | return ids, after, nil |
| 599 | } |
| 600 | lastErr = err |
| 601 | if !errors.Is(err, errDeckBusy) { |
| 602 | return nil, nil, err |
| 603 | } |
| 604 | // Our copy's Seq is what just lost; re-read it before retrying. |
| 605 | if err := a.db.G.WithContext(ctx).First(d, d.ID).Error; err != nil { |
| 606 | return nil, nil, fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| 607 | } |
| 608 | } |
| 609 | return nil, nil, lastErr |
| 610 | } |
| 611 | |
| 612 | // metaRowUpdates is the decks row's share of a batch: the title and |
| 613 | // theme columns a list, a link and the settings form read, which live |
| 614 | // in the row as well as in the document's meta. |
| 615 | // |
| 616 | // It reads the batch rather than the view the batch produces, and that |
| 617 | // is the point: the row write has to be IN applyOps' one transaction |
| 618 | // with the update-log insert (saveDeckSettings' own rule — the row and |
| 619 | // the document commit or roll back together), and the view only exists |
| 620 | // after the commit, because reading it is a round trip into the wasm |
| 621 | // module that would hold SQLite's single writer for its whole |
| 622 | // duration. set_meta is the only operation that touches meta, so |
| 623 | // walking the batch answers exactly what the view would: last write in |
| 624 | // the batch wins, a key the batch left out is a column left alone. |
| 625 | // |
| 626 | // The theme is folded in only when it is one of the app's six. The |
| 627 | // core takes any string there, so an agent can put something else in |
| 628 | // the document's meta; the row is what themes a render and what the |
| 629 | // settings form offers, and a value that is not in that set has no |
| 630 | // business in it. Nil when the batch changes no meta at all, which is |
| 631 | // the vast majority of them. |
| 632 | func metaRowUpdates(ops []map[string]json.RawMessage) map[string]any { |
| 633 | var out map[string]any |
| 634 | set := func(column string, value any) { |
| 635 | if out == nil { |
| 636 | out = map[string]any{} |
| 637 | } |
| 638 | out[column] = value |
| 639 | } |
| 640 | for _, op := range ops { |
| 641 | if rawString(op, "op") != "set_meta" { |
| 642 | continue |
| 643 | } |
| 644 | if _, has := op["title"]; has { |
| 645 | set("title", rawString(op, "title")) |
| 646 | } |
| 647 | if _, has := op["theme"]; has { |
| 648 | if theme := rawString(op, "theme"); validTheme(theme) { |
| 649 | set("theme", theme) |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | return out |
| 654 | } |
| 655 | |
| 656 | // mintOpIDs fills in the ids the core requires and the caller left |
| 657 | // out, in place, and returns them keyed by the operation's index as a |
| 658 | // string — a JSON object's keys are strings, and "3" is the third |
| 659 | // operation the caller sent. |
| 660 | // |
| 661 | // It keeps a running count of each slide's blocks, starting from the |
| 662 | // document and updated as it walks the batch, because duplicate_slide |
| 663 | // needs exactly as many new block ids as the slide it copies has — |
| 664 | // including blocks an earlier operation in the same batch added. |
| 665 | // |
| 666 | // It validates nothing else. Every vocabulary, every reference and |
| 667 | // every required field is the core's to check (core/src/ops.rs), and a |
| 668 | // second opinion here would be a copy to keep in step for no checking |
| 669 | // that is not already done. |
| 670 | func mintOpIDs(ops []map[string]json.RawMessage, view *deck.Deck) (map[string]string, error) { |
| 671 | blocks := map[string]int{} |
| 672 | for _, s := range view.Slides { |
| 673 | blocks[s.ID] = len(s.Blocks) |
| 674 | } |
| 675 | |
| 676 | ids := map[string]string{} |
| 677 | for i, op := range ops { |
| 678 | name := rawString(op, "op") |
| 679 | switch name { |
| 680 | case "add_slide": |
| 681 | id, err := existingOrNew(op, "id", ids, i) |
| 682 | if err != nil { |
| 683 | return nil, err |
| 684 | } |
| 685 | blocks[id] = 0 |
| 686 | case "add_block": |
| 687 | if _, err := existingOrNew(op, "id", ids, i); err != nil { |
| 688 | return nil, err |
| 689 | } |
| 690 | blocks[rawString(op, "slide")]++ |
| 691 | case "add_scene": |
| 692 | if _, err := existingOrNew(op, "id", ids, i); err != nil { |
| 693 | return nil, err |
| 694 | } |
| 695 | case "remove_block": |
| 696 | if slide := rawString(op, "slide"); blocks[slide] > 0 { |
| 697 | blocks[slide]-- |
| 698 | } |
| 699 | case "remove_slide": |
| 700 | delete(blocks, rawString(op, "id")) |
| 701 | case "duplicate_slide": |
| 702 | source := rawString(op, "id") |
| 703 | copyID, err := existingOrNew(op, "new_id", ids, i) |
| 704 | if err != nil { |
| 705 | return nil, err |
| 706 | } |
| 707 | n := blocks[source] |
| 708 | if _, has := op["new_block_ids"]; !has { |
| 709 | list := make([]string, 0, n) |
| 710 | for range n { |
| 711 | id, err := newID() |
| 712 | if err != nil { |
| 713 | return nil, err |
| 714 | } |
| 715 | list = append(list, id) |
| 716 | } |
| 717 | encoded, err := json.Marshal(list) |
| 718 | if err != nil { |
| 719 | return nil, fmt.Errorf("slides: encode new_block_ids: %w", err) |
| 720 | } |
| 721 | op["new_block_ids"] = encoded |
| 722 | } |
| 723 | blocks[copyID] = n |
| 724 | } |
| 725 | } |
| 726 | return ids, nil |
| 727 | } |
| 728 | |
| 729 | // existingOrNew returns the id at key, minting and recording one when |
| 730 | // the caller left it out. |
| 731 | func existingOrNew(op map[string]json.RawMessage, key string, ids map[string]string, index int) (string, error) { |
| 732 | if raw, has := op[key]; has { |
| 733 | var id string |
| 734 | if err := json.Unmarshal(raw, &id); err == nil && id != "" { |
| 735 | return id, nil |
| 736 | } |
| 737 | // A key that is there but is not a usable id is left alone for |
| 738 | // the core to refuse by name — overwriting it would silently |
| 739 | // turn a caller's mistake into a slide it never asked for. |
| 740 | return "", nil |
| 741 | } |
| 742 | id, err := newID() |
| 743 | if err != nil { |
| 744 | return "", err |
| 745 | } |
| 746 | encoded, err := json.Marshal(id) |
| 747 | if err != nil { |
| 748 | return "", fmt.Errorf("slides: encode a minted id: %w", err) |
| 749 | } |
| 750 | op[key] = encoded |
| 751 | ids[strconv.Itoa(index)] = id |
| 752 | return id, nil |
| 753 | } |
| 754 | |
| 755 | // rawString reads a JSON string out of an op, answering "" for a key |
| 756 | // that is absent or is not a string. The core is what refuses either; |
| 757 | // this only needs enough of the op to know what to mint. |
| 758 | func rawString(op map[string]json.RawMessage, key string) string { |
| 759 | raw, ok := op[key] |
| 760 | if !ok { |
| 761 | return "" |
| 762 | } |
| 763 | var s string |
| 764 | if err := json.Unmarshal(raw, &s); err != nil { |
| 765 | return "" |
| 766 | } |
| 767 | return s |
| 768 | } |
| 769 | |
| 770 | // --- GET /api/v1/decks/{sqid}/slides/{id}.html --- |
| 771 | |
| 772 | // apiSlide renders one slide as the section the viewer would show it |
| 773 | // in — spec §7.2's "so an agent can look at what it made", standing in |
| 774 | // for the SVG thumbnail until slice 3 has one. |
| 775 | // |
| 776 | // text/html rather than JSON, and the section alone rather than a |
| 777 | // page: it is markup to look at, paste into a report, or diff against |
| 778 | // the last one, and a whole document around it would be noise. |
| 779 | func (a *app) apiSlide(w http.ResponseWriter, r *http.Request) { |
| 780 | p, ok := a.apiPrincipal(w, r) |
| 781 | if !ok { |
| 782 | return |
| 783 | } |
| 784 | d, ok := a.apiDeckFor(w, r, p) |
| 785 | if !ok { |
| 786 | return |
| 787 | } |
| 788 | // The picture twin (thumbs.go). §7.2 asked for the HTML "standing |
| 789 | // in for the SVG thumbnail until slice 3 has one"; this is it, and |
| 790 | // the markup stays because an agent diffing what it made wants |
| 791 | // words rather than coordinates. |
| 792 | if strings.HasSuffix(chi.URLParam(r, "file"), ".svg") { |
| 793 | a.serveThumb(w, r, d, "/d/"+d.Sqid, func() { apiFail(w, http.StatusNotFound, errNotFound) }) |
| 794 | return |
| 795 | } |
| 796 | |
| 797 | slideID, ok := strings.CutSuffix(chi.URLParam(r, "file"), ".html") |
| 798 | if !ok || slideID == "" { |
| 799 | apiFail(w, http.StatusNotFound, errNotFound) |
| 800 | return |
| 801 | } |
| 802 | |
| 803 | h, view, err := a.openDeck(r.Context(), d) |
| 804 | if err != nil { |
| 805 | a.logger.Error("slides: open a deck to render a slide", "deck", d.Sqid, "err", err) |
| 806 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 807 | return |
| 808 | } |
| 809 | defer h.Close(r.Context()) |
| 810 | |
| 811 | index := -1 |
| 812 | for i, s := range view.Slides { |
| 813 | if s.ID == slideID { |
| 814 | index = i |
| 815 | break |
| 816 | } |
| 817 | } |
| 818 | if index < 0 { |
| 819 | apiFail(w, http.StatusNotFound, errNotFound) |
| 820 | return |
| 821 | } |
| 822 | |
| 823 | vp := slidehtml.Desktop |
| 824 | if r.URL.Query().Get("vp") == "phone" { |
| 825 | vp = slidehtml.Phone |
| 826 | } |
| 827 | // The signed-in surface's base. An agent reads this markup rather |
| 828 | // than rendering it, and pointing it somewhere that needs no |
| 829 | // session would be inventing a fourth capability for a caller that |
| 830 | // already has a bearer token for the deck. |
| 831 | section, err := slidehtml.SlideWith(view, index, vp, |
| 832 | slidehtml.Options{AssetBase: assetBaseFor("/d/" + d.Sqid), QRAlt: qrAlt(r), QR: a.followCodes(r.Context(), d, view, "/d/"+d.Sqid)}) |
| 833 | if err != nil { |
| 834 | a.logger.Error("slides: render a slide for the API", "deck", d.Sqid, "slide", slideID, "err", err) |
| 835 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 836 | return |
| 837 | } |
| 838 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 839 | w.Header().Set("ETag", strconv.Quote(strconv.FormatInt(d.Seq, 10)+"-"+slideID+"-"+vp.String())) |
| 840 | w.WriteHeader(http.StatusOK) |
| 841 | fmt.Fprint(w, section) |
| 842 | } |
| 843 | |
| 844 | // --- POST /api/v1/decks/{sqid}/present --- |
| 845 | |
| 846 | // apiPresent starts a talk, or picks up the one this agent already has |
| 847 | // open on this deck — startPresenting's behaviour (presentation.go) |
| 848 | // and startPresenting's row, reached by an agent rather than by a |
| 849 | // button. |
| 850 | // |
| 851 | // Reusing rather than starting a second session is what makes this |
| 852 | // safe to call again: a projector already showing /p/{session} keeps |
| 853 | // showing the same talk, and the agent gets a FRESH remote token, |
| 854 | // which is the one surprising thing here and is deliberate — only the |
| 855 | // hash is stored, so the old token cannot be handed back. |
| 856 | // |
| 857 | // All four addresses come back absolute, built on a.cfg.Origin rather |
| 858 | // than on the request's Host: an agent puts these in a chat message or |
| 859 | // on a projector, and the origin is what the app resolved at boot and |
| 860 | // refused to start without (config.go). |
| 861 | func (a *app) apiPresent(w http.ResponseWriter, r *http.Request) { |
| 862 | p, ok := a.apiPrincipal(w, r) |
| 863 | if !ok { |
| 864 | return |
| 865 | } |
| 866 | d, ok := a.apiDeckFor(w, r, p) |
| 867 | if !ok { |
| 868 | return |
| 869 | } |
| 870 | |
| 871 | token, err := newRemoteToken() |
| 872 | if err != nil { |
| 873 | a.logger.Error("slides: mint a remote token for the API", "err", err) |
| 874 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 875 | return |
| 876 | } |
| 877 | actor := p.actor() |
| 878 | g := a.deckGuard(r.Context(), p.operator, d) |
| 879 | |
| 880 | var live Presentation |
| 881 | err = a.livePresentations(r).Where("deck_id = ? AND actor = ?", d.ID, actor). |
| 882 | Order("started_at DESC").Take(&live).Error |
| 883 | switch { |
| 884 | case err == nil: |
| 885 | if err := a.guarded(r.Context(), g, func(db *gorm.DB) error { |
| 886 | return db.Model(&Presentation{}). |
| 887 | Where("id = ? AND ended_at IS NULL", live.ID). |
| 888 | Update("remote_token_hash", hashRemoteToken(token)).Error |
| 889 | }); err != nil { |
| 890 | if guardRefusedJSON(w, err) { |
| 891 | return |
| 892 | } |
| 893 | a.logger.Error("slides: re-pair a presentation for the API", "err", err) |
| 894 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 895 | return |
| 896 | } |
| 897 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 898 | live, err = a.createPresentation(r, d, actor, token, g) |
| 899 | if guardRefusedJSON(w, err) { |
| 900 | return |
| 901 | } |
| 902 | if err != nil { |
| 903 | a.logger.Error("slides: start a presentation for the API", "err", err) |
| 904 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 905 | return |
| 906 | } |
| 907 | default: |
| 908 | a.logger.Error("slides: look for a live presentation for the API", "err", err) |
| 909 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 910 | return |
| 911 | } |
| 912 | |
| 913 | a.writeJSON(w, http.StatusOK, map[string]any{ |
| 914 | "session": live.Sqid, |
| 915 | // The projector's address: a viewing capability, safe to put on |
| 916 | // a screen in front of a room. |
| 917 | "present_url": a.cfg.Origin + "/p/" + live.Sqid, |
| 918 | // The presenter's own view, and the remote — both carry the |
| 919 | // driving capability, so both are secrets. |
| 920 | "notes_url": a.cfg.Origin + "/p/" + live.Sqid + "/notes?t=" + token, |
| 921 | "remote_url": a.cfg.Origin + "/r/" + live.Code + "?t=" + token, |
| 922 | "code": live.Code, |
| 923 | }) |
| 924 | } |
| 925 | |