| 1 | package sheets |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | |
| 9 | "amadan.net/rastrillo/rastrillo/jobs" |
| 10 | "amadan.net/rastrillo/rastrillo/sessions" |
| 11 | |
| 12 | "amadan.net/oficina/sheets/internal/sheets/xlsx" |
| 13 | ) |
| 14 | |
| 15 | // maxImportBytes caps an upload. A tab holds store.MaxCellsPerTab |
| 16 | // (200,000) cells and an XLSX file is compressed, so 20 MB is far more |
| 17 | // than a workbook that fits can weigh — the cap is here to bound what |
| 18 | // one request can make the process hold, not to express a product |
| 19 | // limit. The cell cap is the product limit, and it is checked by |
| 20 | // xlsx.Import against the real cell count rather than guessed from a |
| 21 | // byte count. |
| 22 | const maxImportBytes = 20 << 20 |
| 23 | |
| 24 | // multipartSlack is what MaxBytesReader gets ON TOP of maxImportBytes. |
| 25 | // |
| 26 | // MaxBytesReader bounds the whole request body — part headers, boundary |
| 27 | // markers and the trailing boundary as well as the file — so reusing |
| 28 | // maxImportBytes as the body limit refuses a file of exactly the size |
| 29 | // the form advertises, and a slightly smaller one too. The form says |
| 30 | // 20 MB, so 20 MB has to get through; the slack covers the framing and |
| 31 | // the file's own size is then checked exactly, against the bytes that |
| 32 | // actually arrived. |
| 33 | const multipartSlack = 1 << 20 |
| 34 | |
| 35 | // importField is the file input's name, in the form and in the handler. |
| 36 | const importField = "file" |
| 37 | |
| 38 | // importJobName is what the status page calls this job, and it is a |
| 39 | // CONSTANT rather than the uploaded filename on purpose: rastrillo's |
| 40 | // jobs package logs the name on every start, finish and failure |
| 41 | // (jobs.run's slog calls), and `carlos logs` is platform-held storage |
| 42 | // we cannot grep. A filename is a sheet title in waiting — AGENTS.md |
| 43 | // forbids it in a log line exactly as it forbids a cell's contents. |
| 44 | const importJobName = "Spreadsheet import" |
| 45 | |
| 46 | // workbookExts are the extensions import accepts. Both are ordinary |
| 47 | // Excel workbooks; .xlsm differs only by carrying macros, which we |
| 48 | // ignore rather than run. |
| 49 | // |
| 50 | // Checked before a sheet is created, because an extension is free to |
| 51 | // check and a person who dropped a PDF should be told so immediately |
| 52 | // rather than through a background job that had to build a sheet in |
| 53 | // order to fail. |
| 54 | var workbookExts = map[string]bool{".xlsx": true, ".xlsm": true} |
| 55 | |
| 56 | // Refusals a person can act on. Each is a whole sentence naming what to |
| 57 | // do differently, because this text is the only thing a person who |
| 58 | // dropped the wrong file has to go on. |
| 59 | const ( |
| 60 | refusalNoFile = "Choose a spreadsheet to import." |
| 61 | refusalNotWorkbook = "That is not an Excel workbook. Import takes .xlsx and .xlsm files." |
| 62 | refusalTooLarge = "That file is bigger than 20 MB, which is more than import takes." |
| 63 | refusalBusy = "You already have an import running. Wait for it to finish, then try again." |
| 64 | refusalUnreadable = "That upload could not be read." |
| 65 | ) |
| 66 | |
| 67 | // handleSheetImport takes an uploaded workbook, makes the sheet it will |
| 68 | // land in, and runs the import as a background job. |
| 69 | // |
| 70 | // The sheet is created HERE, synchronously, rather than inside the job, |
| 71 | // for one reason: jobs.Start needs the finished job's location up front, |
| 72 | // and that location must be a path this code built rather than anything |
| 73 | // a user supplied (jobs.Start's own contract). Knowing the sheet id |
| 74 | // before the job starts is what makes "/sheets/{id}" constructible. |
| 75 | // |
| 76 | // The cost is a sheet row that exists before its contents do, and |
| 77 | // createFillingSheet is what pays it: the row is invisible on every |
| 78 | // read path until runImport reveals it. Cleanup is then a tidiness |
| 79 | // measure rather than the thing correctness rests on — which matters, |
| 80 | // because the one failure no cleanup can cover is the process dying |
| 81 | // mid-import. |
| 82 | func (a *App) handleSheetImport(w http.ResponseWriter, r *http.Request) { |
| 83 | actor, ok := a.actor(r) |
| 84 | if !ok { |
| 85 | a.forbidden(w, r) |
| 86 | return |
| 87 | } |
| 88 | if !a.teamMemberOnly(w, r) { |
| 89 | return |
| 90 | } |
| 91 | // jobs keys ownership on the session Subject, and jobs.Handlers |
| 92 | // reads that same value back out of sessions.Current to decide who |
| 93 | // may see a job. Starting one under any other identifier makes it |
| 94 | // unreachable: Get answers only the owner, so the page we are about |
| 95 | // to redirect to would 404 — a working import that looks like a |
| 96 | // broken one. |
| 97 | sess, ok := sessions.Current(r) |
| 98 | if !ok { |
| 99 | a.forbidden(w, r) |
| 100 | return |
| 101 | } |
| 102 | |
| 103 | // Reclaim here as well as at boot. Boot alone leaves a gap with no |
| 104 | // second chance in it: a process that dies during a YOUNG import is |
| 105 | // replaced by one that starts before the threshold, finds nothing |
| 106 | // old enough to sweep, and never looks again — so the hidden row, |
| 107 | // its cells and its grant sit there until some later restart |
| 108 | // happens to fall the right side of the age check. Importing is the |
| 109 | // natural moment to look, it is one indexed query, and anybody |
| 110 | // affected by an abandoned import is by definition someone who |
| 111 | // imports. |
| 112 | a.sweepStaleImports() |
| 113 | |
| 114 | data, filename, refusal := readUpload(w, r) |
| 115 | if refusal != "" { |
| 116 | a.renderImportPage(w, r, http.StatusBadRequest, refusal) |
| 117 | return |
| 118 | } |
| 119 | |
| 120 | s, err := a.createFillingSheet(a.memberGuard(r.Context()), titleFromFilename(filename), actor) |
| 121 | if a.guardRefused(w, r, err) { |
| 122 | return |
| 123 | } |
| 124 | if err != nil { |
| 125 | a.fail(w, r, err) |
| 126 | return |
| 127 | } |
| 128 | |
| 129 | // The job lands on the import report, which says what came across |
| 130 | // and links to the sheet; the native client is given the sheet |
| 131 | // itself (handleNativeJob). |
| 132 | location := importReportPath(s.ID) |
| 133 | job, err := a.jobs.Start(sess.Subject, importJobName, location, |
| 134 | func(ctx context.Context, progress func(string)) error { |
| 135 | return a.runImport(ctx, s, data, progress) |
| 136 | }) |
| 137 | if err != nil { |
| 138 | // The sheet was made for a job that never started, so it holds |
| 139 | // nothing and nobody asked for it. |
| 140 | a.discardSheet(s.ID) |
| 141 | if errors.Is(err, jobs.ErrOwnerBusy) { |
| 142 | a.renderImportPage(w, r, http.StatusTooManyRequests, refusalBusy) |
| 143 | return |
| 144 | } |
| 145 | a.fail(w, r, err) |
| 146 | return |
| 147 | } |
| 148 | if wantsNative(r) { |
| 149 | nativeJSON(w, 202, map[string]string{"job": job.ID}) |
| 150 | return |
| 151 | } |
| 152 | http.Redirect(w, r, "/jobs/"+job.ID, http.StatusSeeOther) |
| 153 | } |
| 154 | |
| 155 | // runImport is the job body: open the new sheet's tab, read the |
| 156 | // workbook into it, and either reveal the sheet or leave nothing |
| 157 | // behind. |
| 158 | // |
| 159 | // The sheet is invisible for the whole of this function |
| 160 | // (createFillingSheet, store.Sheet.FillingSince) and becomes visible |
| 161 | // only on the last line. That is what makes the three ways this can go |
| 162 | // wrong all end somewhere safe: a handled failure discards it, an |
| 163 | // unhandled one leaves it hidden, and a process that dies mid-import — |
| 164 | // a deploy, which the jobs package warns is a harder deadline than any |
| 165 | // timeout — leaves a hidden row rather than a half-filled sheet the |
| 166 | // whole team can see and nothing left alive to clean it up. |
| 167 | // |
| 168 | // It is not interruptible. xlsx.Import takes no context and runs to |
| 169 | // completion, so ctx is checked at the top and not again — an honest |
| 170 | // statement of what cancellation does here rather than a select that |
| 171 | // implies more than it delivers. |
| 172 | func (a *App) runImport(ctx context.Context, s SheetSummary, data []byte, progress func(string)) error { |
| 173 | if err := ctx.Err(); err != nil { |
| 174 | a.discardSheet(s.ID) |
| 175 | return err |
| 176 | } |
| 177 | progress("reading the workbook") |
| 178 | |
| 179 | h, err := a.openTabFor(s) |
| 180 | if err != nil { |
| 181 | a.discardSheet(s.ID) |
| 182 | return errors.New("that sheet could not be opened") |
| 183 | } |
| 184 | defer h.Release() |
| 185 | |
| 186 | rep, err := xlsx.Import(bytes.NewReader(data), h) |
| 187 | if err != nil { |
| 188 | a.discardSheet(s.ID) |
| 189 | return importFailure(err) |
| 190 | } |
| 191 | // Reveal it with its report, and only then report success. If this |
| 192 | // fails the sheet stays hidden, without a report, and the job says |
| 193 | // so, which is the right way round: the alternative is telling |
| 194 | // somebody their import worked and sending them to a sheet the list |
| 195 | // will not show. |
| 196 | if err := a.revealImport(s.ID, rep); err != nil { |
| 197 | return errors.New("that sheet could not be opened") |
| 198 | } |
| 199 | // The list orders by real activity, and an imported sheet's |
| 200 | // activity is the import. |
| 201 | a.touchSheet(s.ID) |
| 202 | return nil |
| 203 | } |
| 204 | |