gunk-dev/the-valley

server.go

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