gunk-dev/the-valley

server.go

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