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 "strings"
8
9 "amadan.net/oficina/sheets/internal/sheets/store"
10)
11
12// maxFormatCells bounds one format write.
13//
14// Formatting a range is a per-cell write — a Format row interned once,
15// then one Cell row updated per coordinate — so "select the column and
16// make it bold" over a hundred-thousand-cell selection is a hundred
17// thousand updates inside one request. Capped rather than streamed
18// because the cap is generous against any selection a person makes by
19// hand, and a bounded refusal beats a request that appears to hang.
20const maxFormatCells = 4000
21
22// handleFormatPost applies a format patch to a rectangle of cells.
23//
24// It is a sibling of handleCellPost and deliberately shaped like it:
25// same auth, same tab resolution, same publish-then-answer, same
26// response type. A format change IS a change to the grid, and a client
27// that had to merge two different response shapes would have two paints
28// that could disagree.
29//
30// **Formatting is not in the event log, so it is not undoable.** Undo
31// is cell-level and replays input events (spec §7); a format carries no
32// event, so Ctrl-Z after bolding undoes the last VALUE edit instead,
33// which is surprising in the way this app tries not to be. It is a
34// deliberate, named limitation of this slice rather than an oversight —
35// the fix is a format event kind, which changes the undo model and is
36// not a thing to do in passing. Until then the UI does not offer undo
37// for formatting.
38func (a *App) handleFormatPost(w http.ResponseWriter, r *http.Request) {
39 // The viewer is checked but not recorded: formatting appends no
40 // event, so there is no actor column to write one to.
41 viewer, ok := a.actor(r)
42 if !ok {
43 http.Error(w, "Sign in first.", http.StatusForbidden)
44 return
45 }
46 h, ok := a.openTab(w, r, SheetEditor)
47 if !ok {
48 return
49 }
50 defer h.Release()
51
52 // One route, two decoders, converging on one patch BEFORE anything
53 // is validated (this slice's decision D). The scriptless table view
54 // posts a form here; the grid posts JSON. Everything below this
55 // point is identical for both, which is what keeps the allowlist,
56 // the bounds and the cell cap from existing twice.
57 var p formatPatch
58 form := isFormPost(r)
59 if form {
60 // The same 8 KiB the JSON branch has always had. Without it the
61 // form path was the one way into this handler with no body
62 // bound at all: FormValue parses the whole request before the
63 // shared maxFormatCells check is anywhere near being reached.
64 r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
65 var ok bool
66 if p, ok = formatFromForm(r); !ok {
67 http.Error(w, "Malformed request.", http.StatusBadRequest)
68 return
69 }
70 } else if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10)).Decode(&p); err != nil {
71 // Not echoed: a number-format pattern is authored content, and
72 // an error string is a log line waiting to happen (AGENTS.md).
73 http.Error(w, "Malformed request.", http.StatusBadRequest)
74 return
75 }
76 if err := p.validate(); err != nil {
77 http.Error(w, "That formatting could not be applied.", http.StatusBadRequest)
78 return
79 }
80 r1, c1, r2, c2, ok := p.normalize(maxWindowRows*10, maxWindowCols*10)
81 if !ok {
82 http.Error(w, "Range out of bounds.", http.StatusBadRequest)
83 return
84 }
85 if (r2-r1+1)*(c2-c1+1) > maxFormatCells {
86 http.Error(w, "That range is too large to format in one go.", http.StatusRequestEntityTooLarge)
87 return
88 }
89
90 coords, err := a.applyFormat(h.Guarded(a.writeGuard(r.Context(), sheetIDFrom(r), viewer, SheetEditor)), h, p, r1, c1, r2, c2)
91 if a.guardRefused(w, r, err) {
92 return
93 }
94 if err != nil {
95 a.fail(w, r, err)
96 return
97 }
98 resp, err := formatResponse(h, coords, p.Client)
99 if err != nil {
100 a.fail(w, r, err)
101 return
102 }
103 a.touchSheet(sheetIDFrom(r))
104 a.publish(tabIDFrom(r), resp)
105 if form {
106 // 303 back to the page, so a reload does not re-post the patch.
107 //
108 // The target is BUILT HERE from the sheet id in the path and a
109 // page number this function bounds itself — never taken from
110 // the request. A caller-supplied return is an open redirect,
111 // and this repo has already shipped one fix in that family
112 // (fix/safe-return-backslash).
113 http.Redirect(w, r, tableReturn(sheetIDFrom(r), r.FormValue("page")), http.StatusSeeOther)
114 return
115 }
116 writeJSON(w, http.StatusOK, resp)
117}
118
119// isFormPost reports whether this request is the scriptless table
120// view's rather than the grid's.
121//
122// Content-Type and not a query flag or a hidden field: the body's own
123// encoding is the thing that actually differs, a flag could disagree
124// with it, and r.FormValue on a JSON body silently reads nothing at all
125// — which would decode as a patch of zeroes rather than as an error.
126// Only url-encoded. multipart/form-data was accepted by the first
127// version of this and is not: the rendered form posts url-encoded, so
128// multipart bought nothing and cost a parser that will happily read a
129// far larger body than the cap above intends before any of this
130// handler's own bounds apply.
131func isFormPost(r *http.Request) bool {
132 return strings.HasPrefix(r.Header.Get("Content-Type"),
133 "application/x-www-form-urlencoded")
134}
135
136// tableReturn builds the table page URL to send a form caller back to.
137//
138// page is parsed and bounded rather than concatenated: it arrives from
139// the form, and the one thing a redirect target must not contain is
140// anything the caller chose. An unparseable or out-of-range page falls
141// back to the first, which is a worse landing than the one they came
142// from and a better one than a URL somebody else wrote.
143func tableReturn(sheetID uint64, page string) string {
144 n, err := strconv.Atoi(page)
145 pages := (maxWindowRows + tableRowsPerPage - 1) / tableRowsPerPage
146 if err != nil || n < 1 || n > pages {
147 n = 1
148 }
149 return "/sheets/" + strconv.FormatUint(sheetID, 10) + "/table?page=" + strconv.Itoa(n)
150}
151
152// applyFormat writes the patch across the rectangle and returns the
153// coordinates it touched.
154//
155// Every cell in the range is visited, including blank ones: a coloured
156// header nobody has typed into yet is a real thing to want, and
157// store.Handle.SetFormat creates the Cell row to carry it.
158//
159// Each cell's format is written through wr, the handle under the
160// request's write guard (team_guard.go).
161func (a *App) applyFormat(wr store.Writer, h *store.Handle, p formatPatch, r1, c1, r2, c2 int) ([]store.CellCoord, error) {
162 existing, err := h.Formats()
163 if err != nil {
164 return nil, err
165 }
166
167 out := make([]store.CellCoord, 0, (r2-r1+1)*(c2-c1+1))
168 for row := r1; row <= r2; row++ {
169 rowID, err := h.EnsureRow(row)
170 if err != nil {
171 return nil, err
172 }
173 for col := c1; col <= c2; col++ {
174 colID, err := h.EnsureCol(col)
175 if err != nil {
176 return nil, err
177 }
178 coord := store.CellCoord{RowID: rowID, ColID: colID}
179
180 // The cell's CURRENT format is the base, so a patch that
181 // only sets bold keeps the fill somebody applied earlier.
182 // Merging against the zero value instead would make every
183 // toolbar button a reset button for the other eight.
184 base := store.Format{}
185 if f, ok := existing[coord]; ok && f != nil {
186 base = *f
187 }
188 if err := wr.SetFormat(rowID, colID, p.applyTo(base)); err != nil {
189 return nil, err
190 }
191 out = append(out, coord)
192 }
193 }
194 return out, nil
195}
196
197// formatResponse re-reads the touched cells and builds the paint.
198//
199// Re-read rather than predicted, for one reason worth stating: a number
200// format changes the DISPLAY string, and the server owns every string
201// on screen (grid.go's display). A response that echoed the patch and
202// left the client to re-render would put a number-format implementation
203// in JavaScript, which is the one thing this design will not do.
204func formatResponse(h *store.Handle, coords []store.CellCoord, client string) (gridResponse, error) {
205 idx := newPosIndex(h)
206 formats, err := h.Formats()
207 if err != nil {
208 return gridResponse{}, err
209 }
210 col := newCollector(formats)
211
212 cells := make([]gridCell, 0, len(coords))
213 for _, c := range coords {
214 rowPos, ok := idx.rowPos[c.RowID]
215 if !ok {
216 continue
217 }
218 colPos, ok := idx.colPos[c.ColID]
219 if !ok {
220 continue
221 }
222 raw, _ := h.RawInput(c.RowID, c.ColID)
223 cells = append(cells, gridCell{
224 R: rowPos, C: colPos,
225 Raw: raw,
226 Display: display(h.Value(c.RowID, c.ColID), col.numFmtFor(c.RowID, c.ColID)),
227 Num: isNumber(h.Value(c.RowID, c.ColID)),
228 F: col.keyFor(c.RowID, c.ColID),
229 })
230 }
231 return gridResponse{
232 // The tab's version is unchanged: a format writes no input
233 // event, so nothing has advanced it. Sending the current
234 // version rather than zero matters — applyBatch discards a
235 // batch whose version TRAILS what it has painted, and zero
236 // would be discarded by every client that had ever seen an
237 // edit.
238 Version: h.Version(),
239 Cells: cells,
240 Formats: col.done(),
241 Client: client,
242 }, nil
243}
244