gunk-dev/the-valley

server.go

sourceee200607ca12main's published tip history
36.2 KiB
1// Package server is the web UI's read side. It serves the active export
2// of a receiver's store to anonymous readers, as the store's authorization
3// allows: the plan page, each knot, and a source browser over the main of
4// each project the authorization lets anyone read.
5//
6// # Snapshots
7//
8// Every request reads the store's authorization when it arrives, opens
9// the store's active generation once, with export.Store.Open, and renders
10// its whole response from that generation under that authorization. An
11// activation during the request changes nothing the request reads. The
12// server keeps a snapshot of the newest generation it has read under one
13// authorization: the export, decoded, and its index for anyone. A request
14// opens its generation only once the generation has a snapshot under the
15// authorization it read, and every such request serves from the one
16// snapshot. A new authorization indexes the cached export again, and
17// reads no export.json.
18//
19// A request whose generation has no snapshot yet waits for a load. A load
20// runs in a worker of its own, which opens the active generation, holds
21// it while it reads and indexes the export, and then gives it back. At
22// most MaxLoads workers run at once. The requests that wait for a
23// generation share one load, so each export is read once. A waiting
24// request holds no generation, and stops waiting when its reader goes away
25// or its time runs out. A load stops once no request waits for it, and
26// the server keeps nothing of what it read.
27//
28// # Admission
29//
30// Every request's time is bounded from when it arrives: its waits, its
31// git commands and its rendering. A source request runs git, and at most
32// MaxGit run at once. A source request takes one of those slots before
33// it opens a generation, and waits for one only while fewer than
34// MaxWaiting wait. A request waits for a load only while fewer than
35// MaxLoadWaiting wait, and it is admitted among them before it opens
36// anything. A request the server cannot admit, or that runs out of time,
37// answers 503.
38//
39// A source request holds its git slot for gitTimeout at most. That time
40// runs from when it takes the slot, and covers its wait for its
41// generation's export to be read and its git commands. It gives the slot
42// back before it renders its page. A source request that runs out of
43// that time answers 503.
44//
45// # Responses
46//
47// A response is rendered whole before it is written. A request gives back
48// its git slot before it renders, and its generation before it writes, so
49// a reader that reads slowly holds neither. It keeps its response until
50// the response is written.
51//
52// A response's body is at most MaxResponse bytes. A page that would pass
53// it stops rendering there, and the request answers with a short page
54// that says the page is too large. Rendered responses take their memory
55// from a budget of MaxBuffered bytes, which they give back once they are
56// written. A request that finds the budget spent answers 503.
57//
58// Responses larger than SmallPage hold at most MaxLarge of the budget
59// between them, counting their first SmallPage bytes. So readers that
60// never read large pages hold at most MaxLarge, however many there are,
61// and the rest of the budget is always there for small pages: the plan,
62// most knots, and most directories and files.
63//
64// # Routes
65//
66// The server answers GET and HEAD alone. A project's pages are under its
67// group's name and its own web name, which need not be its identifier:
68//
69// / the plan page
70// /<group>/<project>/ a redirect to the tree at main's tip
71// /<group>/<project>/knots/<id> one knot, with its body and comments
72// /<group>/<project>/source/ a redirect to the tree at main's tip
73// /<group>/<project>/source/tree/<commit>/<path> a directory and its README
74// /<group>/<project>/source/blob/<commit>/<path> a file
75// /<group>/<project>/source/log/<commit> the history that ends at a commit
76// /<group>/<project>/source/log/<commit>?from=… an older page of that history
77// /<group>/<former name>/… a permanent redirect
78// /<alias>/… a permanent redirect
79// /-/... the server's own paths
80//
81// A group's alias redirects to the same path under the group's name, a
82// project's former name to the same path under its web name, and a
83// project's short alias to the same path under /<group>/<project>. The
84// redirect keeps the rest of the path and the query as they were sent.
85//
86// Every path but / and those under /-/ starts with a group's name or an
87// alias. No name starts with "-", so no group's path is ever one of the
88// server's own, whatever paths the server adds there. It serves no page
89// under /-/, and answers each path there with the one 404. Package export
90// refuses an export whose group names and aliases collide, or whose
91// projects' web names and former names collide within a group.
92//
93// Every source link names its group and project, a full commit ID and a
94// path. A commit is served only when export.Reachable finds it reachable
95// from the project's published source tip, and a path is resolved one
96// tree entry at a time from that commit's tree, so no other object can be
97// named.
98//
99// # Access
100//
101// The store's authorization decides what is served. A request reads it
102// from the store when it arrives, and reads it again once its response is
103// rendered, before the first byte is written. A response rendered under an
104// authorization that has since been replaced is not written: the request
105// renders again under the new one. So the next request after the receiver
106// stores an authorization is held to it, with no restart and no cache in
107// between. A store with no authorization, or one that cannot be read,
108// serves no project: every page says nothing is published.
109//
110// The index a request serves from holds only the projects the
111// authorization lets anyone read, under the identity the export gives
112// them (visible). Every route, every reference between projects, every
113// alias and every redirect is built from that index, so a project the
114// authorization does not name answers exactly as a project that does not
115// exist: every 404 is the same page, made once when the server starts.
116//
117// # Safety
118//
119// Every page is rendered on the server with html/template, so everything
120// read from the export or a repository is escaped. Each response carries
121// a strict Content-Security-Policy: default-src 'self', and one inline
122// stylesheet and one inline script admitted by their SHA-256 hashes. No
123// repository file is served as itself: a file is shown as escaped text,
124// and a binary file or one larger than MaxFile is not shown at all.
125package server
126
127import (
128 "bytes"
129 "context"
130 "errors"
131 "fmt"
132 "io"
133 "log"
134 "net/http"
135 "net/url"
136 "os"
137 "strconv"
138 "strings"
139 "sync"
140 "syscall"
141 "time"
142
143 "the-valley/web/export"
144)
145
146// StaleAfter is how old an export may be before its pages mark it stale.
147const StaleAfter = 5 * time.Minute
148
149// The bounds on what one request reads from a repository.
150const (
151 // MaxFile is the largest file a page shows, README or otherwise.
152 MaxFile = 1 << 20
153 // MaxLines is the most lines of a file a page shows.
154 MaxLines = 10_000
155 // MaxShown is the most bytes a page spends on a file's text once it
156 // is escaped, counting each line's markup on a file page. A page
157 // stops at the line that would take it past MaxShown.
158 MaxShown = 2 << 20
159 // MaxEntries is the most entries a directory page lists.
160 MaxEntries = 1000
161 // MaxRead is the most bytes of output a page reads from one git
162 // listing: a directory's entries, or a page of history. git is
163 // stopped once it prints more.
164 MaxRead = 4 << 20
165 // MaxDepth is the most path segments a source route takes.
166 MaxDepth = 64
167 // MaxPlanDepth is the most levels of knots a milestone's tree
168 // shows, and the most parents a knot's trail names.
169 MaxPlanDepth = 32
170 // LogPage is the number of commits on one page of a log.
171 LogPage = 50
172 // MaxFrontier is the most commits a link to an older page of a log
173 // names: the commits that page starts from.
174 MaxFrontier = 64
175 // MaxLeftToShow is the most commits a page of a log leaves to show.
176 // Its Older link starts from MaxFrontier of them, and each of the
177 // rest has a link of its own. A page ends before a merge that would
178 // leave more.
179 MaxLeftToShow = 192
180 // MaxParents is the most parents of one commit that a page of a log
181 // follows: the first MaxParents, in the commit's order. A page marks
182 // a merge that has more, and leaves none of its others to show.
183 MaxParents = 128
184 // MaxGit is the most source requests that run git at once.
185 MaxGit = 8
186 // MaxWaiting is the most source requests that wait for one of the
187 // MaxGit to finish. A source request that finds every slot taken
188 // and MaxWaiting waiting answers 503 at once.
189 MaxWaiting = 16
190 // requestTimeout bounds a request from when it arrives: its wait for
191 // a git slot or for its generation's export to be read, its git
192 // commands and its rendering.
193 requestTimeout = 15 * time.Second
194 // gitTimeout bounds how long a source request holds its git slot,
195 // from when it takes it: its wait for its generation's export to be
196 // read, and its git commands, all of them together. A source request
197 // still holding its slot past it answers 503.
198 gitTimeout = 5 * time.Second
199 // MaxLoads is the most loads that run at once, each in a worker of
200 // its own that reads one generation's export.
201 MaxLoads = 2
202 // MaxLoadWaiting is the most requests that wait for loads. A request
203 // that would wait while MaxLoadWaiting do answers 503 at once.
204 MaxLoadWaiting = 64
205 // MaxResponse is the most bytes a response's body takes. A page
206 // that would take more stops rendering, and the request answers with
207 // a short page that says the page is too large.
208 MaxResponse = 8 << 20
209 // MaxBuffered is the most bytes of rendered responses the server
210 // holds at once, from when each starts rendering until it is
211 // written. A response takes them in pieces of pieceSize as it
212 // renders.
213 MaxBuffered = 64 << 20
214 // SmallPage is the largest response that takes from MaxBuffered
215 // alone.
216 SmallPage = 256 << 10
217 // MaxLarge is the most of MaxBuffered that responses larger than
218 // SmallPage hold between them, all of each counted. The rest,
219 // MaxBuffered less MaxLarge, is left to smaller responses.
220 MaxLarge = 48 << 20
221 // pieceSize is the size of the pieces a response is rendered into.
222 pieceSize = 64 << 10
223)
224
225// Config is what a Server serves from.
226type Config struct {
227 // Store is the receiver's state directory.
228 Store *export.Store
229 // Now is the clock an export's age is read against. Nil is time.Now.
230 Now func() time.Time
231 // Log is told of each failure a reader sees only as an error page.
232 // Nil logs with the standard logger.
233 Log func(error)
234}
235
236// Server is the read side's HTTP handler.
237type Server struct {
238 store *export.Store
239 now func() time.Time
240 log func(error)
241 // timeout is requestTimeout, gitTime is gitTimeout, and maxResponse
242 // is MaxResponse. A test shortens any of them.
243 timeout time.Duration
244 gitTime time.Duration
245 maxResponse int
246 // slots holds a token for each source request running git, and
247 // waiting one for each source request waiting for a slot.
248 slots chan struct{}
249 waiting chan struct{}
250 // loaders holds a token for each load's worker, and loadWaiting one
251 // for each request waiting for a load.
252 loaders chan struct{}
253 loadWaiting chan struct{}
254 // pieces guards the response budget. held counts the pieces of
255 // responses being rendered or written, of MaxBuffered bytes in pieces
256 // of pieceSize. large counts the pieces of those responses that are
257 // larger than SmallPage, every piece of each, of MaxLarge bytes.
258 pieces sync.Mutex
259 held int
260 large int
261
262 mu sync.Mutex
263 // cached is the newest generation's snapshot read so far, under the
264 // authorization a load read last.
265 cached *snapshot
266 // auth is the last valid authorization readAuthorization read.
267 auth authState
268 // loads are the loads a request that waits may still join: those that
269 // have not ended, and that some request waits for.
270 loads map[*load]struct{}
271
272 // The test hooks. opened, when set, is called with each generation a
273 // request opens, before the request reads anything from it. admitted
274 // is called when a source request takes a git slot, before it opens
275 // a generation. loading is called by a load's worker with the
276 // generation it opened, before it reads the generation's export.
277 // rendering is called with a page's name before the page renders.
278 opened func(export.Generation)
279 admitted func()
280 loading func(export.Generation)
281 rendering func(name string)
282 // checked is called once a request has rendered its response, before
283 // it reads the authorization again. starting is called once that read
284 // found the authorization unchanged, with the serving lock held, before
285 // the response's headers are written.
286 checked func()
287 starting func()
288}
289
290// New is a Server over c's store.
291func New(c Config) *Server {
292 s := &Server{store: c.Store, now: c.Now, log: c.Log,
293 timeout: requestTimeout, gitTime: gitTimeout, maxResponse: MaxResponse,
294 slots: make(chan struct{}, MaxGit), waiting: make(chan struct{}, MaxWaiting),
295 loaders: make(chan struct{}, MaxLoads), loadWaiting: make(chan struct{}, MaxLoadWaiting),
296 loads: map[*load]struct{}{}}
297 if s.now == nil {
298 s.now = time.Now
299 }
300 if s.log == nil {
301 s.log = func(err error) { log.Print(err) }
302 }
303 return s
304}
305
306// snapshot is one generation's export, decoded, and its index under one
307// authorization, for anyone. A generation's export.json never changes once
308// it is active, and its sequence names it, and auth is the stored
309// authorization's signed note the index was built under, so a snapshot
310// serves every request that opens its generation under that authorization.
311type snapshot struct {
312 seq int64
313 auth authState
314 e *export.Export
315 idx *index
316}
317
318// authState is the stored authorization as one read found it: the signed
319// note, and the authorization parsed from it, or the error that left none.
320// Two reads are of one revision when their notes are the same bytes.
321type authState struct {
322 signed []byte
323 a *export.Authorization
324 err error
325}
326
327// same reports whether two reads found one revision of the authorization.
328func (st authState) same(o authState) bool {
329 return bytes.Equal(st.signed, o.signed) && (st.a == nil) == (o.a == nil)
330}
331
332// readAuthorization reads the stored authorization. It reads the file on
333// every call, and parses it again only when its bytes changed since the
334// last valid one it read.
335func (s *Server) readAuthorization() authState {
336 signed, err := s.store.ReadAuthorization()
337 if err != nil {
338 return authState{err: err}
339 }
340 s.mu.Lock()
341 last := s.auth
342 s.mu.Unlock()
343 if last.a != nil && bytes.Equal(last.signed, signed) {
344 return last
345 }
346 a, err := export.ReadStoredAuthorization(signed)
347 if err != nil {
348 return authState{signed: signed, err: err}
349 }
350 st := authState{signed: signed, a: a}
351 s.mu.Lock()
352 s.auth = st
353 s.mu.Unlock()
354 return st
355}
356
357// load reads the active generation's export for every request that
358// waits for it. It starts once one of those requests takes a loader slot
359// for it, and runs in a worker of its own, so a request can stop waiting
360// while the load goes on for the others.
361type load struct {
362 // wants counts the requests that wait for the load. cancel is set once
363 // the load has started, and stops its worker. The worker sets opened
364 // and seq once it has opened a generation. All are guarded by the
365 // server's mu.
366 wants int
367 cancel context.CancelFunc
368 opened bool
369 seq int64
370 auth authState
371 // started is closed once the load starts, and done once its worker
372 // ends. err is the worker's error, set before done is closed.
373 started chan struct{}
374 done chan struct{}
375 err error
376}
377
378// request is one request, the generation it serves from, and the
379// response it renders.
380type request struct {
381 s *Server
382 w http.ResponseWriter
383 r *http.Request
384 // ctx is the context the request waits and renders under. It ends
385 // at the request's deadline, or when its reader goes away. git is
386 // the context a source request holds its git slot under: it waits
387 // for its generation's export and runs git under it. git ends
388 // gitTime after the request takes its slot, or with ctx. slot gives
389 // the slot back.
390 ctx context.Context
391 git context.Context
392 slot func()
393 g export.Generation
394 e *export.Export
395 idx *index
396 now time.Time
397 // auth is the stored authorization as the request read it when it
398 // arrived. The request serves what it allows, and its response is
399 // written only if the authorization is the same when it is.
400 auth authState
401
402 // The response: a status and a page, or a redirect. It is written
403 // once the request has given back its generation and git slot, and
404 // the page's pieces are given back to the budget once it is written.
405 status int
406 ctype string
407 body *body
408 location string
409 permanent bool
410}
411
412// ServeHTTP reads the stored authorization, renders the response under
413// it, and reads it again before the first byte is written. A response the
414// authorization changed under is not written: the request is rendered
415// again under the new one, at most maxRenders times in all, and then
416// answers 503. So every response, a redirect and an error page too, is
417// one the authorization stored when it is written allows.
418func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
419 ctx, cancel := context.WithTimeout(r.Context(), s.timeout)
420 defer cancel()
421 for render := 1; ; render++ {
422 h := w.Header()
423 for k := range h {
424 delete(h, k)
425 }
426 setHeaders(h)
427 q := &request{s: s, w: w, r: r, ctx: ctx, now: s.now(), auth: s.readAuthorization()}
428 q.serve()
429 if s.checked != nil {
430 s.checked()
431 }
432 // The last read and the response's headers happen under the
433 // serving lock, shared, and the receiver renames a new
434 // authorization into place under it, exclusively. A response
435 // whose headers are written after the receiver replies was
436 // checked against the new authorization. The wait ends with the
437 // request's deadline, or when its reader goes away, and then
438 // nothing rendered is written: busy answers 503, or nothing to a
439 // reader that went away.
440 release, err := s.store.HoldServing(ctx)
441 if err != nil {
442 q.discard()
443 if ctx.Err() == nil {
444 q.s.log(fmt.Errorf("taking the serving lock: %w", err))
445 }
446 q.busy()
447 q.write(func() {})
448 return
449 }
450 if s.readAuthorization().same(q.auth) {
451 if s.starting != nil {
452 s.starting()
453 }
454 q.write(release)
455 q.drop()
456 return
457 }
458 release()
459 q.discard()
460 if render == maxRenders {
461 q.busy()
462 q.write(func() {})
463 return
464 }
465 }
466}
467
468// maxRenders is how many times a request is rendered while the stored
469// authorization keeps changing under it.
470const maxRenders = 3
471
472// serve renders the request's response. A source request is admitted
473// first, and holds its git slot until it renders, or until serve returns
474// when it renders nothing. Every request holds its generation until serve
475// returns.
476func (q *request) serve() {
477 if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead {
478 q.w.Header().Set("Allow", "GET, HEAD")
479 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
480 Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.",
481 })
482 return
483 }
484 if q.auth.a == nil {
485 if !errors.Is(q.auth.err, export.ErrNoAuthorization) {
486 q.s.log(fmt.Errorf("the stored authorization cannot be read, so nothing is served: %w", q.auth.err))
487 }
488 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
489 Heading: "Nothing published yet", Text: "This server holds no authorization to serve anything.",
490 })
491 return
492 }
493 parts, ok := segments(q.r.URL.EscapedPath())
494 wait := q.ctx
495 if ok && runsGit(parts) {
496 done, admitted := q.s.admit(q.ctx)
497 if !admitted {
498 q.busy()
499 return
500 }
501 q.slot = done
502 defer q.giveSlot()
503 var cancel context.CancelFunc
504 q.git, cancel = context.WithTimeout(q.ctx, q.s.gitTime)
505 defer cancel()
506 wait = q.git
507 if q.s.admitted != nil {
508 q.s.admitted()
509 }
510 }
511 g, snap, release, err := q.s.open(wait, q.auth)
512 defer release()
513 switch {
514 case errors.Is(err, export.ErrNoExport):
515 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
516 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
517 })
518 return
519 case errors.Is(err, errLoadsFull), errors.Is(err, errAuthorizationChanged):
520 q.busy()
521 return
522 case err != nil:
523 q.fail(err)
524 return
525 }
526 if q.s.opened != nil {
527 q.s.opened(g)
528 }
529 q.g, q.e, q.idx = g, snap.e, snap.idx
530 q.route(parts, ok)
531}
532
533// runsGit reports whether a path is a source route that reads a
534// repository: a tree, a file or a log of something that may be a group's
535// project. It reads the path's shape alone, before the export is read, so
536// a path through a group's alias that has the shape takes a git slot too,
537// and gives it back when it redirects.
538func runsGit(parts []string) bool {
539 return len(parts) >= 4 && export.ValidName(parts[0]) && export.ValidName(parts[1]) && parts[2] == "source" &&
540 (parts[3] == "tree" || parts[3] == "blob" || parts[3] == "log")
541}
542
543// giveSlot gives back the request's git slot, when it holds one.
544func (q *request) giveSlot() {
545 if q.slot != nil {
546 q.slot()
547 q.slot = nil
548 }
549}
550
551// admit takes a git slot for a source request. When every slot is taken,
552// it waits for one until ctx is done, unless MaxWaiting requests wait
553// already. done gives the slot back.
554func (s *Server) admit(ctx context.Context) (done func(), ok bool) {
555 give := func() { <-s.slots }
556 select {
557 case s.slots <- struct{}{}:
558 return give, true
559 default:
560 }
561 select {
562 case s.waiting <- struct{}{}:
563 default:
564 return nil, false
565 }
566 defer func() { <-s.waiting }()
567 select {
568 case s.slots <- struct{}{}:
569 return give, true
570 case <-ctx.Done():
571 return nil, false
572 }
573}
574
575// errLoadsFull is open's error for a request that would wait for a load
576// while MaxLoadWaiting requests wait already.
577var errLoadsFull = errors.New("too many requests wait for exports to be read")
578
579// errAuthorizationChanged is open's error for a request whose
580// authorization was replaced while it waited. ServeHTTP renders it again
581// under the new one.
582var errAuthorizationChanged = errors.New("the stored authorization changed")
583
584// open opens the active generation once its snapshot under auth is
585// cached, and returns both. release gives the generation back.
586//
587// A request whose active generation has no snapshot waits for a load,
588// and opens nothing until the load ends. It is admitted among the
589// MaxLoadWaiting requests that may wait before it waits, and it keeps its
590// place until open returns. Once the load ends it looks again, since
591// another generation may have been activated meanwhile.
592func (s *Server) open(ctx context.Context, auth authState) (g export.Generation, snap *snapshot, release func(), err error) {
593 release = func() {}
594 waiting := false
595 defer func() {
596 if waiting {
597 <-s.loadWaiting
598 }
599 }()
600 for {
601 seq, err := s.store.Active()
602 if err != nil {
603 return g, nil, release, err
604 }
605 s.mu.Lock()
606 snap = s.cached
607 s.mu.Unlock()
608 if snap != nil && snap.seq == seq && snap.auth.same(auth) {
609 g, release, err = s.store.Open()
610 if err != nil || g.Sequence == seq {
611 return g, snap, release, err
612 }
613 release() // active moved on since it was read
614 release = func() {}
615 continue
616 }
617 if !waiting {
618 select {
619 case s.loadWaiting <- struct{}{}:
620 waiting = true
621 default:
622 return g, nil, release, errLoadsFull
623 }
624 }
625 if err := s.await(ctx, seq, auth); err != nil {
626 return g, nil, release, err
627 }
628 if !s.readAuthorization().same(auth) {
629 return g, nil, release, errAuthorizationChanged
630 }
631 }
632}
633
634// await waits until a load of generation seq under auth, or of a newer
635// generation, ends, or until ctx is done. It joins a load that will read
636// one of those, since a worker reads whatever generation is active and
637// whatever authorization is stored once it starts, and otherwise makes
638// one.
639//
640// A load starts only once one of its requests takes a loader slot for
641// it. While every slot is taken, each of its requests waits for one, and
642// the first to take one starts the load, so no load is queued that no
643// request waits for. A request that stops waiting leaves the load, and
644// the last to leave stops it.
645func (s *Server) await(ctx context.Context, seq int64, auth authState) error {
646 s.mu.Lock()
647 if c := s.cached; c != nil && (c.seq > seq || c.seq == seq && c.auth.same(auth)) {
648 s.mu.Unlock()
649 return nil
650 }
651 var l *load
652 for m := range s.loads {
653 if !m.opened || m.seq > seq || m.seq == seq && m.auth.same(auth) {
654 l = m
655 break
656 }
657 }
658 if l == nil {
659 l = &load{started: make(chan struct{}), done: make(chan struct{})}
660 s.loads[l] = struct{}{}
661 }
662 l.wants++
663 s.mu.Unlock()
664 select {
665 case <-l.started:
666 case s.loaders <- struct{}{}:
667 if !s.start(l) {
668 <-s.loaders
669 }
670 case <-ctx.Done():
671 s.leave(l)
672 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
673 }
674 select {
675 case <-l.done:
676 return l.err
677 case <-ctx.Done():
678 s.leave(l)
679 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
680 }
681}
682
683// start starts l's worker, for the request that took a loader slot for
684// it. It is false when another request started it already.
685func (s *Server) start(l *load) bool {
686 s.mu.Lock()
687 defer s.mu.Unlock()
688 if l.cancel != nil {
689 return false
690 }
691 ctx, cancel := context.WithCancel(context.Background())
692 l.cancel = cancel
693 close(l.started)
694 go s.run(ctx, l)
695 return true
696}
697
698// leave is a request that stopped waiting for l. Once no request waits for
699// it, no request may join it, and a load that started is stopped.
700func (s *Server) leave(l *load) {
701 s.mu.Lock()
702 defer s.mu.Unlock()
703 if l.wants--; l.wants > 0 {
704 return
705 }
706 delete(s.loads, l)
707 if l.cancel != nil {
708 l.cancel()
709 }
710}
711
712// run is l's worker. It caches the snapshot it reads when the snapshot's
713// generation is newer than the cached one's, or the same generation under
714// another authorization, so a load of an older generation never displaces
715// a newer. A load that was stopped caches nothing: leave stops it under
716// mu, and run looks under mu. The worker gives back its generation before
717// it ends, and then its loader slot.
718func (s *Server) run(ctx context.Context, l *load) {
719 snap, err := s.read(ctx, l)
720 s.mu.Lock()
721 delete(s.loads, l)
722 if snap != nil && ctx.Err() == nil && (s.cached == nil || s.cached.seq < snap.seq ||
723 s.cached.seq == snap.seq && !s.cached.auth.same(snap.auth)) {
724 s.cached = snap
725 }
726 l.err = err
727 s.mu.Unlock()
728 l.cancel()
729 close(l.done)
730 <-s.loaders
731}
732
733// read opens the active generation for l, reads the stored
734// authorization, and holds the generation while it reads and indexes the
735// generation's export under that authorization. It reads nothing when the
736// generation is cached already under that authorization or another load
737// reads the same, and its waiting requests look again. A generation cached
738// under another authorization is not read again: its export is indexed
739// anew. It stops reading once ctx is done.
740func (s *Server) read(ctx context.Context, l *load) (snap *snapshot, err error) {
741 // Cancellation can close the file during any operation. Report the
742 // context error instead of the resulting descriptor error.
743 defer func() {
744 if stopped := ctx.Err(); stopped != nil {
745 snap, err = nil, stopped
746 }
747 }()
748 if err := ctx.Err(); err != nil {
749 return nil, err
750 }
751 g, release, err := s.store.Open()
752 if err != nil {
753 return nil, err
754 }
755 defer release()
756 auth := s.readAuthorization()
757 if auth.a == nil {
758 return nil, nil
759 }
760 s.mu.Lock()
761 cached := s.cached
762 read := cached == nil || cached.seq < g.Sequence || cached.seq == g.Sequence && !cached.auth.same(auth)
763 for m := range s.loads {
764 if m != l && m.opened && m.seq == g.Sequence && m.auth.same(auth) {
765 read = false
766 }
767 }
768 l.opened, l.seq, l.auth = true, g.Sequence, auth
769 s.mu.Unlock()
770 if !read {
771 return nil, nil
772 }
773 if cached != nil && cached.seq == g.Sequence {
774 idx, err := newIndex(ctx, cached.e, visible(cached.e, auth.a, export.Anyone))
775 if err != nil {
776 return nil, err
777 }
778 return &snapshot{seq: g.Sequence, auth: auth, e: cached.e, idx: idx}, nil
779 }
780 if s.loading != nil {
781 s.loading(g)
782 }
783 f, err := os.OpenFile(g.ExportPath(), os.O_RDONLY|syscall.O_NONBLOCK, 0)
784 if err != nil {
785 return nil, err
786 }
787 defer f.Close()
788 // Nonblocking open avoids waiting for a FIFO writer. Go's file poller
789 // waits for reads, and Close wakes a read when the last waiter leaves.
790 stop := context.AfterFunc(ctx, func() { _ = f.Close() })
791 defer stop()
792 info, err := f.Stat()
793 if err != nil {
794 return nil, err
795 }
796 data, err := io.ReadAll(&contextReader{ctx: ctx, r: f, waitForData: info.Mode()&os.ModeNamedPipe != 0})
797 if ctx.Err() != nil {
798 return nil, ctx.Err()
799 }
800 if err != nil {
801 return nil, fmt.Errorf("reading generation %d's export: %w", g.Sequence, err)
802 }
803 e, err := export.DecodeContext(ctx, bytes.NewReader(data))
804 if err != nil {
805 return nil, err
806 }
807 if err := ctx.Err(); err != nil {
808 return nil, err
809 }
810 idx, err := newIndex(ctx, e, visible(e, auth.a, export.Anyone))
811 if err != nil {
812 return nil, err
813 }
814 return &snapshot{seq: g.Sequence, auth: auth, e: e, idx: idx}, nil
815}
816
817// contextReader reads from r until ctx is done.
818type contextReader struct {
819 ctx context.Context
820 r io.Reader
821 waitForData bool
822}
823
824func (c *contextReader) Read(p []byte) (int, error) {
825 for {
826 if err := c.ctx.Err(); err != nil {
827 return 0, err
828 }
829 n, err := c.r.Read(p)
830 if n > 0 {
831 c.waitForData = false
832 }
833 if !c.waitForData || err != io.EOF {
834 return n, err
835 }
836 // A nonblocking FIFO reports EOF before its first writer arrives.
837 // Wait for that writer without holding a blocking open syscall.
838 timer := time.NewTimer(10 * time.Millisecond)
839 select {
840 case <-c.ctx.Done():
841 timer.Stop()
842 return 0, c.ctx.Err()
843 case <-timer.C:
844 }
845 }
846}
847
848// route dispatches on the path's segments, each unescaped on its own, so
849// an escaped slash stays inside its segment. ok is false for a path whose
850// segments do not unescape. The first segment is a group's name or an
851// alias, and under a group's name the second is a project's name.
852func (q *request) route(parts []string, ok bool) {
853 switch {
854 case !ok:
855 q.notFound()
856 case len(parts) == 1 && parts[0] == "":
857 q.plan()
858 case parts[0] == own:
859 q.notFound()
860 default:
861 if to, ok := q.idx.aliases[parts[0]]; ok {
862 q.moved(to, 1)
863 return
864 }
865 if len(parts) >= 2 {
866 if p := q.idx.groups[parts[0]][parts[1]]; p != nil {
867 q.projectRoute(p.Name, parts[2:])
868 return
869 }
870 if to, ok := q.idx.formers[parts[0]][parts[1]]; ok {
871 q.moved(to, 2)
872 return
873 }
874 }
875 q.notFound()
876 }
877}
878
879// projectRoute dispatches on the segments of a path after its group's and
880// its project's names.
881func (q *request) projectRoute(project string, rest []string) {
882 switch {
883 case len(rest) == 0, len(rest) == 1 && rest[0] == "":
884 q.home(project)
885 case len(rest) == 2 && rest[0] == "knots":
886 q.knot(project, rest[1])
887 case len(rest) >= 1 && rest[0] == "source":
888 q.source(project, rest[1:])
889 default:
890 q.notFound()
891 }
892}
893
894// moved answers a path under an alias or a former name with a permanent
895// redirect to the same path under to, the escaped URL the path's first n
896// segments stand for. The rest of the path after them, and the query,
897// are kept as they were sent, even a query that is a bare "?".
898func (q *request) moved(to string, n int) {
899 esc := strings.Split(strings.TrimPrefix(q.r.URL.EscapedPath(), "/"), "/")
900 rest := ""
901 if len(esc) > n {
902 rest = "/" + strings.Join(esc[n:], "/")
903 }
904 if q.r.URL.RawQuery != "" || q.r.URL.ForceQuery {
905 rest += "?" + q.r.URL.RawQuery
906 }
907 q.location, q.permanent = to+rest, true
908}
909
910// own is the first segment of the server's own paths, /-/. No group's
911// name, and no alias, can be it, or start with it.
912const own = "-"
913
914// home answers /<group>/<project>/, and /<group>/<project>, with a
915// redirect to the project's page: the tree at its published tip, with its
916// README.
917func (q *request) home(project string) {
918 p, ok := q.project(project)
919 if !ok {
920 q.notFound()
921 return
922 }
923 q.redirect(treeURL(q.idx.bases[p.Name], p.SourceTip, nil))
924}
925
926func segments(escaped string) ([]string, bool) {
927 rest, ok := strings.CutPrefix(escaped, "/")
928 if !ok {
929 return nil, false
930 }
931 parts := strings.Split(rest, "/")
932 for i, p := range parts {
933 u, err := url.PathUnescape(p)
934 if err != nil {
935 return nil, false
936 }
937 parts[i] = u
938 }
939 return parts, true
940}
941
942// project is the export's project called name, when the export holds it
943// as public, in a group. Every route that names a project asks here
944// first, and a project it refuses answers as one that does not exist.
945func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) }
946
947func (idx *index) project(name string) (*export.Project, bool) {
948 p, ok := idx.projects[name]
949 if _, placed := idx.bases[name]; !ok || !placed {
950 return nil, false
951 }
952 return p, true
953}
954
955// notFound is the one 404 page, whatever was not found. It is made once,
956// when the server starts, and names nothing of the request or the export,
957// so a hidden project, a missing one, an unreachable commit and a missing
958// path all answer alike, byte for byte.
959func (q *request) notFound() {
960 q.static(http.StatusNotFound, htmlType, notFoundPage)
961}
962
963// fail logs err and answers with the one 500 page, which says nothing of
964// the failure. A reader that went away is answered with nothing: git
965// killed for it fails, and that is no failure of the server's. A request
966// that ran out of time, or held its git slot past gitTime, answers 503.
967func (q *request) fail(err error) {
968 if q.r.Context().Err() != nil {
969 return
970 }
971 if q.ctx.Err() == nil && q.git != nil && q.git.Err() != nil {
972 err = fmt.Errorf("the request held its git slot past %v: %w", q.s.gitTime, err)
973 }
974 q.s.log(err)
975 if q.ctx.Err() != nil || q.git != nil && q.git.Err() != nil {
976 q.busy()
977 return
978 }
979 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
980 Heading: "Something went wrong", Text: "The server could not read this page.",
981 })
982}
983
984// busy answers a request the server has no room for: a source request it
985// could not admit, a request that ran out of time, or a page the response
986// budget has no room for. A reader that went away is answered with
987// nothing.
988func (q *request) busy() {
989 if q.r.Context().Err() != nil {
990 return
991 }
992 q.w.Header().Set("Retry-After", "5")
993 q.static(http.StatusServiceUnavailable, htmlType, busyPage)
994}
995
996// discard drops the rendered response, a page or a redirect, so that none
997// of it is written.
998func (q *request) discard() {
999 q.drop()
1000 q.status, q.body, q.location, q.permanent = 0, nil, "", false
1001}
1002
1003// redirect answers with a redirect to url.
1004func (q *request) redirect(url string) { q.location = url }
1005
1006// write writes the rendered response, or nothing for a reader that went
1007// away. It returns once the response is written, or the connection
1008// failed or timed out. A permanent redirect names its location as it was
1009// made, with no cleaning, so the path it redirects to is the one the
1010// reader sent under another name.
1011//
1012// released is called once the headers are written, and before the body is,
1013// or at once when there is nothing to write.
1014func (q *request) write(released func()) {
1015 defer released()
1016 switch {
1017 case q.location != "" && q.permanent:
1018 q.w.Header().Set("Location", q.location)
1019 q.w.WriteHeader(http.StatusPermanentRedirect)
1020 case q.location != "":
1021 http.Redirect(releasing{q.w, released}, q.r, q.location, http.StatusFound)
1022 case q.status != 0:
1023 h := q.w.Header()
1024 h.Set("Content-Type", q.ctype)
1025 h.Set("Content-Length", strconv.Itoa(q.body.n))
1026 q.w.WriteHeader(q.status)
1027 released()
1028 for _, p := range q.body.pieces {
1029 if _, err := q.w.Write(p); err != nil {
1030 return
1031 }
1032 }
1033 }
1034}
1035
1036// releasing is a response writer that calls released once the headers are
1037// written, before any of the body is, so http.Redirect writes its short
1038// body after the serving lock is let go, as every other response does.
1039type releasing struct {
1040 http.ResponseWriter
1041 released func()
1042}
1043
1044func (w releasing) WriteHeader(status int) {
1045 w.ResponseWriter.WriteHeader(status)
1046 w.released()
1047}
1048
1049// setHeaders sets the headers every response carries.
1050func setHeaders(h http.Header) {
1051 h.Set("Content-Security-Policy", csp)
1052 h.Set("X-Content-Type-Options", "nosniff")
1053 h.Set("X-Frame-Options", "DENY")
1054 h.Set("Referrer-Policy", "no-referrer")
1055 h.Set("Cross-Origin-Opener-Policy", "same-origin")
1056 h.Set("Cross-Origin-Resource-Policy", "same-origin")
1057 h.Set("Cache-Control", "no-cache")
1058}