gunk-dev/the-valley

server.go

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