gunk-dev/the-valley

server.go

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