| 1 | // scenestills.go is how an agent gives a scene its stills and its code |
| 2 | // (scenes and clips spec §4, §8 calls 4 and 5), over the bearer API. |
| 3 | // |
| 4 | // PUT /api/v1/decks/{sqid}/scenes/{id}/stills/{state}?made=<version> |
| 5 | // PUT /api/v1/decks/{sqid}/scenes/{id}/code |
| 6 | // POST /api/v1/decks/{sqid}/scene-bundles |
| 7 | // |
| 8 | // The body is the file itself, not JSON and not a signed upload: an |
| 9 | // agent has no browser to PUT to a bucket. Each is judged as the upload |
| 10 | // flow judges the same bytes (a still as assets.go judges a picture, a |
| 11 | // bundle as scenes.go does), stored under its own hash, recorded as |
| 12 | // verified for this deck, and, for the first two, written into the |
| 13 | // document through the ops path as the agent, so live editors see it and |
| 14 | // it has a seq, an actor and an undo step like any other change. |
| 15 | // |
| 16 | // A still carries `made`, the scene's version when the picture was |
| 17 | // drawn, and is refused with 409 stale when the scene has moved on: |
| 18 | // a picture of code the scene no longer runs is not one to file as its |
| 19 | // own. The check and the write are two reads of the deck apart, so a |
| 20 | // hand edit landing between them can still leave a still marked as made |
| 21 | // from a version that has just passed; it then shows as out of date, |
| 22 | // which is the truth, and the next upload replaces it. |
| 23 | package slides |
| 24 | |
| 25 | import ( |
| 26 | "bytes" |
| 27 | "context" |
| 28 | "encoding/json" |
| 29 | "errors" |
| 30 | "image" |
| 31 | "io" |
| 32 | "net/http" |
| 33 | "time" |
| 34 | |
| 35 | "github.com/go-chi/chi/v5" |
| 36 | "gorm.io/gorm" |
| 37 | "gorm.io/gorm/clause" |
| 38 | |
| 39 | "amadan.net/oficina/slides/internal/slides/deck" |
| 40 | "amadan.net/rastrillo/rastrillo/blobs" |
| 41 | ) |
| 42 | |
| 43 | // maxStillBytes is the most a scene's still may be: a scene's pictures |
| 44 | // are drawn at presentation size, and a deck of them should stay small. |
| 45 | const maxStillBytes = 4 << 20 |
| 46 | |
| 47 | // apiSceneFailures is the developer's sentence for each code the three |
| 48 | // routes answer, with the 404 and 503 the rest of the API says in one |
| 49 | // word. |
| 50 | var apiSceneFailures = map[string]string{ |
| 51 | "stale": "made is not the scene's current version: the scene's code, data or words changed since the still was drawn. Read the deck, draw again, and send the new version.", |
| 52 | "too_large": "A still may be at most 4 MiB, and a scene's code at most 2 MiB.", |
| 53 | "not_an_image": "A still is a PNG or a WebP that decodes, at most 30000 pixels either way.", |
| 54 | "not_html": "A scene's code must be one UTF-8 HTML document opening with <!doctype html> or <html>.", |
| 55 | "no_store": "This instance has no object store to keep files in.", |
| 56 | } |
| 57 | |
| 58 | // apiSceneFail answers a refusal with its code and, where there is one, |
| 59 | // its sentence. |
| 60 | func apiSceneFail(w http.ResponseWriter, status int, code string) { |
| 61 | body := map[string]string{"error": code} |
| 62 | if m := apiSceneFailures[code]; m != "" { |
| 63 | body["message"] = m |
| 64 | } |
| 65 | b, _ := json.Marshal(body) |
| 66 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 67 | w.WriteHeader(status) |
| 68 | w.Write(append(b, '\n')) |
| 69 | } |
| 70 | |
| 71 | // readLimited reads a request body of at most limit bytes, answering |
| 72 | // 413 itself when it is more. |
| 73 | func readLimited(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, bool) { |
| 74 | raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, limit)) |
| 75 | if err != nil { |
| 76 | var tooBig *http.MaxBytesError |
| 77 | if errors.As(err, &tooBig) { |
| 78 | apiSceneFail(w, http.StatusRequestEntityTooLarge, "too_large") |
| 79 | } else { |
| 80 | apiFail(w, http.StatusBadRequest, errInvalid) |
| 81 | } |
| 82 | return nil, false |
| 83 | } |
| 84 | return raw, true |
| 85 | } |
| 86 | |
| 87 | // keepScene stores a scene's bundle under its own hash and records it |
| 88 | // as one of this deck's: what registering an upload does with bytes it |
| 89 | // has judged (registerScene). |
| 90 | func (a *app) keepScene(ctx context.Context, u User, d Deck, store blobs.Store, raw []byte) (string, error) { |
| 91 | stored, err := store.Put(ctx, bytes.NewReader(raw), sceneType) |
| 92 | if err != nil { |
| 93 | return "", err |
| 94 | } |
| 95 | err = a.guarded(ctx, a.deckGuard(ctx, u, d), func(db *gorm.DB) error { |
| 96 | return db.Clauses(clause.OnConflict{DoNothing: true}). |
| 97 | Create(&SceneBundle{DeckID: d.ID, Ref: stored.Hash, CreatedAt: time.Now().UTC()}).Error |
| 98 | }) |
| 99 | return stored.Hash, err |
| 100 | } |
| 101 | |
| 102 | // sceneForAPI is the deck and the scene a request names, as the |
| 103 | // operator may read them; it answers 404 itself for either that is not |
| 104 | // there, or 503 with no store to keep files in. |
| 105 | func (a *app) sceneForAPI(w http.ResponseWriter, r *http.Request, needScene bool) (p principal, d Deck, scene deck.Scene, id string, ok bool) { |
| 106 | p, ok = a.apiPrincipal(w, r) |
| 107 | if !ok { |
| 108 | return |
| 109 | } |
| 110 | if d, ok = a.apiDeckFor(w, r, p); !ok { |
| 111 | return |
| 112 | } |
| 113 | if a.cfg.Blobs == nil { |
| 114 | apiSceneFail(w, http.StatusServiceUnavailable, "no_store") |
| 115 | ok = false |
| 116 | return |
| 117 | } |
| 118 | if !needScene { |
| 119 | return |
| 120 | } |
| 121 | id = chi.URLParam(r, "id") |
| 122 | h, view, err := a.openDeck(r.Context(), d) |
| 123 | if err != nil { |
| 124 | a.logger.Error("slides: open a deck for a scene's file", "deck", d.Sqid, "err", err) |
| 125 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 126 | ok = false |
| 127 | return |
| 128 | } |
| 129 | h.Close(r.Context()) |
| 130 | if scene, ok = view.Scenes[id]; !ok { |
| 131 | apiFail(w, http.StatusNotFound, errNotFound) |
| 132 | } |
| 133 | return |
| 134 | } |
| 135 | |
| 136 | // sceneOp is one op of a batch, from the values it carries. |
| 137 | func sceneOp(fields map[string]any) map[string]json.RawMessage { |
| 138 | op := make(map[string]json.RawMessage, len(fields)) |
| 139 | for k, v := range fields { |
| 140 | op[k], _ = json.Marshal(v) |
| 141 | } |
| 142 | return op |
| 143 | } |
| 144 | |
| 145 | // apiPutStill serves PUT /api/v1/decks/{sqid}/scenes/{id}/stills/{state}. |
| 146 | func (a *app) apiPutStill(w http.ResponseWriter, r *http.Request) { |
| 147 | p, d, scene, id, ok := a.sceneForAPI(w, r, true) |
| 148 | if !ok { |
| 149 | return |
| 150 | } |
| 151 | state := chi.URLParam(r, "state") |
| 152 | known := false |
| 153 | for _, s := range scene.States { |
| 154 | known = known || s.ID == state |
| 155 | } |
| 156 | if !known { |
| 157 | apiFail(w, http.StatusNotFound, errNotFound) |
| 158 | return |
| 159 | } |
| 160 | made := r.URL.Query().Get("made") |
| 161 | version := deck.SceneVersion(scene) |
| 162 | if made != version { |
| 163 | apiSceneFail(w, http.StatusConflict, "stale") |
| 164 | return |
| 165 | } |
| 166 | |
| 167 | raw, ok := readLimited(w, r, maxStillBytes) |
| 168 | if !ok { |
| 169 | return |
| 170 | } |
| 171 | // Judged as an agent's picture is (agent_assets.go): by its bytes, a |
| 172 | // type of the two a still is drawn as, and a header that reads as a |
| 173 | // size a picture may be: 30000 pixels either way and maxImagePixels |
| 174 | // (svg.MaxDecodePixels, 50 megapixels) together, the budget every |
| 175 | // decode of it (thumbnail, export) is held to. The size is what the |
| 176 | // image says it is, which is the only size there is for an agent to |
| 177 | // be held to. |
| 178 | kind := sniffImage(raw) |
| 179 | cfg, _, err := image.DecodeConfig(bytes.NewReader(raw)) |
| 180 | if (kind != "image/png" && kind != "image/webp") || err != nil || |
| 181 | cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxAssetDimension || cfg.Height > maxAssetDimension || |
| 182 | cfg.Width*cfg.Height > maxImagePixels { |
| 183 | apiSceneFail(w, http.StatusUnprocessableEntity, "not_an_image") |
| 184 | return |
| 185 | } |
| 186 | stored, err := a.cfg.Blobs.Put(r.Context(), bytes.NewReader(raw), kind) |
| 187 | if err != nil { |
| 188 | a.logger.Error("slides: keep a still", "deck", d.Sqid, "err", err) |
| 189 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 190 | return |
| 191 | } |
| 192 | ref := stored.Hash |
| 193 | if err := a.guarded(r.Context(), a.deckGuard(r.Context(), p.operator, d), func(db *gorm.DB) error { |
| 194 | return db.Clauses(clause.OnConflict{DoNothing: true}). |
| 195 | Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| 196 | }); err != nil { |
| 197 | if guardRefusedJSON(w, err) { |
| 198 | return |
| 199 | } |
| 200 | a.logger.Error("slides: record a verified still", "deck", d.Sqid, "err", err) |
| 201 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 202 | return |
| 203 | } |
| 204 | |
| 205 | // The deck serves a picture only once its assets map names the ref, |
| 206 | // so the same batch registers it, unless it already does. The |
| 207 | // version is checked again here, against the document the write is |
| 208 | // made on (applyAgentOpsFrom), because a hand edit or a newer still |
| 209 | // can land between the early check above and this write. |
| 210 | assetID, err := newID() |
| 211 | if err != nil { |
| 212 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 213 | return |
| 214 | } |
| 215 | build := func(view *deck.Deck) ([]map[string]json.RawMessage, error) { |
| 216 | now, ok := view.Scenes[id] |
| 217 | if !ok { |
| 218 | return nil, errSceneGone |
| 219 | } |
| 220 | if deck.SceneVersion(now) != version { |
| 221 | return nil, errStillStale |
| 222 | } |
| 223 | if BeforeSceneWrite != nil { |
| 224 | BeforeSceneWrite() |
| 225 | } |
| 226 | var ops []map[string]json.RawMessage |
| 227 | registered := false |
| 228 | for _, asset := range view.Assets { |
| 229 | registered = registered || asset.Ref == ref |
| 230 | } |
| 231 | if !registered { |
| 232 | alt := now.Name |
| 233 | for _, s := range now.States { |
| 234 | if s.ID == state { |
| 235 | switch { |
| 236 | case s.Description != "": |
| 237 | alt = s.Description |
| 238 | case s.Name != "": |
| 239 | alt = s.Name |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | ops = append(ops, sceneOp(map[string]any{ |
| 244 | "op": "register_asset", "id": assetID, "ref": ref, "name": state + ".png", |
| 245 | "width": cfg.Width, "height": cfg.Height, "alt": trimTo(alt, maxAssetAlt), |
| 246 | })) |
| 247 | } |
| 248 | return append(ops, sceneOp(map[string]any{ |
| 249 | "op": "set_scene", "id": id, |
| 250 | "stills": map[string]any{state: map[string]string{"ref": ref, "made": version}}, |
| 251 | })), nil |
| 252 | } |
| 253 | if _, _, err := a.applyAgentOpsFrom(r.Context(), &d, p.actor(), build, a.deckGuard(r.Context(), p.operator, d)); err != nil { |
| 254 | a.sceneWriteFailed(w, d, err) |
| 255 | return |
| 256 | } |
| 257 | a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "made": version}) |
| 258 | } |
| 259 | |
| 260 | var ( |
| 261 | errStillStale = errors.New("slides: the scene moved on before the still was written") |
| 262 | errSceneGone = errors.New("slides: the scene is gone") |
| 263 | ) |
| 264 | |
| 265 | // BeforeSceneWrite is a test seam: called when a still's write has been |
| 266 | // checked against the document it will land on and before it is made, |
| 267 | // so a test can land another edit in between. Nil in production. |
| 268 | var BeforeSceneWrite func() |
| 269 | |
| 270 | // sceneWriteFailed answers a scene write refused: stale, gone, or any |
| 271 | // batch refusal. |
| 272 | func (a *app) sceneWriteFailed(w http.ResponseWriter, d Deck, err error) { |
| 273 | switch { |
| 274 | case errors.Is(err, errStillStale): |
| 275 | apiSceneFail(w, http.StatusConflict, "stale") |
| 276 | case errors.Is(err, errSceneGone): |
| 277 | apiFail(w, http.StatusNotFound, errNotFound) |
| 278 | default: |
| 279 | a.apiOpsFailed(w, d, err) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | // apiPutSceneCode serves PUT /api/v1/decks/{sqid}/scenes/{id}/code. |
| 284 | func (a *app) apiPutSceneCode(w http.ResponseWriter, r *http.Request) { |
| 285 | p, d, _, id, ok := a.sceneForAPI(w, r, true) |
| 286 | if !ok { |
| 287 | return |
| 288 | } |
| 289 | ref, ok := a.apiKeepBundle(w, r, p, d) |
| 290 | if !ok { |
| 291 | return |
| 292 | } |
| 293 | build := func(view *deck.Deck) ([]map[string]json.RawMessage, error) { |
| 294 | if _, ok := view.Scenes[id]; !ok { |
| 295 | return nil, errSceneGone |
| 296 | } |
| 297 | if BeforeSceneWrite != nil { |
| 298 | BeforeSceneWrite() |
| 299 | } |
| 300 | return []map[string]json.RawMessage{sceneOp(map[string]any{"op": "set_scene", "id": id, "code": ref})}, nil |
| 301 | } |
| 302 | _, after, err := a.applyAgentOpsFrom(r.Context(), &d, p.actor(), build, a.deckGuard(r.Context(), p.operator, d)) |
| 303 | if err != nil { |
| 304 | a.sceneWriteFailed(w, d, err) |
| 305 | return |
| 306 | } |
| 307 | // The version of the scene as the write left it, with whatever |
| 308 | // edits landed while the bundle was uploading. |
| 309 | a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "version": deck.SceneVersion(after.Scenes[id])}) |
| 310 | } |
| 311 | |
| 312 | // apiPostSceneBundle serves POST /api/v1/decks/{sqid}/scene-bundles: a |
| 313 | // bundle registered for the deck before any scene names it, for an |
| 314 | // add_scene to use. |
| 315 | func (a *app) apiPostSceneBundle(w http.ResponseWriter, r *http.Request) { |
| 316 | p, d, _, _, ok := a.sceneForAPI(w, r, false) |
| 317 | if !ok { |
| 318 | return |
| 319 | } |
| 320 | ref, ok := a.apiKeepBundle(w, r, p, d) |
| 321 | if !ok { |
| 322 | return |
| 323 | } |
| 324 | a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref}) |
| 325 | } |
| 326 | |
| 327 | // apiKeepBundle reads the body as a scene's code, refuses what registerScene |
| 328 | // would, and keeps it for the deck. |
| 329 | func (a *app) apiKeepBundle(w http.ResponseWriter, r *http.Request, p principal, d Deck) (string, bool) { |
| 330 | raw, ok := readLimited(w, r, maxSceneBytes) |
| 331 | if !ok { |
| 332 | return "", false |
| 333 | } |
| 334 | if !sniffScene(raw) { |
| 335 | apiSceneFail(w, http.StatusUnprocessableEntity, "not_html") |
| 336 | return "", false |
| 337 | } |
| 338 | ref, err := a.keepScene(r.Context(), p.operator, d, a.cfg.Blobs, raw) |
| 339 | if err != nil { |
| 340 | if guardRefusedJSON(w, err) { |
| 341 | return "", false |
| 342 | } |
| 343 | a.logger.Error("slides: keep a scene's code", "deck", d.Sqid, "err", err) |
| 344 | apiFail(w, http.StatusInternalServerError, errInternal) |
| 345 | return "", false |
| 346 | } |
| 347 | return ref, true |
| 348 | } |
| 349 | |