gunk-dev/the-valley

server.go

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