gunk-dev/the-valley

server.go

sourcecfedff357a41main's published tip history
62.4 KiB
1// Package server is the web UI's read side. It serves the active export
2// of a receiver's store to each reader as the store's authorization
3// allows: the projects page, the knots page, each project's knots page,
4// each knot, and a source browser over the main of each project the
5// reader may read. The source browser also serves a gzipped tar archive
6// of each reachable commit.
7//
8// # Readers and views
9//
10// Every request is read as one principal, its reader. Started with
11// --origin, valley-web reads a request that carries a valid session as
12// the session's principal, and every other request as anyone. A request
13// that carries a session cookie while the browser state cannot be read
14// is answered as unavailable. A request's view is built from the projects
15// its reader may see: those the authorization lets anyone read, and those
16// it lets the reader read (visible). Each of those projects is copied for
17// the reader, with what it says of other projects' knots taken out
18// (projectForReader), and the view's index is built from the copies. So
19// every route, every reference between projects, every alias and every
20// redirect a reader is served is built from that reader's projects alone.
21//
22// # Requests, loads and indexes
23//
24// Every request reads the store's authorization when it arrives, and
25// renders its whole response under it. A request takes, in this order:
26//
27// 1. its reader and its authorization;
28// 2. the active generation's export, decoded, and the index of its view;
29// 3. its route, resolved through that index;
30// 4. a missing page, or a redirect, answered from the index alone;
31// 5. for a source route that reads a repository, a git slot, and then
32// the generation its view was built from, opened;
33// 6. its whole response, rendered;
34// 7. the generation and the index given back;
35// 8. the authorization read again, and the response's headers written.
36//
37// It holds no generation while it waits for an index or a git slot. When
38// the active generation is another by the time it opens one, it gives
39// back its slot, its generation and its index, and takes its view again,
40// within its time. An activation during the request changes nothing the
41// request reads.
42//
43// The server keeps the newest generation's export it has read, decoded.
44// A request whose generation has no decoded export yet waits for a load.
45// A load runs in a worker of its own, which opens the active generation,
46// holds it while it reads and decodes the export, and then gives it back.
47// At most MaxLoads loads run at once. One of their workers runs a load
48// only while an anonymous request waits for it, so loads that only named
49// readers wait for take one worker at most. When the last anonymous
50// request leaves a load on that worker, the load moves to the other
51// worker if it is free. Otherwise the load is stopped and gives the worker
52// back at once, and its named readers' requests wait for a worker again.
53// The requests that wait for a generation share one read. A waiting
54// request holds no generation, and stops waiting when its reader goes
55// away or its time runs out. A load stops once no request waits for it,
56// and the server keeps nothing of what it read, so a later request may
57// read that generation again, as it may after a load stopped as above.
58//
59// Indexes are kept apart from decoded exports. An index is named by its
60// generation, the authorization's revision, and the sorted names and
61// identities of its view's projects, so readers who may see the same
62// projects share one index, and who they are never reaches it. An index
63// is built once its export is decoded, after the load has given back its
64// worker, in a worker of its own that stops once no request waits for it.
65//
66// Indexes take places of two pools. Anonymous requests have anonymousViews
67// places of their own, for the index of what anyone may see: the current
68// generation's, and the one that replaces or is replaced by it. Named
69// readers' requests share MaxViews places. A named reader who may see no
70// more than anyone serves from the same index as anonymous requests, but
71// takes a named place for it. So an index takes a place in the pool of
72// each kind of request that serves from it or waits for it to be built,
73// and gives back a pool's place once only the other pool's requests pin
74// it. An index no request pins keeps the place of the last request that
75// let it go. An index being built takes its places too. No named
76// reader's request ever keeps an anonymous place: when the named places
77// are full, named readers' requests wait for one, and an anonymous request
78// for the current generation never waits on a named one for its index.
79//
80// An index whose build was stopped keeps its place until its worker ends,
81// and no request joins it, so the workers that build indexes are never
82// more than the places. An index no request serves from may be dropped to
83// make room in its pool, and no other. A request that finds no room in
84// its pool waits for some, and answers 503 at its deadline. No worker
85// waits for an index while it holds a load worker, and no load waits for
86// an index.
87//
88// # Admission
89//
90// Every request's time is bounded from when it arrives: its waits, its
91// git commands and its rendering. A source request that reads a
92// repository runs git, and at most MaxGit run at once. A request takes one
93// of those slots once its route is resolved through its index, before it
94// opens a generation, and waits for one only while fewer than MaxWaiting
95// wait. So a project the reader may not see, a project that does not
96// exist, a redirect and a missing page take no slot. A request waits for
97// its view, a load or an index, only while fewer than MaxLoadWaiting wait.
98// A named reader's request waits only while fewer than MaxNamedWaiting
99// named readers' requests wait too. So named readers never take the last
100// MaxLoadWaiting less MaxNamedWaiting places: those are left to anonymous
101// requests, which wait there for a loader and for the anonymous places of
102// indexes, which named readers never take either. A request the server
103// cannot admit, or that runs out of time, answers 503.
104//
105// A source request holds its git slot for gitTimeout at most. That time
106// runs from when it takes the slot, and covers its git commands. It gives
107// the slot back before it renders its page. A source request that runs
108// out of that time answers 503.
109//
110// A source request that shows Markdown renders it after its git commands,
111// and at most MaxRendering render at once. A request waits for a
112// rendering slot while it still holds its git slot, within its gitTimeout,
113// and gives the git slot back once it has one. So the requests that hold
114// a file's text while they wait to render are among the MaxGit. The
115// memory rendering takes grows with the file and not with the page, and
116// one render allocates less than 128 MiB (package markdown), so the
117// renders at once allocate at most MaxRendering times that.
118//
119// Every bound but the indexes' places is shared by every reader: MaxGit,
120// MaxRendering, MaxBuffered, MaxLarge and MaxResponse, and the bounds on
121// an archive. More readers do not make any of them larger.
122//
123// # Responses
124//
125// A response is rendered whole before it is written. A request gives back
126// its git slot before it renders, and its generation and its index before
127// it writes, so a reader that reads slowly holds none of them. It keeps
128// its response until the response is written.
129//
130// A response's body is at most MaxResponse bytes. A page or archive that
131// exceeds MaxResponse stops there, and the request answers with a short
132// page saying the page is too large. The server builds an archive in full
133// into the response body while holding the request's git slot. It writes
134// the tar itself from the commit's tree, applying no git attribute, and
135// streams each file through tar and gzip into the body, so it never holds
136// a whole file. An archive whose files add up to more than
137// MaxArchiveInput, or whose tree holds more than MaxArchiveEntries
138// entries, is refused with the same short page before any file is read.
139// Rendered
140// responses take their memory from a budget of MaxBuffered bytes, which
141// they give back once they are written. A request that finds the budget
142// spent answers 503.
143//
144// Responses larger than SmallPage hold at most MaxLarge of the budget
145// between them, counting their first SmallPage bytes. So readers that
146// never read large pages hold at most MaxLarge, however many there are,
147// and the rest of the budget is always there for small pages: the knots
148// page, most knots, and most directories and files.
149//
150// # Routes
151//
152// The server answers GET and HEAD alone. A project's pages are under its
153// group's name and its own web name, which need not be its identifier:
154//
155// / a redirect to the projects page, or to the one project's tree
156// /-/projects the projects page: every project the reader may read, by group
157// /-/knots the knots page of every project the reader may read
158// /<group>/ and /<group> the projects page of one group
159// /<group>/<project>/ a redirect to the tree at main's tip
160// /<group>/<project>/knots the project's knots page
161// /<group>/<project>/knots/<id> one knot, with its body and comments
162// /<group>/<project>/source/ a redirect to the tree at main's tip
163// /<group>/<project>/source/tree/<commit>/<path> a directory and its README
164// /<group>/<project>/source/blob/<commit>/<path> a file
165// /<group>/<project>/source/log/<commit> the history that ends at a commit
166// /<group>/<project>/source/log/<commit>?from=… an older page of that history
167// /<group>/<project>/source/archive/<commit>.tar.gz the commit's tree as a gzipped tar archive
168// /<group>/<project>/source/archive/main.tar.gz a redirect to the archive of main's tip
169// /<group>/<former name>/… a permanent redirect
170// /<alias>/… a permanent redirect
171// /-/... the server's own paths
172//
173// A group's alias redirects to the same path under the group's name, a
174// project's former name to the same path under its web name, and a
175// project's short alias to the same path under /<group>/<project>. The
176// redirect keeps the rest of the path and the query as they were sent.
177//
178// Every path but / and those under /-/ starts with a group's name or an
179// alias. No name starts with "-", so no group's path is ever one of the
180// server's own, whatever paths the server adds there. Under /-/ it serves
181// the projects page, the knots page and the reader pages, and answers
182// every other path there with the one 404. / redirects to the tree at
183// main's published tip of the one project the reader may see, and to the
184// projects page when the reader may see several or none. A first segment
185// is read as an alias before it is read as a group's name, so an alias
186// that was also a group's name would win; package export refuses an
187// export whose group names and aliases collide, or whose projects' web
188// names and former names collide within a group. A group's page answers
189// as a path that does not exist when the reader may see none of its
190// projects.
191//
192// Every source link names its group and project, a full commit ID, and a
193// path, or a full commit ID alone for an archive. A commit is served only
194// when export.Reachable finds it reachable from the project's published
195// source tip, and a path is resolved one tree entry at a time from that
196// commit's tree, so no other object can be named.
197//
198// # Access
199//
200// The store's authorization decides what is served. A request reads it
201// from the store when it arrives, and reads it again once its response is
202// rendered, before the first byte is written. A response rendered under an
203// authorization that has since been replaced is not written: the request
204// renders again under the new one. So the next request after the receiver
205// stores an authorization is held to it, with no restart and no cache in
206// between. A store with no authorization, or one that cannot be read,
207// serves no project: every page says nothing is published.
208//
209// A project the reader may not see answers exactly as a project that does
210// not exist: every 404 is the same page, made once when the server
211// starts, and a group none of whose projects the reader may see has no
212// alias.
213//
214// # Safety
215//
216// Every page is rendered on the server with html/template, so everything
217// read from the export or a repository is escaped. Each response carries
218// its route's strict Content-Security-Policy: default-src 'self', the one
219// inline stylesheet admitted by its SHA-256 hash, no connection from a
220// script, and, on the knots pages alone, their one inline script admitted
221// by its hash. Every response, a redirect and an error too, is private and
222// never stored by a cache: Cache-Control: private, no-store, and Vary:
223// Cookie. No response carries an ETag, and none answers 304. No page
224// serves a repository file as raw content: a file is shown as escaped
225// text, and a binary file or one larger than MaxFile is not shown at all.
226// Raw repository files are served only inside a gzipped tar archive sent
227// as an attachment.
228//
229// A Markdown file, and a directory's Markdown README, is rendered by
230// package markdown, and ?plain=1 shows the file as escaped text. The
231// renderer writes only its own fixed set of elements and attributes, and
232// escapes every byte it takes from the file, raw HTML included. It
233// writes a link only for an http, https or mailto destination, or for a
234// relative one resolved to a page of the source browser at the same
235// commit, and no img, script, form or style attribute. So rendered
236// Markdown is no active content, and the policy above admits it as it
237// is. What a project's own files and knots say is published as written:
238// the filter takes out what a page says of other projects, never what
239// their authors wrote.
240package server
241
242import (
243 "bytes"
244 "context"
245 "errors"
246 "fmt"
247 "io"
248 "log"
249 "net/http"
250 "net/url"
251 "os"
252 "strconv"
253 "strings"
254 "sync"
255 "syscall"
256 "time"
257
258 "the-valley/web/export"
259 "the-valley/web/readerstate"
260)
261
262// StaleAfter is how old an export may be before its pages mark it stale.
263const StaleAfter = 5 * time.Minute
264
265// The bounds on what one request reads from a repository.
266const (
267 // MaxFile is the largest file a page shows, README or otherwise.
268 MaxFile = 1 << 20
269 // MaxLines is the most lines of a file a page shows.
270 MaxLines = 10_000
271 // MaxShown is the most bytes a page spends on a file's text once it
272 // is escaped, counting each line's markup on a file page. A page
273 // stops at the line that would take it past MaxShown.
274 MaxShown = 2 << 20
275 // MaxEntries is the most entries a directory page lists.
276 MaxEntries = 1000
277 // MaxRead is the most bytes of output a page reads from one git
278 // listing: a directory's entries, or a page of history. git is
279 // stopped once it prints more.
280 MaxRead = 4 << 20
281 // MaxArchiveInput is the most bytes of files an archive holds before
282 // it is gzipped: the sizes of the files and symbolic links in its
283 // commit's tree, added up. An archive of a larger tree is refused
284 // before any file is read.
285 MaxArchiveInput = 32 << 20
286 // MaxArchiveEntries is the most entries an archive holds: its
287 // files, symbolic links, directories and submodules together. An
288 // archive of a tree that holds more is refused as one that passes
289 // MaxArchiveInput is.
290 MaxArchiveEntries = 10_000
291 // MaxDepth is the most path segments a source route takes.
292 MaxDepth = 64
293 // MaxPlanDepth is the most levels of knots a milestone's tree
294 // shows, and the most parents a knot's trail names.
295 MaxPlanDepth = 32
296 // LogPage is the number of commits on one page of a log.
297 LogPage = 50
298 // MaxFrontier is the most commits a link to an older page of a log
299 // names: the commits that page starts from.
300 MaxFrontier = 64
301 // MaxLeftToShow is the most commits a page of a log leaves to show.
302 // Its Older link starts from MaxFrontier of them, and each of the
303 // rest has a link of its own. A page ends before a merge that would
304 // leave more.
305 MaxLeftToShow = 192
306 // MaxParents is the most parents of one commit that a page of a log
307 // follows: the first MaxParents, in the commit's order. A page marks
308 // a merge that has more, and leaves none of its others to show.
309 MaxParents = 128
310 // MaxGit is the most source requests that run git at once.
311 MaxGit = 8
312 // MaxWaiting is the most source requests that wait for one of the
313 // MaxGit to finish. A source request that finds every slot taken
314 // and MaxWaiting waiting answers 503 at once.
315 MaxWaiting = 16
316 // MaxRendering is the most source requests that render Markdown at
317 // once.
318 MaxRendering = 2
319 // requestTimeout bounds a request from when it arrives: its wait for
320 // its view, for a git slot or for a rendering slot, its git commands
321 // and its rendering.
322 requestTimeout = 15 * time.Second
323 // gitTimeout bounds how long a source request holds its git slot,
324 // from when it takes it: its git commands, all of them together, and
325 // its wait for a rendering slot. A source request still holding its
326 // slot past it answers 503.
327 gitTimeout = 5 * time.Second
328 // MaxLoads is the most loads that run at once, each in a worker of
329 // its own that reads one generation's export. One of them runs only
330 // while an anonymous request waits for it.
331 MaxLoads = 2
332 // MaxLoadWaiting is the most requests that wait for their views: for
333 // a load, or for an index to be built or to have room. A request that
334 // would wait while MaxLoadWaiting do answers 503 at once.
335 MaxLoadWaiting = 64
336 // MaxNamedWaiting is the most of the MaxLoadWaiting places that
337 // requests read as a named reader take. The rest, MaxLoadWaiting less
338 // MaxNamedWaiting, are left to anonymous requests. A named reader's
339 // request that would wait while MaxNamedWaiting named readers'
340 // requests do answers 503 at once.
341 MaxNamedWaiting = 48
342 // MaxViews is how many places the server keeps for the indexes named
343 // readers' requests serve from or wait for: those of views of more
344 // than anyone may see, and that of what anyone may see while a named
345 // reader who may see no more pins it. Those it keeps, those being
346 // built, and those requests serve from count together.
347 MaxViews = 8
348 // anonymousViews is how many places the server keeps for the indexes
349 // anonymous requests serve from or wait for: the current index of
350 // what anyone may see, and the one that replaces or is replaced by it.
351 // No named reader's request takes one.
352 anonymousViews = 2
353 // MaxResponse is the most bytes a response's body takes. A page
354 // that would take more stops rendering, and the request answers with
355 // a short page that says the page is too large.
356 MaxResponse = 8 << 20
357 // MaxBuffered is the most bytes of rendered responses the server
358 // holds at once, from when each starts rendering until it is
359 // written. A response takes them in pieces of pieceSize as it
360 // renders.
361 MaxBuffered = 64 << 20
362 // SmallPage is the largest response that takes from MaxBuffered
363 // alone.
364 SmallPage = 256 << 10
365 // MaxLarge is the most of MaxBuffered that responses larger than
366 // SmallPage hold between them, all of each counted. The rest,
367 // MaxBuffered less MaxLarge, is left to smaller responses.
368 MaxLarge = 48 << 20
369 // pieceSize is the size of the pieces a response is rendered into.
370 pieceSize = 64 << 10
371)
372
373// Config is what a Server serves from.
374type Config struct {
375 // Store is the receiver's state directory.
376 Store *export.Store
377 // Now is the clock an export's age is read against. Nil is time.Now.
378 Now func() time.Time
379 // Log is told of each failure a reader sees only as an error page.
380 // Nil logs with the standard logger.
381 Log func(error)
382 // Readers is the browser state, which holds the read links redeemed
383 // here and their sessions, and Origin the public HTTPS origin, such
384 // as https://example.org, that a reader page's POST must come from.
385 // With no Readers, every request is read as anyone, and the server
386 // has no reader pages.
387 Readers *readerstate.State
388 Origin string
389}
390
391// Server is the read side's HTTP handler.
392type Server struct {
393 store *export.Store
394 now func() time.Time
395 log func(error)
396 readers *readerstate.State
397 origin string
398 // timeout is requestTimeout, gitTime is gitTimeout, and maxResponse
399 // is MaxResponse. A test shortens any of them.
400 timeout time.Duration
401 gitTime time.Duration
402 maxResponse int
403 // gitMu guards the git slots. running counts the source requests
404 // that hold a slot, and queue holds a channel for each that waits for
405 // one, the longest waiting first. A slot given back while requests
406 // wait passes to the first of them: its channel is closed, and it
407 // leaves queue then, so queue holds only requests that have no slot.
408 gitMu sync.Mutex
409 running int
410 queue []chan struct{}
411 // renders holds a token for each source request rendering
412 // Markdown.
413 renders chan struct{}
414 // anonLoader holds a token for the load an anonymous request started
415 // on it, and loaders one for each other load. A request that is not
416 // anonymous starts a load only with a token of loaders, and a load
417 // that only named readers' requests still wait for gives anonLoader
418 // back (leave), so anonymous requests always have a worker. loadWaiting
419 // holds one for each request waiting for its view, and namedWaiting
420 // one more for each of those read as a named reader.
421 anonLoader chan struct{}
422 loaders chan struct{}
423 loadWaiting chan struct{}
424 namedWaiting chan struct{}
425 // pieces guards the response budget. held counts the pieces of
426 // responses being rendered or written, of MaxBuffered bytes in pieces
427 // of pieceSize. large counts the pieces of those responses that are
428 // larger than SmallPage, every piece of each, of MaxLarge bytes.
429 pieces sync.Mutex
430 held int
431 large int
432
433 mu sync.Mutex
434 // exported is the newest generation's export decoded so far.
435 exported *decoded
436 // auth is the last valid authorization readAuthorization read.
437 auth authState
438 // loads are the loads a request that waits may still join: those that
439 // have not ended, that some request waits for, and that leave has not
440 // dropped.
441 loads map[*load]struct{}
442 // views are the indexes the server holds, by name: built, being
443 // built, or pinned by the requests that serve from them. stopping are
444 // the views whose builds were stopped and whose workers have not
445 // ended: no request takes them, and each keeps its place until its
446 // worker ends. freed is closed, and replaced, whenever a view may have
447 // left a place free. used counts the views requests have taken, and
448 // orders the views by when each was last taken.
449 views map[viewKey]*view
450 stopping map[*view]struct{}
451 freed chan struct{}
452 used uint64
453
454 // reader, when set, names the principal each request is read as, in
455 // place of its session. Tests name readers with it.
456 reader func(*http.Request) string
457
458 // The test hooks. viewed is called once a request has its view,
459 // before it resolves its route. admitted is called when a source
460 // request takes a git slot, before it opens a generation. opened,
461 // when set, is called with each generation a request opens, before
462 // the request reads anything from it. loading is called by a load's
463 // worker with the generation it opened, before it reads the
464 // generation's export. indexing is called by a view's worker before
465 // it builds the view's index, with the worker's context and the
466 // view's name. rendering is called with a page's name before the page
467 // renders.
468 viewed func()
469 admitted func()
470 opened func(export.Generation)
471 loading func(export.Generation)
472 indexing func(ctx context.Context, key viewKey)
473 rendering func(name string)
474 // checked is called once a request has rendered its response, before
475 // it reads the authorization again. starting is called once that read
476 // found the authorization unchanged, with the serving lock held, before
477 // the response's headers are written.
478 checked func()
479 starting func()
480}
481
482// New is a Server over c's store.
483func New(c Config) *Server {
484 s := &Server{store: c.Store, now: c.Now, log: c.Log, readers: c.Readers, origin: c.Origin,
485 timeout: requestTimeout, gitTime: gitTimeout, maxResponse: MaxResponse,
486 renders: make(chan struct{}, MaxRendering),
487 anonLoader: make(chan struct{}, 1), loaders: make(chan struct{}, MaxLoads-1),
488 loadWaiting: make(chan struct{}, MaxLoadWaiting), namedWaiting: make(chan struct{}, MaxNamedWaiting),
489 loads: map[*load]struct{}{}, views: map[viewKey]*view{}, stopping: map[*view]struct{}{},
490 freed: make(chan struct{})}
491 if s.now == nil {
492 s.now = time.Now
493 }
494 if s.log == nil {
495 s.log = func(err error) { log.Print(err) }
496 }
497 return s
498}
499
500// decoded is one generation's export, decoded. A generation's export.json
501// never changes once it is active, and its sequence names it, so one
502// decoded export serves every request that opens its generation, under
503// any authorization and for any reader.
504type decoded struct {
505 seq int64
506 e *export.Export
507}
508
509// authState is the stored authorization as one read found it: the signed
510// note, and the authorization parsed from it, or the error that left none.
511// Two reads are of one revision when their notes are the same bytes.
512type authState struct {
513 signed []byte
514 a *export.Authorization
515 err error
516}
517
518// same reports whether two reads found one revision of the authorization.
519func (st authState) same(o authState) bool {
520 return bytes.Equal(st.signed, o.signed) && (st.a == nil) == (o.a == nil)
521}
522
523// readAuthorization reads the stored authorization. It reads the file on
524// every call, and parses it again only when its bytes changed since the
525// last valid one it read.
526func (s *Server) readAuthorization() authState {
527 signed, err := s.store.ReadAuthorization()
528 if err != nil {
529 return authState{err: err}
530 }
531 s.mu.Lock()
532 last := s.auth
533 s.mu.Unlock()
534 if last.a != nil && bytes.Equal(last.signed, signed) {
535 return last
536 }
537 a, err := export.ReadStoredAuthorization(signed)
538 if err != nil {
539 return authState{signed: signed, err: err}
540 }
541 st := authState{signed: signed, a: a}
542 s.mu.Lock()
543 s.auth = st
544 s.mu.Unlock()
545 return st
546}
547
548// load reads the active generation's export for every request that
549// waits for it. It starts once one of those requests takes a loader slot
550// for it, and runs in a worker of its own, so a request can stop waiting
551// while the load goes on for the others.
552type load struct {
553 // wants counts the requests that wait for the load, and anon those of
554 // them that are anonymous. cancel is set once the load has started,
555 // and stops its worker. token is the slot the load holds, anonLoader
556 // or loaders, from when it starts until its worker ends or leave gives
557 // the slot back. The worker sets opened and seq once it has opened a
558 // generation. All are guarded by the server's mu.
559 wants int
560 anon int
561 cancel context.CancelFunc
562 token chan struct{}
563 opened bool
564 seq int64
565 // started is closed once the load starts, and done once its worker
566 // ends. err is the worker's error, set before done is closed. dropped
567 // is closed when leave stops the load to give back anonLoader while
568 // named readers' requests still wait for it: they wait for another.
569 started chan struct{}
570 done chan struct{}
571 dropped chan struct{}
572 err error
573}
574
575// viewKey names one index: the generation whose export it is built from,
576// the authorization's revision it is built under, as the signed note's
577// bytes, and its view's projects, each name and identity on a line of its
578// own, in the export's order, which is the names' order. Who the reader is
579// is no part of it.
580type viewKey struct {
581 seq int64
582 auth string
583 projects string
584}
585
586// pool is the places views take for one kind of request: anonymous
587// requests', or named readers'.
588type pool int
589
590const (
591 anonymousPool pool = iota
592 namedPool
593 pools
594)
595
596// poolOf is the pool whose places the requests read as reader take.
597func poolOf(reader string) pool {
598 if reader == export.Anyone {
599 return anonymousPool
600 }
601 return namedPool
602}
603
604// size is how many places p holds: anonymousViews for anonymous requests,
605// and MaxViews for named readers'.
606func (p pool) size() int {
607 if p == anonymousPool {
608 return anonymousViews
609 }
610 return MaxViews
611}
612
613// view is one index the server holds, the requests that hold it, and the
614// places it takes.
615type view struct {
616 key viewKey
617 // e is the decoded export the index is built from, and shown its
618 // view's projects.
619 e *export.Export
620 shown map[string]bool
621 // pins counts the requests that serve from the view or wait for it to
622 // be built, by the pool of each, and holds is set for each pool whose
623 // place the view takes. A view that requests pin takes a place in the
624 // pool of each kind of request that pins it, and in no other. A view
625 // no request pins keeps the one place of the last request that let it
626 // go. used is when a request last took it, and cancel stops the worker
627 // that builds it. All are guarded by the server's mu.
628 pins [pools]int
629 holds [pools]bool
630 used uint64
631 cancel context.CancelFunc
632 // done is closed once the worker ends, and idx is the index then, or
633 // err why there is none.
634 done chan struct{}
635 idx *index
636 err error
637}
638
639// pinned reports whether a request pins v. It is called with the
640// server's mu held.
641func (v *view) pinned() bool { return v.pins[anonymousPool]+v.pins[namedPool] > 0 }
642
643// request is one request, the view it serves from, and the response it
644// renders.
645type request struct {
646 s *Server
647 w http.ResponseWriter
648 r *http.Request
649 // parts are the request path's segments, each unescaped, and ok is
650 // false for a path whose segments do not unescape.
651 parts []string
652 ok bool
653 // reader is the principal the request is read as, and sess the
654 // session it carries, which names it. rpage is the reader page the
655 // path names, or "".
656 reader string
657 sess session
658 rpage string
659 // ctx is the context the request waits and renders under. It ends
660 // at the request's deadline, or when its reader goes away. git is
661 // the context a source request holds its git slot under: it runs git
662 // under it. git ends gitTime after the request takes its slot, or
663 // with ctx. slot gives the slot back.
664 ctx context.Context
665 git context.Context
666 slot func()
667 // view is the view the request serves from, pinned until it renders,
668 // and e and idx are its export and index.
669 view *view
670 e *export.Export
671 idx *index
672 now time.Time
673 // auth is the stored authorization as the request read it when it
674 // arrived. The request serves what it allows, and its response is
675 // written only if the authorization is the same when it is.
676 auth authState
677
678 // The response: a status and a page, or a redirect. It is written
679 // once the request has given back its generation, its view and its
680 // git slot, and the page's pieces are given back to the budget once
681 // it is written. disposition is the Content-Disposition of an
682 // archive, and "" for any other response.
683 status int
684 ctype string
685 disposition string
686 body *body
687 location string
688 permanent bool
689}
690
691// ServeHTTP answers a POST to a reader page once, with no rendering
692// (post). Every other request it reads under the stored authorization and
693// the session the request carries, renders its response, and reads both
694// again before the first byte is written. A response the authorization or
695// the session changed under is not written: the request is rendered again
696// under the new ones, at most maxRenders times in all, and then answers
697// 503. So every response, a redirect and an error page too, is one the
698// authorization stored when it is written allows its reader. A response
699// whose reader has a valid session renews the session's cookie, only once
700// that last check found it valid.
701func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
702 ctx, cancel := context.WithTimeout(r.Context(), s.timeout)
703 defer cancel()
704 parts, ok := segments(r.URL.EscapedPath())
705 rpage := s.readerPageOf(parts, ok)
706 policy := policyFor(parts, ok)
707 if rpage != "" {
708 policy = readerPolicy
709 if r.Method == http.MethodPost && posted(rpage) {
710 setHeaders(w.Header(), policy)
711 s.post(ctx, w, r, rpage)
712 return
713 }
714 }
715 carried, token := carriedCookie(r)
716 for render := 1; ; render++ {
717 h := w.Header()
718 for k := range h {
719 delete(h, k)
720 }
721 setHeaders(h, policy)
722 q := &request{s: s, w: w, r: r, parts: parts, ok: ok, rpage: rpage, ctx: ctx, now: s.now(),
723 auth: s.readAuthorization()}
724 s.prepare(ctx, q.auth)
725 q.sess = s.resolve(ctx, carried, token, q.auth.a)
726 q.reader = q.sess.reader
727 if s.reader != nil {
728 q.reader = s.reader(r)
729 }
730 q.serve()
731 if s.checked != nil {
732 s.checked()
733 }
734 // The last read and the response's headers happen under the
735 // browser state's read lock and the serving lock, shared, in that
736 // order. The receiver renames a new authorization into place under
737 // the serving lock, exclusively, and a logout replaces the browser
738 // state under its write lock. So a response whose headers are
739 // written after the receiver replies, or after a logout answers,
740 // was checked against what they stored. The wait for either lock
741 // ends with the request's deadline, or when its reader goes away,
742 // and then nothing rendered is written: busy answers 503, or
743 // nothing to a reader that went away, and no session is renewed.
744 state, done, err := s.readState(ctx)
745 var release func()
746 if err == nil {
747 if release, err = s.store.HoldServing(ctx); err != nil {
748 done()
749 }
750 }
751 if err != nil {
752 q.discard()
753 if ctx.Err() == nil {
754 q.s.log(fmt.Errorf("taking the serving lock: %w", err))
755 }
756 q.busy()
757 q.write(func() {})
758 return
759 }
760 auth := s.readAuthorization()
761 if auth.same(q.auth) && s.sessionOf(state, carried, token, auth.a).same(q.sess) {
762 if s.starting != nil {
763 s.starting()
764 }
765 // A response whose deadline passed by its last check is not
766 // written, and renews no session.
767 if ctx.Err() != nil {
768 release()
769 done()
770 q.discard()
771 q.busy()
772 q.write(func() {})
773 return
774 }
775 if q.sess.valid {
776 h.Set("Set-Cookie", sessionCookie(q.sess.token))
777 }
778 q.write(sync.OnceFunc(func() { release(); done() }))
779 q.drop()
780 return
781 }
782 release()
783 done()
784 q.discard()
785 if render == maxRenders {
786 q.busy()
787 q.write(func() {})
788 return
789 }
790 }
791}
792
793// maxRenders is how many times a request is rendered while the stored
794// authorization keeps changing under it.
795const maxRenders = 3
796
797// serve renders the request's response, in the order the package comment
798// gives. It takes the request's view, resolves the route through it, and
799// answers from the index alone where it can. A route that reads a
800// repository is admitted to a git slot, holds it until it renders, and
801// holds its generation until it has rendered. The request gives back its
802// view once it has rendered, before serve returns.
803func (q *request) serve() {
804 if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead {
805 allow, text := "GET, HEAD", "This server answers GET and HEAD alone."
806 if posted(q.rpage) {
807 allow, text = "GET, HEAD, POST", "This page answers GET, HEAD and POST alone."
808 }
809 q.w.Header().Set("Allow", allow)
810 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
811 Heading: "Method not allowed", Text: text,
812 })
813 return
814 }
815 if q.sess.unavailable {
816 q.unavailablePage()
817 return
818 }
819 if q.rpage != "" {
820 q.readerPage()
821 return
822 }
823 if q.auth.a == nil {
824 if !errors.Is(q.auth.err, export.ErrNoAuthorization) {
825 q.s.log(fmt.Errorf("the stored authorization cannot be read, so nothing is served: %w", q.auth.err))
826 }
827 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
828 Heading: "Nothing published yet", Text: "This server holds no authorization to serve anything.",
829 })
830 return
831 }
832 defer q.release()
833 for {
834 v, err := q.s.viewFor(q.ctx, q.auth, q.reader)
835 switch {
836 case errors.Is(err, export.ErrNoExport):
837 q.nothingPublished()
838 return
839 case errors.Is(err, errLoadsFull):
840 q.busy()
841 return
842 case err != nil:
843 q.fail(err)
844 return
845 }
846 q.view, q.e, q.idx = v, v.e, v.idx
847 if q.s.viewed != nil {
848 q.s.viewed()
849 }
850 op := q.route()
851 if op == nil || !q.runGit(op) {
852 return
853 }
854 q.release()
855 }
856}
857
858// nothingPublished answers a request when the store has no active
859// generation.
860func (q *request) nothingPublished() {
861 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
862 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
863 })
864}
865
866// release gives back the request's view, when it holds one.
867func (q *request) release() {
868 if q.view != nil {
869 q.s.unpin(q.view, poolOf(q.reader))
870 q.view, q.e, q.idx = nil, nil, nil
871 }
872}
873
874// gitOp is the work of a source route in a repository: the project whose
875// repository it reads, and what it does there, under the request's git
876// context, once the request holds a git slot and its generation.
877type gitOp struct {
878 project *export.Project
879 run func(ctx context.Context, repo string) error
880}
881
882// runGit admits the request to a git slot, opens the active generation,
883// and runs op in the generation's repository of op's project. again is set
884// when the active generation is no longer the one the request's view was
885// built from: the request has then given back its slot and the generation,
886// and rendered nothing, and takes its view again.
887func (q *request) runGit(op *gitOp) (again bool) {
888 done, admitted := q.s.admit(q.ctx)
889 if !admitted {
890 q.busy()
891 return false
892 }
893 q.slot = done
894 defer q.giveSlot()
895 var cancel context.CancelFunc
896 q.git, cancel = context.WithTimeout(q.ctx, q.s.gitTime)
897 defer cancel()
898 defer func() {
899 if again {
900 q.git = nil
901 }
902 }()
903 if q.s.admitted != nil {
904 q.s.admitted()
905 }
906 g, release, err := q.s.store.Open()
907 switch {
908 case errors.Is(err, export.ErrNoExport):
909 q.nothingPublished()
910 return false
911 case err != nil:
912 q.fail(err)
913 return false
914 }
915 defer release()
916 if g.Sequence != q.view.key.seq {
917 return true
918 }
919 if q.s.opened != nil {
920 q.s.opened(g)
921 }
922 repo, ok := g.Repo(op.project.Name)
923 if !ok {
924 q.notFound()
925 return false
926 }
927 if err := op.run(q.git, repo); err != nil {
928 q.fail(err)
929 }
930 return false
931}
932
933// giveSlot gives back the request's git slot, when it holds one.
934func (q *request) giveSlot() {
935 if q.slot != nil {
936 q.slot()
937 q.slot = nil
938 }
939}
940
941// admit takes a git slot for a source request. When every slot is taken,
942// it waits for one until ctx is done, unless MaxWaiting requests wait
943// already. A request stops counting as waiting when it is given its slot,
944// not when it next runs, so a request that has its slot never takes a
945// waiting place from another. done gives the slot back.
946func (s *Server) admit(ctx context.Context) (done func(), ok bool) {
947 s.gitMu.Lock()
948 if s.running < MaxGit {
949 s.running++
950 s.gitMu.Unlock()
951 return s.giveGit, true
952 }
953 if len(s.queue) >= MaxWaiting {
954 s.gitMu.Unlock()
955 return nil, false
956 }
957 given := make(chan struct{})
958 s.queue = append(s.queue, given)
959 s.gitMu.Unlock()
960 select {
961 case <-given:
962 return s.giveGit, true
963 case <-ctx.Done():
964 }
965 s.gitMu.Lock()
966 for i, c := range s.queue {
967 if c == given {
968 s.queue = append(s.queue[:i], s.queue[i+1:]...)
969 s.gitMu.Unlock()
970 return nil, false
971 }
972 }
973 s.gitMu.Unlock()
974 // The slot was given as ctx ended: pass it on.
975 s.giveGit()
976 return nil, false
977}
978
979// giveGit gives back a git slot: to the request that has waited longest
980// for one, or to no one when no request waits.
981func (s *Server) giveGit() {
982 s.gitMu.Lock()
983 defer s.gitMu.Unlock()
984 if len(s.queue) == 0 {
985 s.running--
986 return
987 }
988 close(s.queue[0])
989 s.queue = s.queue[1:]
990}
991
992// errLoadsFull is viewFor's error for a request that would wait for its
993// view while MaxLoadWaiting requests wait already, or, for a named
994// reader's request, while MaxNamedWaiting named readers' requests do.
995var errLoadsFull = errors.New("too many requests wait for their views")
996
997// viewFor is the view of the active generation that a request under auth,
998// read as reader, serves from, pinned for the request in reader's pool:
999// unpin gives it back. The view holds the generation's export, decoded,
1000// and the index of the projects the reader may see (visible). A named
1001// reader who may see no more than anyone has the view of what anyone may
1002// see, and pins it in the named readers' pool.
1003//
1004// A request whose active generation has no decoded export waits for a
1005// load, and one whose view has no index waits for it to be built, or for
1006// room for it. It holds no generation while it waits. It is admitted among
1007// the MaxLoadWaiting requests that may wait before it first waits, and
1008// keeps its place until viewFor returns. A request read as a named reader
1009// is admitted only while fewer than MaxNamedWaiting such requests wait, so
1010// anonymous requests always have places of their own. Once a load ends it
1011// looks again, since another generation may have been activated meanwhile.
1012func (s *Server) viewFor(ctx context.Context, auth authState, reader string) (*view, error) {
1013 anyone := reader == export.Anyone
1014 p := poolOf(reader)
1015 waiting := false
1016 defer func() {
1017 if waiting {
1018 <-s.loadWaiting
1019 if !anyone {
1020 <-s.namedWaiting
1021 }
1022 }
1023 }()
1024 wait := func() error {
1025 if waiting {
1026 return nil
1027 }
1028 if !anyone {
1029 select {
1030 case s.namedWaiting <- struct{}{}:
1031 default:
1032 return errLoadsFull
1033 }
1034 }
1035 select {
1036 case s.loadWaiting <- struct{}{}:
1037 waiting = true
1038 return nil
1039 default:
1040 if !anyone {
1041 <-s.namedWaiting
1042 }
1043 return errLoadsFull
1044 }
1045 }
1046 for {
1047 if err := ctx.Err(); err != nil {
1048 return nil, err
1049 }
1050 seq, err := s.store.Active()
1051 if err != nil {
1052 return nil, err
1053 }
1054 s.mu.Lock()
1055 d := s.exported
1056 s.mu.Unlock()
1057 if d == nil || d.seq < seq {
1058 if err := wait(); err != nil {
1059 return nil, err
1060 }
1061 if err := s.await(ctx, seq, anyone); err != nil {
1062 return nil, err
1063 }
1064 continue
1065 }
1066 if d.seq > seq {
1067 continue // the active generation moved on since it was read
1068 }
1069 shown := visible(d.e, auth.a, reader)
1070 key := viewKey{seq: seq, auth: string(auth.signed), projects: projectsKey(d.e, shown)}
1071 v, freed := s.pin(key, p, d.e, shown)
1072 if v == nil {
1073 if err := wait(); err != nil {
1074 return nil, err
1075 }
1076 select {
1077 case <-freed:
1078 continue
1079 case <-ctx.Done():
1080 return nil, fmt.Errorf("waiting for room to index generation %d: %w", seq, ctx.Err())
1081 }
1082 }
1083 select {
1084 case <-v.done:
1085 default:
1086 if err := wait(); err != nil {
1087 s.unpin(v, p)
1088 return nil, err
1089 }
1090 select {
1091 case <-v.done:
1092 case <-ctx.Done():
1093 s.unpin(v, p)
1094 return nil, fmt.Errorf("waiting for generation %d's index: %w", seq, ctx.Err())
1095 }
1096 }
1097 if v.err != nil {
1098 s.unpin(v, p)
1099 return nil, v.err
1100 }
1101 return v, nil
1102 }
1103}
1104
1105// projectsKey is the part of a view's name that names its projects: the
1106// name and identity of each project of e that shown names, in e's order.
1107func projectsKey(e *export.Export, shown map[string]bool) string {
1108 var b strings.Builder
1109 for _, p := range e.Projects {
1110 if shown[p.Name] {
1111 b.WriteString(p.Name + " " + p.Identity + "\n")
1112 }
1113 }
1114 return b.String()
1115}
1116
1117// pin is the view called key, pinned for one request of pool p: the view
1118// the server holds, built or being built, or a new one, which a worker of
1119// its own starts to build. The view takes a place of p for the request,
1120// unless it holds one already. A view no request pinned gives back the
1121// place it kept for another pool. A view whose build was stopped keeps its
1122// place until its worker ends, and is never pinned again. When every
1123// place of p is taken, room drops the view that keeps one with no request
1124// pinning it and was taken longest ago. When every place of p is pinned or
1125// stopping, pin is nil, and freed is closed once a place may be free.
1126func (s *Server) pin(key viewKey, p pool, e *export.Export, shown map[string]bool) (v *view, freed chan struct{}) {
1127 s.mu.Lock()
1128 defer s.mu.Unlock()
1129 s.used++
1130 v = s.views[key]
1131 if (v == nil || !v.holds[p]) && !s.room(p) {
1132 return nil, s.freed
1133 }
1134 if v == nil {
1135 ctx, cancel := context.WithCancel(context.Background())
1136 v = &view{key: key, e: e, shown: shown, cancel: cancel, done: make(chan struct{})}
1137 s.views[key] = v
1138 go s.build(ctx, v)
1139 } else if !v.pinned() && !v.holds[p] {
1140 v.holds = [pools]bool{}
1141 s.wake()
1142 }
1143 v.holds[p] = true
1144 v.pins[p]++
1145 v.used = s.used
1146 return v, nil
1147}
1148
1149// room is whether a view may take one more place of p. When every place of
1150// p is taken, it drops the view no request pins that keeps one and was
1151// taken longest ago, and is false when there is none: every place of p is
1152// held by a view requests of p pin, or by one whose build was stopped. It
1153// is called with mu held.
1154func (s *Server) room(p pool) bool {
1155 taken := 0
1156 for o := range s.stopping {
1157 if o.holds[p] {
1158 taken++
1159 }
1160 }
1161 var oldest *view
1162 for _, o := range s.views {
1163 if !o.holds[p] {
1164 continue
1165 }
1166 taken++
1167 if !o.pinned() && (oldest == nil || o.used < oldest.used) {
1168 oldest = o
1169 }
1170 }
1171 if taken < p.size() {
1172 return true
1173 }
1174 if oldest == nil {
1175 return false
1176 }
1177 delete(s.views, oldest.key)
1178 return true
1179}
1180
1181// unpin is a request of pool p that no longer holds v: it has rendered,
1182// or stopped waiting. A view that requests of p no longer pin while
1183// requests of the other pool do gives back its place of p. A view no
1184// request pins keeps its place of p, and is stopped when it is still being
1185// built: no request takes it again, and it keeps its place until its
1186// worker ends (build). A built view no request pins is dropped when its
1187// generation is older than the newest decoded export or the authorization
1188// it was built under is no longer the newest read. Its place may then be
1189// taken.
1190func (s *Server) unpin(v *view, p pool) {
1191 s.mu.Lock()
1192 defer s.mu.Unlock()
1193 if v.pins[p]--; v.pins[p] > 0 {
1194 return
1195 }
1196 if v.pinned() {
1197 v.holds[p] = false
1198 s.wake()
1199 return
1200 }
1201 building := v.idx == nil && v.err == nil
1202 if building || s.stale(v) {
1203 if s.views[v.key] == v {
1204 delete(s.views, v.key)
1205 }
1206 if building {
1207 s.stopping[v] = struct{}{}
1208 }
1209 v.cancel()
1210 }
1211 s.wake()
1212}
1213
1214// stale reports whether a view serves no request to come: its generation
1215// is older than the newest decoded export, or the authorization it was
1216// built under is not the newest read. It is called with mu held.
1217func (s *Server) stale(v *view) bool {
1218 return s.exported != nil && v.key.seq < s.exported.seq || v.key.auth != string(s.auth.signed)
1219}
1220
1221// wake tells the requests that wait for a place that one may be free. It
1222// is called with mu held.
1223func (s *Server) wake() {
1224 close(s.freed)
1225 s.freed = make(chan struct{})
1226}
1227
1228// build is v's worker. It builds v's index from v's decoded export, which
1229// a load has read already: it holds no loader slot, and waits for none.
1230// A view whose build fails, or is stopped, is dropped. A view whose build
1231// unpin stopped gives back its place only here, as its worker ends.
1232func (s *Server) build(ctx context.Context, v *view) {
1233 if s.indexing != nil {
1234 s.indexing(ctx, v.key)
1235 }
1236 idx, err := newIndex(ctx, v.e, v.shown)
1237 if err == nil {
1238 err = ctx.Err()
1239 }
1240 s.mu.Lock()
1241 if err != nil {
1242 v.err = err
1243 if s.views[v.key] == v {
1244 delete(s.views, v.key)
1245 }
1246 s.wake()
1247 } else {
1248 v.idx = idx
1249 }
1250 if _, stopped := s.stopping[v]; stopped {
1251 delete(s.stopping, v)
1252 s.wake()
1253 }
1254 s.mu.Unlock()
1255 v.cancel()
1256 close(v.done)
1257}
1258
1259// await waits until a load of generation seq, or of a newer generation,
1260// ends, or until ctx is done. It joins a load that will read one of those,
1261// since a worker reads whatever generation is active once it starts, and
1262// otherwise makes one.
1263//
1264// A load starts only once one of its requests takes a loader slot for it.
1265// While every slot it may take is taken, each of its requests waits for
1266// one, and the first to take one starts the load, so no load is queued
1267// that no request waits for. An anonymous request may take anonLoader or
1268// a slot of loaders, and any other request a slot of loaders alone. A
1269// request that stops waiting leaves the load, and the last to leave stops
1270// it. When leave drops a load to give back anonLoader, the requests still
1271// waiting for it wait for another load.
1272func (s *Server) await(ctx context.Context, seq int64, anonymous bool) error {
1273 for {
1274 s.mu.Lock()
1275 if d := s.exported; d != nil && d.seq >= seq {
1276 s.mu.Unlock()
1277 return nil
1278 }
1279 var l *load
1280 for m := range s.loads {
1281 if !m.opened || m.seq >= seq {
1282 l = m
1283 break
1284 }
1285 }
1286 if l == nil {
1287 l = &load{started: make(chan struct{}), done: make(chan struct{}), dropped: make(chan struct{})}
1288 s.loads[l] = struct{}{}
1289 }
1290 l.wants++
1291 if anonymous {
1292 l.anon++
1293 }
1294 s.mu.Unlock()
1295 var anon chan struct{}
1296 if anonymous {
1297 anon = s.anonLoader
1298 select {
1299 case <-l.started:
1300 case anon <- struct{}{}:
1301 if !s.start(l, anon) {
1302 <-anon
1303 }
1304 default:
1305 }
1306 }
1307 select {
1308 case <-l.started:
1309 case anon <- struct{}{}:
1310 if !s.start(l, anon) {
1311 <-anon
1312 }
1313 case s.loaders <- struct{}{}:
1314 if !s.start(l, s.loaders) {
1315 <-s.loaders
1316 }
1317 case <-ctx.Done():
1318 s.leave(l, anonymous)
1319 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
1320 }
1321 select {
1322 case <-l.done:
1323 select {
1324 case <-l.dropped:
1325 continue
1326 default:
1327 return l.err
1328 }
1329 case <-l.dropped:
1330 continue
1331 case <-ctx.Done():
1332 s.leave(l, anonymous)
1333 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
1334 }
1335 }
1336}
1337
1338// start starts l's worker, for the request that took token's slot for it.
1339// It is false when another request started it already.
1340func (s *Server) start(l *load, token chan struct{}) bool {
1341 s.mu.Lock()
1342 defer s.mu.Unlock()
1343 if l.cancel != nil {
1344 return false
1345 }
1346 ctx, cancel := context.WithCancel(context.Background())
1347 l.cancel, l.token = cancel, token
1348 close(l.started)
1349 go s.run(ctx, l)
1350 return true
1351}
1352
1353// leave is a request that stopped waiting for l. Once no request waits for
1354// it, no request may join it, and a load that started is stopped.
1355//
1356// anonLoader runs a load only while an anonymous request waits for it.
1357// When the last anonymous request leaves a load that runs on anonLoader
1358// while others wait for it, the load takes a free slot of loaders and
1359// runs on, so the requests that wait lose nothing. With no slot of
1360// loaders free, it is dropped: it is stopped, no request may join it, and
1361// those that wait for it wait for another load, within their own time.
1362// Either way it gives back anonLoader at once.
1363func (s *Server) leave(l *load, anonymous bool) {
1364 s.mu.Lock()
1365 defer s.mu.Unlock()
1366 l.wants--
1367 if anonymous {
1368 l.anon--
1369 }
1370 if l.wants == 0 {
1371 delete(s.loads, l)
1372 if l.cancel != nil {
1373 l.cancel()
1374 }
1375 return
1376 }
1377 if l.anon > 0 || l.token != s.anonLoader {
1378 return
1379 }
1380 select {
1381 case s.loaders <- struct{}{}:
1382 l.token = s.loaders
1383 default:
1384 delete(s.loads, l)
1385 l.cancel()
1386 l.token = nil
1387 close(l.dropped)
1388 }
1389 <-s.anonLoader
1390}
1391
1392// run is l's worker. It keeps the export it decodes when its generation is
1393// newer than the kept one's, so a load of an older generation never
1394// displaces a newer, and drops the views of older generations that no
1395// request pins, waking the requests that wait for room. A load that was
1396// stopped keeps nothing: leave stops it under mu, and run looks under mu.
1397// The worker gives back its generation before it ends, and then the
1398// loader slot its load holds, if leave has not given it back already. It
1399// builds no index.
1400func (s *Server) run(ctx context.Context, l *load) {
1401 d, err := s.read(ctx, l)
1402 s.mu.Lock()
1403 delete(s.loads, l)
1404 if d != nil && ctx.Err() == nil && (s.exported == nil || s.exported.seq < d.seq) {
1405 s.exported = d
1406 for key, v := range s.views {
1407 if !v.pinned() && s.stale(v) {
1408 delete(s.views, key)
1409 }
1410 }
1411 s.wake()
1412 }
1413 l.err = err
1414 token := l.token
1415 l.token = nil
1416 s.mu.Unlock()
1417 l.cancel()
1418 close(l.done)
1419 if token != nil {
1420 <-token
1421 }
1422}
1423
1424// read opens the active generation for l, and holds the generation while
1425// it reads and decodes the generation's export. It reads nothing when the
1426// generation's export is decoded already or another load reads the same,
1427// and its waiting requests look again. It stops reading once ctx is done.
1428func (s *Server) read(ctx context.Context, l *load) (d *decoded, err error) {
1429 // Cancellation can close the file during any operation. Report the
1430 // context error instead of the resulting descriptor error.
1431 defer func() {
1432 if stopped := ctx.Err(); stopped != nil {
1433 d, err = nil, stopped
1434 }
1435 }()
1436 if err := ctx.Err(); err != nil {
1437 return nil, err
1438 }
1439 g, release, err := s.store.Open()
1440 if err != nil {
1441 return nil, err
1442 }
1443 defer release()
1444 s.mu.Lock()
1445 read := s.exported == nil || s.exported.seq < g.Sequence
1446 for m := range s.loads {
1447 if m != l && m.opened && m.seq == g.Sequence {
1448 read = false
1449 }
1450 }
1451 l.opened, l.seq = true, g.Sequence
1452 s.mu.Unlock()
1453 if !read {
1454 return nil, nil
1455 }
1456 if s.loading != nil {
1457 s.loading(g)
1458 }
1459 f, err := os.OpenFile(g.ExportPath(), os.O_RDONLY|syscall.O_NONBLOCK, 0)
1460 if err != nil {
1461 return nil, err
1462 }
1463 defer f.Close()
1464 // Nonblocking open avoids waiting for a FIFO writer. Go's file poller
1465 // waits for reads, and Close wakes a read when the last waiter leaves.
1466 stop := context.AfterFunc(ctx, func() { _ = f.Close() })
1467 defer stop()
1468 info, err := f.Stat()
1469 if err != nil {
1470 return nil, err
1471 }
1472 data, err := io.ReadAll(&contextReader{ctx: ctx, r: f, waitForData: info.Mode()&os.ModeNamedPipe != 0})
1473 if ctx.Err() != nil {
1474 return nil, ctx.Err()
1475 }
1476 if err != nil {
1477 return nil, fmt.Errorf("reading generation %d's export: %w", g.Sequence, err)
1478 }
1479 e, err := export.DecodeContext(ctx, bytes.NewReader(data))
1480 if err != nil {
1481 return nil, err
1482 }
1483 if err := ctx.Err(); err != nil {
1484 return nil, err
1485 }
1486 return &decoded{seq: g.Sequence, e: e}, nil
1487}
1488
1489// contextReader reads from r until ctx is done.
1490type contextReader struct {
1491 ctx context.Context
1492 r io.Reader
1493 waitForData bool
1494}
1495
1496func (c *contextReader) Read(p []byte) (int, error) {
1497 for {
1498 if err := c.ctx.Err(); err != nil {
1499 return 0, err
1500 }
1501 n, err := c.r.Read(p)
1502 if n > 0 {
1503 c.waitForData = false
1504 }
1505 if !c.waitForData || err != io.EOF {
1506 return n, err
1507 }
1508 // A nonblocking FIFO reports EOF before its first writer arrives.
1509 // Wait for that writer without holding a blocking open syscall.
1510 timer := time.NewTimer(10 * time.Millisecond)
1511 select {
1512 case <-c.ctx.Done():
1513 timer.Stop()
1514 return 0, c.ctx.Err()
1515 case <-timer.C:
1516 }
1517 }
1518}
1519
1520// route dispatches on the request path's segments, each unescaped on its
1521// own, so an escaped slash stays inside its segment, through the request's
1522// index. The first segment is a group's name or an alias, and under a
1523// group's name the second is a project's name. It answers every route
1524// from the index alone, but a source route that reads a repository, whose
1525// work it returns for runGit to run.
1526func (q *request) route() *gitOp {
1527 parts := q.parts
1528 switch {
1529 case !q.ok:
1530 q.notFound()
1531 case len(parts) == 1 && parts[0] == "":
1532 q.landing()
1533 case isKnotsPage(parts):
1534 q.plan()
1535 case isProjectsPage(parts):
1536 q.projects()
1537 case parts[0] == own:
1538 q.notFound()
1539 default:
1540 if to, ok := q.idx.aliases[parts[0]]; ok {
1541 q.moved(to, 1)
1542 return nil
1543 }
1544 if len(parts) == 1 || len(parts) == 2 && parts[1] == "" {
1545 q.group(parts[0])
1546 return nil
1547 }
1548 if len(parts) >= 2 {
1549 if p := q.idx.groups[parts[0]][parts[1]]; p != nil {
1550 return q.projectRoute(p.Name, parts[2:])
1551 }
1552 if to, ok := q.idx.formers[parts[0]][parts[1]]; ok {
1553 q.moved(to, 2)
1554 return nil
1555 }
1556 }
1557 q.notFound()
1558 }
1559 return nil
1560}
1561
1562// isKnotsPage reports whether a path's segments name the knots page of
1563// every project, /-/knots.
1564func isKnotsPage(parts []string) bool {
1565 return len(parts) == 2 && parts[0] == own && parts[1] == "knots"
1566}
1567
1568// isProjectKnotsPage reports whether a path's segments have the shape of
1569// a project's knots page, /<group>/<project>/knots, whether or not the
1570// project is in the reader's view.
1571func isProjectKnotsPage(parts []string) bool {
1572 return len(parts) == 3 && parts[0] != own && parts[2] == "knots"
1573}
1574
1575// isProjectsPage reports whether a path's segments name the projects
1576// page, /-/projects.
1577func isProjectsPage(parts []string) bool {
1578 return len(parts) == 2 && parts[0] == own && parts[1] == "projects"
1579}
1580
1581// projectRoute dispatches on the segments of a path after its group's and
1582// its project's names.
1583func (q *request) projectRoute(project string, rest []string) *gitOp {
1584 switch {
1585 case len(rest) == 0, len(rest) == 1 && rest[0] == "":
1586 q.home(project)
1587 case len(rest) == 1 && rest[0] == "knots":
1588 q.projectPlan(project)
1589 case len(rest) == 2 && rest[0] == "knots":
1590 q.knot(project, rest[1])
1591 case len(rest) >= 1 && rest[0] == "source":
1592 return q.source(project, rest[1:])
1593 default:
1594 q.notFound()
1595 }
1596 return nil
1597}
1598
1599// moved answers a path under an alias or a former name with a permanent
1600// redirect to the same path under to, the escaped URL the path's first n
1601// segments stand for. The rest of the path after them, and the query,
1602// are kept as they were sent, even a query that is a bare "?".
1603func (q *request) moved(to string, n int) {
1604 esc := strings.Split(strings.TrimPrefix(q.r.URL.EscapedPath(), "/"), "/")
1605 rest := ""
1606 if len(esc) > n {
1607 rest = "/" + strings.Join(esc[n:], "/")
1608 }
1609 if q.r.URL.RawQuery != "" || q.r.URL.ForceQuery {
1610 rest += "?" + q.r.URL.RawQuery
1611 }
1612 q.location, q.permanent = to+rest, true
1613}
1614
1615// own is the first segment of the server's own paths, /-/. No group's
1616// name, and no alias, can be it, or start with it.
1617const own = "-"
1618
1619// The paths of the two pages the server serves under /-/ for every
1620// reader: the knots page of every project, and the projects page.
1621const (
1622 knotsURL = "/" + own + "/knots"
1623 projectsURL = "/" + own + "/projects"
1624)
1625
1626// landing answers / with a redirect. When the reader may see exactly one
1627// project, it goes to that project's page: the tree at its published tip.
1628// Otherwise, with several projects or none, it goes to the projects page.
1629func (q *request) landing() {
1630 if len(q.idx.public) == 1 {
1631 q.home(q.idx.public[0])
1632 return
1633 }
1634 q.redirect(projectsURL)
1635}
1636
1637// home answers /<group>/<project>/, and /<group>/<project>, with a
1638// redirect to the project's page: the tree at its published tip, with its
1639// README.
1640func (q *request) home(project string) {
1641 p, ok := q.project(project)
1642 if !ok {
1643 q.notFound()
1644 return
1645 }
1646 q.redirect(treeURL(q.idx.bases[p.Name], p.SourceTip, nil))
1647}
1648
1649func segments(escaped string) ([]string, bool) {
1650 rest, ok := strings.CutPrefix(escaped, "/")
1651 if !ok {
1652 return nil, false
1653 }
1654 parts := strings.Split(rest, "/")
1655 for i, p := range parts {
1656 u, err := url.PathUnescape(p)
1657 if err != nil {
1658 return nil, false
1659 }
1660 parts[i] = u
1661 }
1662 return parts, true
1663}
1664
1665// project is the project called name in the request's index: one the
1666// reader may see, in a group. Every route that names a project asks here
1667// first, and a project it refuses answers as one that does not exist.
1668func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) }
1669
1670func (idx *index) project(name string) (*export.Project, bool) {
1671 p, ok := idx.projects[name]
1672 if _, placed := idx.bases[name]; !ok || !placed {
1673 return nil, false
1674 }
1675 return p, true
1676}
1677
1678// notFound is the one 404 page, whatever was not found. It is made once,
1679// when the server starts, and names nothing of the request or the export,
1680// so a hidden project, a missing one, an unreachable commit and a missing
1681// path all answer alike, byte for byte.
1682func (q *request) notFound() {
1683 q.static(http.StatusNotFound, htmlType, notFoundPage)
1684}
1685
1686// fail logs err and answers with the one 500 page, which says nothing of
1687// the failure. A reader that went away is answered with nothing: git
1688// killed for it fails, and that is no failure of the server's. A request
1689// that ran out of time, or held its git slot past gitTime, answers 503.
1690func (q *request) fail(err error) {
1691 if q.r.Context().Err() != nil {
1692 return
1693 }
1694 if q.ctx.Err() == nil && q.git != nil && q.git.Err() != nil {
1695 err = fmt.Errorf("the request held its git slot past %v: %w", q.s.gitTime, err)
1696 }
1697 q.s.log(err)
1698 if q.ctx.Err() != nil || q.git != nil && q.git.Err() != nil {
1699 q.busy()
1700 return
1701 }
1702 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
1703 Heading: "Something went wrong", Text: "The server could not read this page.",
1704 })
1705}
1706
1707// busy answers a request the server has no room for: a source request it
1708// could not admit, a request that ran out of time, or a page the response
1709// budget has no room for. A reader that went away is answered with
1710// nothing.
1711func (q *request) busy() {
1712 if q.r.Context().Err() != nil {
1713 return
1714 }
1715 q.w.Header().Set("Retry-After", "5")
1716 q.static(http.StatusServiceUnavailable, htmlType, busyPage)
1717}
1718
1719// discard drops the rendered response, a page or a redirect, so that none
1720// of it is written.
1721func (q *request) discard() {
1722 q.drop()
1723 q.status, q.disposition, q.body, q.location, q.permanent = 0, "", nil, "", false
1724}
1725
1726// redirect answers with a redirect to url.
1727func (q *request) redirect(url string) { q.location = url }
1728
1729// write writes the rendered response, or nothing for a reader that went
1730// away. It returns once the response is written, or the connection
1731// failed or timed out. A permanent redirect names its location as it was
1732// made, with no cleaning, so the path it redirects to is the one the
1733// reader sent under another name.
1734//
1735// released is called once the headers are written, and before the body is,
1736// or at once when there is nothing to write.
1737func (q *request) write(released func()) {
1738 defer released()
1739 switch {
1740 case q.location != "" && q.permanent:
1741 q.w.Header().Set("Location", q.location)
1742 q.w.WriteHeader(http.StatusPermanentRedirect)
1743 case q.location != "":
1744 http.Redirect(releasing{q.w, released}, q.r, q.location, http.StatusFound)
1745 case q.status != 0:
1746 h := q.w.Header()
1747 h.Set("Content-Type", q.ctype)
1748 if q.disposition != "" {
1749 h.Set("Content-Disposition", q.disposition)
1750 }
1751 h.Set("Content-Length", strconv.Itoa(q.body.n))
1752 q.w.WriteHeader(q.status)
1753 released()
1754 for _, p := range q.body.pieces {
1755 if _, err := q.w.Write(p); err != nil {
1756 return
1757 }
1758 }
1759 }
1760}
1761
1762// releasing is a response writer that calls released once the headers are
1763// written, before any of the body is, so http.Redirect writes its short
1764// body after the serving lock is let go, as every other response does.
1765type releasing struct {
1766 http.ResponseWriter
1767 released func()
1768}
1769
1770func (w releasing) WriteHeader(status int) {
1771 w.ResponseWriter.WriteHeader(status)
1772 w.released()
1773}
1774
1775// setHeaders sets the headers every response carries, with policy, its
1776// route's Content-Security-Policy. Every response is the reader's own, so
1777// no cache stores it, and none is told it may be reused: no response
1778// carries an ETag or a Last-Modified.
1779func setHeaders(h http.Header, policy string) {
1780 h.Set("Content-Security-Policy", policy)
1781 h.Set("X-Content-Type-Options", "nosniff")
1782 h.Set("X-Frame-Options", "DENY")
1783 h.Set("Referrer-Policy", "no-referrer")
1784 h.Set("Cross-Origin-Opener-Policy", "same-origin")
1785 h.Set("Cross-Origin-Resource-Policy", "same-origin")
1786 h.Set("Cache-Control", "private, no-store")
1787 h.Set("Vary", "Cookie")
1788}