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