gunk-dev/the-valley

server.go

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