gunk-dev/the-valley

render.go

source30e24c82839bmain's published tip history
12.8 KiB
1package server
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "embed"
8 "encoding/base64"
9 "errors"
10 "fmt"
11 "html/template"
12 "net/http"
13 "strconv"
14 "strings"
15 "time"
16)
17
18// The pages' templates, the one stylesheet they carry inline, and the two
19// scripts: the knots pages', and the reader pages'. Nothing else is
20// served: no font, image or script is fetched.
21var (
22 //go:embed templates/*.tmpl
23 templateFiles embed.FS
24 //go:embed assets/style.css
25 styleCSS string
26 //go:embed assets/plan.js
27 planJS string
28 //go:embed assets/reader.js
29 readerJS string
30)
31
32// The Content-Security-Policy of each route. Every policy admits the
33// inline stylesheet by its SHA-256 hash, fetches nothing from another
34// origin, and takes no plugin, base URL, form submission or frame. The
35// knots pages' policy admits their one inline script by its hash, and the
36// reader pages' theirs, which alone may connect, to this origin only.
37// Every other route's admits no script at all, and no route but the
38// reader pages lets a script connect. An error page answers with its
39// route's policy.
40var (
41 knotsPolicy = policy("script-src "+inlineHash(planJS), "connect-src 'none'")
42 readerPolicy = policy("script-src "+inlineHash(readerJS), "connect-src 'self'")
43 contentPolicy = policy("script-src 'none'", "connect-src 'none'")
44)
45
46func policy(scripts, connect string) string {
47 return "default-src 'self'; " + scripts + "; style-src " + inlineHash(styleCSS) +
48 "; " + connect + "; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
49}
50
51// policyFor is the policy of the route a path's segments name: the knots
52// pages' for /-/knots and for every path of the shape
53// /<group>/<project>/knots, and every other route's for the rest. It
54// reads the path's shape alone, so a project the reader may not see
55// answers with the same policy as one they may. ServeHTTP gives the
56// reader pages theirs.
57func policyFor(parts []string, ok bool) string {
58 if ok && (isKnotsPage(parts) || isProjectKnotsPage(parts)) {
59 return knotsPolicy
60 }
61 return contentPolicy
62}
63
64func inlineHash(s string) string {
65 sum := sha256.Sum256([]byte(s))
66 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
67}
68
69var pages = parsePages("plan", "projects", "knot", "tree", "blob", "log", "error", "notfound", redeemPage, logoutPage)
70
71// parsePages parses each page's template over the shared layout.
72func parsePages(names ...string) map[string]*template.Template {
73 funcs := template.FuncMap{"glyph": glyphClass, "label": stateLabel, "inc": func(i int) int { return i + 1 }}
74 base := template.Must(template.New("layout").Funcs(funcs).ParseFS(templateFiles, "templates/layout.tmpl"))
75 m := map[string]*template.Template{}
76 for _, name := range names {
77 m[name] = template.Must(template.Must(base.Clone()).ParseFS(templateFiles, "templates/"+name+".tmpl"))
78 }
79 return m
80}
81
82// layout is what every page shares: its title, the inline stylesheet, the
83// script of a knots page or of a reader page, the site navigation, and the
84// export's age. The navigation links the projects page and, for a reader
85// with a valid session, sign out. A page that belongs to one project
86// carries its project header in its own content (projectHead).
87type layout struct {
88 Title string
89 Style template.CSS
90 Script template.JS
91 Nav []link
92 Fresh *freshness
93 Content any
94}
95
96// errorPage is a page that answers a request with no content of its own.
97type errorPage struct {
98 Heading string
99 Text string
100}
101
102// link is one link: its text and where it goes.
103type link struct {
104 Text string
105 URL string
106}
107
108// page renders the page called name with content as the response, to be
109// written with status. A page is rendered whole before anything is
110// written, so a failure to render answers 500 rather than half a page. A
111// page that would pass the server's maxResponse stops rendering there,
112// and answers with the short page that says it is too large. A page the
113// response budget has no room for, or whose request runs out of time
114// while it renders, answers 503. A request runs no git once it renders,
115// so it gives back its git slot first.
116func (q *request) page(status int, name, title string, content any) {
117 q.giveSlot()
118 data := layout{Title: title, Style: template.CSS(styleCSS), Content: content}
119 switch name {
120 case "plan":
121 data.Script = template.JS(planJS)
122 case redeemPage, logoutPage:
123 data.Script = template.JS(readerJS)
124 }
125 if q.e != nil {
126 data.Nav = append(data.Nav, link{"projects", projectsURL})
127 data.Fresh = freshnessOf(q.e.Collected, q.auth.a.Checked, q.now)
128 }
129 // The session's link is the request's own, and never reaches an
130 // index: it is added here, for each page.
131 if q.sess.valid {
132 data.Nav = append(data.Nav, link{"Sign out", logoutURL})
133 }
134 q.drop()
135 if q.s.rendering != nil {
136 q.s.rendering(name)
137 }
138 b := &body{s: q.s, ctx: q.ctx}
139 err := pages[name].ExecuteTemplate(b, "layout", data)
140 if err == nil {
141 q.status, q.ctype, q.body = status, htmlType, b
142 return
143 }
144 b.free()
145 switch {
146 case errors.Is(err, errNoBudget):
147 q.busy()
148 case errors.Is(err, errTooLarge):
149 q.tooLarge()
150 case q.ctx.Err() != nil:
151 q.fail(fmt.Errorf("rendering %s: %w", name, err))
152 default:
153 q.s.log(fmt.Errorf("rendering %s: %w", name, err))
154 q.static(http.StatusInternalServerError, "text/plain; charset=utf-8", notRendered)
155 }
156}
157
158const htmlType = "text/html; charset=utf-8"
159
160// tooLarge logs a response that would pass the server's maxResponse, and
161// answers with the short page that says the page is too large.
162func (q *request) tooLarge() {
163 q.s.log(fmt.Errorf("rendering %q: the page is larger than %d bytes", q.r.URL.EscapedPath(), q.s.maxResponse))
164 q.static(http.StatusInternalServerError, htmlType, tooLargePage)
165}
166
167// static answers with a response made once, when the server starts. It
168// shows no export, and takes nothing from the budget.
169func (q *request) static(status int, ctype string, page []byte) {
170 q.drop()
171 q.status, q.ctype, q.body = status, ctype, &body{pieces: [][]byte{page}, n: len(page)}
172}
173
174// drop gives back the pieces of the response the request rendered, if it
175// rendered one.
176func (q *request) drop() {
177 if q.body != nil {
178 q.body.free()
179 q.body = nil
180 }
181}
182
183// The responses made once: four pages, and the text that answers a page
184// that failed to render. The not-found page is the one every 404 answers
185// with. It shows the box of text the operator chose, whose last line
186// links to /, and it names no site, no project and nothing of the
187// request.
188var (
189 busyPage = staticPage("error", "Busy", errorPage{
190 Heading: "Busy", Text: "The server is serving too many pages at once. Try again in a few seconds.",
191 })
192 tooLargePage = staticPage("error", "Page too large", errorPage{
193 Heading: "Page too large", Text: "This page is larger than the server sends.",
194 })
195 notFoundPage = staticPage("notfound", "Not found", nil)
196 unavailableHTML = staticPage("error", "Unavailable", errorPage{
197 Heading: "Sign-in unavailable", Text: "This server cannot check sign-ins right now. Try again later.",
198 })
199 notRendered = []byte("The server could not render this page.\n")
200)
201
202func staticPage(name, title string, content any) []byte {
203 var b bytes.Buffer
204 data := layout{Title: title, Style: template.CSS(styleCSS), Content: content}
205 if err := pages[name].ExecuteTemplate(&b, "layout", data); err != nil {
206 panic(err)
207 }
208 return b.Bytes()
209}
210
211// The errors a body's Write fails with: the page is larger than the
212// server sends, or the response budget has no piece left for it.
213var (
214 errTooLarge = errors.New("the page is larger than the server sends")
215 errNoBudget = errors.New("the response budget is spent")
216)
217
218// body is a response's body: the pieces it is held in, and their length.
219// A page is rendered into pieces of pieceSize, each taken from the
220// server's budget and given back by free, until its request's ctx is
221// done. Once a body grows past its first SmallPage bytes, all of its
222// pieces are held against the large budget too. A static page is one
223// piece of its own, and its body has no server.
224type body struct {
225 s *Server
226 ctx context.Context
227 pieces [][]byte
228 n int
229}
230
231// Write appends p to the body. It writes nothing of p that would take the
232// body past the server's maxResponse, and fails with errTooLarge, and
233// nothing once ctx is done. It fails with errNoBudget when the budget, or
234// for a body past its first SmallPage bytes the large budget, has no room
235// left for the rest of p.
236func (b *body) Write(p []byte) (int, error) {
237 if err := b.ctx.Err(); err != nil {
238 return 0, err
239 }
240 if len(p) > b.s.maxResponse-b.n {
241 return 0, errTooLarge
242 }
243 written := 0
244 for written < len(p) {
245 last := len(b.pieces) - 1
246 if last < 0 || len(b.pieces[last]) == cap(b.pieces[last]) {
247 if !b.s.take(len(b.pieces)) {
248 return written, errNoBudget
249 }
250 b.pieces = append(b.pieces, make([]byte, 0, pieceSize))
251 last++
252 }
253 piece := b.pieces[last]
254 k := copy(piece[len(piece):cap(piece)], p[written:])
255 b.pieces[last] = piece[:len(piece)+k]
256 written += k
257 b.n += k
258 }
259 return written, nil
260}
261
262// free gives the body's pieces back to the budget, once.
263func (b *body) free() {
264 if b.s != nil {
265 b.s.give(len(b.pieces))
266 }
267 b.pieces, b.n = nil, 0
268}
269
270// The budget in pieces: all of it, the large budget, and how many of a
271// response's pieces SmallPage is.
272const (
273 budgetPieces = MaxBuffered / pieceSize
274 largePieces = MaxLarge / pieceSize
275 smallPieces = SmallPage / pieceSize
276)
277
278// take takes a response's piece i from the budget. A response's first
279// smallPieces pieces take from the budget alone. The piece that takes it
280// past them takes from the large budget too, for itself and for every
281// piece before it, and each piece after that takes one more. So responses
282// larger than SmallPage hold at most MaxLarge in all, counting their
283// first SmallPage bytes, and the rest of the budget is left to the
284// others. take takes nothing and is false when either budget has too
285// little left.
286func (s *Server) take(i int) bool {
287 large := 0
288 switch {
289 case i == smallPieces:
290 large = smallPieces + 1
291 case i > smallPieces:
292 large = 1
293 }
294 s.pieces.Lock()
295 defer s.pieces.Unlock()
296 if s.held == budgetPieces || s.large+large > largePieces {
297 return false
298 }
299 s.held++
300 s.large += large
301 return true
302}
303
304// give gives back the n pieces a response took.
305func (s *Server) give(n int) {
306 s.pieces.Lock()
307 defer s.pieces.Unlock()
308 s.held -= n
309 if n > smallPieces {
310 s.large -= n
311 }
312}
313
314// freshness is when the export's plan was collected, and when the
315// publisher last finished a check of the policy, with that check's age as
316// of the request. The pages are stale once that check is older than
317// StaleAfter: the publisher checks the policy on every pass, whether or
318// not the content changed, so a page goes stale only once the publisher
319// stops reaching the edge. The collection time is shown apart, and says
320// how old the content is; a recent check does not make old content new.
321type freshness struct {
322 Collected string
323 Checked string
324 Age string
325 Stale bool
326}
327
328func freshnessOf(collected string, checked, now time.Time) *freshness {
329 f := &freshness{Collected: stampOf(collected), Checked: stamp(checked)}
330 age := now.Sub(checked)
331 f.Age, f.Stale = ago(age), age > StaleAfter
332 return f
333}
334
335// stamp is a time as the pages show it, to the minute, in UTC.
336func stamp(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") }
337
338func parseTime(s string) (time.Time, error) { return time.Parse(time.RFC3339, s) }
339
340// stampOf is stamp of an RFC 3339 time, or the text as it is when it is
341// not one.
342func stampOf(s string) string {
343 t, err := parseTime(s)
344 if err != nil {
345 return s
346 }
347 return stamp(t)
348}
349
350// ago is an age in words. A negative age, from a clock behind the
351// publisher's, reads as the youngest.
352func ago(d time.Duration) string {
353 switch {
354 case d < time.Minute:
355 return "less than a minute ago"
356 case d < time.Hour:
357 return count(int(d/time.Minute), "minute") + " ago"
358 case d < 48*time.Hour:
359 return count(int(d/time.Hour), "hour") + " ago"
360 }
361 return count(int(d/(24*time.Hour)), "day") + " ago"
362}
363
364// trimEnd is text without the line ends that close it, which a
365// preformatted block would show as blank lines.
366func trimEnd(s string) string { return strings.TrimRight(s, "\r\n") }
367
368func count(n int, noun string) string {
369 if n == 1 {
370 return "1 " + noun
371 }
372 return strconv.Itoa(n) + " " + noun + "s"
373}
374
375// The derived states valley-plan/v1 gives a knot, and the words the pages
376// show for each. ready is shown as free to start.
377var stateWords = map[string]string{
378 "ready": "free to start",
379 "in-progress": "in progress",
380 "blocked": "blocked",
381 "active": "question or idea",
382 "done": "done",
383 "abandoned": "abandoned",
384}
385
386// glyphClass is the class of a state's glyph. A state the pages do not
387// know is drawn as active.
388func glyphClass(state string) string {
389 if _, ok := stateWords[state]; ok {
390 return state
391 }
392 return "active"
393}
394
395func stateLabel(state string) string {
396 if w, ok := stateWords[state]; ok {
397 return w
398 }
399 return state
400}