gunk-dev/the-valley

server.go

sourcec374b23ad1f3main's published tip history
35.4 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.
437 release, err := s.store.HoldServing()
438 if err != nil {
439 q.drop()
440 q.s.log(fmt.Errorf("taking the serving lock: %w", err))
441 q.busy()
442 q.write(func() {})
443 return
444 }
445 if s.readAuthorization().same(q.auth) {
446 if s.starting != nil {
447 s.starting()
448 }
449 q.write(release)
450 q.drop()
451 return
452 }
453 release()
454 q.drop()
455 if render == maxRenders {
456 q.busy()
457 q.write(func() {})
458 return
459 }
460 }
461}
462
463// maxRenders is how many times a request is rendered while the stored
464// authorization keeps changing under it.
465const maxRenders = 3
466
467// serve renders the request's response. A source request is admitted
468// first, and holds its git slot until it renders, or until serve returns
469// when it renders nothing. Every request holds its generation until serve
470// returns.
471func (q *request) serve() {
472 if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead {
473 q.w.Header().Set("Allow", "GET, HEAD")
474 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
475 Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.",
476 })
477 return
478 }
479 if q.auth.a == nil {
480 if !errors.Is(q.auth.err, export.ErrNoAuthorization) {
481 q.s.log(fmt.Errorf("the stored authorization cannot be read, so nothing is served: %w", q.auth.err))
482 }
483 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
484 Heading: "Nothing published yet", Text: "This server holds no authorization to serve anything.",
485 })
486 return
487 }
488 parts, ok := segments(q.r.URL.EscapedPath())
489 wait := q.ctx
490 if ok && runsGit(parts) {
491 done, admitted := q.s.admit(q.ctx)
492 if !admitted {
493 q.busy()
494 return
495 }
496 q.slot = done
497 defer q.giveSlot()
498 var cancel context.CancelFunc
499 q.git, cancel = context.WithTimeout(q.ctx, q.s.gitTime)
500 defer cancel()
501 wait = q.git
502 if q.s.admitted != nil {
503 q.s.admitted()
504 }
505 }
506 g, snap, release, err := q.s.open(wait, q.auth)
507 defer release()
508 switch {
509 case errors.Is(err, export.ErrNoExport):
510 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
511 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
512 })
513 return
514 case errors.Is(err, errLoadsFull), errors.Is(err, errAuthorizationChanged):
515 q.busy()
516 return
517 case err != nil:
518 q.fail(err)
519 return
520 }
521 if q.s.opened != nil {
522 q.s.opened(g)
523 }
524 q.g, q.e, q.idx = g, snap.e, snap.idx
525 q.route(parts, ok)
526}
527
528// runsGit reports whether a path is a source route that reads a
529// repository: a tree, a file or a log of something that may be a group's
530// project. It reads the path's shape alone, before the export is read, so
531// a path through a group's alias that has the shape takes a git slot too,
532// and gives it back when it redirects.
533func runsGit(parts []string) bool {
534 return len(parts) >= 4 && export.ValidName(parts[0]) && export.ValidName(parts[1]) && parts[2] == "source" &&
535 (parts[3] == "tree" || parts[3] == "blob" || parts[3] == "log")
536}
537
538// giveSlot gives back the request's git slot, when it holds one.
539func (q *request) giveSlot() {
540 if q.slot != nil {
541 q.slot()
542 q.slot = nil
543 }
544}
545
546// admit takes a git slot for a source request. When every slot is taken,
547// it waits for one until ctx is done, unless MaxWaiting requests wait
548// already. done gives the slot back.
549func (s *Server) admit(ctx context.Context) (done func(), ok bool) {
550 give := func() { <-s.slots }
551 select {
552 case s.slots <- struct{}{}:
553 return give, true
554 default:
555 }
556 select {
557 case s.waiting <- struct{}{}:
558 default:
559 return nil, false
560 }
561 defer func() { <-s.waiting }()
562 select {
563 case s.slots <- struct{}{}:
564 return give, true
565 case <-ctx.Done():
566 return nil, false
567 }
568}
569
570// errLoadsFull is open's error for a request that would wait for a load
571// while MaxLoadWaiting requests wait already.
572var errLoadsFull = errors.New("too many requests wait for exports to be read")
573
574// errAuthorizationChanged is open's error for a request whose
575// authorization was replaced while it waited. ServeHTTP renders it again
576// under the new one.
577var errAuthorizationChanged = errors.New("the stored authorization changed")
578
579// open opens the active generation once its snapshot under auth is
580// cached, and returns both. release gives the generation back.
581//
582// A request whose active generation has no snapshot waits for a load,
583// and opens nothing until the load ends. It is admitted among the
584// MaxLoadWaiting requests that may wait before it waits, and it keeps its
585// place until open returns. Once the load ends it looks again, since
586// another generation may have been activated meanwhile.
587func (s *Server) open(ctx context.Context, auth authState) (g export.Generation, snap *snapshot, release func(), err error) {
588 release = func() {}
589 waiting := false
590 defer func() {
591 if waiting {
592 <-s.loadWaiting
593 }
594 }()
595 for {
596 seq, err := s.store.Active()
597 if err != nil {
598 return g, nil, release, err
599 }
600 s.mu.Lock()
601 snap = s.cached
602 s.mu.Unlock()
603 if snap != nil && snap.seq == seq && snap.auth.same(auth) {
604 g, release, err = s.store.Open()
605 if err != nil || g.Sequence == seq {
606 return g, snap, release, err
607 }
608 release() // active moved on since it was read
609 release = func() {}
610 continue
611 }
612 if !waiting {
613 select {
614 case s.loadWaiting <- struct{}{}:
615 waiting = true
616 default:
617 return g, nil, release, errLoadsFull
618 }
619 }
620 if err := s.await(ctx, seq, auth); err != nil {
621 return g, nil, release, err
622 }
623 if !s.readAuthorization().same(auth) {
624 return g, nil, release, errAuthorizationChanged
625 }
626 }
627}
628
629// await waits until a load of generation seq under auth, or of a newer
630// generation, ends, or until ctx is done. It joins a load that will read
631// one of those, since a worker reads whatever generation is active and
632// whatever authorization is stored once it starts, and otherwise makes
633// one.
634//
635// A load starts only once one of its requests takes a loader slot for
636// it. While every slot is taken, each of its requests waits for one, and
637// the first to take one starts the load, so no load is queued that no
638// request waits for. A request that stops waiting leaves the load, and
639// the last to leave stops it.
640func (s *Server) await(ctx context.Context, seq int64, auth authState) error {
641 s.mu.Lock()
642 if c := s.cached; c != nil && (c.seq > seq || c.seq == seq && c.auth.same(auth)) {
643 s.mu.Unlock()
644 return nil
645 }
646 var l *load
647 for m := range s.loads {
648 if !m.opened || m.seq > seq || m.seq == seq && m.auth.same(auth) {
649 l = m
650 break
651 }
652 }
653 if l == nil {
654 l = &load{started: make(chan struct{}), done: make(chan struct{})}
655 s.loads[l] = struct{}{}
656 }
657 l.wants++
658 s.mu.Unlock()
659 select {
660 case <-l.started:
661 case s.loaders <- struct{}{}:
662 if !s.start(l) {
663 <-s.loaders
664 }
665 case <-ctx.Done():
666 s.leave(l)
667 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
668 }
669 select {
670 case <-l.done:
671 return l.err
672 case <-ctx.Done():
673 s.leave(l)
674 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
675 }
676}
677
678// start starts l's worker, for the request that took a loader slot for
679// it. It is false when another request started it already.
680func (s *Server) start(l *load) bool {
681 s.mu.Lock()
682 defer s.mu.Unlock()
683 if l.cancel != nil {
684 return false
685 }
686 ctx, cancel := context.WithCancel(context.Background())
687 l.cancel = cancel
688 close(l.started)
689 go s.run(ctx, l)
690 return true
691}
692
693// leave is a request that stopped waiting for l. Once no request waits for
694// it, no request may join it, and a load that started is stopped.
695func (s *Server) leave(l *load) {
696 s.mu.Lock()
697 defer s.mu.Unlock()
698 if l.wants--; l.wants > 0 {
699 return
700 }
701 delete(s.loads, l)
702 if l.cancel != nil {
703 l.cancel()
704 }
705}
706
707// run is l's worker. It caches the snapshot it reads when the snapshot's
708// generation is newer than the cached one's, or the same generation under
709// another authorization, so a load of an older generation never displaces
710// a newer. A load that was stopped caches nothing: leave stops it under
711// mu, and run looks under mu. The worker gives back its generation before
712// it ends, and then its loader slot.
713func (s *Server) run(ctx context.Context, l *load) {
714 snap, err := s.read(ctx, l)
715 s.mu.Lock()
716 delete(s.loads, l)
717 if snap != nil && ctx.Err() == nil && (s.cached == nil || s.cached.seq < snap.seq ||
718 s.cached.seq == snap.seq && !s.cached.auth.same(snap.auth)) {
719 s.cached = snap
720 }
721 l.err = err
722 s.mu.Unlock()
723 l.cancel()
724 close(l.done)
725 <-s.loaders
726}
727
728// read opens the active generation for l, reads the stored
729// authorization, and holds the generation while it reads and indexes the
730// generation's export under that authorization. It reads nothing when the
731// generation is cached already under that authorization or another load
732// reads the same, and its waiting requests look again. A generation cached
733// under another authorization is not read again: its export is indexed
734// anew. It stops reading once ctx is done.
735func (s *Server) read(ctx context.Context, l *load) (snap *snapshot, err error) {
736 // Cancellation can close the file during any operation. Report the
737 // context error instead of the resulting descriptor error.
738 defer func() {
739 if stopped := ctx.Err(); stopped != nil {
740 snap, err = nil, stopped
741 }
742 }()
743 if err := ctx.Err(); err != nil {
744 return nil, err
745 }
746 g, release, err := s.store.Open()
747 if err != nil {
748 return nil, err
749 }
750 defer release()
751 auth := s.readAuthorization()
752 if auth.a == nil {
753 return nil, nil
754 }
755 s.mu.Lock()
756 cached := s.cached
757 read := cached == nil || cached.seq < g.Sequence || cached.seq == g.Sequence && !cached.auth.same(auth)
758 for m := range s.loads {
759 if m != l && m.opened && m.seq == g.Sequence && m.auth.same(auth) {
760 read = false
761 }
762 }
763 l.opened, l.seq, l.auth = true, g.Sequence, auth
764 s.mu.Unlock()
765 if !read {
766 return nil, nil
767 }
768 if cached != nil && cached.seq == g.Sequence {
769 idx, err := newIndex(ctx, cached.e, visible(cached.e, auth.a, export.Anyone))
770 if err != nil {
771 return nil, err
772 }
773 return &snapshot{seq: g.Sequence, auth: auth, e: cached.e, idx: idx}, nil
774 }
775 if s.loading != nil {
776 s.loading(g)
777 }
778 f, err := os.OpenFile(g.ExportPath(), os.O_RDONLY|syscall.O_NONBLOCK, 0)
779 if err != nil {
780 return nil, err
781 }
782 defer f.Close()
783 // Nonblocking open avoids waiting for a FIFO writer. Go's file poller
784 // waits for reads, and Close wakes a read when the last waiter leaves.
785 stop := context.AfterFunc(ctx, func() { _ = f.Close() })
786 defer stop()
787 info, err := f.Stat()
788 if err != nil {
789 return nil, err
790 }
791 data, err := io.ReadAll(&contextReader{ctx: ctx, r: f, waitForData: info.Mode()&os.ModeNamedPipe != 0})
792 if ctx.Err() != nil {
793 return nil, ctx.Err()
794 }
795 if err != nil {
796 return nil, fmt.Errorf("reading generation %d's export: %w", g.Sequence, err)
797 }
798 e, err := export.DecodeContext(ctx, bytes.NewReader(data))
799 if err != nil {
800 return nil, err
801 }
802 if err := ctx.Err(); err != nil {
803 return nil, err
804 }
805 idx, err := newIndex(ctx, e, visible(e, auth.a, export.Anyone))
806 if err != nil {
807 return nil, err
808 }
809 return &snapshot{seq: g.Sequence, auth: auth, e: e, idx: idx}, nil
810}
811
812// contextReader reads from r until ctx is done.
813type contextReader struct {
814 ctx context.Context
815 r io.Reader
816 waitForData bool
817}
818
819func (c *contextReader) Read(p []byte) (int, error) {
820 for {
821 if err := c.ctx.Err(); err != nil {
822 return 0, err
823 }
824 n, err := c.r.Read(p)
825 if n > 0 {
826 c.waitForData = false
827 }
828 if !c.waitForData || err != io.EOF {
829 return n, err
830 }
831 // A nonblocking FIFO reports EOF before its first writer arrives.
832 // Wait for that writer without holding a blocking open syscall.
833 timer := time.NewTimer(10 * time.Millisecond)
834 select {
835 case <-c.ctx.Done():
836 timer.Stop()
837 return 0, c.ctx.Err()
838 case <-timer.C:
839 }
840 }
841}
842
843// route dispatches on the path's segments, each unescaped on its own, so
844// an escaped slash stays inside its segment. ok is false for a path whose
845// segments do not unescape. The first segment is a group's name or an
846// alias, and under a group's name the second is a project's name.
847func (q *request) route(parts []string, ok bool) {
848 switch {
849 case !ok:
850 q.notFound()
851 case len(parts) == 1 && parts[0] == "":
852 q.plan()
853 case parts[0] == own:
854 q.notFound()
855 default:
856 if to, ok := q.idx.aliases[parts[0]]; ok {
857 q.moved(to, 1)
858 return
859 }
860 if len(parts) >= 2 {
861 if p := q.idx.groups[parts[0]][parts[1]]; p != nil {
862 q.projectRoute(p.Name, parts[2:])
863 return
864 }
865 if to, ok := q.idx.formers[parts[0]][parts[1]]; ok {
866 q.moved(to, 2)
867 return
868 }
869 }
870 q.notFound()
871 }
872}
873
874// projectRoute dispatches on the segments of a path after its group's and
875// its project's names.
876func (q *request) projectRoute(project string, rest []string) {
877 switch {
878 case len(rest) == 0, len(rest) == 1 && rest[0] == "":
879 q.home(project)
880 case len(rest) == 2 && rest[0] == "knots":
881 q.knot(project, rest[1])
882 case len(rest) >= 1 && rest[0] == "source":
883 q.source(project, rest[1:])
884 default:
885 q.notFound()
886 }
887}
888
889// moved answers a path under an alias or a former name with a permanent
890// redirect to the same path under to, the escaped URL the path's first n
891// segments stand for. The rest of the path after them, and the query,
892// are kept as they were sent, even a query that is a bare "?".
893func (q *request) moved(to string, n int) {
894 esc := strings.Split(strings.TrimPrefix(q.r.URL.EscapedPath(), "/"), "/")
895 rest := ""
896 if len(esc) > n {
897 rest = "/" + strings.Join(esc[n:], "/")
898 }
899 if q.r.URL.RawQuery != "" || q.r.URL.ForceQuery {
900 rest += "?" + q.r.URL.RawQuery
901 }
902 q.location, q.permanent = to+rest, true
903}
904
905// own is the first segment of the server's own paths, /-/. No group's
906// name, and no alias, can be it, or start with it.
907const own = "-"
908
909// home answers /<group>/<project>/, and /<group>/<project>, with a
910// redirect to the project's page: the tree at its published tip, with its
911// README.
912func (q *request) home(project string) {
913 p, ok := q.project(project)
914 if !ok {
915 q.notFound()
916 return
917 }
918 q.redirect(treeURL(q.idx.bases[p.Name], p.SourceTip, nil))
919}
920
921func segments(escaped string) ([]string, bool) {
922 rest, ok := strings.CutPrefix(escaped, "/")
923 if !ok {
924 return nil, false
925 }
926 parts := strings.Split(rest, "/")
927 for i, p := range parts {
928 u, err := url.PathUnescape(p)
929 if err != nil {
930 return nil, false
931 }
932 parts[i] = u
933 }
934 return parts, true
935}
936
937// project is the export's project called name, when the export holds it
938// as public, in a group. Every route that names a project asks here
939// first, and a project it refuses answers as one that does not exist.
940func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) }
941
942func (idx *index) project(name string) (*export.Project, bool) {
943 p, ok := idx.projects[name]
944 if _, placed := idx.bases[name]; !ok || !placed {
945 return nil, false
946 }
947 return p, true
948}
949
950// notFound is the one 404 page, whatever was not found. It is made once,
951// when the server starts, and names nothing of the request or the export,
952// so a hidden project, a missing one, an unreachable commit and a missing
953// path all answer alike, byte for byte.
954func (q *request) notFound() {
955 q.static(http.StatusNotFound, htmlType, notFoundPage)
956}
957
958// fail logs err and answers with the one 500 page, which says nothing of
959// the failure. A reader that went away is answered with nothing: git
960// killed for it fails, and that is no failure of the server's. A request
961// that ran out of time, or held its git slot past gitTime, answers 503.
962func (q *request) fail(err error) {
963 if q.r.Context().Err() != nil {
964 return
965 }
966 if q.ctx.Err() == nil && q.git != nil && q.git.Err() != nil {
967 err = fmt.Errorf("the request held its git slot past %v: %w", q.s.gitTime, err)
968 }
969 q.s.log(err)
970 if q.ctx.Err() != nil || q.git != nil && q.git.Err() != nil {
971 q.busy()
972 return
973 }
974 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
975 Heading: "Something went wrong", Text: "The server could not read this page.",
976 })
977}
978
979// busy answers a request the server has no room for: a source request it
980// could not admit, a request that ran out of time, or a page the response
981// budget has no room for. A reader that went away is answered with
982// nothing.
983func (q *request) busy() {
984 if q.r.Context().Err() != nil {
985 return
986 }
987 q.w.Header().Set("Retry-After", "5")
988 q.static(http.StatusServiceUnavailable, htmlType, busyPage)
989}
990
991// redirect answers with a redirect to url.
992func (q *request) redirect(url string) { q.location = url }
993
994// write writes the rendered response, or nothing for a reader that went
995// away. It returns once the response is written, or the connection
996// failed or timed out. A permanent redirect names its location as it was
997// made, with no cleaning, so the path it redirects to is the one the
998// reader sent under another name.
999//
1000// released is called once the headers are written, and before the body is,
1001// or at once when there is nothing to write.
1002func (q *request) write(released func()) {
1003 defer released()
1004 switch {
1005 case q.location != "" && q.permanent:
1006 q.w.Header().Set("Location", q.location)
1007 q.w.WriteHeader(http.StatusPermanentRedirect)
1008 case q.location != "":
1009 http.Redirect(q.w, q.r, q.location, http.StatusFound)
1010 case q.status != 0:
1011 h := q.w.Header()
1012 h.Set("Content-Type", q.ctype)
1013 h.Set("Content-Length", strconv.Itoa(q.body.n))
1014 q.w.WriteHeader(q.status)
1015 released()
1016 for _, p := range q.body.pieces {
1017 if _, err := q.w.Write(p); err != nil {
1018 return
1019 }
1020 }
1021 }
1022}
1023
1024// setHeaders sets the headers every response carries.
1025func setHeaders(h http.Header) {
1026 h.Set("Content-Security-Policy", csp)
1027 h.Set("X-Content-Type-Options", "nosniff")
1028 h.Set("X-Frame-Options", "DENY")
1029 h.Set("Referrer-Policy", "no-referrer")
1030 h.Set("Cross-Origin-Opener-Policy", "same-origin")
1031 h.Set("Cross-Origin-Resource-Policy", "same-origin")
1032 h.Set("Cache-Control", "no-cache")
1033}