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 "encoding/json"
5 "net/http"
6 "strconv"
7
8 "github.com/go-chi/chi/v5"
9
10 "amadan.net/oficina/sheets/internal/sheets/live"
11 "amadan.net/oficina/sheets/internal/sheets/store"
12)
13
14// maxRawBytes caps one cell's input.
15//
16// A formula or a label, not a document. The engine would happily parse
17// a megabyte of nesting and spend a long time doing it, and the cell
18// that holds it is one nobody can read anyway. The number is
19// store.MaxInputBytes, which import holds normalised text to as well.
20const maxRawBytes = store.MaxInputBytes
21
22// cellWrite is the POST body.
23//
24// An explicit struct, decoded field by field — never bound onto a GORM
25// model (AGENTS.md), which would let a request set UpdatedBy, a version
26// or a tab id.
27type cellWrite struct {
28 R int `json:"r"`
29 C int `json:"c"`
30 Raw string `json:"raw"`
31 Client string `json:"client"`
32
33 // FromR and FromC name the cell this input was COPIED FROM, and
34 // turn an ordinary write into spec §4.2's translation pass: every
35 // relative reference in Raw is offset by the destination minus the
36 // origin before anything is stored. Absent — the ordinary case,
37 // somebody typing — nothing is translated.
38 //
39 // Pointers, so "copied from row 0" and "not a copy" are different
40 // requests. With plain ints they are the same zero value, and every
41 // paste into row 0 or column A would translate by its full offset
42 // from a cell nobody copied.
43 FromR *int `json:"fromR"`
44 FromC *int `json:"fromC"`
45}
46
47// origin validates the copy origin and returns the offset to apply.
48//
49// The bounds are the same ones the destination is checked against, and
50// for the same reason: both come from the request. An unbounded origin
51// asks calc to offset a reference by millions and Render to print a
52// column label with six letters in it, which parses back as a name.
53func (in cellWrite) origin() (dRow, dCol int, ok bool) {
54 if in.FromR == nil || in.FromC == nil {
55 return 0, 0, true
56 }
57 if !inCellRange(*in.FromR, *in.FromC) {
58 return 0, 0, false
59 }
60 return in.R - *in.FromR, in.C - *in.FromC, true
61}
62
63// inCellRange is the one definition of "a coordinate this route will
64// accept", used for the destination and for the copy origin. Two copies
65// of it is two places for the bound to drift.
66func inCellRange(r, c int) bool {
67 return r >= 0 && c >= 0 && r < maxWindowRows*10 && c < maxWindowCols*10
68}
69
70// handleCellsGet serves a window of a tab.
71func (a *App) handleCellsGet(w http.ResponseWriter, r *http.Request) {
72 h, ok := a.openTab(w, r, SheetViewer)
73 if !ok {
74 return
75 }
76 defer h.Release()
77
78 rows := clamp(intParam(r, "rows"), defaultWindowRows, maxWindowRows)
79 cols := clamp(intParam(r, "cols"), defaultWindowCols, maxWindowCols)
80
81 firstRow, firstCol := intParam(r, "firstRow"), intParam(r, "firstCol")
82 if firstRow < 0 || firstCol < 0 || firstRow >= maxWindowRows || firstCol >= maxWindowCols {
83 http.Error(w, "Window out of range.", 400)
84 return
85 }
86 cells, styles, err := snapshotWindow(h, newPosIndex(h), firstRow, firstCol, rows, cols)
87 if err != nil {
88 a.fail(w, r, err)
89 return
90 }
91 // Sizes ride along with the window rather than needing a second
92 // round trip: they are layout, so a page that fetched them
93 // afterwards would visibly reflow every column once.
94 resp := gridResponse{
95 Version: h.Version(), Rows: rows, Cols: cols, Cells: cells, Formats: styles,
96 }
97 if cw, rh, err := h.Sizes(); err == nil && (len(cw) > 0 || len(rh) > 0) {
98 resp.Sizes = &wireSizes{Cols: intKeys(cw), Rows: intKeys(rh)}
99 }
100 writeJSON(w, http.StatusOK, resp)
101}
102
103// handleCellPost writes one cell and fans the result out.
104func (a *App) handleCellPost(w http.ResponseWriter, r *http.Request) {
105 actor, ok := a.actor(r)
106 if !ok {
107 http.Error(w, "Sign in first.", http.StatusForbidden)
108 return
109 }
110 h, ok := a.openTab(w, r, SheetEditor)
111 if !ok {
112 return
113 }
114 defer h.Release()
115
116 var in cellWrite
117 if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRawBytes*2)).Decode(&in); err != nil {
118 // The body is not echoed. It is a cell's contents, and an error
119 // string is a log line waiting to happen (AGENTS.md).
120 http.Error(w, "Malformed request.", http.StatusBadRequest)
121 return
122 }
123 if !inCellRange(in.R, in.C) {
124 http.Error(w, "Cell out of range.", http.StatusBadRequest)
125 return
126 }
127 if len(in.Raw) > maxRawBytes {
128 http.Error(w, "Cell input too long.", http.StatusRequestEntityTooLarge)
129 return
130 }
131 // §4.2's translation pass, before the length check has any more
132 // work to do and before anything reaches the store: what is written
133 // and what the formula bar later shows must be the same string, so
134 // the rewrite happens here and not on the way back out.
135 dRow, dCol, ok := in.origin()
136 if !ok {
137 http.Error(w, "Cell out of range.", http.StatusBadRequest)
138 return
139 }
140 in.Raw = translateCopied(in.Raw, dRow, dCol)
141 // Re-checked AFTER translating. Render is not length-preserving —
142 // "A1" becomes "AA100" — so a formula that fitted on the way in can
143 // exceed the cap on the way to storage, and the check above would
144 // have passed it. Cheap, and the alternative is a stored cell
145 // larger than the limit this route advertises.
146 if len(in.Raw) > maxRawBytes {
147 http.Error(w, "Cell input too long.", http.StatusRequestEntityTooLarge)
148 return
149 }
150
151 // EnsureRow/EnsureCol so typing into a cell nothing has touched
152 // works: a tab starts with no rows or columns at all, and a grid
153 // coordinate has to become a stable id before anything can be
154 // written to it.
155 rowID, err := h.EnsureRow(in.R)
156 if err != nil {
157 a.fail(w, r, err)
158 return
159 }
160 colID, err := h.EnsureCol(in.C)
161 if err != nil {
162 a.fail(w, r, err)
163 return
164 }
165
166 rep, err := h.Guarded(a.writeGuard(r.Context(), sheetIDFrom(r), actor, SheetEditor)).SetReport(rowID, colID, in.Raw, actor.ID)
167 if a.guardRefused(w, r, err) {
168 return
169 }
170 if err != nil {
171 // A parse failure is the caller's fault and a storage failure is
172 // ours, but neither may quote the input, so both answer the same
173 // fixed string with the coordinate the caller already knows.
174 http.Error(w, "That cell could not be written.", http.StatusBadRequest)
175 return
176 }
177
178 cells, styles := fromReport(rep, newPosIndex(h), h)
179 resp := gridResponse{
180 Version: rep.Version,
181 Cells: cells,
182 Formats: styles,
183 Resync: rep.Capped,
184 Stamps: rep.Stamps,
185 Client: in.Client,
186 }
187 a.touchSheet(sheetIDFrom(r))
188 a.publish(tabIDFrom(r), resp)
189 writeJSON(w, http.StatusOK, resp)
190}
191
192// publish fans a write out to every other tab on this one.
193//
194// Marshalled once here rather than once per subscriber: with ten tabs
195// open, encoding per subscriber is ten encodings of identical bytes.
196func (a *App) publish(tabID uint64, resp gridResponse) {
197 if a.hub == nil || tabID == 0 {
198 return
199 }
200 data, err := marshalGrid(resp)
201 if err != nil {
202 return
203 }
204 a.hub.Publish(tabID, live.Message{Version: resp.Version, Data: data})
205}
206
207// openTab resolves {sheetID}/{tabID}, checks the viewer holds at least
208// `need` on the sheet, and opens the tab's handle. It answers for
209// itself if it cannot; the bool is whether the caller should carry on.
210//
211// The tab is checked against the sheet, not just looked up: both ids
212// come from the URL, so without the pairing check any tab could be read
213// through any sheet, and the sheet id in the path — the thing the grant
214// is keyed on — would mean nothing.
215//
216// Every refusal here is a 404. A viewer asking to write, and a stranger
217// asking to read, both get the same answer as a sheet that does not
218// exist. Anything else lets somebody enumerate the team's sheets by
219// status code.
220func (a *App) openTab(w http.ResponseWriter, r *http.Request, need SheetRole) (*store.Handle, bool) {
221 if a.db == nil || a.sealer == nil {
222 a.fail(w, r, errNoSealer)
223 return nil, false
224 }
225 viewer, ok := a.actor(r)
226 if !ok {
227 a.notFound(w, r)
228 return nil, false
229 }
230 sheetID, tabID := sheetIDFrom(r), tabIDFrom(r)
231 if sheetID == 0 || tabID == 0 || !a.tabBelongsTo(sheetID, tabID) {
232 a.notFound(w, r)
233 return nil, false
234 }
235 if role, has := a.roleFor(sheetID, viewer); !has || !role.Allows(need) {
236 a.notFound(w, r)
237 return nil, false
238 }
239 h, err := store.Open(a.db, a.sealer, tabID)
240 if err != nil {
241 a.fail(w, r, err)
242 return nil, false
243 }
244 return h, true
245}
246
247func sheetIDFrom(r *http.Request) uint64 { return uintParam(r, "sheetID") }
248func tabIDFrom(r *http.Request) uint64 { return uintParam(r, "tabID") }
249
250// uintParam reads a path parameter. A malformed one is 0, which every
251// caller treats as "not found" — a URL that was never ours.
252func uintParam(r *http.Request, name string) uint64 {
253 v, err := strconv.ParseUint(chi.URLParam(r, name), 10, 64)
254 if err != nil {
255 return 0
256 }
257 return v
258}
259
260// intParam reads a query parameter, defaulting to 0 so clamp can apply
261// the real default in one place.
262func intParam(r *http.Request, name string) int {
263 v, err := strconv.Atoi(r.URL.Query().Get(name))
264 if err != nil {
265 return 0
266 }
267 return v
268}
269
270// writeJSON sends a response. An encode failure means the connection is
271// already gone, so there is nothing left to say about it.
272func writeJSON(w http.ResponseWriter, status int, resp gridResponse) {
273 w.Header().Set("Cache-Control", "no-store")
274 w.Header().Set("Content-Type", "application/json; charset=utf-8")
275 w.WriteHeader(status)
276 _ = json.NewEncoder(w).Encode(resp)
277}
278