oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// exports.go is the PDF export as a person meets it (spec §4.3): the
2// button, the job behind it, the status page it lands on, and the file
3// at the end. export.go is the pipeline it calls; this is everything
4// around it.
5//
6// GET /d/{sqid}/export the little form: with notes or not
7// POST /d/{sqid}/export start the job
8// GET /d/{sqid}/export/{job} the status page (rastrillo/jobs)
9// GET /d/{sqid}/export/{job}/fragment what the shim polls
10// GET /d/{sqid}/export/{job}/events the SSE it can ride instead
11// GET /d/{sqid}/export/{job}.pdf the file
12//
13// # Why it is a job
14//
15// A deck of two hundred slides takes seconds to render, and a request
16// that blocks for seconds is a request some proxy will cut. So the POST
17// answers immediately with somewhere to watch, exactly as the plan's
18// global constraints require, and the work happens in a goroutine under
19// rastrillo/jobs' own bounds: four running per person, fifteen minutes
20// each, the context expiring with the job.
21//
22// A job is a goroutine, and a deploy — or the platform hibernating this
23// instance — ends one mid-flight (rastrillo skill §6). Nothing here is
24// written down, so an interrupted export is simply not there when the
25// process comes back and the person presses the button again. That is
26// the honest behaviour for work that produces a file and no state:
27// re-running it is cheap and produces the same PDF.
28//
29// # Where the bytes live
30//
31// With no object store bound — which is this deployment today — the
32// finished PDF is held in memory for an hour and served from here. That
33// is bounded on purpose and in two directions: 50 MiB of held exports
34// per deck, 200 MiB across the instance (exportPerDeckBytes,
35// exportPerInstanceBytes). Past either, the job fails with a sentence
36// saying so rather than the instance failing with an OOM nobody can
37// read.
38//
39// When a store IS bound the same job uploads the PDF to it and drops
40// the held bytes, and the download route 302s to a presigned GET (or
41// streams it back from a store that cannot presign, which is what
42// blobs.Dir is in development). Both paths are in one handler, so
43// neither can rot: exportPDF below.
44package slides
45
46import (
47 "bytes"
48 "context"
49 "errors"
50 "fmt"
51 "io"
52 "net/http"
53 "net/url"
54 "strconv"
55 "strings"
56 "sync"
57 "time"
58
59 "github.com/go-chi/chi/v5"
60
61 "amadan.net/rastrillo/rastrillo"
62 "amadan.net/rastrillo/rastrillo/blobs"
63 "amadan.net/rastrillo/rastrillo/flash"
64 "amadan.net/rastrillo/rastrillo/jobs"
65 "amadan.net/rastrillo/rastrillo/sessions"
66
67 "amadan.net/oficina/slides/internal/slides/layout"
68 "amadan.net/oficina/slides/internal/slides/pdfcore"
69)
70
71// How long a finished export is answerable, and how much of it this
72// process will hold at once.
73//
74// The hour is the spec's (§4.3) and the same hour a presigned URL
75// lives. The two byte caps are the plan's, and they are the reason
76// holding a PDF in memory is a defensible thing to do at all: the worst
77// case is bounded and the failure is a sentence rather than a killed
78// process.
79const (
80 exportHoldFor = time.Hour
81 exportPerDeckBytes = 50 << 20
82 exportPerInstanceBytes = 200 << 20
83)
84
85// exportContentType is what the file is, said once.
86const exportContentType = "application/pdf"
87
88// --- the compiled module ---
89
90// pdfRuntime is the app's PDF module: compiled at most once, on the
91// first export, and closed with the app.
92//
93// On the app rather than in a package variable, so a test binary that
94// builds twenty apps releases twenty runtimes rather than leaking them
95// into a package that nothing can close. Lazy rather than built in New,
96// unlike the CRDT core: compiling costs the best part of a second and
97// most processes — every test app, every instance nobody exports
98// from — never render a page. The cost of that choice is that a
99// slides_pdf.wasm this host cannot load is a failed export rather than
100// a startup refusal; the gate's cmp against a fresh build is what
101// actually catches that, and it catches it before the binary is built.
102type pdfRuntime struct {
103 once sync.Once
104 rt *pdfcore.Runtime
105 err error
106}
107
108func (p *pdfRuntime) get(ctx context.Context) (*pdfcore.Runtime, error) {
109 p.once.Do(func() { p.rt, p.err = pdfcore.New(ctx) })
110 return p.rt, p.err
111}
112
113// close releases the module if one was ever built. Safe to call on a
114// runtime nobody used, which is the common case.
115func (p *pdfRuntime) close(ctx context.Context) error {
116 if p == nil || p.rt == nil {
117 return nil
118 }
119 return p.rt.Close(ctx)
120}
121
122// --- the held bytes ---
123
124// heldExport is one finished (or running) export: who asked, which
125// deck, and where the file is.
126//
127// It is created when the job starts, so a status page and a download
128// URL can be checked against the deck in the path before the file
129// exists. bytes is what an instance with no object store holds; hash is
130// the store's own key once the bytes are up there, and exactly one of
131// the two is ever set.
132type heldExport struct {
133 deck string // the deck's sqid
134 owner string // the job's owner, as jobs.Get keys it
135 actor string // person:<id> or agent:<id> — who asked (§6.2)
136 name string // the job's own label (exportFallback shows it)
137 filename string // what the browser should call the file
138 bytes []byte
139 hash string
140 warnings []layout.Warning
141 started time.Time
142 done time.Time // zero while the job is running
143}
144
145// exportStore is every export this process is holding. One mutex, a
146// map, and two caps.
147//
148// Sweeping happens inside its own methods rather than on a timer: there
149// is no goroutine to leak and nothing to shut down, and the caps — not
150// the sweep — are what bound the memory. The cost is that the last
151// export of the day is held until somebody exports again, which is
152// bytes and not a correctness problem.
153type exportStore struct {
154 mu sync.Mutex
155 held map[string]*heldExport
156
157 // perDeck and perInstance are exportPerDeckBytes and
158 // exportPerInstanceBytes, as fields so a test can prove the refusal
159 // without making a 50 MiB PDF first.
160 perDeck, perInstance int64
161 ttl time.Duration
162 now func() time.Time
163}
164
165func newExportStore() *exportStore {
166 return &exportStore{
167 held: map[string]*heldExport{},
168 perDeck: exportPerDeckBytes,
169 perInstance: exportPerInstanceBytes,
170 ttl: exportHoldFor,
171 now: time.Now,
172 }
173}
174
175// SetExportCaps moves the two byte caps for this app.
176//
177// Exported because the *app New returns is unexported, so the only
178// thing outside this package that can reach it is a method — and the
179// suite has to be able to prove the refusal without first making a
180// 50 MiB PDF, which would be a minute of CPU to assert one sentence.
181// It is also where an operator-tunable setting would land if a bigger
182// instance ever wanted one.
183func (a *app) SetExportCaps(perDeck, perInstance int64) {
184 a.exports.mu.Lock()
185 defer a.exports.mu.Unlock()
186 a.exports.perDeck, a.exports.perInstance = perDeck, perInstance
187}
188
189// ForgetExportJobs gives this app an empty job registry, leaving the
190// exports it is holding alone.
191//
192// Exported for SetExportCaps's reason: rastrillo/jobs sweeps a finished
193// job ten minutes after it ends and offers no way to bring that
194// forward, so the suite proves exportFallback by handing the app a
195// registry that has forgotten — which is what the sweep leaves behind,
196// and what a restarted process has. Both the registry and the handlers
197// built over it are replaced, because the handlers hold their own
198// reference to it.
199//
200// Nothing else may call this: replacing the registry while a job is
201// running orphans it.
202func (a *app) ForgetExportJobs() error {
203 a.jobs = jobs.New(a.logger)
204 pages, err := jobs.NewHandlers(jobs.Config{
205 Jobs: a.jobs,
206 Render: a.renderExportPage,
207 RenderFragment: a.renderExportFragment,
208 })
209 if err != nil {
210 return err
211 }
212 a.jobPages = pages
213 return nil
214}
215
216// begin records a job that has just started. The entry carries no bytes
217// yet; what it carries is the deck and the owner, which is what the
218// download and status routes check before they answer anything.
219func (s *exportStore) begin(id string, e heldExport) []string {
220 s.mu.Lock()
221 defer s.mu.Unlock()
222 dropped := s.sweepLocked()
223 e.started = s.now()
224 s.held[id] = &e
225 return dropped
226}
227
228// errExportTooBig is what a job returns when the finished PDF does not
229// fit under the caps. The message a person sees is the caller's.
230var errExportTooBig = errors.New("slides: the export is bigger than this instance will hold")
231
232// finish attaches the finished file. It is where the caps are enforced,
233// because the size of a PDF is not knowable before it exists: over
234// either cap, the entry is dropped and the job fails with a sentence
235// instead of the instance filling up quietly.
236func (s *exportStore) finish(id string, pdf []byte, warnings []layout.Warning) error {
237 s.mu.Lock()
238 defer s.mu.Unlock()
239 e, ok := s.held[id]
240 if !ok {
241 return errors.New("slides: this export was swept before it finished")
242 }
243 var deckBytes, allBytes int64
244 for otherID, other := range s.held {
245 if otherID == id {
246 continue
247 }
248 allBytes += int64(len(other.bytes))
249 if other.deck == e.deck {
250 deckBytes += int64(len(other.bytes))
251 }
252 }
253 size := int64(len(pdf))
254 if deckBytes+size > s.perDeck || allBytes+size > s.perInstance {
255 delete(s.held, id)
256 return errExportTooBig
257 }
258 e.bytes = pdf
259 e.warnings = warnings
260 e.done = s.now()
261 return nil
262}
263
264// stored replaces the held bytes with the store's key for them, once
265// the upload has happened. The bytes go, because holding a copy of
266// something the object store now has is the whole cost this avoids.
267func (s *exportStore) stored(id, hash string, warnings []layout.Warning) {
268 s.mu.Lock()
269 defer s.mu.Unlock()
270 e, ok := s.held[id]
271 if !ok {
272 return
273 }
274 e.bytes = nil
275 e.hash = hash
276 e.warnings = warnings
277 e.done = s.now()
278}
279
280// forget drops an export whose job failed, so a failure holds nothing.
281func (s *exportStore) forget(id string) {
282 s.mu.Lock()
283 defer s.mu.Unlock()
284 delete(s.held, id)
285}
286
287// get answers one export, sweeping first so an expired one is gone
288// rather than merely old.
289func (s *exportStore) get(id string) (heldExport, []string, bool) {
290 s.mu.Lock()
291 defer s.mu.Unlock()
292 dropped := s.sweepLocked()
293 e, ok := s.held[id]
294 if !ok {
295 return heldExport{}, dropped, false
296 }
297 return *e, dropped, true
298}
299
300// sweepLocked drops finished exports past the TTL and returns the store
301// hashes that no live entry refers to any more, for the caller to
302// delete from the bucket. A running job is never swept: its entry is
303// what the status page checks the deck against.
304func (s *exportStore) sweepLocked() []string {
305 cutoff := s.now().Add(-s.ttl)
306 var candidates []string
307 for id, e := range s.held {
308 if !e.done.IsZero() && e.done.Before(cutoff) {
309 if e.hash != "" {
310 candidates = append(candidates, e.hash)
311 }
312 delete(s.held, id)
313 }
314 }
315 // Content addressing means two identical exports share a key, so an
316 // object is only orphaned once nothing left refers to it.
317 var orphans []string
318 for _, hash := range candidates {
319 used := false
320 for _, e := range s.held {
321 if e.hash == hash {
322 used = true
323 break
324 }
325 }
326 if !used {
327 orphans = append(orphans, hash)
328 }
329 }
330 return orphans
331}
332
333// dropObjects deletes swept exports from the object store, best effort:
334// a failure here is a file left in a bucket, which is worth a log line
335// and nothing more.
336func (a *app) dropObjects(ctx context.Context, hashes []string) {
337 if len(hashes) == 0 || a.cfg.Blobs == nil {
338 return
339 }
340 for _, hash := range hashes {
341 if err := a.cfg.Blobs.Delete(ctx, hash); err != nil {
342 a.logger.Error("slides: delete an expired export", "hash", hash, "err", err)
343 }
344 }
345}
346
347// --- GET /d/{sqid}/export ---
348
349// exportPage is the little form, and the notice a refused start lands
350// back on.
351type exportPage struct {
352 shell
353 Title string
354 DeckTitle string
355 Body string
356 NotesLabel string
357 Submit string
358 Notice string // a refused start, from the flash cookie
359 Held string
360 BackHref string
361 BackLabel string
362 Action string
363}
364
365// exportForm is the one screen that starts an export: one job per
366// screen, and the checkbox that decides what the PDF contains is on it
367// rather than beside a button somewhere else.
368func (a *app) exportForm(w http.ResponseWriter, r *http.Request) {
369 u, ok := a.viewer(w, r)
370 if !ok {
371 return
372 }
373 d, ok := a.deckFor(w, r, u)
374 if !ok {
375 return
376 }
377 notice := ""
378 if f, has := flash.Take(w, r); has {
379 notice = f.Message
380 }
381 render(w, "deck_export", exportPage{
382 shell: a.shellFor(r, u, onDeck(rastrillo.T(r, "slides.export.title"), d.Title)),
383 Title: rastrillo.T(r, "slides.export.title"),
384 DeckTitle: d.Title,
385 Body: rastrillo.T(r, "slides.export.body"),
386 NotesLabel: rastrillo.T(r, "slides.export.notes"),
387 Submit: rastrillo.T(r, "slides.export.submit"),
388 Held: rastrillo.T(r, "slides.export.held"),
389 Notice: notice,
390 BackHref: "/d/" + d.Sqid,
391 BackLabel: rastrillo.T(r, "slides.deck.back"),
392 Action: "/d/" + d.Sqid + "/export",
393 })
394}
395
396// --- POST /d/{sqid}/export ---
397
398// exportWords are the sentences an export may have to say, resolved
399// from the catalog while the request that started it is still here.
400//
401// A job outlives its request, and rastrillo.T reads the locale off the
402// request, so a job that translated its own progress line would either
403// be holding a request it must not hold or answering in the wrong
404// language. Resolving them up front is the honest way round: the words
405// belong to the person who pressed the button.
406type exportWords struct {
407 name string
408 progress string
409 open string
410 render string
411 tooMany string
412 tooBig string
413 store string
414}
415
416func exportWordsFor(r *http.Request, title string) exportWords {
417 return exportWords{
418 name: rastrillo.Tf(r, "slides.export.job", "title", title),
419 progress: rastrillo.T(r, "slides.export.progress"),
420 open: rastrillo.T(r, "slides.export.error.open"),
421 render: rastrillo.T(r, "slides.export.error.render"),
422 tooMany: rastrillo.Tf(r, "slides.export.error.toomany", "max", MaxExportSlides),
423 tooBig: rastrillo.T(r, "slides.export.error.toobig"),
424 store: rastrillo.T(r, "slides.export.error.store"),
425 }
426}
427
428// fillWords is rastrillo.Tf's substitution against an already-resolved
429// string: {name} replaced wherever it appears. It exists because a job
430// has words but no request to translate them with (exportWords).
431func fillWords(text string, pairs ...any) string {
432 for i := 0; i+1 < len(pairs); i += 2 {
433 key, ok := pairs[i].(string)
434 if !ok {
435 continue
436 }
437 text = strings.ReplaceAll(text, "{"+key+"}", fmt.Sprint(pairs[i+1]))
438 }
439 return text
440}
441
442// startExport is the button. It refuses two things before it starts a
443// goroutine — a deck over the slide cap, and a person who already has
444// four jobs running — and both refusals are a flash on the form they
445// came from rather than an error page: neither is a fault, and the
446// answer to both is "try again, differently or later".
447func (a *app) startExport(w http.ResponseWriter, r *http.Request) {
448 u, ok := a.viewer(w, r)
449 if !ok {
450 return
451 }
452 d, ok := a.deckFor(w, r, u)
453 if !ok {
454 return
455 }
456 owner, ok := a.sessionSubject(w, r)
457 if !ok {
458 return
459 }
460 back := "/d/" + d.Sqid + "/export"
461
462 // The slide cap, before any work: Export refuses the same deck, but
463 // it would do it inside a job, where the answer is a failed status
464 // page rather than a sentence on the form.
465 if n, counted := a.slideCount(r.Context(), d); counted && n > MaxExportSlides {
466 flash.Set(w, r, "error", rastrillo.Tf(r, "slides.export.error.toomany", "max", MaxExportSlides))
467 http.Redirect(w, r, back, http.StatusSeeOther)
468 return
469 }
470
471 withNotes := r.FormValue("notes") != ""
472 words := exportWordsFor(r, d.Title)
473
474 // The job's own id is not known until Start returns, and Start has
475 // already begun running the function by then. So the function is
476 // handed its id down a channel and waits for it: what it does
477 // first is record the export against this deck, and doing that
478 // under an id nobody knows yet is not possible.
479 //
480 // Location is deliberately empty. jobs.StatusPage 303s a finished
481 // job to its Location, and the page the owner wants is the one they
482 // are on — the download link and the warnings are ON the status
483 // page, so a Location of the status page itself would be a redirect
484 // loop and a Location of the file would take the warnings away.
485 id := make(chan string, 1)
486 job, err := a.jobs.Start(owner, words.name, "",
487 a.exportJob(id, d, actorFor(u), withNotes, words))
488 switch {
489 case errors.Is(err, jobs.ErrOwnerBusy):
490 flash.Set(w, r, "error", rastrillo.T(r, "slides.export.error.busy"))
491 http.Redirect(w, r, back, http.StatusSeeOther)
492 return
493 case err != nil:
494 a.fail(w, r, "start an export", err)
495 return
496 }
497 a.startedExport(job.ID, d, owner, actorFor(u), words.name)
498 id <- job.ID
499 http.Redirect(w, r, back+"/"+job.ID, http.StatusSeeOther)
500}
501
502// exportJob is the work itself, as jobs.Start takes it.
503//
504// Everything it needs is captured by value here — the deck row, the
505// actor, the words — because the request is gone by the time it runs.
506// The context is the job's own: it expires after fifteen minutes and is
507// honoured at every step, which is the whole of what "honour ctx" means
508// for work that is one render.
509//
510// Its errors are shown to the person who asked, so they are the
511// catalog's sentences and never a wrapped internal one; what an
512// operator needs is logged here instead.
513func (a *app) exportJob(id <-chan string, d Deck, actor string, withNotes bool, words exportWords) func(context.Context, func(string)) error {
514 return func(ctx context.Context, progress func(string)) error {
515 var jobID string
516 select {
517 case jobID = <-id:
518 case <-ctx.Done():
519 return ctx.Err()
520 }
521
522 h, view, err := a.openDeck(ctx, d)
523 if err != nil {
524 a.logger.Error("slides: open a deck to export", "deck", d.Sqid, "err", err)
525 return errors.New(words.open)
526 }
527 defer h.Close(ctx)
528 view = view.ForReaders()
529 if len(view.Slides) > MaxExportSlides {
530 return errors.New(words.tooMany)
531 }
532
533 rt, err := a.pdf.get(ctx)
534 if err != nil {
535 a.logger.Error("slides: compile the pdf module", "err", err)
536 return errors.New(words.render)
537 }
538
539 total := len(view.Slides)
540 pdf, warnings, err := Export(ctx, view, ExportOptions{
541 WithNotes: withNotes,
542 Runtime: rt,
543 Assets: a.assetBytes(ctx, d, view),
544 Fonts: a.fontLoader(ctx, d.ID),
545 QR: a.followCodes(ctx, d, view, "/d/"+d.Sqid),
546 Progress: func(slide, of int) {
547 progress(fillWords(words.progress, "n", slide, "total", of))
548 },
549 })
550 if err != nil {
551 if errors.Is(err, ErrTooManySlides) {
552 return errors.New(words.tooMany)
553 }
554 a.logger.Error("slides: render an export", "deck", d.Sqid, "slides", total, "err", err)
555 return errors.New(words.render)
556 }
557 a.logger.Info("slides: exported", "deck", d.Sqid, "actor", actor,
558 "slides", total, "notes", withNotes, "bytes", len(pdf), "warnings", len(warnings))
559
560 // With a store, the bytes belong in it and not in this process.
561 if store := a.cfg.Blobs; store != nil {
562 ref, err := store.Put(ctx, bytes.NewReader(pdf), exportContentType)
563 if err != nil {
564 a.logger.Error("slides: store an export", "deck", d.Sqid, "err", err)
565 return errors.New(words.store)
566 }
567 a.exports.stored(jobID, ref.Hash, warnings)
568 return nil
569 }
570 if err := a.exports.finish(jobID, pdf, warnings); err != nil {
571 if errors.Is(err, errExportTooBig) {
572 return errors.New(words.tooBig)
573 }
574 a.logger.Error("slides: hold an export", "deck", d.Sqid, "err", err)
575 return errors.New(words.render)
576 }
577 return nil
578 }
579}
580
581// --- GET /d/{sqid}/export/{id} and .pdf ---
582
583// exportJobRoute is the one route behind two things: the status page,
584// and the file itself at the same address with `.pdf` on the end.
585//
586// One handler because chi matches a whole path segment: `{id}` would
587// swallow `{id}.pdf` whichever order they were registered in, and a
588// second pattern that only sometimes wins is worse than reading the
589// extension here, which is what the thumbnail routes do too.
590func (a *app) exportJobRoute(w http.ResponseWriter, r *http.Request) {
591 if id, isPDF := strings.CutSuffix(chi.URLParam(r, "id"), ".pdf"); isPDF {
592 a.exportPDF(w, r, id)
593 return
594 }
595 if !a.exportJobIsHere(w, r) {
596 return
597 }
598 if d, ok := a.exportFallback(r); ok {
599 a.renderExportPage(w, r, d)
600 return
601 }
602 a.jobPages.StatusPage(w, a.exportPrincipal(r))
603}
604
605// exportFragment and exportEvents are the polled twins of the page,
606// behind the same check.
607func (a *app) exportFragment(w http.ResponseWriter, r *http.Request) {
608 if !a.exportJobIsHere(w, r) {
609 return
610 }
611 if d, ok := a.exportFallback(r); ok {
612 a.renderExportFragment(w, r, d)
613 return
614 }
615 a.jobPages.Fragment(w, a.exportPrincipal(r))
616}
617
618// exportFallback is what the status page and its fragment answer with
619// once rastrillo/jobs has forgotten the job but this app is still
620// holding the file. ok is false in the ordinary case — the registry
621// still has the job — and jobs.StatusPage answers as it always did.
622//
623// The two records have deliberately different lifetimes, and this is
624// where they are made to agree. The registry sweeps a finished job ten
625// minutes after it ends; the bytes stay answerable for an hour, which
626// is what the page itself told the person ("held for an hour"). Left
627// alone, the page 404s for the last fifty of those minutes while
628// `.pdf` at the same address still hands over the file — the page and
629// the download disagreeing about whether the export exists, which is
630// what somebody who left the tab open over lunch would meet. The other
631// way to make them agree was to shorten the hold to the registry's ten
632// minutes, and that throws away a download that was promised and buys
633// nothing. So the page falls back to the record that outlives the
634// registry.
635//
636// Nothing is invented: the name, both times and Done all come off the
637// held record, which this app wrote when it started the job and
638// finished it. A job that failed leaves no finished record, so a
639// failure still expires into a 404 rather than reappearing as a
640// success.
641// It reads the session itself rather than through sessionSubject: a
642// missing one is jobs.StatusPage's 403 to write, not a 500 here on top
643// of it.
644func (a *app) exportFallback(r *http.Request) (jobs.PageData, bool) {
645 r = a.exportPrincipal(r)
646 s, ok := sessions.Current(r)
647 if !ok || s.Subject == "" {
648 return jobs.PageData{}, false
649 }
650 owner := s.Subject
651 id := chi.URLParam(r, "id")
652 if _, live := a.jobs.Get(id, owner); live {
653 return jobs.PageData{}, false
654 }
655 held, dropped, found := a.exports.get(id)
656 a.dropObjects(r.Context(), dropped)
657 if !found || held.owner != owner || held.done.IsZero() {
658 return jobs.PageData{}, false
659 }
660 // PollSeconds is left at zero: the template reads it only while the
661 // job is running, and this job is finished by construction.
662 return jobs.PageData{Job: jobs.Job{
663 ID: id,
664 Owner: owner,
665 Name: held.name,
666 Status: jobs.Done,
667 StartedAt: held.started,
668 FinishedAt: held.done,
669 }}, true
670}
671
672func (a *app) exportEvents(w http.ResponseWriter, r *http.Request) {
673 if !a.exportJobIsHere(w, r) {
674 return
675 }
676 a.jobPages.Events(w, a.exportPrincipal(r))
677}
678
679// exportJobIsHere is the deck check rastrillo/jobs cannot make: it
680// knows the owner and nothing about a deck, and these URLs name both.
681// A job of this person's for ANOTHER deck, addressed under this one, is
682// a 404 like every other mismatched capability in this app.
683//
684// The deck itself is resolved through deckFor, so a person who cannot
685// read the deck never reaches the job. A job the registry has swept
686// still reaches the status page: exportFallback answers it from this
687// app's own record, which is the one whose TTL the page quoted.
688func (a *app) exportJobIsHere(w http.ResponseWriter, r *http.Request) bool {
689 u, ok := a.viewer(w, r)
690 if !ok {
691 return false
692 }
693 d, ok := a.deckFor(w, r, u)
694 if !ok {
695 return false
696 }
697 held, dropped, found := a.exports.get(chi.URLParam(r, "id"))
698 a.dropObjects(r.Context(), dropped)
699 if found && held.deck != d.Sqid {
700 a.notFound(w, r)
701 return false
702 }
703 return true
704}
705
706// exportPDF serves the file: the held bytes, or a redirect to the
707// object store, from one handler so the two paths cannot drift.
708//
709// Three gates, all of them 404 on failure: the deck has to be one this
710// person may read, the export has to be for THIS deck, and it has to be
711// theirs — heldExport.owner, compared against the session's subject,
712// which is the same string rastrillo/jobs keys a job by.
713//
714// Its OWN record rather than jobs.Get: a finished job is swept from the
715// registry ten minutes after it ends, and the file is answerable for an
716// hour, which is what the page told the person. Asking the registry
717// would take the download away fifty minutes early. The status page
718// reads the same record for the same fifty minutes (exportFallback), so
719// the page and the file agree about whether the export is still there.
720func (a *app) exportPDF(w http.ResponseWriter, r *http.Request, id string) {
721 u, ok := a.viewer(w, r)
722 if !ok {
723 return
724 }
725 d, ok := a.deckFor(w, r, u)
726 if !ok {
727 return
728 }
729 owner, ok := a.sessionSubject(w, r)
730 if !ok {
731 return
732 }
733 held, dropped, found := a.exports.get(id)
734 a.dropObjects(r.Context(), dropped)
735 if !found || held.deck != d.Sqid || held.owner != owner || held.done.IsZero() {
736 a.notFound(w, r)
737 return
738 }
739 a.serveExport(w, r, held, a.presignTTLFor(u), func() { a.notFound(w, r) })
740}
741
742// serveExport writes one finished export, whichever of the two places
743// it is in. missing is how the surface asking says "no longer here" —
744// the app's 404 page on a screen, the API's JSON on the other side.
745//
746// ttl is how long a presigned URL may live: presignTTL, or in team mode
747// no longer than the standing it was minted on (presignTTLFor).
748func (a *app) serveExport(w http.ResponseWriter, r *http.Request, held heldExport, ttl time.Duration, missing func()) {
749 if held.hash != "" {
750 store := a.cfg.Blobs
751 if store == nil {
752 missing()
753 return
754 }
755 // A store that can presign hands the browser a URL of its own
756 // and this process never sees the bytes — the point of putting
757 // them there. One that cannot (blobs.Dir, in development) is
758 // streamed back through here, so the same page works either way.
759 if p, canPresign := store.(presigner); canPresign {
760 url, err := p.PresignGet(held.hash, ttl)
761 if err != nil {
762 a.fail(w, r, "presign an export", err)
763 return
764 }
765 http.Redirect(w, r, url, http.StatusFound)
766 return
767 }
768 rc, err := store.Get(r.Context(), held.hash)
769 if err != nil {
770 if errors.Is(err, blobs.ErrNotFound) {
771 missing()
772 return
773 }
774 a.fail(w, r, "read an export", err)
775 return
776 }
777 defer rc.Close()
778 exportHeaders(w, held.filename)
779 io.Copy(w, rc)
780 return
781 }
782 if len(held.bytes) == 0 {
783 missing()
784 return
785 }
786 exportHeaders(w, held.filename)
787 w.Header().Set("Content-Length", strconv.Itoa(len(held.bytes)))
788 w.Write(held.bytes)
789}
790
791// exportHeaders says what the file is and what to call it.
792//
793// Both spellings of the name: the ASCII one every client understands,
794// and the RFC 5987 one that carries a deck called "Präsentation"
795// intact. no-store because the URL is a job's capability and the file
796// is somebody's document — nothing in between should keep a copy.
797func exportHeaders(w http.ResponseWriter, filename string) {
798 w.Header().Set("Content-Type", exportContentType)
799 w.Header().Set("X-Content-Type-Options", "nosniff")
800 w.Header().Set("Cache-Control", "private, no-store")
801 w.Header().Set("Content-Disposition", fmt.Sprintf(
802 `attachment; filename="%s"; filename*=UTF-8''%s`,
803 asciiFilename(filename), url.PathEscape(filename)))
804}
805
806// pdfFilename turns a deck's title into something a file manager will
807// take: the title's own words, anything else dropped, bounded, and
808// never empty.
809func pdfFilename(title string) string {
810 var b strings.Builder
811 lastSpace := false
812 for _, r := range strings.TrimSpace(title) {
813 switch {
814 case r == '/' || r == '\\' || r == ':' || r == '"' || r < 0x20 || r == 0x7f:
815 // A path separator, a quote or a control character: dropped
816 // rather than replaced, because none of them is part of a
817 // name anybody typed on purpose.
818 case r == ' ' || r == '\t':
819 if !lastSpace && b.Len() > 0 {
820 b.WriteByte(' ')
821 lastSpace = true
822 }
823 default:
824 b.WriteRune(r)
825 lastSpace = false
826 }
827 if b.Len() > 80 {
828 break
829 }
830 }
831 name := strings.TrimSpace(b.String())
832 if name == "" {
833 name = "deck"
834 }
835 return name + ".pdf"
836}
837
838// asciiFilename is the plain-ASCII fallback of the same name, for the
839// unstarred filename parameter — which is a quoted string in a header
840// and may hold nothing else.
841func asciiFilename(name string) string {
842 var b strings.Builder
843 for _, r := range name {
844 if r < 0x20 || r > 0x7e || r == '"' || r == '\\' {
845 b.WriteByte('-')
846 continue
847 }
848 b.WriteRune(r)
849 }
850 return b.String()
851}
852
853// --- the status page ---
854
855// exportWarning is one line of the warnings list: the slide it is
856// about, and what happened.
857type exportWarning struct {
858 Slide string
859 Detail string
860}
861
862// exportStatus is the status page and its polled fragment — one struct,
863// because they are one rendering seen through two holes (render.go
864// builds the same file as a page and as a fragment).
865type exportStatus struct {
866 shell
867 Title string
868 DeckTitle string
869 BackHref string
870 BackLabel string
871
872 // The job-status partial's own keys.
873 Name string
874 Status string
875 Progress string
876 Err string
877 PollURL string
878 PushURL string
879 PollSeconds int
880
881 Running bool
882 Failed bool
883
884 Done string
885 DownloadHref string
886 DownloadLabel string
887 Held string
888 Gone string
889 AgainHref string
890 AgainLabel string
891 WarningsLabel string
892 WarningsBody string
893 Warnings []exportWarning
894}
895
896// renderExportPage and renderExportFragment are jobs.Config's two
897// seams. The page is the whole screen; the fragment is the ONE element
898// the shim swaps in, which is why the running and finished states are
899// alternatives rather than a wrapper around a partial: the shim keeps
900// the first element of what it fetches and drops the rest.
901func (a *app) renderExportPage(w http.ResponseWriter, r *http.Request, d jobs.PageData) {
902 r = restoreExportPrincipal(r)
903 u, ok := a.viewer(w, r)
904 if !ok {
905 return
906 }
907 page := a.exportStatusFor(r, d)
908 page.shell = a.shellFor(r, u, titled(page.Title))
909 render(w, "export_status", page)
910}
911
912func (a *app) renderExportFragment(w http.ResponseWriter, r *http.Request, d jobs.PageData) {
913 r = restoreExportPrincipal(r)
914 renderFragment(w, "export_status", "export-body", a.exportStatusFor(r, d))
915}
916
917// exportStatusFor is the view data for both, built from the job's own
918// snapshot and this app's record of what the job produced.
919func (a *app) exportStatusFor(r *http.Request, d jobs.PageData) exportStatus {
920 sqid := chi.URLParam(r, "sqid")
921 base := "/d/" + sqid + "/export"
922 self := base + "/" + d.Job.ID
923 page := exportStatus{
924 Title: rastrillo.T(r, "slides.export.title"),
925 BackHref: "/d/" + sqid,
926 BackLabel: rastrillo.T(r, "slides.deck.back"),
927 Name: d.Job.Name,
928 Status: string(d.Job.Status),
929 Progress: d.Job.Progress,
930 Err: d.Job.Err,
931 PollURL: self + "/fragment",
932 PushURL: self + "/events",
933 PollSeconds: d.PollSeconds,
934 Running: d.Job.Status == jobs.Running,
935 Failed: d.Job.Status == jobs.Failed,
936 AgainHref: base,
937 AgainLabel: rastrillo.T(r, "slides.export.again"),
938 }
939 // FragmentPath and EventsPath off PageData are rastrillo's own
940 // /jobs/{id}/… mounting, which this app does not use: these pages
941 // live under the deck they belong to, so the paths are built here.
942 if page.Running || page.Failed {
943 return page
944 }
945
946 held, dropped, found := a.exports.get(d.Job.ID)
947 a.dropObjects(r.Context(), dropped)
948 if !found || held.done.IsZero() {
949 // The job says it finished and the bytes are not here: the hour
950 // is up, or the process holding them was replaced.
951 page.Gone = rastrillo.T(r, "slides.export.gone")
952 return page
953 }
954 page.Done = rastrillo.T(r, "slides.export.done")
955 page.DownloadHref = self + ".pdf"
956 page.DownloadLabel = rastrillo.T(r, "slides.export.download")
957 page.Held = rastrillo.T(r, "slides.export.held")
958 if len(held.warnings) > 0 {
959 page.WarningsLabel = rastrillo.T(r, "slides.export.warnings")
960 page.WarningsBody = rastrillo.T(r, "slides.export.warnings.body")
961 page.Warnings = a.exportWarningsFor(r, held)
962 }
963 return page
964}
965
966// exportWarningsFor turns the export's warnings into lines a person can
967// act on: the slide's own label rather than its id, and the sentence
968// the layout engine or the export wrote.
969//
970// The deck is opened once for the labels, and a deck that will not open
971// costs the labels and not the list — a warning with no slide name is
972// still worth reading.
973func (a *app) exportWarningsFor(r *http.Request, held heldExport) []exportWarning {
974 labels := map[string]string{}
975 var d Deck
976 if err := a.db.G.WithContext(r.Context()).Where("sqid = ?", held.deck).Take(&d).Error; err == nil {
977 if h, view, err := a.openDeck(r.Context(), d); err == nil {
978 defer h.Close(r.Context())
979 for i, s := range view.ForReaders().Slides {
980 labels[s.ID] = slideLabel(r, s, i+1)
981 }
982 }
983 }
984 out := make([]exportWarning, 0, len(held.warnings))
985 for _, warn := range held.warnings {
986 out = append(out, exportWarning{Slide: labels[warn.Slide], Detail: warn.Detail})
987 }
988 return out
989}
990
991// --- the drive API's twins (spec §7.2) ---
992//
993// Here rather than in api.go because they are the export, and the
994// export is one thing: the same job, the same held bytes, the same
995// caps, answered in the API's own shapes.
996//
997// An agent's export is owned by its OPERATOR — the person the agent
998// acts for — spelled as the users row's address, which is the same
999// string a session's Subject carries. So an operator watching from the
1000// API and an operator watching from the screen are watching one job.
1001
1002// apiExportOwner is that string. An agent owns nothing (agents.go): a
1003// token can be revoked and a job it started must not become
1004// unwatchable because it was.
1005//
1006// In team mode it is the operator's user (teamJobOwner), as every
1007// team-mode session's is: a Home-only operator has no address.
1008func (a *app) apiExportOwner(p principal) string {
1009 if a.team != nil {
1010 return teamJobOwner(p.operator.ID)
1011 }
1012 return p.operator.Email
1013}
1014
1015// apiStartExport serves POST /api/v1/decks/{sqid}/export. 202, because
1016// nothing is ready yet: what comes back is where to watch and where
1017// the file will be.
1018func (a *app) apiStartExport(w http.ResponseWriter, r *http.Request) {
1019 p, ok := a.apiPrincipal(w, r)
1020 if !ok {
1021 return
1022 }
1023 d, ok := a.apiDeckFor(w, r, p)
1024 if !ok {
1025 return
1026 }
1027 var body struct {
1028 Notes bool `json:"notes"`
1029 }
1030 // An empty body is the ordinary case ("just export it"), and
1031 // readJSON refuses one, so only a body that IS there is read.
1032 if r.ContentLength > 0 && !a.readJSON(w, r, &body) {
1033 return
1034 }
1035 if n, counted := a.slideCount(r.Context(), d); counted && n > MaxExportSlides {
1036 a.apiInvalid(w, fmt.Sprintf("this deck has %d slides, and the most one export will take is %d", n, MaxExportSlides), -1)
1037 return
1038 }
1039
1040 owner := a.apiExportOwner(p)
1041 words := exportWordsFor(r, d.Title)
1042 id := make(chan string, 1)
1043 job, err := a.jobs.Start(owner, words.name, "", a.exportJob(id, d, p.actor(), body.Notes, words))
1044 switch {
1045 case errors.Is(err, jobs.ErrOwnerBusy):
1046 // 429: this is a rate, not a fault in the request. The caller
1047 // waits for one of its exports to finish.
1048 apiFail(w, http.StatusTooManyRequests, "busy")
1049 return
1050 case err != nil:
1051 a.logger.Error("slides: start an export for the API", "deck", d.Sqid, "err", err)
1052 apiFail(w, http.StatusInternalServerError, errInternal)
1053 return
1054 }
1055 a.startedExport(job.ID, d, owner, p.actor(), words.name)
1056 id <- job.ID
1057
1058 base := fmt.Sprintf("%s/decks/%s/export/%s", apiPrefix, d.Sqid, job.ID)
1059 a.writeJSON(w, http.StatusAccepted, map[string]any{
1060 "job": job.ID,
1061 "status_url": base,
1062 "pdf_url": base + ".pdf",
1063 })
1064}
1065
1066// apiExportStatus serves GET /api/v1/decks/{sqid}/export/{id} and, with
1067// `.pdf` on the end, the file itself — one handler, exportJobRoute's
1068// reason.
1069func (a *app) apiExportStatus(w http.ResponseWriter, r *http.Request) {
1070 p, ok := a.apiPrincipal(w, r)
1071 if !ok {
1072 return
1073 }
1074 d, ok := a.apiDeckFor(w, r, p)
1075 if !ok {
1076 return
1077 }
1078 id, wantsPDF := strings.CutSuffix(chi.URLParam(r, "id"), ".pdf")
1079 owner := a.apiExportOwner(p)
1080 held, dropped, found := a.exports.get(id)
1081 a.dropObjects(r.Context(), dropped)
1082 if found && (held.deck != d.Sqid || held.owner != owner) {
1083 apiFail(w, http.StatusNotFound, errNotFound)
1084 return
1085 }
1086
1087 // The file outlives the job record (exportPDF says why), so both
1088 // halves of this endpoint ask this app's own record — the download
1089 // for the bytes, the status for the state once the registry has
1090 // forgotten the job. A caller polling here must not be told the job
1091 // never existed while `.pdf` at the same address still answers.
1092 if wantsPDF {
1093 if !found || held.done.IsZero() {
1094 apiFail(w, http.StatusNotFound, errNotFound)
1095 return
1096 }
1097 a.serveExport(w, r, held, a.presignTTLFor(p.operator), func() { apiFail(w, http.StatusNotFound, errNotFound) })
1098 return
1099 }
1100
1101 job, isTheirs := a.jobs.Get(id, owner)
1102 if !isTheirs {
1103 // exportFallback's answer in the API's shape: a finished export
1104 // this app is still holding, rebuilt from that record.
1105 if !found || held.done.IsZero() {
1106 apiFail(w, http.StatusNotFound, errNotFound)
1107 return
1108 }
1109 job = jobs.Job{
1110 ID: id,
1111 Owner: owner,
1112 Name: held.name,
1113 Status: jobs.Done,
1114 StartedAt: held.started,
1115 FinishedAt: held.done,
1116 }
1117 }
1118
1119 // state, not "status": the word a caller branches on, and the same
1120 // three rastrillo/jobs has. The warnings are the export's own and
1121 // are only there once there is a file to warn about.
1122 out := map[string]any{"state": string(job.Status), "progress": job.Progress}
1123 if job.Err != "" {
1124 out["message"] = job.Err
1125 }
1126 if job.Status == jobs.Done {
1127 warnings := []layout.Warning{}
1128 if found {
1129 warnings = append(warnings, held.warnings...)
1130 }
1131 out["warnings"] = warnings
1132 if !found || held.done.IsZero() {
1133 // Finished, and the file has expired out from under the
1134 // caller. Said plainly rather than as a 404 on this
1135 // endpoint, which would read as "no such job".
1136 out["expired"] = true
1137 }
1138 }
1139 a.writeJSON(w, http.StatusOK, out)
1140}
1141
1142// --- shared bits ---
1143
1144// sessionSubject is the string rastrillo/jobs keys a job by: the
1145// session's Subject, which under rastrillo/auth is an email address.
1146// Past RequireSession there is always one, so its absence is a 500 and
1147// not a redirect.
1148//
1149// It is the one place in this app that reads a Subject for anything but
1150// mapping it to a users row (auth.go's currentUser and its warning
1151// about sessions.UserID): jobs.Get answers the owner and nobody else,
1152// and the owner it compares against is this string.
1153func (a *app) sessionSubject(w http.ResponseWriter, r *http.Request) (string, bool) {
1154 r = a.exportPrincipal(r)
1155 s, ok := sessions.Current(r)
1156 if !ok || s.Subject == "" {
1157 a.fail(w, r, "no session subject past the session gate", nil)
1158 return "", false
1159 }
1160 return s.Subject, true
1161}
1162
1163// startedExport is the record this app keeps beside rastrillo's job: it
1164// exists from the moment the job starts so the status and download
1165// routes have a deck to check against, and it is where the finished
1166// bytes land.
1167func (a *app) startedExport(id string, d Deck, owner, actor, name string) {
1168 dropped := a.exports.begin(id, heldExport{
1169 deck: d.Sqid,
1170 owner: owner,
1171 actor: actor,
1172 name: name,
1173 filename: pdfFilename(d.Title),
1174 })
1175 a.dropObjects(context.Background(), dropped)
1176}
1177