gunk-dev/the-valley

server.go

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