oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package xlsx converts between an XLSX workbook and one tab of this
2// app's own storage (internal/sheets/store). excelize is confined to
3// this package deliberately: its calc engine works against a file model
4// rather than our dependency graph (internal/sheets/calc), so letting any
5// other package import it would couple our storage to theirs.
6package xlsx
7
8import (
9 "bytes"
10 "errors"
11 "fmt"
12 "io"
13 "sort"
14
15 "github.com/xuri/excelize/v2"
16
17 "amadan.net/oficina/sheets/internal/sheets/store"
18)
19
20// importActor is the actor id Import's own writes are attributed with.
21// Import's signature (fixed by the interface this package implements)
22// carries no caller identity, and the background-job wrapper that would
23// thread a real uploading user's id through (spec §11: "Import runs as a
24// rastrillo background job") is plan 2, not built in this repo yet. 0 is
25// not a real user id anywhere in this schema, so it reads unambiguously
26// as "the system, not a person" in the event log.
27const importActor uint64 = 0
28
29// openLimits bounds what a workbook may decompress to.
30//
31// XLSX is a ZIP, so the size of the upload bounds nothing: excelize's
32// own defaults are UnzipSizeLimit 16GB and an unzipXML limit derived
33// from it, and the caller's byte cap on the HTTP body is a cap on
34// COMPRESSED bytes. A small file of highly compressible XML therefore
35// reaches OpenReader and GetRows — both of which materialise what they
36// read — long before Import's own MaxCellsPerTab check gets a chance to
37// refuse it, because that check counts cells that have already been
38// decompressed into memory.
39//
40// UnzipSizeLimit is the hard bound and the one doing the work here:
41// 256MB unzipped is generous for a workbook that has to fit in
42// MaxCellsPerTab (200,000 cells) and small enough that several
43// concurrent imports cannot exhaust an instance.
44//
45// UnzipXMLSizeLimit is NOT a second rejection threshold, whatever its
46// name suggests — excelize uses it to decide when a worksheet or shared
47// string table is large enough to stream through temporary storage
48// instead of memory (its default is StreamChunkSize). Setting it lower
49// than the total therefore bounds resident memory rather than refusing
50// anything, which is worth having and is not the protection.
51//
52// This is a bound, not validation: a legitimate workbook past it is
53// refused the same as a malicious one, and that is the right trade for
54// a limit whose job is to stop the process dying.
55var openLimits = excelize.Options{
56 UnzipSizeLimit: 256 << 20,
57 UnzipXMLSizeLimit: 64 << 20,
58}
59
60// maxWorkbookBytes bounds what Import reads from r. The upload handler
61// caps a file at 20 MB; this is the converter's own bound, since both
62// excelize and the worksheet scan need the whole file in memory.
63const maxWorkbookBytes = 32 << 20
64
65// Import reads an XLSX workbook's first worksheet into h and reports
66// what it changed or left behind.
67//
68// Literal values become literal input; text that would otherwise read
69// as something else is kept as text (store.TextInput). A formula is
70// kept when this app's own engine can calculate it (never excelize's —
71// see the package doc), and its result is compared with the value the
72// workbook saved. Any other formula is replaced by its saved value, and
73// a formula with no trustworthy saved value refuses the whole import:
74// a value is never manufactured. Fill, number format, bold, italic,
75// ink and alignment are carried over via SetFormat.
76//
77// Errors carry coordinates and codes, never cell content (spec §2.4):
78// import runs as a background job whose error text reaches the owner and
79// platform logs this app cannot grep, so "cannot parse cell B7" is what
80// gets said — never what B7 actually contained.
81func Import(r io.Reader, h *store.Handle) (Report, error) {
82 data, err := io.ReadAll(io.LimitReader(r, maxWorkbookBytes+1))
83 if err != nil {
84 return Report{}, fmt.Errorf("xlsx: read workbook: %w", err)
85 }
86 if len(data) > maxWorkbookBytes {
87 return Report{}, errScanLimit
88 }
89 f, err := excelize.OpenReader(bytes.NewReader(data), openLimits)
90 if err != nil {
91 return Report{}, fmt.Errorf("xlsx: open workbook: %w", err)
92 }
93 defer f.Close()
94
95 sheetList := f.GetSheetList()
96 if len(sheetList) == 0 {
97 return Report{}, errors.New("xlsx: workbook has no worksheets")
98 }
99 sheetName := sheetList[0]
100
101 // The second reader: what the worksheet XML itself says about
102 // formulas and their saved values. It must name the same first
103 // sheet excelize does, or neither is trusted.
104 scan, err := scanWorkbook(data)
105 if err != nil {
106 return Report{}, fmt.Errorf("xlsx: scan worksheet: %w", err)
107 }
108 if scan.Name != sheetName {
109 return Report{}, errScanInconsistent
110 }
111
112 rows, err := f.GetRows(sheetName, excelize.Options{RawCellValue: true})
113 if err != nil {
114 return Report{}, fmt.Errorf("xlsx: read worksheet: %w", err)
115 }
116
117 // Fail before writing anything: a partial import left behind by
118 // hitting the cap mid-way through would be a confusing half state.
119 positions := cellPositions(rows, scan)
120 if len(positions) > store.MaxCellsPerTab {
121 return Report{}, store.ErrTabTooLarge
122 }
123
124 base, err := f.GetStyle(0)
125 if err != nil {
126 return Report{}, fmt.Errorf("xlsx: read the default style: %w", err)
127 }
128 im := &importer{f: f, sheet: sheetName, h: h, scan: scan, base: base,
129 rep: &Report{Worksheets: len(sheetList)}}
130 for _, p := range positions {
131 raw := ""
132 if p.Row < len(rows) && p.Col < len(rows[p.Row]) {
133 raw = rows[p.Row][p.Col]
134 }
135 if err := im.cell(p, raw); err != nil {
136 return Report{}, err
137 }
138 }
139 im.compare()
140 reportOmissions(f, sheetName, scan, im.rep)
141
142 // Layout last, and best effort. A workbook whose widths cannot be
143 // read is still a workbook whose cells can, and refusing the import
144 // over its margins would trade the document for its formatting.
145 widest := 0
146 for _, p := range positions {
147 widest = max(widest, p.Col+1)
148 }
149 importSizes(f, sheetName, h, len(rows), widest)
150 return *im.rep, nil
151}
152
153// cellPositions is every position import visits, in row-major order:
154// each cell excelize's row reader returned, plus each formula or
155// string cell the scan found. The second half matters because the row
156// reader drops empty values from the end of a row, and a formula whose
157// saved value is "" or an empty-string text cell is not nothing.
158func cellPositions(rows [][]string, scan *sheetScan) []posKey {
159 seen := make(map[posKey]bool, len(scan.Cells))
160 var out []posKey
161 for r, row := range rows {
162 for c := range row {
163 p := posKey{Row: r, Col: c}
164 seen[p] = true
165 out = append(out, p)
166 }
167 }
168 for p := range scan.Cells {
169 if !seen[p] {
170 out = append(out, p)
171 }
172 }
173 sort.Slice(out, func(i, j int) bool {
174 if out[i].Row != out[j].Row {
175 return out[i].Row < out[j].Row
176 }
177 return out[i].Col < out[j].Col
178 })
179 return out
180}
181