oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "errors"
5 "strings"
6 "time"
7
8 "gorm.io/gorm"
9
10 "amadan.net/oficina/sheets/internal/sheets/store"
11)
12
13// maxTitleRunes caps a sheet title. It is a UI-shaped limit, not a
14// storage one — the sealed column would take anything — and exists so a
15// pasted paragraph cannot become a sheet name that breaks every row of
16// the list.
17const maxTitleRunes = 200
18
19// firstTabName is what a new sheet's only tab is called. Sealed like
20// any other tab name: a tab name is sheet content (spec §2.1), and the
21// fact that this particular one is predictable does not make it exempt —
22// an exemption would be a plaintext write on the same column every
23// sealed name uses.
24const firstTabName = "Sheet 1"
25
26// The grid paints a window, never a whole tab. Spec §6's reasoning for
27// the 200,000-cell cap is that a tab rendered whole is a
28// several-hundred-megabyte page; a window is the smallest thing that
29// honours it, and it is a window rather than virtual scrolling because
30// virtualisation is a lot of client code to write before anybody has
31// typed into a single cell.
32//
33// defaultWindow* is what a page opens with. maxWindow* is what a
34// request may ask for: past it the numbers are clamped, not refused,
35// because refusing turns a too-wide window into a broken page while
36// clamping turns it into a slightly smaller one.
37const (
38 defaultWindowRows = 100
39 defaultWindowCols = 26 // A..Z, which is what a person expects to see
40 maxWindowRows = 500
41 maxWindowCols = 60
42)
43
44// errNoSealer is returned rather than panicking when an App built
45// without a sealer (page-rendering tests) reaches a path that needs one.
46var errNoSealer = errors.New("sheets: no sealer configured")
47
48// SheetSummary is one row of the sheet list: what a list row or a page
49// header needs, with the title already unsealed.
50//
51// TabID is the sheet's FIRST tab, which is the one a bare /sheets/{id}
52// opens. Carrying it here means the grid page never has to query for it,
53// and multi-tab navigation later adds a field rather than a round trip.
54type SheetSummary struct {
55 ID uint64
56 Title string
57 TabID uint64
58 // TabName is the first tab's name, for the tab strip along the
59 // bottom of the grid. Sealed at rest like every other piece of
60 // authored text, and unsealed here beside the title so the page has
61 // one place that opens a sheet's names rather than two.
62 //
63 // A tab whose name will not unseal falls back to "Sheet 1" rather
64 // than failing the page: the strip is chrome, and a grid nobody can
65 // open because its tab has an unreadable name is a worse outcome
66 // than a tab labelled generically.
67 TabName string
68 UpdatedAt time.Time
69}
70
71// createSheet makes a sheet and its first tab in one transaction.
72//
73// One transaction because a sheet with no tab is not openable: it would
74// appear in the list and then 404 when clicked. Nothing outside this
75// function ever creates a Sheet row, which is what makes "every sheet
76// has at least one tab" a real invariant rather than a convention
77// everyone remembers.
78// createSheet makes an ordinary, immediately visible sheet.
79//
80// g is the request's write guard (team_guard.go: member-only in team
81// mode), run inside the transaction; nil outside team mode.
82func (a *App) createSheet(g store.Guard, title string, by Member) (SheetSummary, error) {
83 return a.newSheet(g, title, by, false)
84}
85
86// createFillingSheet makes a sheet that is HIDDEN until something
87// finishes filling it — import's shape (store.Sheet.FillingSince).
88//
89// The caller owns the other half: markFilled on success, discardSheet
90// on failure. A caller that does neither leaves an invisible row, which
91// is the failure this is designed to have.
92func (a *App) createFillingSheet(g store.Guard, title string, by Member) (SheetSummary, error) {
93 return a.newSheet(g, title, by, true)
94}
95
96func (a *App) newSheet(g store.Guard, title string, by Member, filling bool) (SheetSummary, error) {
97 return a.newSheetWithTab(g, title, firstTabName, by, filling)
98}
99
100// newSheetWithTab shares the ordinary creation transaction and owner grant.
101// Agent callers validate their explicit first-tab name before entering it.
102func (a *App) newSheetWithTab(g store.Guard, title, tabName string, by Member, filling bool) (SheetSummary, error) {
103 if a.db == nil {
104 return SheetSummary{}, errNoDB
105 }
106 if a.sealer == nil {
107 return SheetSummary{}, errNoSealer
108 }
109 clean := strings.TrimSpace(title)
110 if clean == "" {
111 return SheetSummary{}, errors.New("sheets: a sheet needs a title")
112 }
113 if r := []rune(clean); len(r) > maxTitleRunes {
114 clean = string(r[:maxTitleRunes])
115 }
116 sealedTitle, err := a.sealer.Seal("sheet.title", []byte(clean))
117 if err != nil {
118 return SheetSummary{}, err
119 }
120 sealedName, err := a.sealer.Seal("tab.name", []byte(tabName))
121 if err != nil {
122 return SheetSummary{}, err
123 }
124
125 sheet := store.Sheet{TitleSealed: sealedTitle, CreatedBy: by.ID}
126 if filling {
127 now := time.Now().UTC()
128 sheet.FillingSince = &now
129 }
130 tab := store.Tab{NameSealed: sealedName, Position: 0}
131 if err := a.db.Transaction(func(tx *gorm.DB) error {
132 return g.Run(func() error {
133 if err := tx.Create(&sheet).Error; err != nil {
134 return err
135 }
136 tab.SheetID = sheet.ID
137 if err := tx.Create(&tab).Error; err != nil {
138 return err
139 }
140 // The creator owns it, written here rather than inferred from
141 // Sheet.CreatedBy. Inferring would mean two sources of truth
142 // for one question, and the share screen could not then take
143 // ownership away or hand it on.
144 return tx.Create(&Grant{
145 SheetID: sheet.ID, MemberID: by.ID,
146 Role: string(SheetOwner), GrantedBy: by.ID,
147 }).Error
148 })
149 }); err != nil {
150 return SheetSummary{}, err
151 }
152 return SheetSummary{
153 ID: sheet.ID, Title: clean, TabID: tab.ID,
154 TabName: tabName, UpdatedAt: sheet.UpdatedAt,
155 }, nil
156}
157
158// listSheets returns the sheets a member may see, most recently
159// touched first.
160//
161// It grew the hand-written grants join the previous comment here
162// promised — visibleSheets, grants.go — and it did NOT grow a
163// scope.Owned. scope.Owned is single-column equality on user_id, our
164// sheets are team-shared, and applied here it would return only the
165// sheets somebody created: a plausible short list rather than an error
166// (AGENTS.md / Mechanical rules).
167//
168// A team owner or member sees every sheet, which is what one instance
169// per team means. A guest sees exactly what they were granted.
170func (a *App) listSheets(viewer Member) ([]SheetSummary, error) {
171 if a.db == nil {
172 return nil, errNoDB
173 }
174 if a.sealer == nil {
175 return nil, errNoSealer
176 }
177 rows, err := a.visibleSheets(viewer)
178 if err != nil {
179 return nil, err
180 }
181 out := make([]SheetSummary, 0, len(rows))
182 for _, s := range rows {
183 sum, err := a.summarize(s)
184 if err != nil {
185 return nil, err
186 }
187 out = append(out, sum)
188 }
189 return out, nil
190}
191
192// sheetSummary reads one sheet a viewer may see.
193//
194// A sheet that is not there and a sheet they may not reach are the same
195// answer, on purpose: handlers turn both into a 404, never a 403
196// (AGENTS.md). A 403 confirms the row exists, and on an instance where
197// guests hold single-sheet grants the set of ids that 403 is a map of
198// the team's sheets.
199func (a *App) sheetSummary(id uint64, viewer Member) (SheetSummary, error) {
200 if a.db == nil {
201 return SheetSummary{}, errNoDB
202 }
203 if a.sealer == nil {
204 return SheetSummary{}, errNoSealer
205 }
206 if !a.mayRead(id, viewer) {
207 return SheetSummary{}, errNoAccess
208 }
209 var s store.Sheet
210 if err := a.db.Where("id = ? AND deleted_at IS NULL AND filling_since IS NULL", id).First(&s).Error; err != nil {
211 return SheetSummary{}, err
212 }
213 return a.summarize(s)
214}
215
216// tabBelongsTo reports whether a tab is part of a sheet.
217//
218// Every grid and stream route takes both ids from the URL, so without
219// this a caller could pair any sheet id with any tab id and read a tab
220// through a sheet it does not belong to. Once grants exist, the sheet is
221// where permission will be checked, which makes this pairing check the
222// thing that keeps the permission meaningful.
223func (a *App) tabBelongsTo(sheetID, tabID uint64) bool {
224 if a.db == nil {
225 return false
226 }
227 var n int64
228 if err := a.db.Model(&store.Tab{}).
229 Where("id = ? AND sheet_id = ?", tabID, sheetID).Count(&n).Error; err != nil {
230 return false
231 }
232 return n == 1
233}
234
235// touchSheet bumps a sheet's UpdatedAt so the list orders by real
236// activity rather than by creation. Called on every cell write; a
237// failure is not worth failing the write over, so callers ignore the
238// error and the list is merely stale.
239func (a *App) touchSheet(sheetID uint64) {
240 if a.db == nil {
241 return
242 }
243 a.db.Model(&store.Sheet{}).Where("id = ?", sheetID).
244 Update("updated_at", time.Now().UTC())
245}
246
247// summarize unseals a Sheet row's title and finds its first tab.
248func (a *App) summarize(s store.Sheet) (SheetSummary, error) {
249 title, err := a.sealer.Open("sheet.title", s.TitleSealed)
250 if err != nil {
251 return SheetSummary{}, err
252 }
253 var tab store.Tab
254 if err := a.db.Where("sheet_id = ?", s.ID).
255 Order("position ASC, id ASC").First(&tab).Error; err != nil {
256 return SheetSummary{}, err
257 }
258 return SheetSummary{
259 ID: s.ID, Title: string(title), TabID: tab.ID,
260 TabName: tabName(a, tab), UpdatedAt: s.UpdatedAt,
261 }, nil
262}
263
264// tabName unseals a tab's name, falling back to a generic label.
265//
266// The fallback is for a name that will not open — a row written under a
267// key this process does not have. It is not for an empty NameSealed:
268// newSheet has always sealed firstTabName, so no tab this app has
269// made lacks one. Either way the answer is the same and it is the
270// right one: the tab strip is chrome, and a grid nobody can open
271// because its tab's name is unreadable is a worse outcome than a tab
272// labelled generically.
273func tabName(a *App, tab store.Tab) string {
274 if len(tab.NameSealed) == 0 {
275 return "Sheet 1"
276 }
277 name, err := a.sealer.Open("tab.name", tab.NameSealed)
278 if err != nil || len(name) == 0 {
279 return "Sheet 1"
280 }
281 return string(name)
282}
283