| 1 | package store |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "math" |
| 6 | |
| 7 | "amadan.net/oficina/sheets/internal/sheets/calc" |
| 8 | ) |
| 9 | |
| 10 | // RangeCell is one coordinate and its raw/calculated content at one watermark. |
| 11 | type RangeCell struct { |
| 12 | Row, Col int |
| 13 | Raw string |
| 14 | Value calc.Value |
| 15 | } |
| 16 | type RangeSnapshot struct { |
| 17 | Version uint64 |
| 18 | Cells []RangeCell |
| 19 | } |
| 20 | |
| 21 | // ReadRange takes one lock for inputs, calculated values and next-stamp version. |
| 22 | // It never grows axes or evaluates a formula. App authority is checked upstream. |
| 23 | func (h *Handle) ReadRange(row, col, height, width int) (RangeSnapshot, error) { |
| 24 | if row < 0 || col < 0 || height < 1 || width < 1 || height > MaxCellBatch || width > MaxCellBatch || height > MaxCellBatch/width || row > math.MaxInt-height || col > math.MaxInt-width { |
| 25 | return RangeSnapshot{}, errors.New("store: invalid range") |
| 26 | } |
| 27 | h.mu.Lock() |
| 28 | defer h.mu.Unlock() |
| 29 | // A capped browser edit leaves durable dirty markers and old graph caches. |
| 30 | // Refuse the tab until recovery completes; never label those values current. |
| 31 | var stale int |
| 32 | if err := h.db.Raw("SELECT 1 FROM cells WHERE tab_id=? AND cache_version < input_version LIMIT 1", h.tabID).Scan(&stale).Error; err != nil { |
| 33 | return RangeSnapshot{}, err |
| 34 | } |
| 35 | if stale != 0 { |
| 36 | return RangeSnapshot{}, errors.New("store: calculation incomplete") |
| 37 | } |
| 38 | out := RangeSnapshot{Version: h.nextVersion, Cells: make([]RangeCell, 0, height*width)} |
| 39 | for r := row; r < row+height; r++ { |
| 40 | for c := col; c < col+width; c++ { |
| 41 | key := calc.CellKey{RowID: uint64(r) + 1, ColID: uint64(c) + 1} |
| 42 | value, cached := h.graph.CachedValue(key) |
| 43 | if !cached && h.rawText[key] != "" { |
| 44 | return RangeSnapshot{}, errors.New("store: calculation cache unavailable") |
| 45 | } |
| 46 | out.Cells = append(out.Cells, RangeCell{Row: r, Col: c, Raw: h.rawText[key], Value: value}) |
| 47 | } |
| 48 | } |
| 49 | return out, nil |
| 50 | } |
| 51 | |