Slides: a still's stale check is made on the document it is written to
The version is rechecked inside the write's retry loop, against the document each attempt opened, so an edit landing between the early check and the write refuses the still with 409. A code upload answers the version of the scene as the write left it. The stillsCurrent tests move to their own file; the oversize-PNG test has a valid header checksum.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
5 files changed,
+230
−82
fixtures/scene-stills.test.mjs+58 −0fixtures/scenes.test.mjs+1 −34internal/slides/api.go+24 −8internal/slides/scenestills.go+79 −38internal/slidestest/scenes_agent_test.go+68 −2
diff --git a/fixtures/scene-stills.test.mjs b/fixtures/scene-stills.test.mjs| new file mode 100644 |
| index 0000000..94a0eeb |
| --- /dev/null |
| +++ b/fixtures/scene-stills.test.mjs |
| @@ -0,0 +1,58 @@ |
| +// scene-stills.test.mjs: stillsCurrent (scenes and clips spec §4, plan task 5), |
| +// which says whether a scene's stills match the scene as it is now. |
| +import test from 'node:test' |
| +import assert from 'node:assert/strict' |
| +import * as Y from 'yjs' |
| +import { applyOps, view } from './ops.mjs' |
| +import { sceneVersion, stillsCurrent } from './scenes.mjs' |
| + |
| +const STILL = '1'.repeat(64) |
| +const CODE = 'a'.repeat(64) |
| + |
| +function deck () { |
| + const doc = new Y.Doc({ guid: 'scenes' }) |
| + doc.clientID = 1 |
| + applyOps(doc, [{ |
| + op: 'add_scene', |
| + id: 'worldsceneaa', |
| + name: 'The world', |
| + code: CODE, |
| + states: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], |
| + words: { title: 'Vienna' }, |
| + data: { n: 3 } |
| + }]) |
| + return doc |
| +} |
| + |
| +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/fixtures/scenes.test.mjs b/fixtures/scenes.test.mjs| index 9c63654..7f991cd 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, stillsCurrent } from './scenes.mjs' |
| +import { sceneCanonical, sceneVersion } from './scenes.mjs' |
| const CODE = '0123456789abcdef'.repeat(4) |
| const CODE2 = 'fedcba9876543210'.repeat(4) |
| @@ -307,36 +307,3 @@ 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 06fd1ee..9217621 100644 |
| --- a/internal/slides/api.go |
| +++ b/internal/slides/api.go |
| @@ -551,17 +551,33 @@ func (a *app) apiOpsFailed(w http.ResponseWriter, d Deck, err error) { |
| // already written into the ops, so it mints nothing new and the caller |
| // is told the same ids either way. |
| func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []map[string]json.RawMessage, g writeGuard) (map[string]string, error) { |
| + ids, _, err := a.applyAgentOpsFrom(ctx, d, actor, func(*deck.Deck) ([]map[string]json.RawMessage, error) { return ops, nil }, g) |
| + return ids, err |
| +} |
| + |
| +// applyAgentOpsFrom is applyAgentOps for a batch that depends on the |
| +// document it lands on: build is given the view each attempt opened, so |
| +// whatever it checked is what the write is made against. The optimistic |
| +// lock refuses the write if the deck has moved since that open, and the |
| +// retry builds again from the newer one. It answers the document as the |
| +// write left it. |
| +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) { |
| var ids map[string]string |
| var lastErr error |
| for attempt := 0; attempt < 2; attempt++ { |
| h, view, err := a.openDeck(ctx, *d) |
| if err != nil { |
| - return nil, err |
| + return nil, nil, err |
| + } |
| + ops, err := build(view) |
| + if err != nil { |
| + h.Close(ctx) |
| + return nil, nil, err |
| } |
| minted, err := mintOpIDs(ops, view) |
| if err != nil { |
| h.Close(ctx) |
| - return nil, err |
| + return nil, nil, err |
| } |
| if attempt == 0 { |
| ids = minted |
| @@ -569,23 +585,23 @@ func (a *app) applyAgentOps(ctx context.Context, d *Deck, actor string, ops []ma |
| encoded, err := json.Marshal(ops) |
| if err != nil { |
| h.Close(ctx) |
| - return nil, fmt.Errorf("slides: encode ops: %w", err) |
| + return nil, nil, fmt.Errorf("slides: encode ops: %w", err) |
| } |
| - _, err = a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops), g) |
| + after, err := a.applyOps(ctx, h, d, actor, encoded, metaRowUpdates(ops), g) |
| h.Close(ctx) |
| if err == nil { |
| - return ids, nil |
| + return ids, after, nil |
| } |
| lastErr = err |
| if !errors.Is(err, errDeckBusy) { |
| - return nil, err |
| + return nil, nil, err |
| } |
| // Our copy's Seq is what just lost; re-read it before retrying. |
| if err := a.db.G.WithContext(ctx).First(d, d.ID).Error; err != nil { |
| - return nil, fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| + return nil, nil, fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| } |
| } |
| - return nil, lastErr |
| + return nil, nil, lastErr |
| } |
| // metaRowUpdates is the decks row's share of a batch: the title and |
diff --git a/internal/slides/scenestills.go b/internal/slides/scenestills.go| index 75cf901..4a34bc4 100644 |
| --- a/internal/slides/scenestills.go |
| +++ b/internal/slides/scenestills.go |
| @@ -198,55 +198,86 @@ func (a *app) apiPutStill(w http.ResponseWriter, r *http.Request) { |
| } |
| // 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) |
| + // so the same batch registers it, unless it already does. The |
| + // version is checked again here, against the document the write is |
| + // made on (applyAgentOpsFrom), because a hand edit or a newer still |
| + // can land between the early check above and this write. |
| + assetID, err := newID() |
| 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 |
| + build := func(view *deck.Deck) ([]map[string]json.RawMessage, error) { |
| + now, ok := view.Scenes[id] |
| + if !ok { |
| + return nil, errSceneGone |
| + } |
| + if deck.SceneVersion(now) != version { |
| + return nil, errStillStale |
| + } |
| + if BeforeSceneWrite != nil { |
| + BeforeSceneWrite() |
| } |
| - 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 |
| + var ops []map[string]json.RawMessage |
| + registered := false |
| + for _, asset := range view.Assets { |
| + registered = registered || asset.Ref == ref |
| + } |
| + if !registered { |
| + alt := now.Name |
| + for _, s := range now.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": "register_asset", "id": assetID, "ref": ref, "name": state + ".png", |
| - "width": cfg.Width, "height": cfg.Height, "alt": trimTo(alt, maxAssetAlt), |
| - })) |
| + return append(ops, sceneOp(map[string]any{ |
| + "op": "set_scene", "id": id, |
| + "stills": map[string]any{state: map[string]string{"ref": ref, "made": version}}, |
| + })), nil |
| } |
| - 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) |
| + if _, _, err := a.applyAgentOpsFrom(r.Context(), &d, p.actor(), build, a.deckGuard(r.Context(), p.operator, d)); err != nil { |
| + a.sceneWriteFailed(w, d, err) |
| return |
| } |
| a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "made": version}) |
| } |
| +var ( |
| + errStillStale = errors.New("slides: the scene moved on before the still was written") |
| + errSceneGone = errors.New("slides: the scene is gone") |
| +) |
| + |
| +// BeforeSceneWrite is a test seam: called when a still's write has been |
| +// checked against the document it will land on and before it is made, |
| +// so a test can land another edit in between. Nil in production. |
| +var BeforeSceneWrite func() |
| + |
| +// sceneWriteFailed answers a scene write refused: stale, gone, or any |
| +// batch refusal. |
| +func (a *app) sceneWriteFailed(w http.ResponseWriter, d Deck, err error) { |
| + switch { |
| + case errors.Is(err, errStillStale): |
| + apiSceneFail(w, http.StatusConflict, "stale") |
| + case errors.Is(err, errSceneGone): |
| + apiFail(w, http.StatusNotFound, errNotFound) |
| + default: |
| + a.apiOpsFailed(w, d, err) |
| + } |
| +} |
| + |
| // 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) |
| + p, d, _, id, ok := a.sceneForAPI(w, r, true) |
| if !ok { |
| return |
| } |
| @@ -254,13 +285,23 @@ func (a *app) apiPutSceneCode(w http.ResponseWriter, r *http.Request) { |
| 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) |
| + build := func(view *deck.Deck) ([]map[string]json.RawMessage, error) { |
| + if _, ok := view.Scenes[id]; !ok { |
| + return nil, errSceneGone |
| + } |
| + if BeforeSceneWrite != nil { |
| + BeforeSceneWrite() |
| + } |
| + return []map[string]json.RawMessage{sceneOp(map[string]any{"op": "set_scene", "id": id, "code": ref})}, nil |
| + } |
| + _, after, err := a.applyAgentOpsFrom(r.Context(), &d, p.actor(), build, a.deckGuard(r.Context(), p.operator, d)) |
| + if err != nil { |
| + a.sceneWriteFailed(w, d, err) |
| return |
| } |
| - scene.Code = ref |
| - a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "version": deck.SceneVersion(scene)}) |
| + // The version of the scene as the write left it, with whatever |
| + // edits landed while the bundle was uploading. |
| + a.writeJSON(w, http.StatusOK, map[string]string{"ref": ref, "version": deck.SceneVersion(after.Scenes[id])}) |
| } |
| // apiPostSceneBundle serves POST /api/v1/decks/{sqid}/scene-bundles: a |
diff --git a/internal/slidestest/scenes_agent_test.go b/internal/slidestest/scenes_agent_test.go| index 70af810..5b99022 100644 |
| --- a/internal/slidestest/scenes_agent_test.go |
| +++ b/internal/slidestest/scenes_agent_test.go |
| @@ -8,12 +8,16 @@ package slidestest |
| import ( |
| "bytes" |
| + "encoding/binary" |
| "encoding/json" |
| + "hash/crc32" |
| + "image/png" |
| "net/http" |
| "net/http/httptest" |
| "strings" |
| "testing" |
| + slides "amadan.net/oficina/slides/internal/slides" |
| "amadan.net/oficina/slides/internal/slides/deck" |
| ) |
| @@ -274,9 +278,14 @@ 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. |
| + // A PNG whose header, checksum right, declares 40000 x 1: it decodes |
| + // as far as its size, which is over the 30000 the pictures allow. |
| wide := append([]byte{}, onePixelPNG...) |
| - wide[18], wide[19], wide[20], wide[21] = 0, 0, 0x9c, 0x40 |
| + wide[16], wide[17], wide[18], wide[19] = 0, 0, 0x9c, 0x40 |
| + binary.BigEndian.PutUint32(wide[29:33], crc32.ChecksumIEEE(wide[12:29])) |
| + if cfg, err := png.DecodeConfig(bytes.NewReader(wide)); err != nil || cfg.Width != 40000 { |
| + t.Fatalf("the wide PNG is not a valid header of width 40000: %v %+v", err, cfg) |
| + } |
| for name, call := range map[string]struct { |
| body []byte |
| status int |
| @@ -310,3 +319,60 @@ func TestWithoutAStoreThereIsNowhereToPutThem(t *testing.T) { |
| t.Errorf("a bundle with no store: status %d, want 503", rec.Code) |
| } |
| } |
| + |
| +// duringWrite lands one hand edit of the scene's words at the moment a |
| +// scene write has been checked against the document and not yet made. |
| +func duringWrite(t *testing.T, a *testApp, token, sqid, id string) { |
| + t.Helper() |
| + fired := 0 |
| + slides.BeforeSceneWrite = func() { |
| + fired++ |
| + if fired > 1 { |
| + return |
| + } |
| + apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, |
| + `{"ops":[{"op":"set_scene","id":"`+id+`","words":{"one":"Landed in between"}}]}`, http.StatusOK) |
| + } |
| + t.Cleanup(func() { slides.BeforeSceneWrite = nil }) |
| +} |
| + |
| +// TestAHandEditBetweenTheCheckAndTheWriteStillRefusesTheStill: the |
| +// version is checked against the document the write lands on, so an edit |
| +// that arrives after an earlier check cannot be overwritten by a still |
| +// made before it. |
| +func TestAHandEditBetweenTheCheckAndTheWriteStillRefusesTheStill(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + made := deck.SceneVersion(sceneOf(t, a, token, sqid, id)) |
| + duringWrite(t, a, token, sqid, id) |
| + rec := agentCall(t, a, http.MethodPut, stillURL(sqid, id, "one", made), token, onePixelPNG) |
| + if rec.Code != http.StatusConflict || decode(t, rec)["error"] != "stale" { |
| + t.Fatalf("status %d %s, want 409 stale", rec.Code, rec.Body) |
| + } |
| + s := sceneOf(t, a, token, sqid, id) |
| + if len(s.Stills) != 0 { |
| + t.Errorf("a still made from the old version was written: %+v", s.Stills) |
| + } |
| + if s.Words["one"] != "Landed in between" { |
| + t.Errorf("the hand edit is not in the scene: %v", s.Words) |
| + } |
| +} |
| + |
| +// TestACodeUploadAnswersTheVersionTheWriteLeft: an edit of the words that |
| +// lands while the code is being set is in the scene, and so in the |
| +// version the answer names. |
| +func TestACodeUploadAnswersTheVersionTheWriteLeft(t *testing.T) { |
| + a, token, sqid, id := agentScene(t) |
| + duringWrite(t, a, token, sqid, id) |
| + next := append([]byte("<!DOCTYPE html>\n<title>v3</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) |
| + } |
| + s := sceneOf(t, a, token, sqid, id) |
| + if s.Words["one"] != "Landed in between" || s.Code != hashOf(next) { |
| + t.Fatalf("the scene is not the write's: %+v", s) |
| + } |
| + if got := decode(t, rec)["version"]; got != deck.SceneVersion(s) { |
| + t.Errorf("answered version %v, the scene's is %s", got, deck.SceneVersion(s)) |
| + } |
| +} |