gunk-dev/the-valley

server.go

source876e6ddf614dmain's published tip history
25.2 KiB
1// Package server is the web UI's read side. It serves the active export
2// of a receiver's state directory to anonymous readers: the plan page,
3// each knot, and a source browser over each public project's main.
4//
5// # Snapshots
6//
7// Every request opens the store's active generation once, with
8// export.Store.Open, and renders its whole response from that
9// generation. An activation during the request changes nothing the
10// request reads. The server keeps a snapshot of the newest generation it
11// has read: the export, decoded, and its index. A request opens its
12// generation only once the generation has a snapshot, and every request
13// for that generation serves from the one snapshot.
14//
15// A request whose generation has no snapshot yet waits for a load. A load
16// runs in a worker of its own, which opens the active generation, holds
17// it while it reads and indexes the export, and then gives it back. At
18// most MaxLoads workers run at once. The requests that wait for a
19// generation share one load, so each export is read once. A waiting
20// request holds no generation, and stops waiting when its reader goes away
21// or its time runs out. A load stops once no request waits for it, and
22// the server keeps nothing of what it read.
23//
24// # Admission
25//
26// Every request's time is bounded from when it arrives: its waits, its
27// git commands and its rendering. A source request runs git, and at most
28// MaxGit run at once. A source request takes one of those slots before
29// it opens a generation, and waits for one only while fewer than
30// MaxWaiting wait. A request waits for a load only while fewer than
31// MaxLoadWaiting wait, and it is admitted among them before it opens
32// anything. A request the server cannot admit, or that runs out of time,
33// answers 503.
34//
35// # Responses
36//
37// A response is rendered whole before it is written. A request gives back
38// its generation and its git slot before it writes, so a reader that
39// reads slowly holds neither. It keeps its response until the response
40// is written.
41//
42// A response's body is at most MaxResponse bytes. A page that would pass
43// it stops rendering there, and the request answers with a short page
44// that says the page is too large. Rendered responses take their memory
45// from a budget of MaxBuffered bytes, which they give back once they are
46// written. A request that finds the budget spent answers 503.
47//
48// A response's first SmallPage bytes may take any of the budget, and the
49// rest of it only MaxLarge of it. So readers that never read large pages
50// hold at most MaxLarge, and the rest of the budget is always there for
51// small pages: the plan, most knots, and most directories and files.
52//
53// # Routes
54//
55// The server answers GET and HEAD alone:
56//
57// / the plan page
58// /<project>/ a redirect to the tree at main's tip
59// /<project>/knots/<id> one knot, with its body and comments
60// /<project>/source/ a redirect to the tree at main's tip
61// /<project>/source/tree/<commit>/<path> a directory and its README
62// /<project>/source/blob/<commit>/<path> a file
63// /<project>/source/log/<commit> the history that ends at a commit
64// /-/... the server's own paths
65//
66// Every path but / and those under /-/ starts with a project's name. No
67// project name starts with "-", so no project's path is ever one of the
68// server's own, whatever paths the server adds there. It serves no page
69// under /-/, and answers each path there with the one 404.
70//
71// Every source link names its project, a full commit ID and a path. A
72// commit is served only when export.Reachable finds it reachable from the
73// project's published source tip, and a path is resolved one tree entry
74// at a time from that commit's tree, so no other object can be named.
75//
76// # Access
77//
78// Every route checks that the export holds its project as public. A
79// project it does not hold answers exactly as a project that does not
80// exist: every 404 is the same page.
81//
82// # Safety
83//
84// Every page is rendered on the server with html/template, so everything
85// read from the export or a repository is escaped. Each response carries
86// a strict Content-Security-Policy: default-src 'self', and one inline
87// stylesheet and one inline script admitted by their SHA-256 hashes. No
88// repository file is served as itself: a file is shown as escaped text,
89// and a binary file or one larger than MaxFile is not shown at all.
90package server
91
92import (
93 "bytes"
94 "context"
95 "errors"
96 "fmt"
97 "io"
98 "log"
99 "net/http"
100 "net/url"
101 "os"
102 "strconv"
103 "strings"
104 "sync"
105 "syscall"
106 "time"
107
108 "the-valley/webui/export"
109)
110
111// StaleAfter is how old an export may be before its pages mark it stale.
112const StaleAfter = 5 * time.Minute
113
114// The bounds on what one request reads from a repository.
115const (
116 // MaxFile is the largest file a page shows, README or otherwise.
117 MaxFile = 1 << 20
118 // MaxLines is the most lines of a file a page shows.
119 MaxLines = 10_000
120 // MaxShown is the most bytes a page spends on a file's text once it
121 // is escaped, counting each line's markup on a file page. A page
122 // stops at the line that would take it past MaxShown.
123 MaxShown = 2 << 20
124 // MaxEntries is the most entries a directory page lists.
125 MaxEntries = 1000
126 // MaxRead is the most bytes of output a page reads from one git
127 // listing: a directory's entries, or a page of history. git is
128 // stopped once it prints more.
129 MaxRead = 4 << 20
130 // MaxDepth is the most path segments a source route takes.
131 MaxDepth = 64
132 // MaxPlanDepth is the most levels of knots a milestone's tree
133 // shows, and the most parents a knot's trail names.
134 MaxPlanDepth = 32
135 // LogPage is the number of commits on one page of a log.
136 LogPage = 50
137 // MaxSkip is the most commits a page of a log skips, which git walks
138 // before the page. The page whose older page would skip more links
139 // it as the log that ends at its last commit, less that commit.
140 MaxSkip = 10_000
141 // MaxGit is the most source requests that run git at once.
142 MaxGit = 8
143 // MaxWaiting is the most source requests that wait for one of the
144 // MaxGit to finish. A source request that finds every slot taken
145 // and MaxWaiting waiting answers 503 at once.
146 MaxWaiting = 16
147 // requestTimeout bounds a request from when it arrives: its wait for
148 // a git slot or for its generation's export to be read, its git
149 // commands and its rendering.
150 requestTimeout = 15 * time.Second
151 // gitTimeout bounds a source request's git commands, all of them
152 // together, from when it holds its git slot. A source request whose
153 // git runs past it answers 503.
154 gitTimeout = 5 * time.Second
155 // MaxLoads is the most loads that run at once, each in a worker of
156 // its own that reads one generation's export.
157 MaxLoads = 2
158 // MaxLoadWaiting is the most requests that wait for loads. A request
159 // that would wait while MaxLoadWaiting do answers 503 at once.
160 MaxLoadWaiting = 64
161 // MaxResponse is the most bytes a response's body takes. A page
162 // that would take more stops rendering, and the request answers with
163 // a short page that says the page is too large.
164 MaxResponse = 8 << 20
165 // MaxBuffered is the most bytes of rendered responses the server
166 // holds at once, from when each starts rendering until it is
167 // written. A response takes them in pieces of pieceSize as it
168 // renders.
169 MaxBuffered = 64 << 20
170 // SmallPage is how much of a response may take any of MaxBuffered.
171 SmallPage = 256 << 10
172 // MaxLarge is the most of MaxBuffered that responses hold past their
173 // first SmallPage bytes. The rest, MaxBuffered less MaxLarge, only
174 // a response's first SmallPage bytes may take.
175 MaxLarge = 48 << 20
176 // pieceSize is the size of the pieces a response is rendered into.
177 pieceSize = 64 << 10
178)
179
180// Config is what a Server serves from.
181type Config struct {
182 // Store is the receiver's state directory.
183 Store *export.Store
184 // Now is the clock an export's age is read against. Nil is time.Now.
185 Now func() time.Time
186 // Log is told of each failure a reader sees only as an error page.
187 // Nil logs with the standard logger.
188 Log func(error)
189}
190
191// Server is the read side's HTTP handler.
192type Server struct {
193 store *export.Store
194 now func() time.Time
195 log func(error)
196 // timeout is requestTimeout, gitTime is gitTimeout, and maxResponse
197 // is MaxResponse. A test shortens any of them.
198 timeout time.Duration
199 gitTime time.Duration
200 maxResponse int
201 // slots holds a token for each source request running git, and
202 // waiting one for each source request waiting for a slot.
203 slots chan struct{}
204 waiting chan struct{}
205 // loaders holds a token for each load's worker, and loadWaiting one
206 // for each request waiting for a load.
207 loaders chan struct{}
208 loadWaiting chan struct{}
209 // budget holds a token for each piece of a response that is being
210 // rendered or written: MaxBuffered bytes, in pieces of pieceSize.
211 // large holds a second token for each such piece past a response's
212 // first SmallPage bytes: MaxLarge bytes.
213 budget chan struct{}
214 large chan struct{}
215
216 mu sync.Mutex
217 // cached is the newest generation's snapshot read so far.
218 cached *snapshot
219 // loads are the loads a request that waits may still join: those that
220 // have not ended, and that some request waits for.
221 loads map[*load]struct{}
222
223 // The test hooks. opened, when set, is called with each generation a
224 // request opens, before the request reads anything from it. admitted
225 // is called when a source request takes a git slot, before it opens
226 // a generation. loading is called by a load's worker with the
227 // generation it opened, before it reads the generation's export.
228 opened func(export.Generation)
229 admitted func()
230 loading func(export.Generation)
231}
232
233// New is a Server over c's store.
234func New(c Config) *Server {
235 s := &Server{store: c.Store, now: c.Now, log: c.Log,
236 timeout: requestTimeout, gitTime: gitTimeout, maxResponse: MaxResponse,
237 slots: make(chan struct{}, MaxGit), waiting: make(chan struct{}, MaxWaiting),
238 loaders: make(chan struct{}, MaxLoads), loadWaiting: make(chan struct{}, MaxLoadWaiting),
239 budget: make(chan struct{}, MaxBuffered/pieceSize), large: make(chan struct{}, MaxLarge/pieceSize),
240 loads: map[*load]struct{}{}}
241 if s.now == nil {
242 s.now = time.Now
243 }
244 if s.log == nil {
245 s.log = func(err error) { log.Print(err) }
246 }
247 return s
248}
249
250// snapshot is one generation's export, decoded, and its index. A
251// generation is immutable once active, and its sequence names it, so a
252// snapshot serves every request that opens its generation.
253type snapshot struct {
254 seq int64
255 e *export.Export
256 idx *index
257}
258
259// load reads the active generation's export for every request that
260// waits for it. It starts once one of those requests takes a loader slot
261// for it, and runs in a worker of its own, so a request can stop waiting
262// while the load goes on for the others.
263type load struct {
264 // wants counts the requests that wait for the load. cancel is set once
265 // the load has started, and stops its worker. The worker sets opened
266 // and seq once it has opened a generation. All are guarded by the
267 // server's mu.
268 wants int
269 cancel context.CancelFunc
270 opened bool
271 seq int64
272 // started is closed once the load starts, and done once its worker
273 // ends. err is the worker's error, set before done is closed.
274 started chan struct{}
275 done chan struct{}
276 err error
277}
278
279// request is one request, the generation it serves from, and the
280// response it renders.
281type request struct {
282 s *Server
283 w http.ResponseWriter
284 r *http.Request
285 // ctx is the context the request waits and renders under. It ends
286 // at the request's deadline, or when its reader goes away. git is
287 // the context a source request runs git under, which ends gitTime
288 // after its view starts, or with ctx.
289 ctx context.Context
290 git context.Context
291 g export.Generation
292 e *export.Export
293 idx *index
294 now time.Time
295
296 // The response: a status and a page, or a redirect. It is written
297 // once the request has given back its generation and git slot, and
298 // the page's pieces are given back to the budget once it is written.
299 status int
300 ctype string
301 body *body
302 location string
303}
304
305func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
306 setHeaders(w.Header())
307 ctx, cancel := context.WithTimeout(r.Context(), s.timeout)
308 defer cancel()
309 q := &request{s: s, w: w, r: r, ctx: ctx, now: s.now()}
310 defer q.drop()
311 q.serve()
312 q.write()
313}
314
315// serve renders the request's response. A source request is admitted
316// first, and holds its git slot until serve returns. Every request holds
317// its generation until serve returns.
318func (q *request) serve() {
319 if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead {
320 q.w.Header().Set("Allow", "GET, HEAD")
321 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
322 Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.",
323 })
324 return
325 }
326 parts, ok := segments(q.r.URL.EscapedPath())
327 if ok && runsGit(parts) {
328 done, admitted := q.s.admit(q.ctx)
329 if !admitted {
330 q.busy()
331 return
332 }
333 defer done()
334 if q.s.admitted != nil {
335 q.s.admitted()
336 }
337 }
338 g, snap, release, err := q.s.open(q.ctx)
339 defer release()
340 switch {
341 case errors.Is(err, export.ErrNoExport):
342 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
343 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
344 })
345 return
346 case errors.Is(err, errLoadsFull):
347 q.busy()
348 return
349 case err != nil:
350 q.fail(err)
351 return
352 }
353 if q.s.opened != nil {
354 q.s.opened(g)
355 }
356 q.g, q.e, q.idx = g, snap.e, snap.idx
357 q.route(parts, ok)
358}
359
360// runsGit reports whether a path is a source route that reads a
361// repository: a tree, a file or a log of something that may be a project.
362func runsGit(parts []string) bool {
363 return len(parts) >= 3 && export.ValidName(parts[0]) && parts[1] == "source" &&
364 (parts[2] == "tree" || parts[2] == "blob" || parts[2] == "log")
365}
366
367// admit takes a git slot for a source request. When every slot is taken,
368// it waits for one until ctx is done, unless MaxWaiting requests wait
369// already. done gives the slot back.
370func (s *Server) admit(ctx context.Context) (done func(), ok bool) {
371 give := func() { <-s.slots }
372 select {
373 case s.slots <- struct{}{}:
374 return give, true
375 default:
376 }
377 select {
378 case s.waiting <- struct{}{}:
379 default:
380 return nil, false
381 }
382 defer func() { <-s.waiting }()
383 select {
384 case s.slots <- struct{}{}:
385 return give, true
386 case <-ctx.Done():
387 return nil, false
388 }
389}
390
391// errLoadsFull is open's error for a request that would wait for a load
392// while MaxLoadWaiting requests wait already.
393var errLoadsFull = errors.New("too many requests wait for exports to be read")
394
395// open opens the active generation once its snapshot is cached, and
396// returns both. release gives the generation back.
397//
398// A request whose active generation has no snapshot waits for a load,
399// and opens nothing until the load ends. It is admitted among the
400// MaxLoadWaiting requests that may wait before it waits, and it keeps its
401// place until open returns. Once the load ends it looks again, since
402// another generation may have been activated meanwhile.
403func (s *Server) open(ctx context.Context) (g export.Generation, snap *snapshot, release func(), err error) {
404 release = func() {}
405 waiting := false
406 defer func() {
407 if waiting {
408 <-s.loadWaiting
409 }
410 }()
411 for {
412 seq, err := s.store.Active()
413 if err != nil {
414 return g, nil, release, err
415 }
416 s.mu.Lock()
417 snap = s.cached
418 s.mu.Unlock()
419 if snap != nil && snap.seq == seq {
420 g, release, err = s.store.Open()
421 if err != nil || g.Sequence == seq {
422 return g, snap, release, err
423 }
424 release() // active moved on since it was read
425 release = func() {}
426 continue
427 }
428 if !waiting {
429 select {
430 case s.loadWaiting <- struct{}{}:
431 waiting = true
432 default:
433 return g, nil, release, errLoadsFull
434 }
435 }
436 if err := s.await(ctx, seq); err != nil {
437 return g, nil, release, err
438 }
439 }
440}
441
442// await waits until a load of generation seq, or of a newer one, ends,
443// or until ctx is done. It joins a load that will read seq or a newer
444// generation, since a worker reads whatever generation is active once it
445// starts, and otherwise makes one.
446//
447// A load starts only once one of its requests takes a loader slot for
448// it. While every slot is taken, each of its requests waits for one, and
449// the first to take one starts the load, so no load is queued that no
450// request waits for. A request that stops waiting leaves the load, and
451// the last to leave stops it.
452func (s *Server) await(ctx context.Context, seq int64) error {
453 s.mu.Lock()
454 if c := s.cached; c != nil && c.seq >= seq {
455 s.mu.Unlock()
456 return nil
457 }
458 var l *load
459 for m := range s.loads {
460 if !m.opened || m.seq >= seq {
461 l = m
462 break
463 }
464 }
465 if l == nil {
466 l = &load{started: make(chan struct{}), done: make(chan struct{})}
467 s.loads[l] = struct{}{}
468 }
469 l.wants++
470 s.mu.Unlock()
471 select {
472 case <-l.started:
473 case s.loaders <- struct{}{}:
474 if !s.start(l) {
475 <-s.loaders
476 }
477 case <-ctx.Done():
478 s.leave(l)
479 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
480 }
481 select {
482 case <-l.done:
483 return l.err
484 case <-ctx.Done():
485 s.leave(l)
486 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
487 }
488}
489
490// start starts l's worker, for the request that took a loader slot for
491// it. It is false when another request started it already.
492func (s *Server) start(l *load) bool {
493 s.mu.Lock()
494 defer s.mu.Unlock()
495 if l.cancel != nil {
496 return false
497 }
498 ctx, cancel := context.WithCancel(context.Background())
499 l.cancel = cancel
500 close(l.started)
501 go s.run(ctx, l)
502 return true
503}
504
505// leave is a request that stopped waiting for l. Once no request waits for
506// it, no request may join it, and a load that started is stopped.
507func (s *Server) leave(l *load) {
508 s.mu.Lock()
509 defer s.mu.Unlock()
510 if l.wants--; l.wants > 0 {
511 return
512 }
513 delete(s.loads, l)
514 if l.cancel != nil {
515 l.cancel()
516 }
517}
518
519// run is l's worker. It caches the snapshot it reads when the snapshot's
520// generation is newer than the cached one's, so a load of an older
521// generation never displaces a newer. A load that was stopped caches
522// nothing: leave stops it under mu, and run looks under mu. The worker
523// gives back its generation before it ends, and then its loader slot.
524func (s *Server) run(ctx context.Context, l *load) {
525 snap, err := s.read(ctx, l)
526 s.mu.Lock()
527 delete(s.loads, l)
528 if snap != nil && ctx.Err() == nil && (s.cached == nil || s.cached.seq < snap.seq) {
529 s.cached = snap
530 }
531 l.err = err
532 s.mu.Unlock()
533 l.cancel()
534 close(l.done)
535 <-s.loaders
536}
537
538// read opens the active generation for l, and holds it while it reads
539// and indexes the generation's export. It reads nothing when the
540// generation is cached already or another load reads it, and its waiting
541// requests look again. It stops reading once ctx is done.
542func (s *Server) read(ctx context.Context, l *load) (snap *snapshot, err error) {
543 // Cancellation can close the file during any operation. Report the
544 // context error instead of the resulting descriptor error.
545 defer func() {
546 if stopped := ctx.Err(); stopped != nil {
547 snap, err = nil, stopped
548 }
549 }()
550 if err := ctx.Err(); err != nil {
551 return nil, err
552 }
553 g, release, err := s.store.Open()
554 if err != nil {
555 return nil, err
556 }
557 defer release()
558 s.mu.Lock()
559 read := s.cached == nil || s.cached.seq < g.Sequence
560 for m := range s.loads {
561 if m != l && m.opened && m.seq == g.Sequence {
562 read = false
563 }
564 }
565 l.opened, l.seq = true, g.Sequence
566 s.mu.Unlock()
567 if !read {
568 return nil, nil
569 }
570 if s.loading != nil {
571 s.loading(g)
572 }
573 f, err := os.OpenFile(g.ExportPath(), os.O_RDONLY|syscall.O_NONBLOCK, 0)
574 if err != nil {
575 return nil, err
576 }
577 defer f.Close()
578 // Nonblocking open avoids waiting for a FIFO writer. Go's file poller
579 // waits for reads, and Close wakes a read when the last waiter leaves.
580 stop := context.AfterFunc(ctx, func() { _ = f.Close() })
581 defer stop()
582 info, err := f.Stat()
583 if err != nil {
584 return nil, err
585 }
586 data, err := io.ReadAll(&contextReader{ctx: ctx, r: f, waitForData: info.Mode()&os.ModeNamedPipe != 0})
587 if ctx.Err() != nil {
588 return nil, ctx.Err()
589 }
590 if err != nil {
591 return nil, fmt.Errorf("reading generation %d's export: %w", g.Sequence, err)
592 }
593 e, err := export.DecodeContext(ctx, bytes.NewReader(data))
594 if err != nil {
595 return nil, err
596 }
597 if err := ctx.Err(); err != nil {
598 return nil, err
599 }
600 idx, err := newIndex(ctx, e)
601 if err != nil {
602 return nil, err
603 }
604 return &snapshot{seq: g.Sequence, e: e, idx: idx}, nil
605}
606
607// contextReader reads from r until ctx is done.
608type contextReader struct {
609 ctx context.Context
610 r io.Reader
611 waitForData bool
612}
613
614func (c *contextReader) Read(p []byte) (int, error) {
615 for {
616 if err := c.ctx.Err(); err != nil {
617 return 0, err
618 }
619 n, err := c.r.Read(p)
620 if n > 0 {
621 c.waitForData = false
622 }
623 if !c.waitForData || err != io.EOF {
624 return n, err
625 }
626 // A nonblocking FIFO reports EOF before its first writer arrives.
627 // Wait for that writer without holding a blocking open syscall.
628 timer := time.NewTimer(10 * time.Millisecond)
629 select {
630 case <-c.ctx.Done():
631 timer.Stop()
632 return 0, c.ctx.Err()
633 case <-timer.C:
634 }
635 }
636}
637
638// route dispatches on the path's segments, each unescaped on its own, so
639// an escaped slash stays inside its segment. ok is false for a path whose
640// segments do not unescape.
641func (q *request) route(parts []string, ok bool) {
642 switch {
643 case !ok:
644 q.notFound()
645 case len(parts) == 1 && parts[0] == "":
646 q.plan()
647 case parts[0] == own:
648 q.notFound()
649 case len(parts) == 1, len(parts) == 2 && parts[1] == "":
650 q.home(parts[0])
651 case len(parts) == 3 && parts[1] == "knots":
652 q.knot(parts[0], parts[2])
653 case len(parts) >= 2 && parts[1] == "source":
654 q.source(parts[0], parts[2:])
655 default:
656 q.notFound()
657 }
658}
659
660// own is the first segment of the server's own paths, /-/. No project's
661// name can be it, or start with it.
662const own = "-"
663
664// home answers /<project>/, and /<project>, with a redirect to the
665// project's page: the tree at its published tip, with its README.
666func (q *request) home(project string) {
667 p, ok := q.project(project)
668 if !ok {
669 q.notFound()
670 return
671 }
672 q.redirect(treeURL(p.Name, p.SourceTip, nil))
673}
674
675func segments(escaped string) ([]string, bool) {
676 rest, ok := strings.CutPrefix(escaped, "/")
677 if !ok {
678 return nil, false
679 }
680 parts := strings.Split(rest, "/")
681 for i, p := range parts {
682 u, err := url.PathUnescape(p)
683 if err != nil {
684 return nil, false
685 }
686 parts[i] = u
687 }
688 return parts, true
689}
690
691// project is the export's project called name, when the export holds it
692// as public. Every route that names a project asks here first, and a
693// project it refuses answers as one that does not exist.
694func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) }
695
696func (idx *index) project(name string) (*export.Project, bool) {
697 p, ok := idx.projects[name]
698 if !ok || p.Visibility != export.Public {
699 return nil, false
700 }
701 return p, true
702}
703
704// notFound is the one 404 page, whatever was not found. It names nothing
705// of the request, so a hidden project, a missing one, an unreachable
706// commit and a missing path all answer alike.
707func (q *request) notFound() {
708 q.page(http.StatusNotFound, "error", "Not found", errorPage{
709 Heading: "Not found", Text: "Nothing is published at this address.",
710 })
711}
712
713// fail logs err and answers with the one 500 page, which says nothing of
714// the failure. A reader that went away is answered with nothing: git
715// killed for it fails, and that is no failure of the server's. A request
716// that ran out of time, or whose git did, answers 503.
717func (q *request) fail(err error) {
718 if q.r.Context().Err() != nil {
719 return
720 }
721 if q.ctx.Err() == nil && q.git != nil && q.git.Err() != nil {
722 err = fmt.Errorf("the request's git ran past %v: %w", q.s.gitTime, err)
723 }
724 q.s.log(err)
725 if q.ctx.Err() != nil || q.git != nil && q.git.Err() != nil {
726 q.busy()
727 return
728 }
729 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
730 Heading: "Something went wrong", Text: "The server could not read this page.",
731 })
732}
733
734// busy answers a request the server has no room for: a source request it
735// could not admit, a request that ran out of time, or a page the response
736// budget has no room for. A reader that went away is answered with
737// nothing.
738func (q *request) busy() {
739 if q.r.Context().Err() != nil {
740 return
741 }
742 q.w.Header().Set("Retry-After", "5")
743 q.static(http.StatusServiceUnavailable, htmlType, busyPage)
744}
745
746// redirect answers with a redirect to url.
747func (q *request) redirect(url string) { q.location = url }
748
749// write writes the rendered response, or nothing for a reader that went
750// away. It returns once the response is written, or the connection
751// failed or timed out.
752func (q *request) write() {
753 switch {
754 case q.location != "":
755 http.Redirect(q.w, q.r, q.location, http.StatusFound)
756 case q.status != 0:
757 h := q.w.Header()
758 h.Set("Content-Type", q.ctype)
759 h.Set("Content-Length", strconv.Itoa(q.body.n))
760 q.w.WriteHeader(q.status)
761 for _, p := range q.body.pieces {
762 if _, err := q.w.Write(p); err != nil {
763 return
764 }
765 }
766 }
767}
768
769// setHeaders sets the headers every response carries.
770func setHeaders(h http.Header) {
771 h.Set("Content-Security-Policy", csp)
772 h.Set("X-Content-Type-Options", "nosniff")
773 h.Set("X-Frame-Options", "DENY")
774 h.Set("Referrer-Policy", "no-referrer")
775 h.Set("Cross-Origin-Opener-Policy", "same-origin")
776 h.Set("Cross-Origin-Resource-Policy", "same-origin")
777 h.Set("Cache-Control", "no-cache")
778}