gunk-dev/the-valley

server.go

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