Slides: agents upload scene stills and code; stillsCurrent marks stale ones
PUT .../scenes/{id}/stills/{state}?made=<version> takes a PNG or WebP
(4 MiB), refuses a stale made with 409, registers the picture for the deck
and applies set_scene{stills} as the agent. PUT .../scenes/{id}/code and
POST .../scene-bundles take one HTML document (2 MiB), checked as bundle
registration does. stillsCurrent(scene) in fixtures/scenes.mjs answers
{current, missing, stale} for the editor's note.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
8 files changed,
+725
−18
docs/api.md+39 −0fixtures/scene-version.mjs+20 −0fixtures/scenes.mjs+1 −1fixtures/scenes.test.mjs+34 −1internal/slides/api.go+14 −2internal/slides/scenes.go+3 −14internal/slides/scenestills.go+302 −0internal/slidestest/scenes_agent_test.go+312 −0
diff --git a/docs/api.md b/docs/api.md| index 5ebb644..d862d5e 100644 |
| --- a/docs/api.md |
| +++ b/docs/api.md |
| @@ -649,6 +649,45 @@ blocks that name it as they are. |
| -d '{"ops":[{"op":"remove_scene","id":"'"$C"'"}]}' |
| ``` |
| +### Stills and code from an agent |
| + |
| +These three take the file as the request body, not JSON, and the same |
| +bearer as the rest. Each registers the file for the deck and applies the |
| +matching op as you, so editors with the deck open see it at once. Without |
| +an object store, each answers `503 no_store`. |
| + |
| +**`POST /api/v1/decks/{sqid}/scene-bundles`** — a scene's first bundle, |
| +before the scene exists. The body is one HTML document, 2 MiB at most, |
| +opening with `<!doctype html>` or `<html>`. Answers `{"ref": "…"}`, which |
| +an `add_scene` then names as its `code`. |
| + |
| +**`PUT /api/v1/decks/{sqid}/scenes/{id}/code`** — new code for a scene. |
| +Same body and same checks, then `set_scene` with the ref (the server sets |
| +`author`). Answers `{"ref": "…", "version": "…"}`, the scene's version |
| +now. Stills made before it are out of date. |
| + |
| +**`PUT /api/v1/decks/{sqid}/scenes/{id}/stills/{state}?made=<version>`** — |
| +a state's still. The body is a PNG or a WebP, 4 MiB at most, that decodes |
| +and is no more than 30000 pixels either way. `made` must be the scene's |
| +current version, which you work out as above, or the answer is |
| +`409 stale` and nothing changes. On success the picture is registered as |
| +an asset of the deck and set on the scene with `set_scene`, and the answer |
| +is `{"ref": "…", "made": "…"}`. |
| + |
| +```sh |
| +curl -X PUT -H "Authorization: Bearer $SLIDES_TOKEN" \ |
| + --data-binary @city.png \ |
| + "https://slides.example/api/v1/decks/k7m2xq9dwb/scenes/$C/stills/city?made=$VERSION" |
| +``` |
| + |
| +Refusals are `{"error": "…", "message": "…"}`: `not_found` (no such |
| +deck, scene or state, or not yours; 404), `stale` (409), `too_large` |
| +(413), `not_an_image` and `not_html` (422). |
| + |
| +The editor tells a scene's stills are out of date the same way: a state |
| +with no still is missing, and one whose `made` is not the scene's version |
| +is stale. |
| + |
| --- |
| ## Getting the bytes there |
diff --git a/fixtures/scene-version.mjs b/fixtures/scene-version.mjs| index fb11b15..d70f64c 100644 |
| --- a/fixtures/scene-version.mjs |
| +++ b/fixtures/scene-version.mjs |
| @@ -51,3 +51,23 @@ export const utf8 = s => new TextEncoder().encode(s) |
| export function sceneVersion (scene) { |
| return Array.from(digest(utf8(sceneCanonical(scene))), b => b.toString(16).padStart(2, '0')).join('') |
| } |
| + |
| +/** |
| + * Whether a scene's stills are up to date: `missing` is the states with no still, `stale` those whose still was |
| + * made from another version of the scene than the one it has now, and `current` is neither. A still for a state |
| + * the scene no longer has is not counted. |
| + */ |
| +export function stillsCurrent (scene) { |
| + const s = scene || {} |
| + const states = Array.isArray(s.states) ? s.states : [] |
| + const stills = isObject(s.stills) ? s.stills : {} |
| + const version = sceneVersion(s) |
| + const missing = [] |
| + const stale = [] |
| + for (const state of states) { |
| + const still = isObject(state) ? stills[state.id] : undefined |
| + if (!isObject(still) || typeof still.ref !== 'string') missing.push(state.id) |
| + else if (still.made !== version) stale.push(state.id) |
| + } |
| + return { current: missing.length === 0 && stale.length === 0, missing, stale } |
| +} |
diff --git a/fixtures/scenes.mjs b/fixtures/scenes.mjs| index 967344e..bfa68aa 100644 |
| --- a/fixtures/scenes.mjs |
| +++ b/fixtures/scenes.mjs |
| @@ -14,7 +14,7 @@ import * as Y from 'yjs' |
| import { outToJSON, anyToJSON, put } from './ydoc.mjs' |
| import { canonicalJSON, utf8 } from './scene-version.mjs' |
| -export { canonicalJSON, sceneCanonical, sceneVersion } from './scene-version.mjs' |
| +export { canonicalJSON, sceneCanonical, sceneVersion, stillsCurrent } from './scene-version.mjs' |
| // 960 KiB, so a set_scene carrying it always fits one live update (1 MiB). |
| export const MAX_SCENE_DATA = 960 * 1024 |
diff --git a/fixtures/scenes.test.mjs b/fixtures/scenes.test.mjs| index 7f991cd..9c63654 100644 |
| --- a/fixtures/scenes.test.mjs |
| +++ b/fixtures/scenes.test.mjs |
| @@ -8,7 +8,7 @@ import assert from 'node:assert/strict' |
| import { readFileSync } from 'node:fs' |
| import * as Y from 'yjs' |
| import { applyOps, view, OpsError } from './ops.mjs' |
| -import { sceneCanonical, sceneVersion } from './scenes.mjs' |
| +import { sceneCanonical, sceneVersion, stillsCurrent } from './scenes.mjs' |
| const CODE = '0123456789abcdef'.repeat(4) |
| const CODE2 = 'fedcba9876543210'.repeat(4) |
| @@ -307,3 +307,36 @@ test('__proto__ is refused as a state id, a word key and anywhere in data', () = |
| op: 'set_scene', id: 'worldsceneaa', words: { k: '__proto__' }, data: ['__proto__', { v: '__proto__' }], states: [{ id: 'a', name: '__proto__', description: '__proto__' }] |
| }]) |
| }) |
| + |
| +test('stillsCurrent: missing, stale and current', () => { |
| + const doc = deck() |
| + const states = ['a', 'b', 'c'] |
| + let r = stillsCurrent(view(doc).scenes.worldsceneaa) |
| + assert.deepEqual(r, { current: false, missing: states, stale: [] }) |
| + |
| + const made = sceneVersion(view(doc).scenes.worldsceneaa) |
| + const stills = Object.fromEntries(states.map(s => [s, { ref: STILL, made }])) |
| + applyOps(doc, [{ op: 'set_scene', id: 'worldsceneaa', stills }]) |
| + assert.deepEqual(stillsCurrent(view(doc).scenes.worldsceneaa), { current: true, missing: [], stale: [] }) |
| + |
| + // A hand edit of the words, the data or the code makes every still stale. |
| + applyOps(doc, [{ op: 'set_scene', id: 'worldsceneaa', words: { title: 'Wien' } }]) |
| + assert.deepEqual(stillsCurrent(view(doc).scenes.worldsceneaa), { current: false, missing: [], stale: states }) |
| + |
| + // A still made again is current again; a state added later is missing. |
| + const now = sceneVersion(view(doc).scenes.worldsceneaa) |
| + applyOps(doc, [{ op: 'set_scene', id: 'worldsceneaa', stills: { a: { ref: STILL, made: now } } }]) |
| + assert.deepEqual(stillsCurrent(view(doc).scenes.worldsceneaa), { current: false, missing: [], stale: ['b', 'c'] }) |
| + applyOps(doc, [{ op: 'set_scene', id: 'worldsceneaa', stills: { b: { ref: STILL, made: now }, c: { ref: STILL, made: now } } }]) |
| + assert.equal(stillsCurrent(view(doc).scenes.worldsceneaa).current, true) |
| + applyOps(doc, [{ op: 'set_scene', id: 'worldsceneaa', states: [{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }] }]) |
| + assert.deepEqual(stillsCurrent(view(doc).scenes.worldsceneaa), { current: false, missing: ['d'], stale: [] }) |
| + // A still for a state the scene no longer has is not counted. |
| + applyOps(doc, [{ op: 'set_scene', id: 'worldsceneaa', states: [{ id: 'a' }] }]) |
| + assert.equal(stillsCurrent(view(doc).scenes.worldsceneaa).current, true) |
| +}) |
| + |
| +test('stillsCurrent tolerates a scene with no states or stills', () => { |
| + assert.deepEqual(stillsCurrent({}), { current: true, missing: [], stale: [] }) |
| + assert.deepEqual(stillsCurrent(undefined), { current: true, missing: [], stale: [] }) |
| +}) |
diff --git a/internal/slides/api.go b/internal/slides/api.go| index 8e646e6..06fd1ee 100644 |
| --- a/internal/slides/api.go |
| +++ b/internal/slides/api.go |
| @@ -95,6 +95,10 @@ func (a *app) apiRouter() http.Handler { |
| r.Post(apiPrefix+"/decks", a.apiCreateDeck) |
| r.Get(apiPrefix+"/decks/{sqid}", a.apiGetDeck) |
| r.Post(apiPrefix+"/decks/{sqid}/ops", a.apiOps) |
| + // A scene's pictures and code (scenestills.go). |
| + r.Put(apiPrefix+"/decks/{sqid}/scenes/{id}/stills/{state}", a.apiPutStill) |
| + r.Put(apiPrefix+"/decks/{sqid}/scenes/{id}/code", a.apiPutSceneCode) |
| + r.Post(apiPrefix+"/decks/{sqid}/scene-bundles", a.apiPostSceneBundle) |
| // {file} rather than {id}.html: chi can match a static tail inside |
| // a segment, but the extension is part of what this endpoint means |
| // — it is the HTML rendering of a slide, and the .svg thumbnail of |
| @@ -501,9 +505,17 @@ func (a *app) apiOps(w http.ResponseWriter, r *http.Request) { |
| } |
| ids, err := a.applyAgentOps(r.Context(), &d, p.actor(), body.Ops, a.deckGuard(r.Context(), p.operator, d)) |
| + if err != nil { |
| + a.apiOpsFailed(w, d, err) |
| + return |
| + } |
| + a.writeJSON(w, http.StatusOK, map[string]any{"seq": d.Seq, "ids": ids}) |
| +} |
| + |
| +// apiOpsFailed answers a batch applyAgentOps refused, for every route |
| +// that applies one. |
| +func (a *app) apiOpsFailed(w http.ResponseWriter, d Deck, err error) { |
| switch { |
| - case err == nil: |
| - a.writeJSON(w, http.StatusOK, map[string]any{"seq": d.Seq, "ids": ids}) |
| case guardRefusedJSON(w, err): |
| case errors.Is(err, errDeckBusy): |
| // Two attempts have already been made; a third would be |
diff --git a/internal/slides/scenes.go b/internal/slides/scenes.go| index d8932eb..fe3b5cb 100644 |
| --- a/internal/slides/scenes.go |
| +++ b/internal/slides/scenes.go |
| @@ -40,12 +40,9 @@ import ( |
| "mime" |
| "net/http" |
| "strings" |
| - "time" |
| "unicode/utf8" |
| "github.com/go-chi/chi/v5" |
| - "gorm.io/gorm" |
| - "gorm.io/gorm/clause" |
| "amadan.net/oficina/slides/internal/slides/deck" |
| "amadan.net/rastrillo/rastrillo/blobs" |
| @@ -131,21 +128,13 @@ func (a *app) registerScene(w http.ResponseWriter, r *http.Request, u User, d De |
| sceneFail(w, http.StatusUnprocessableEntity, "not_html") |
| return |
| } |
| - stored, err := store.Put(r.Context(), bytes.NewReader(raw), sceneType) |
| + ref, err := a.keepScene(r.Context(), u, d, store, raw) |
| if err != nil { |
| - a.logger.Error("slides: promote a staged scene", "deck", d.Sqid, "err", err) |
| - sceneFail(w, http.StatusInternalServerError, "internal") |
| - return |
| - } |
| - ref := stored.Hash |
| - if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { |
| - return db.Clauses(clause.OnConflict{DoNothing: true}). |
| - Create(&SceneBundle{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| - }); err != nil { |
| if a.guardRefused(w, r, err) { |
| return |
| } |
| - a.fail(w, r, "record a verified scene", err) |
| + a.logger.Error("slides: keep an uploaded scene", "deck", d.Sqid, "err", err) |
| + sceneFail(w, http.StatusInternalServerError, "internal") |
| return |
| } |
| a.spendUpload(r, d, up, object, ref) |
diff --git a/internal/slides/scenestills.go b/internal/slides/scenestills.go| new file mode 100644 |
| index 0000000..75cf901 |
| --- /dev/null |
| +++ b/internal/slides/scenestills.go |
| @@ -0,0 +1,302 @@ |
| +// scenestills.go is how an agent gives a scene its stills and its code |
| +// (scenes and clips spec §4, §8 calls 4 and 5), over the bearer API. |
| +// |
| +// PUT /api/v1/decks/{sqid}/scenes/{id}/stills/{state}?made=<version> |
| +// PUT /api/v1/decks/{sqid}/scenes/{id}/code |
| +// POST /api/v1/decks/{sqid}/scene-bundles |
| +// |
| +// The body is the file itself, not JSON and not a signed upload: an |
| +// agent has no browser to PUT to a bucket. Each is judged as the upload |
| +// flow judges the same bytes (a still as assets.go judges a picture, a |
| +// bundle as scenes.go does), stored under its own hash, recorded as |
| +// verified for this deck, and, for the first two, written into the |
| +// document through the ops path as the agent, so live editors see it and |
| +// it has a seq, an actor and an undo step like any other change. |
| +// |
| +// A still carries `made`, the scene's version when the picture was |
| +// drawn, and is refused with 409 stale when the scene has moved on: |
| +// a picture of code the scene no longer runs is not one to file as its |
| +// own. The check and the write are two reads of the deck apart, so a |
| +// hand edit landing between them can still leave a still marked as made |
| +// from a version that has just passed; it then shows as out of date, |
| +// which is the truth, and the next upload replaces it. |
| +package slides |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "image" |
| + "io" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/go-chi/chi/v5" |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| + |
| + "amadan.net/oficina/slides/internal/slides/deck" |
| + "amadan.net/rastrillo/rastrillo/blobs" |
| +) |
| + |
| +// maxStillBytes is the most a scene's still may be: a scene's pictures |
| +// are drawn at presentation size, and a deck of them should stay small. |
| +const maxStillBytes = 4 << 20 |
| + |
| +// apiSceneFailures is the developer's sentence for each code the three |
| +// routes answer, with the 404 and 503 the rest of the API says in one |
| +// word. |
| +var apiSceneFailures = map[string]string{ |
| + "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.", |
| + "too_large": "A still may be at most 4 MiB, and a scene's code at most 2 MiB.", |
| + "not_an_image": "A still is a PNG or a WebP that decodes, at most 30000 pixels either way.", |
| + "not_html": "A scene's code must be one UTF-8 HTML document opening with <!doctype html> or <html>.", |
| + "no_store": "This instance has no object store to keep files in.", |
| +} |
| + |
| +// apiSceneFail answers a refusal with its code and, where there is one, |
| +// its sentence. |
| +func apiSceneFail(w http.ResponseWriter, status int, code string) { |
| + body := map[string]string{"error": code} |
| + if m := apiSceneFailures[code]; m != "" { |
| + body["message"] = m |
| + } |
| + b, _ := json.Marshal(body) |
| + w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| + w.WriteHeader(status) |
| + w.Write(append(b, '\n')) |
| +} |
| + |
| +// readLimited reads a request body of at most limit bytes, answering |
| +// 413 itself when it is more. |
| +func readLimited(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, bool) { |
| + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, limit)) |
| + if err != nil { |
| + var tooBig *http.MaxBytesError |
| + if errors.As(err, &tooBig) { |
| + apiSceneFail(w, http.StatusRequestEntityTooLarge, "too_large") |
| + } else { |
| + apiFail(w, http.StatusBadRequest, errInvalid) |
| + } |
| + return nil, false |
| + } |
| + return raw, true |
| +} |
| + |
| +// keepScene stores a scene's bundle under its own hash and records it |
| +// as one of this deck's: what registering an upload does with bytes it |
| +// has judged (registerScene). |
| +func (a *app) keepScene(ctx context.Context, u User, d Deck, store blobs.Store, raw []byte) (string, error) { |
| + stored, err := store.Put(ctx, bytes.NewReader(raw), sceneType) |
| + if err != nil { |
| + return "", err |
| + } |
| + err = a.guarded(ctx, a.deckGuard(ctx, u, d), func(db *gorm.DB) error { |
| + return db.Clauses(clause.OnConflict{DoNothing: true}). |
| + Create(&SceneBundle{DeckID: d.ID, Ref: stored.Hash, CreatedAt: time.Now().UTC()}).Error |
| + }) |
| + return stored.Hash, err |
| +} |
| + |
| +// sceneForAPI is the deck and the scene a request names, as the |
| +// operator may read them; it answers 404 itself for either that is not |
| +// there, or 503 with no store to keep files in. |
| +func (a *app) sceneForAPI(w http.ResponseWriter, r *http.Request, needScene bool) (p principal, d Deck, scene deck.Scene, id string, ok bool) { |
| + p, ok = a.apiPrincipal(w, r) |
| + if !ok { |
| + return |
| + } |
| + if d, ok = a.apiDeckFor(w, r, p); !ok { |
| + return |
| + } |
| + if a.cfg.Blobs == nil { |
| + apiSceneFail(w, http.StatusServiceUnavailable, "no_store") |
| + ok = false |
| + return |
| + } |
| + if !needScene { |
| + return |
| + } |
| + id = chi.URLParam(r, "id") |
| + h, view, err := a.openDeck(r.Context(), d) |
| + if err != nil { |
| + a.logger.Error("slides: open a deck for a scene's file", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + ok = false |
| + return |
| + } |
| + h.Close(r.Context()) |
| + if scene, ok = view.Scenes[id]; !ok { |
| + apiFail(w, http.StatusNotFound, errNotFound) |
| + } |
| + return |
| +} |
| + |
| +// sceneOp is one op of a batch, from the values it carries. |
| +func sceneOp(fields map[string]any) map[string]json.RawMessage { |
| + op := make(map[string]json.RawMessage, len(fields)) |
| + for k, v := range fields { |
| + op[k], _ = json.Marshal(v) |
| + } |
| + return op |
| +} |
| + |
| +// apiPutStill serves PUT /api/v1/decks/{sqid}/scenes/{id}/stills/{state}. |
| +func (a *app) apiPutStill(w http.ResponseWriter, r *http.Request) { |
| + p, d, scene, id, ok := a.sceneForAPI(w, r, true) |
| + if !ok { |
| + return |
| + } |
| + state := chi.URLParam(r, "state") |
| + known := false |
| + for _, s := range scene.States { |
| + known = known || s.ID == state |
| + } |
| + if !known { |
| + apiFail(w, http.StatusNotFound, errNotFound) |
| + return |
| + } |
| + made := r.URL.Query().Get("made") |
| + version := deck.SceneVersion(scene) |
| + if made != version { |
| + apiSceneFail(w, http.StatusConflict, "stale") |
| + return |
| + } |
| + |
| + raw, ok := readLimited(w, r, maxStillBytes) |
| + if !ok { |
| + return |
| + } |
| + // Judged as a picture is (registerAsset): by its bytes, and a type |
| + // of the two a still is drawn as. The size is what the image says it |
| + // is, which is the only size there is for an agent to be held to. |
| + kind := sniffImage(raw) |
| + cfg, _, err := image.DecodeConfig(bytes.NewReader(raw)) |
| + if (kind != "image/png" && kind != "image/webp") || err != nil || |
| + cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxAssetDimension || cfg.Height > maxAssetDimension { |
| + apiSceneFail(w, http.StatusUnprocessableEntity, "not_an_image") |
| + return |
| + } |
| + stored, err := a.cfg.Blobs.Put(r.Context(), bytes.NewReader(raw), kind) |
| + if err != nil { |
| + a.logger.Error("slides: keep a still", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + ref := stored.Hash |
| + if err := a.guarded(r.Context(), a.deckGuard(r.Context(), p.operator, d), func(db *gorm.DB) error { |
| + return db.Clauses(clause.OnConflict{DoNothing: true}). |
| + Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| + }); err != nil { |
| + if guardRefusedJSON(w, err) { |
| + return |
| + } |
| + a.logger.Error("slides: record a verified still", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + |
| + // The deck serves a picture only once its assets map names the ref, |
| + // so the same batch registers it, unless it already does. |
| + var ops []map[string]json.RawMessage |
| + h, view, err := a.openDeck(r.Context(), d) |
| + if err != nil { |
| + a.logger.Error("slides: open a deck for a still", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + h.Close(r.Context()) |
| + registered := false |
| + for _, asset := range view.Assets { |
| + registered = registered || asset.Ref == ref |
| + } |
| + if !registered { |
| + assetID, err := newID() |
| + if err != nil { |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return |
| + } |
| + alt := scene.Name |
| + for _, s := range scene.States { |
| + if s.ID == state { |
| + switch { |
| + case s.Description != "": |
| + alt = s.Description |
| + case s.Name != "": |
| + alt = s.Name |
| + } |
| + } |
| + } |
| + ops = append(ops, sceneOp(map[string]any{ |
| + "op": "register_asset", "id": assetID, "ref": ref, "name": state + ".png", |
| + "width": cfg.Width, "height": cfg.Height, "alt": trimTo(alt, maxAssetAlt), |
| + })) |
| + } |
| + ops = append(ops, sceneOp(map[string]any{ |
| + "op": "set_scene", "id": id, |
| + "stills": map[string]any{state: map[string]string{"ref": ref, "made": version}}, |
| + })) |
| + if _, err := a.applyAgentOps(r.Context(), &d, p.actor(), ops, a.deckGuard(r.Context(), p.operator, d)); err != nil { |
| + a.apiOpsFailed(w, d, err) |
| + return |
| + } |
| + a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "made": version}) |
| +} |
| + |
| +// apiPutSceneCode serves PUT /api/v1/decks/{sqid}/scenes/{id}/code. |
| +func (a *app) apiPutSceneCode(w http.ResponseWriter, r *http.Request) { |
| + p, d, scene, id, ok := a.sceneForAPI(w, r, true) |
| + if !ok { |
| + return |
| + } |
| + ref, ok := a.apiKeepBundle(w, r, p, d) |
| + if !ok { |
| + return |
| + } |
| + op := sceneOp(map[string]any{"op": "set_scene", "id": id, "code": ref}) |
| + if _, err := a.applyAgentOps(r.Context(), &d, p.actor(), []map[string]json.RawMessage{op}, a.deckGuard(r.Context(), p.operator, d)); err != nil { |
| + a.apiOpsFailed(w, d, err) |
| + return |
| + } |
| + scene.Code = ref |
| + a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "version": deck.SceneVersion(scene)}) |
| +} |
| + |
| +// apiPostSceneBundle serves POST /api/v1/decks/{sqid}/scene-bundles: a |
| +// bundle registered for the deck before any scene names it, for an |
| +// add_scene to use. |
| +func (a *app) apiPostSceneBundle(w http.ResponseWriter, r *http.Request) { |
| + p, d, _, _, ok := a.sceneForAPI(w, r, false) |
| + if !ok { |
| + return |
| + } |
| + ref, ok := a.apiKeepBundle(w, r, p, d) |
| + if !ok { |
| + return |
| + } |
| + a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref}) |
| +} |
| + |
| +// apiKeepBundle reads the body as a scene's code, refuses what registerScene |
| +// would, and keeps it for the deck. |
| +func (a *app) apiKeepBundle(w http.ResponseWriter, r *http.Request, p principal, d Deck) (string, bool) { |
| + raw, ok := readLimited(w, r, maxSceneBytes) |
| + if !ok { |
| + return "", false |
| + } |
| + if !sniffScene(raw) { |
| + apiSceneFail(w, http.StatusUnprocessableEntity, "not_html") |
| + return "", false |
| + } |
| + ref, err := a.keepScene(r.Context(), p.operator, d, a.cfg.Blobs, raw) |
| + if err != nil { |
| + if guardRefusedJSON(w, err) { |
| + return "", false |
| + } |
| + a.logger.Error("slides: keep a scene's code", "deck", d.Sqid, "err", err) |
| + apiFail(w, http.StatusInternalServerError, errInternal) |
| + return "", false |
| + } |
| + return ref, true |
| +} |
diff --git a/internal/slidestest/scenes_agent_test.go b/internal/slidestest/scenes_agent_test.go| new file mode 100644 |
| index 0000000..70af810 |
| --- /dev/null |
| +++ b/internal/slidestest/scenes_agent_test.go |
| @@ -0,0 +1,312 @@ |
| +package slidestest |
| + |
| +// An agent's scene work through the drive API (scenes and clips spec §4, |
| +// §8 calls 4 and 5; internal/slides/scenestills.go): a bundle before the |
| +// scene exists, new code for one that does, and a still for each state, |
| +// each refused when it was made from a version of the scene that has |
| +// since moved on. |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/slides/internal/slides/deck" |
| +) |
| + |
| +// agentCall is one raw API request with a body that is not JSON. |
| +func agentCall(t *testing.T, a *testApp, method, target, token string, body []byte) *httptest.ResponseRecorder { |
| + t.Helper() |
| + req := httptest.NewRequest(method, target, bytes.NewReader(body)) |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + return send(t, a, req) |
| +} |
| + |
| +func decode(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { |
| + t.Helper() |
| + var out map[string]any |
| + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { |
| + t.Fatalf("body is not a JSON object: %v\n%s", err, rec.Body) |
| + } |
| + return out |
| +} |
| + |
| +// sceneOf reads one scene out of the deck as an agent sees it. |
| +func sceneOf(t *testing.T, a *testApp, token, sqid, id string) deck.Scene { |
| + t.Helper() |
| + rec := agentCall(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, nil) |
| + var view struct { |
| + Scenes map[string]deck.Scene `json:"scenes"` |
| + } |
| + if err := json.Unmarshal(rec.Body.Bytes(), &view); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, ok := view.Scenes[id] |
| + if !ok { |
| + t.Fatalf("the deck has no scene %s: %s", id, rec.Body) |
| + } |
| + return s |
| +} |
| + |
| +// stillsCurrent is the twin of the editor's stillsCurrent |
| +// (fixtures/scenes.mjs): every state has a still, made from the scene's |
| +// version now. |
| +func stillsCurrent(s deck.Scene) bool { |
| + v := deck.SceneVersion(s) |
| + for _, st := range s.States { |
| + if got, ok := s.Stills[st.ID]; !ok || got.Made != v { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func stillURL(sqid, id, state, made string) string { |
| + return "/api/v1/decks/" + sqid + "/scenes/" + id + "/stills/" + state + "?made=" + made |
| +} |
| + |
| +// agentScene is an app, a signed-in person, their agent's token, a deck |
| +// and a scene in it whose bundle went up through the API. |
| +func agentScene(t *testing.T) (a *testApp, token, sqid, id string) { |
| + t.Helper() |
| + cfg, mailer := newConfig(t) |
| + cfg.AllowedAddresses = []string{allowedAddress, otherAddress} |
| + cfg.Blobs = dirStore(t) |
| + a = newAppWith(t, cfg, mailer) |
| + cookies := signedIn(t, a, allowedAddress) |
| + token = mintAgent(t, a, cookies, "scenes") |
| + sqid = apiDeck(t, a, token, "Stills") |
| + rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", token, sceneBundle) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("POST scene-bundles: status %d\n%s", rec.Code, rec.Body) |
| + } |
| + ref, _ := decode(t, rec)["ref"].(string) |
| + if ref != hashOf(sceneBundle) { |
| + t.Fatalf("scene-bundles answered ref %q, want the hash of the bytes", ref) |
| + } |
| + return a, token, sqid, addScene(t, a, token, sqid, ref) |
| +} |
| + |
| +// TestAnAgentUploadsAStillForEveryState: each PUT is checked, stored, |
| +// registered to the deck as a picture and set on the scene as the agent; |
| +// after one for each state the scene's stills are current, and the |
| +// pictures are served by the deck's own picture route. |
| +func TestAnAgentUploadsAStillForEveryState(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + cookies := signedIn(t, a, allowedAddress) |
| + if stillsCurrent(sceneOf(t, a, token, sqid, id)) { |
| + t.Fatal("a scene with no stills reads as current") |
| + } |
| + made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) |
| + for _, state := range []string{"one", "two"} { |
| + rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("PUT still %s: status %d, want 200\n%s", state, rec.Code, rec.Body) |
| + } |
| + out := decode(t, rec) |
| + if out["ref"] != hashOf(onePixelPNG) || out["made"] != made { |
| + t.Errorf("PUT still %s answered %v, want the picture's hash and the version", state, out) |
| + } |
| + } |
| + s := sceneOf(t, a, token, sqid, id) |
| + if !stillsCurrent(s) { |
| + t.Errorf("a still for each state, and the scene's stills are not current: %+v", s.Stills) |
| + } |
| + if got := s.Stills["one"]; got.Ref != hashOf(onePixelPNG) || got.Made != made { |
| + t.Errorf("the scene's still for one is %+v", got) |
| + } |
| + // A picture of the deck: registered, verified, served. |
| + rec := mustGet(t, a, "/d/"+sqid+"/assets/"+hashOf(onePixelPNG), http.StatusOK, cookies) |
| + if !bytes.Equal(rec.Body.Bytes(), onePixelPNG) { |
| + t.Error("the still's bytes differ from what went up") |
| + } |
| + // The change was the agent's, through the op path. |
| + var actor string |
| + if err := a.db.G.Raw("SELECT actor FROM deck_updates WHERE deck_id = (SELECT id FROM decks WHERE sqid = ?) ORDER BY seq DESC LIMIT 1", sqid).Scan(&actor).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix(actor, "agent:") { |
| + t.Errorf("the last update's actor is %q, want an agent's", actor) |
| + } |
| +} |
| + |
| +// TestAStillMadeFromOldCodeIsRefused: a stale or malformed made is a |
| +// 409 stale and the scene is untouched. |
| +func TestAStillMadeFromOldCodeIsRefused(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) |
| + for _, bad := range []string{strings.Repeat("0", 64), "", "nonsense"} { |
| + rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", bad), token, onePixelPNG) |
| + if rec.Code != http.StatusConflict { |
| + t.Errorf("made=%q: status %d, want 409\n%s", bad, rec.Code, rec.Body) |
| + continue |
| + } |
| + if out := decode(t, rec); out["error"] != "stale" { |
| + t.Errorf("made=%q: error %v, want stale", bad, out["error"]) |
| + } |
| + } |
| + if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 { |
| + t.Errorf("a refused still was set anyway: %+v", s.Stills) |
| + } |
| + |
| + // A hand edit of the words moves the version: stills made before it |
| + // are stale to the editor's note, and a new upload against the old |
| + // version is refused. |
| + for _, state := range []string{"one", "two"} { |
| + agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG) |
| + } |
| + apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| + `{"ops":[{"op":"set_scene","id":"`+id+`","words":{"one":"Changed"}}]}`, http.StatusOK) |
| + if stillsCurrent(sceneOf(t, a, token, sqid, id)) { |
| + t.Error("a hand edit of words left the stills current") |
| + } |
| + if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, onePixelPNG); rec.Code != http.StatusConflict { |
| + t.Errorf("a still against the old version: status %d, want 409", rec.Code) |
| + } |
| +} |
| + |
| +// TestStillsAreRefusedForWhatIsNotYours: another person's deck, a scene |
| +// or a state that is not there. |
| +func TestStillsAreRefusedForWhatIsNotYours(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) |
| + theirs := mintAgent(t, a, signedIn(t, a, otherAddress), "theirs") |
| + for name, call := range map[string]struct{ token, target string }{ |
| + "another person's deck": {theirs, stillURL(sqid, id, "one", made)}, |
| + "an unknown scene": {token, stillURL(sqid, "zzzzzzzzzzzz", "one", made)}, |
| + "an unknown state": {token, stillURL(sqid, id, "three", made)}, |
| + } { |
| + rec := agentCall(t, a, http.MethodPut, call.target, call.token, onePixelPNG) |
| + if rec.Code != http.StatusNotFound { |
| + t.Errorf("%s: status %d, want 404\n%s", name, rec.Code, rec.Body) |
| + } |
| + } |
| + // Another person's deck, for their code and a bundle, too. |
| + if rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", theirs, sceneBundle); rec.Code != http.StatusNotFound { |
| + t.Errorf("code for another person's deck: status %d, want 404", rec.Code) |
| + } |
| + if rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", theirs, sceneBundle); rec.Code != http.StatusNotFound { |
| + t.Errorf("a bundle for another person's deck: status %d, want 404", rec.Code) |
| + } |
| + if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 { |
| + t.Errorf("a refused still was set anyway: %+v", s.Stills) |
| + } |
| +} |
| + |
| +// TestNewCodeChangesTheVersionAndMarksStillsStale: PUT code registers the |
| +// bundle, sets it as the scene's code with the agent as its author, and |
| +// answers the new version; stills made before it are stale. |
| +func TestNewCodeChangesTheVersionAndMarksStillsStale(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + cookies := signedIn(t, a, allowedAddress) |
| + made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) |
| + for _, state := range []string{"one", "two"} { |
| + agentCall(t, a, http.MethodPut, stillURL(sqid, id, state, made), token, onePixelPNG) |
| + } |
| + if !stillsCurrent(sceneOf(t, a, token, sqid, id)) { |
| + t.Fatal("the stills were not current to begin with") |
| + } |
| + |
| + next := append([]byte("<!DOCTYPE html>\n<title>v2</title>\n"), sceneBundle...) |
| + rec := agentCall(t, a, http.MethodPut, "/api/v1/decks/"+sqid+"/scenes/"+id+"/code", token, next) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("PUT code: status %d\n%s", rec.Code, rec.Body) |
| + } |
| + out := decode(t, rec) |
| + s := sceneOf(t, a, token, sqid, id) |
| + if out["ref"] != hashOf(next) || s.Code != hashOf(next) { |
| + t.Errorf("code ref: answered %v, scene has %s, want %s", out["ref"], s.Code, hashOf(next)) |
| + } |
| + if out["version"] != deck.SceneVersion(s) || out["version"] == made { |
| + t.Errorf("version answered %v, scene's is %s (was %s)", out["version"], deck.SceneVersion(s), made) |
| + } |
| + if !strings.HasPrefix(s.Author, "agent:") { |
| + t.Errorf("author = %q, want the agent", s.Author) |
| + } |
| + if stillsCurrent(s) { |
| + t.Error("new code left the old stills current") |
| + } |
| + // The new bundle is served under the sealed route of the deck. |
| + rec = mustGet(t, a, "/d/"+sqid+"/scenes/"+id+"/"+hashOf(next), http.StatusOK, cookies) |
| + if !bytes.Equal(rec.Body.Bytes(), next) { |
| + t.Error("the new bundle's bytes differ from what went up") |
| + } |
| + // And a still made against the new version is accepted. |
| + if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", out["version"].(string)), token, onePixelPNG); rec.Code != http.StatusOK { |
| + t.Errorf("a still against the new version: status %d\n%s", rec.Code, rec.Body) |
| + } |
| +} |
| + |
| +// TestACodeBodyThatIsNotOneHTMLDocumentIsRefused: for both routes, and |
| +// over the limit. |
| +func TestACodeBodyThatIsNotOneHTMLDocumentIsRefused(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + big := append([]byte("<!doctype html>"), bytes.Repeat([]byte("x"), 2<<20)...) |
| + for name, call := range map[string]struct { |
| + method, target string |
| + body []byte |
| + status int |
| + code string |
| + }{ |
| + "code, a picture": {http.MethodPut, "/scenes/" + id + "/code", onePixelPNG, http.StatusUnprocessableEntity, "not_html"}, |
| + "code, text": {http.MethodPut, "/scenes/" + id + "/code", []byte("hello"), http.StatusUnprocessableEntity, "not_html"}, |
| + "code, too big": {http.MethodPut, "/scenes/" + id + "/code", big, http.StatusRequestEntityTooLarge, "too_large"}, |
| + "code, unknown scene": {http.MethodPut, "/scenes/zzzzzzzzzzzz/code", sceneBundle, http.StatusNotFound, "not_found"}, |
| + "bundle, a picture": {http.MethodPost, "/scene-bundles", onePixelPNG, http.StatusUnprocessableEntity, "not_html"}, |
| + "bundle, too big": {http.MethodPost, "/scene-bundles", big, http.StatusRequestEntityTooLarge, "too_large"}, |
| + } { |
| + rec := agentCall(t, a, call.method, "/api/v1/decks/"+sqid+call.target, token, call.body) |
| + if rec.Code != call.status || decode(t, rec)["error"] != call.code { |
| + t.Errorf("%s: status %d %s, want %d %s", name, rec.Code, rec.Body, call.status, call.code) |
| + } |
| + } |
| + if s := sceneOf(t, a, token, sqid, id); s.Code != hashOf(sceneBundle) { |
| + t.Errorf("a refused bundle changed the scene's code to %s", s.Code) |
| + } |
| +} |
| + |
| +// TestAStillIsAPictureOfTheRightSize: a PNG or WebP, at most 4 MiB, an |
| +// image that decodes at a size the pictures allow. |
| +func TestAStillIsAPictureOfTheRightSize(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) |
| + big := append(append([]byte{}, onePixelPNG...), bytes.Repeat([]byte{0}, 4<<20)...) |
| + // A PNG header declaring 40000 x 1: over the 30000 the pictures allow. |
| + wide := append([]byte{}, onePixelPNG...) |
| + wide[18], wide[19], wide[20], wide[21] = 0, 0, 0x9c, 0x40 |
| + for name, call := range map[string]struct { |
| + body []byte |
| + status int |
| + code string |
| + }{ |
| + "too big": {big, http.StatusRequestEntityTooLarge, "too_large"}, |
| + "html": {sceneBundle, http.StatusUnprocessableEntity, "not_an_image"}, |
| + "svg": {[]byte(`<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>`), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "jpeg": {[]byte("\xff\xd8\xff\xe0 not really"), http.StatusUnprocessableEntity, "not_an_image"}, |
| + "a broken png": {onePixelPNG[:20], http.StatusUnprocessableEntity, "not_an_image"}, |
| + "empty": {nil, http.StatusUnprocessableEntity, "not_an_image"}, |
| + "too many pixels": {wide, http.StatusUnprocessableEntity, "not_an_image"}, |
| + } { |
| + rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, call.body) |
| + if rec.Code != call.status || decode(t, rec)["error"] != call.code { |
| + t.Errorf("%s: status %d %s, want %d %s", name, rec.Code, rec.Body, call.status, call.code) |
| + } |
| + } |
| + if s := sceneOf(t, a, token, sqid, id); len(s.Stills) != 0 { |
| + t.Errorf("a refused still was set anyway: %+v", s.Stills) |
| + } |
| +} |
| + |
| +// TestWithoutAStoreThereIsNowhereToPutThem: 503, as the pictures answer. |
| +func TestWithoutAStoreThereIsNowhereToPutThem(t *testing.T) { |
| + a := newApp(t) |
| + token := mintAgent(t, a, signedIn(t, a, allowedAddress), "scenes") |
| + sqid := apiDeck(t, a, token, "Bare") |
| + rec := agentCall(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/scene-bundles", token, sceneBundle) |
| + if rec.Code != http.StatusServiceUnavailable { |
| + t.Errorf("a bundle with no store: status %d, want 503", rec.Code) |
| + } |
| +} |