oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// snapshot.go is the accelerator under openDeck: a deck's whole
2// document written down every so often, so opening it replays a short
3// tail instead of every update since it was made.
4//
5// The rule the whole file is built on, and the one to keep if anything
6// here is ever rewritten: THE LOG IS THE DECK. A snapshot is derived
7// data (models.go's DeckSnapshot, Docs' snapshots ruling). Every path
8// in this file is therefore allowed to fail without failing the request
9// that reached it, and openDeck falls back to the plain log when it
10// does.
11package slides
12
13import (
14 "context"
15 "errors"
16 "fmt"
17 "time"
18
19 "gorm.io/gorm"
20
21 "amadan.net/oficina/slides/internal/slides/core"
22)
23
24// snapshotCadence is how many updates may accumulate before the next
25// snapshot is taken: the request whose seq lands on a multiple of this
26// writes one (maybeSnapshot).
27//
28// 200 is the plan's number, and the tail it leaves — at most 199
29// updates to replay — sits about twenty times clear of
30// core.MaxRetainedUpdates (4096), which is the hard wall a handle hits
31// when it has replayed too much to rebuild itself. That headroom is
32// conditional on snapshot writes actually succeeding; each failure is
33// logged at Error for exactly that reason.
34const snapshotCadence = 200
35
36const replayBatchSize = 256
37const replayCheckpointCadence = core.MaxRetainedUpdates / 2
38
39// latestSnapshot returns the newest usable snapshot for deckID, or nil
40// when there is none.
41//
42// Ordering is seq DESC, id DESC: two writers crossing the boundary
43// together may legitimately write equivalent rows at the same seq, so
44// the tie resolves to the last row written rather than being treated as
45// an error worth reporting.
46func (a *app) latestSnapshot(ctx context.Context, deckID int64) (*DeckSnapshot, error) {
47 return latestSnapshotOn(ctx, a.db.G, deckID)
48}
49func latestSnapshotOn(ctx context.Context, db *gorm.DB, deckID int64) (*DeckSnapshot, error) {
50 var row DeckSnapshot
51 err := db.WithContext(ctx).
52 Where("deck_id = ?", deckID).
53 Order("seq DESC, id DESC").
54 Take(&row).Error
55 if errors.Is(err, gorm.ErrRecordNotFound) {
56 return nil, nil
57 }
58 if err != nil {
59 return nil, fmt.Errorf("slides: newest snapshot for deck %d: %w", deckID, err)
60 }
61 return &row, nil
62}
63
64// replayPlan is what openDeck has to apply to reconstitute d: the
65// newest eligible snapshot (or nil) and the first bounded update batch.
66//
67// It is one function rather than two calls at the call site so that the
68// invariant tying them together — the tail starts exactly where the
69// snapshot ends — is written once and can be tested on its own
70// (snapshot_test.go).
71//
72// A snapshot that cannot be read is not an error here. The log alone
73// still answers the question, so the failure is returned to the caller
74// as "no snapshot" plus a log line, and the deck opens slowly rather
75// than not at all.
76func (a *app) replayPlan(ctx context.Context, d Deck) (*DeckSnapshot, []DeckUpdate, error) {
77 return a.replayPlanOn(ctx, a.db.G, d)
78}
79func (a *app) replayPlanOn(ctx context.Context, db *gorm.DB, d Deck) (*DeckSnapshot, []DeckUpdate, error) {
80 snap, err := latestSnapshotOn(ctx, db, d.ID)
81 if err != nil {
82 a.logger.Error("slides: read a deck's newest snapshot, replaying the plain log instead",
83 "deck", d.Sqid, "err", err)
84 snap = nil
85 }
86
87 if snap != nil && (snap.Seq <= 0 || snap.Seq > d.Seq) {
88 snap = nil
89 }
90 var since int64
91 if snap != nil {
92 since = snap.Seq
93 }
94 updates, err := replayLogOn(ctx, db, d, since)
95 return snap, updates, err
96}
97
98func (a *app) replayLog(ctx context.Context, d Deck, since int64) ([]DeckUpdate, error) {
99 return replayLogOn(ctx, a.db.G, d, since)
100}
101func replayLogOn(ctx context.Context, db *gorm.DB, d Deck, since int64) ([]DeckUpdate, error) {
102 var updates []DeckUpdate
103 if err := db.WithContext(ctx).
104 Where("deck_id = ? AND seq > ? AND seq <= ?", d.ID, since, d.Seq).
105 Order("seq").Limit(replayBatchSize).Find(&updates).Error; err != nil {
106 return nil, fmt.Errorf("slides: read deck %s log: %w", d.Sqid, err)
107 }
108 return updates, nil
109}
110
111// maybeSnapshot writes a snapshot when seq lands on the cadence
112// boundary, and does nothing at all otherwise.
113//
114// Two things it is the caller's job to have true, because nothing here
115// can check either:
116//
117// - h holds the document THROUGH seq and no further. Every caller
118// applies its update to h and commits it before calling this, so
119// the number on the row is the number in the bytes.
120// - The transaction that wrote seq has COMMITTED. A snapshot taken
121// from a rolled-back state would be a copy of a deck that never
122// existed, and openDeck would then skip the real rows it claims to
123// cover.
124//
125// Every failure is logged and swallowed. This runs after the update the
126// person actually made is safely on disk; failing their request because
127// the accelerator could not be written would be trading the thing that
128// matters for the thing that does not.
129func (a *app) maybeSnapshot(ctx context.Context, d Deck, h *core.Handle, seq int64) {
130 if seq <= 0 || seq%snapshotCadence != 0 {
131 return
132 }
133
134 state, err := h.State(ctx)
135 if err != nil {
136 a.logger.Error("slides: encode a deck snapshot", "deck", d.Sqid, "seq", seq, "err", err)
137 return
138 }
139
140 row := &DeckSnapshot{
141 DeckID: d.ID,
142 Seq: seq,
143 Bytes: state,
144 CreatedAt: time.Now().UTC(),
145 }
146 err = a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
147 if err := tx.Create(row).Error; err != nil {
148 return fmt.Errorf("slides: persist a snapshot for deck %s at seq %d: %w", d.Sqid, seq, err)
149 }
150 // Superseded snapshots are deleted rather than kept: they are
151 // reproducible from a log that keeps every row, so this deletes
152 // no history, and retaining them would cost one whole copy of
153 // the deck per two hundred updates — the difference between an
154 // accelerator and a second, fatter archive.
155 //
156 // "Superseded" is (seq, id) ordered exactly as latestSnapshot
157 // reads, so what survives is always what latestSnapshot would
158 // return, and a row at a HIGHER seq — written by another
159 // request that got further — is never touched. "Delete
160 // everything that is not mine" would take that one out and
161 // quietly put the deck back to replaying updates it had
162 // already been spared.
163 if err := tx.Where("deck_id = ? AND (seq < ? OR (seq = ? AND id < ?))",
164 d.ID, row.Seq, row.Seq, row.ID).Delete(&DeckSnapshot{}).Error; err != nil {
165 return fmt.Errorf("slides: delete superseded snapshots for deck %s at seq %d: %w", d.Sqid, seq, err)
166 }
167 return nil
168 })
169 if err != nil {
170 a.logger.Error("slides: write a deck snapshot", "deck", d.Sqid, "seq", seq, "err", err)
171 }
172}
173