gunk-dev/the-valley

server.go

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