| 1 | package store |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/sheets/internal/sheets/calc" |
| 5 | "context" |
| 6 | "errors" |
| 7 | |
| 8 | "gorm.io/gorm" |
| 9 | ) |
| 10 | |
| 11 | const MaxCellBatch = 500 |
| 12 | |
| 13 | type CellWrite struct { |
| 14 | Row, Col int |
| 15 | Raw string |
| 16 | } |
| 17 | |
| 18 | var errCellBatch = errors.New("store: invalid cell batch") |
| 19 | |
| 20 | // ErrRevisionConflict means the tab changed since the caller's snapshot. |
| 21 | var ErrRevisionConflict = errors.New("store: tab revision changed") |
| 22 | |
| 23 | // BatchTransaction runs under the canonical handle lock and one writer |
| 24 | // transaction. It may call apply once, with the expected next-stamp watermark, |
| 25 | // or skip it for a completed receipt. It must use tx for every database read |
| 26 | // and must not call another locking method on the handle. Returning an error |
| 27 | // rolls back both the batch and the caller's receipt/authority work. |
| 28 | type BatchTransaction func(tx *gorm.DB, apply func(expected uint64) (uint64, error)) error |
| 29 | |
| 30 | // ValidateCellWrites uses the same shape and parser checks as SetBatch. |
| 31 | func ValidateCellWrites(writes []CellWrite) error { |
| 32 | if len(writes) == 0 || len(writes) > MaxCellBatch { |
| 33 | return errCellBatch |
| 34 | } |
| 35 | seen := make(map[[2]int]bool, len(writes)) |
| 36 | for _, w := range writes { |
| 37 | pos := [2]int{w.Row, w.Col} |
| 38 | if w.Row < 0 || w.Col < 0 || seen[pos] { |
| 39 | return errCellBatch |
| 40 | } |
| 41 | seen[pos] = true |
| 42 | if _, _, err := contentNode(w.Raw); err != nil { |
| 43 | return errCellBatch |
| 44 | } |
| 45 | } |
| 46 | return nil |
| 47 | } |
| 48 | |
| 49 | func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) { |
| 50 | return h.setBatch(nil, writes, actor) |
| 51 | } |
| 52 | func (h *Handle) setBatch(g Guard, writes []CellWrite, actor uint64) (Report, error) { |
| 53 | return h.SetBatchInTransaction(context.Background(), g, writes, actor, nil) |
| 54 | } |
| 55 | |
| 56 | // SetBatchInTransaction extends the native batch with app-owned transactional |
| 57 | // checks and receipts. Only a committed fresh batch replaces the cached graph. |
| 58 | func (h *Handle) SetBatchInTransaction(ctx context.Context, g Guard, writes []CellWrite, actor uint64, run BatchTransaction) (Report, error) { |
| 59 | if err := ValidateCellWrites(writes); err != nil { |
| 60 | return Report{}, err |
| 61 | } |
| 62 | |
| 63 | h.mu.Lock() |
| 64 | defer h.mu.Unlock() |
| 65 | |
| 66 | var staged *Handle |
| 67 | var result Report |
| 68 | err := h.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 69 | return g.Run(func() error { |
| 70 | used := false |
| 71 | var applyErr error |
| 72 | apply := func(expected uint64) (revision uint64, failure error) { |
| 73 | defer func() { applyErr = failure }() |
| 74 | if used { |
| 75 | return 0, errCellBatch |
| 76 | } |
| 77 | used = true |
| 78 | var err error |
| 79 | staged, err = buildHandle(tx, h.sealer, h.tabID) |
| 80 | if err != nil { |
| 81 | return 0, err |
| 82 | } |
| 83 | if staged.nextVersion < h.nextVersion { |
| 84 | staged.nextVersion = h.nextVersion |
| 85 | } |
| 86 | if expected != 0 && expected != staged.nextVersion { |
| 87 | return 0, ErrRevisionConflict |
| 88 | } |
| 89 | changed := make(map[CellCoord]ChangedCell) |
| 90 | direct := make(map[CellCoord]bool) |
| 91 | for _, w := range writes { |
| 92 | r, err := staged.EnsureRow(w.Row) |
| 93 | if err != nil { |
| 94 | return 0, err |
| 95 | } |
| 96 | c, err := staged.EnsureCol(w.Col) |
| 97 | if err != nil { |
| 98 | return 0, err |
| 99 | } |
| 100 | rep, err := staged.SetReport(r, c, w.Raw, actor) |
| 101 | if err != nil { |
| 102 | return 0, err |
| 103 | } |
| 104 | if rep.Capped { |
| 105 | return 0, errCellBatch |
| 106 | } |
| 107 | direct[CellCoord{r, c}] = true |
| 108 | result.Version = rep.Version |
| 109 | for _, cell := range rep.Cells { |
| 110 | changed[CellCoord{cell.RowID, cell.ColID}] = cell |
| 111 | } |
| 112 | if len(changed) > calc.MaxDirtyPerPass { |
| 113 | return 0, errCellBatch |
| 114 | } |
| 115 | } |
| 116 | var count int64 |
| 117 | if err := tx.Model(&Cell{}).Where("tab_id = ?", h.tabID).Count(&count).Error; err != nil { |
| 118 | return 0, err |
| 119 | } |
| 120 | if count > MaxCellsPerTab { |
| 121 | return 0, ErrTabTooLarge |
| 122 | } |
| 123 | for coord, cell := range changed { |
| 124 | cell.Derived = !direct[coord] |
| 125 | result.Cells = append(result.Cells, cell) |
| 126 | } |
| 127 | result.Stamps = len(writes) |
| 128 | return staged.nextVersion, nil |
| 129 | } |
| 130 | if run != nil { |
| 131 | if err := run(tx, apply); err != nil { |
| 132 | return err |
| 133 | } |
| 134 | return applyErr |
| 135 | } |
| 136 | _, err := apply(0) |
| 137 | return err |
| 138 | }) |
| 139 | }) |
| 140 | if err != nil { |
| 141 | return Report{}, err |
| 142 | } |
| 143 | if staged == nil { |
| 144 | return Report{}, nil |
| 145 | } |
| 146 | h.graph, h.rawText, h.keyToIDs = staged.graph, staged.rawText, staged.keyToIDs |
| 147 | h.rowPos, h.colPos = staged.rowPos, staged.colPos |
| 148 | h.rowByPos, h.colByPos = staged.rowByPos, staged.colByPos |
| 149 | h.nextVersion = staged.nextVersion |
| 150 | return result, nil |
| 151 | } |
| 152 | |