gunk-dev/the-valley

render.go

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