oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package store
2
3import (
4 "gorm.io/gorm"
5
6 "amadan.net/oficina/sheets/internal/sheets/calc"
7)
8
9// afterBlankTransactionOneCommits is a test-only seam: called
10// immediately after setBlank's first transaction (the delete, the
11// dependents' dirty-marker bump, and the input event) commits, before
12// anything else runs. It always returns nil in production. A test
13// overrides it to return a non-nil error, simulating a process crash
14// landing exactly between setBlank's two transactions — see
15// TestBlankCrashLeavesDependentsRecoverable.
16var afterBlankTransactionOneCommits = func() error { return nil }
17
18// Set writes a cell's new raw input and recalculates forward from it.
19//
20// It is SetReport with the report thrown away, and exists at this
21// signature because every caller that does not fan out over SSE — XLSX
22// import, and most of this package's tests — wants exactly that. The
23// crash-safety reasoning that used to live here moved to SetReport
24// (handle_report.go), which is now where the work happens.
25func (h *Handle) Set(rowID, colID uint64, raw string, actor uint64) error {
26 _, err := h.SetReport(rowID, colID, raw, actor)
27 return err
28}
29
30// setBlank deletes a cell's row (cells are sparse — models.go) and
31// propagates the change to its dependents.
32//
33// A crash between "the row is gone" and "dependents have been
34// recomputed" is exactly the scenario this whole task exists to close —
35// reached here via delete instead of update. The origin row cannot carry
36// a dirty marker once it no longer exists, so this durably marks every
37// DEPENDENT dirty (bumping its own InputVersion to v, its CacheVersion
38// untouched) in the SAME transaction as the delete. If the process never
39// reaches the recompute below, each dependent's own InputVersion now
40// leads its own CacheVersion, and Open's ordinary per-cell recovery —
41// already proven by TestStaleCacheIsRecomputedOnOpen — finds and fixes
42// it without needing to know anything about deletes specifically.
43// It returns the dependents it actually recomputed, and whether the
44// dependent set was too wide to recompute at all — SetReport turns both
45// into a report a live client can either paint or resync from.
46func (h *Handle) setBlank(guard Guard, rowID, colID uint64, key calc.CellKey, v uint64, actor uint64, prevRaw string) (map[calc.CellKey]struct{}, bool, error) {
47 // TransitiveDependents reads g.dependents[key], which Clear (called
48 // below, after this transaction commits) never touches — only key's
49 // own precedent edges are rewired by Clear — so this is safe to
50 // compute before the delete.
51 touched := h.graph.TransitiveDependents(key)
52 withinCap := len(touched) > 0 && len(touched) <= calc.MaxDirtyPerPass
53
54 if err := h.db.Transaction(func(tx *gorm.DB) error {
55 return guard.Run(func() error {
56 if err := h.advanceContentVersion(tx, v); err != nil {
57 return err
58 }
59 if err := tx.Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID).
60 Delete(&Cell{}).Error; err != nil {
61 return err
62 }
63 // Marking is unconditional on len(touched) > 0 — NOT gated by
64 // withinCap. MaxDirtyPerPass bounds the RECOMPUTE below (a full
65 // Eval of every touched cell), not this marker (one version-bump
66 // UPDATE per touched cell). Past the cap this cell's own row is
67 // gone, so a durable marker on every dependent is the only
68 // recovery signal that will ever exist for them; skipping it
69 // here — as this code once did — left them looking permanently
70 // consistent (CacheVersion == InputVersion, both untouched) while
71 // silently reading a cell that no longer exists. See
72 // TestBlankFeederOverCapDependentsAreRecoverable.
73 if len(touched) > 0 {
74 if err := h.markDirty(tx, touched, v); err != nil {
75 return err
76 }
77 }
78 return AppendInput(tx, h.sealer, InputEvent{
79 TabID: h.tabID, RowID: rowID, ColID: colID, ActorID: actor,
80 OldRaw: prevRaw, NewRaw: "",
81 })
82 })
83 }); err != nil {
84 return nil, false, err
85 }
86 h.nextVersion++
87 // Test seam: a crash landing exactly here — transaction 1 durably
88 // committed, nothing after it has run yet — is what
89 // TestBlankCrashLeavesDependentsRecoverable simulates. Always nil in
90 // production.
91 if err := afterBlankTransactionOneCommits(); err != nil {
92 return nil, false, err
93 }
94 delete(h.rawText, key)
95 delete(h.keyToIDs, key)
96 h.graph.Clear(key)
97
98 if !withinCap {
99 // Either no dependents (nothing to do) or too many to recompute
100 // and persist synchronously — matching recalcAndPersist's own
101 // refusal past calc.MaxDirtyPerPass, not a separate cap. Every
102 // dependent was still marked dirty above regardless of this
103 // cap, so this is not silent: each one's own version gap is
104 // there for Open's ordinary per-cell recovery to find and fix,
105 // the same as any other stale cell.
106 //
107 // capped is true only in the second of those two cases: no
108 // dependents at all is nothing to report, while too many is a
109 // partial truth a live client must not paint.
110 return nil, len(touched) > 0, nil
111 }
112
113 // Transaction 2: recompute the real values and persist them,
114 // clearing the marker transaction 1 just wrote.
115 h.graph.Recalc(key, newHandleEnv())
116 if err := h.persistTouched(touched, v); err != nil {
117 return nil, false, err
118 }
119 return touched, false, nil
120}
121
122// setContent writes a formula or literal cell's new input and
123// recalculates forward from it.
124// It returns everything the recalculation touched — the edited cell
125// included — and whether the pass was too wide to run.
126func (h *Handle) setContent(guard Guard, rowID, colID uint64, key calc.CellKey, node calc.Node, raw string, v uint64, actor uint64, prevRaw string) (map[calc.CellKey]struct{}, bool, error) {
127 sealedInput, err := h.sealer.Seal("cell.input", []byte(raw))
128 if err != nil {
129 return nil, false, err
130 }
131 if err := h.db.Transaction(func(tx *gorm.DB) error {
132 return guard.Run(func() error {
133 if err := h.advanceContentVersion(tx, v); err != nil {
134 return err
135 }
136 res := tx.Model(&Cell{}).
137 Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, rowID, colID).
138 Updates(map[string]any{
139 "input_sealed": sealedInput,
140 "input_version": v,
141 "updated_by": actor,
142 })
143 if res.Error != nil {
144 return res.Error
145 }
146 if res.RowsAffected == 0 {
147 if err := tx.Create(&Cell{
148 TabID: h.tabID, RowID: rowID, ColID: colID,
149 InputSealed: sealedInput, InputVersion: v,
150 UpdatedBy: actor,
151 }).Error; err != nil {
152 return err
153 }
154 }
155 return AppendInput(tx, h.sealer, InputEvent{
156 TabID: h.tabID, RowID: rowID, ColID: colID, ActorID: actor,
157 OldRaw: prevRaw, NewRaw: raw,
158 })
159 })
160 }); err != nil {
161 return nil, false, err
162 }
163 h.nextVersion++
164 h.rawText[key] = raw
165 h.graph.SetFormula(key, node)
166 h.keyToIDs[key] = cellIDs{RowID: rowID, ColID: colID}
167
168 touched, ok := h.recalcTouched(key, true)
169 if !ok {
170 // recalcTouched refuses only past calc.MaxDirtyPerPass here:
171 // includeOrigin puts this cell in the set, so the set is never
172 // empty on this path.
173 return nil, true, nil
174 }
175 if err := h.persistTouched(touched, v); err != nil {
176 return nil, false, err
177 }
178 return touched, false, nil
179}
180
181// markDirty is defined in handle_batch.go, alongside the crash-recovery
182// batching it shares its "bounded number of statements, not one per
183// touched cell" shape with.
184
185// recalcTouched computes origin's touched set — TransitiveDependents,
186// plus origin itself if includeOrigin — and, if it is within
187// calc.MaxDirtyPerPass, runs Graph.Recalc so every touched cell's
188// in-memory cache is current, returning that set with ok=true. Past the
189// cap (or with nothing touched), it does nothing and returns ok=false —
190// the touched set is computed BEFORE Recalc is called specifically so
191// this can be decided without running Recalc at all, matching (not
192// duplicating) Recalc's own cap. See calc.MaxDirtyPerPass's comment for
193// why an over-wide pass is refused rather than run.
194//
195// Split out from the recompute-and-persist pair so a caller that wants
196// to recompute several origins before persisting any of them
197// (recoverStale, handle_batch.go) can do the cheap in-memory part here
198// and defer the expensive part — a transaction commit — to its own
199// batching. setContent and setBlank call it and then persistTouched
200// directly, one commit per Set.
201func (h *Handle) recalcTouched(origin calc.CellKey, includeOrigin bool) (map[calc.CellKey]struct{}, bool) {
202 touched := h.graph.TransitiveDependents(origin)
203 if includeOrigin {
204 touched[origin] = struct{}{}
205 }
206 if len(touched) == 0 || len(touched) > calc.MaxDirtyPerPass {
207 return nil, false
208 }
209 h.graph.Recalc(origin, newHandleEnv())
210 return touched, true
211}
212
213// persistTouched writes each cell in touched's current graph-cached
214// value — sealed as CachedSealed, stamped CacheVersion=v — in one
215// transaction, plus a recalc marker recording how wide the pass was.
216// Callers are expected to have already run Graph.Recalc (or otherwise
217// ensured every touched key has a current cached value) before calling
218// this; a key with nothing cached persists as KindEmpty rather than
219// erroring, matching decodeValue's own empty-input convention.
220//
221// triggerID 0 in the AppendRecalc call below: AppendInput does not hand
222// back the id of the event row it just created, and correlating one
223// would cost a second query for bookkeeping only — the marker's real
224// job, the derived-count, is unaffected. See events.go.
225//
226// Marker granularity is caller-defined, not fixed by this function:
227// setContent/recalcAndPersist call this once per Set, so one marker
228// covers one origin's touched set. recoverStale (handle_batch.go) calls
229// this once per BATCH of up to openRecoveryBatchSize origins during
230// Open's crash recovery, so during batched recovery one marker's
231// DerivedCount covers however many cells that whole batch touched, not
232// one origin's — marker cardinality no longer matches origin
233// cardinality there. This is safe specifically because triggerID is
234// already 0 unconditionally, on every call site, not just the batched
235// one: it has never claimed to name the one event that caused a given
236// marker's cells to be touched, so a marker covering several origins'
237// worth of recomputation asserts nothing false about which trigger
238// caused it — there was never a single-trigger claim to violate.
239func (h *Handle) persistTouched(touched map[calc.CellKey]struct{}, v uint64) error {
240 return h.db.Transaction(func(tx *gorm.DB) error {
241 if err := h.advanceContentVersion(tx, v); err != nil {
242 return err
243 }
244 for key := range touched {
245 ids, ok := h.keyToIDs[key]
246 if !ok {
247 continue // defensive: every touched key was registered via SetFormula
248 }
249 val, _ := h.graph.CachedValue(key)
250 sealedCache, err := h.sealer.Seal("cell.cached", encodeValue(val))
251 if err != nil {
252 return err
253 }
254 if err := tx.Model(&Cell{}).
255 Where("tab_id = ? AND row_id = ? AND col_id = ?", h.tabID, ids.RowID, ids.ColID).
256 Updates(map[string]any{
257 "cached_sealed": sealedCache,
258 "cache_version": v,
259 }).Error; err != nil {
260 return err
261 }
262 }
263 return AppendRecalc(tx, 0, len(touched))
264 })
265}
266