gunk-dev/the-valley

render.go

source262d8ca88ba9main's published tip history
11.1 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", "notfound")
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(q.idx.bases[name], p.SourceTip, nil)})
96 }
97 data.Fresh = freshnessOf(q.e.Collected, q.auth.a.Checked, 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.tooLarge()
115 case q.ctx.Err() != nil:
116 q.fail(fmt.Errorf("rendering %s: %w", name, err))
117 default:
118 q.s.log(fmt.Errorf("rendering %s: %w", name, err))
119 q.static(http.StatusInternalServerError, "text/plain; charset=utf-8", notRendered)
120 }
121}
122
123const htmlType = "text/html; charset=utf-8"
124
125// tooLarge logs a response that would pass the server's maxResponse, and
126// answers with the short page that says the page is too large.
127func (q *request) tooLarge() {
128 q.s.log(fmt.Errorf("rendering %q: the page is larger than %d bytes", q.r.URL.EscapedPath(), q.s.maxResponse))
129 q.static(http.StatusInternalServerError, htmlType, tooLargePage)
130}
131
132// static answers with a response made once, when the server starts. It
133// shows no export, and takes nothing from the budget.
134func (q *request) static(status int, ctype string, page []byte) {
135 q.drop()
136 q.status, q.ctype, q.body = status, ctype, &body{pieces: [][]byte{page}, n: len(page)}
137}
138
139// drop gives back the pieces of the response the request rendered, if it
140// rendered one.
141func (q *request) drop() {
142 if q.body != nil {
143 q.body.free()
144 q.body = nil
145 }
146}
147
148// The responses made once: three pages, and the text that answers a page
149// that failed to render. The not-found page is the one every 404 answers
150// with. It shows the box of text the operator chose, whose last line
151// links to the plan, and it names no site, no project and nothing of the
152// request.
153var (
154 busyPage = staticPage("error", "Busy", errorPage{
155 Heading: "Busy", Text: "The server is serving too many pages at once. Try again in a few seconds.",
156 })
157 tooLargePage = staticPage("error", "Page too large", errorPage{
158 Heading: "Page too large", Text: "This page is larger than the server sends.",
159 })
160 notFoundPage = staticPage("notfound", "Not found", nil)
161 notRendered = []byte("The server could not render this page.\n")
162)
163
164func staticPage(name, title string, content any) []byte {
165 var b bytes.Buffer
166 data := layout{Title: title, Style: template.CSS(styleCSS), Content: content}
167 if err := pages[name].ExecuteTemplate(&b, "layout", data); err != nil {
168 panic(err)
169 }
170 return b.Bytes()
171}
172
173// The errors a body's Write fails with: the page is larger than the
174// server sends, or the response budget has no piece left for it.
175var (
176 errTooLarge = errors.New("the page is larger than the server sends")
177 errNoBudget = errors.New("the response budget is spent")
178)
179
180// body is a response's body: the pieces it is held in, and their length.
181// A page is rendered into pieces of pieceSize, each taken from the
182// server's budget and given back by free, until its request's ctx is
183// done. Once a body grows past its first SmallPage bytes, all of its
184// pieces are held against the large budget too. A static page is one
185// piece of its own, and its body has no server.
186type body struct {
187 s *Server
188 ctx context.Context
189 pieces [][]byte
190 n int
191}
192
193// Write appends p to the body. It writes nothing of p that would take the
194// body past the server's maxResponse, and fails with errTooLarge, and
195// nothing once ctx is done. It fails with errNoBudget when the budget, or
196// for a body past its first SmallPage bytes the large budget, has no room
197// left for the rest of p.
198func (b *body) Write(p []byte) (int, error) {
199 if err := b.ctx.Err(); err != nil {
200 return 0, err
201 }
202 if len(p) > b.s.maxResponse-b.n {
203 return 0, errTooLarge
204 }
205 written := 0
206 for written < len(p) {
207 last := len(b.pieces) - 1
208 if last < 0 || len(b.pieces[last]) == cap(b.pieces[last]) {
209 if !b.s.take(len(b.pieces)) {
210 return written, errNoBudget
211 }
212 b.pieces = append(b.pieces, make([]byte, 0, pieceSize))
213 last++
214 }
215 piece := b.pieces[last]
216 k := copy(piece[len(piece):cap(piece)], p[written:])
217 b.pieces[last] = piece[:len(piece)+k]
218 written += k
219 b.n += k
220 }
221 return written, nil
222}
223
224// free gives the body's pieces back to the budget, once.
225func (b *body) free() {
226 if b.s != nil {
227 b.s.give(len(b.pieces))
228 }
229 b.pieces, b.n = nil, 0
230}
231
232// The budget in pieces: all of it, the large budget, and how many of a
233// response's pieces SmallPage is.
234const (
235 budgetPieces = MaxBuffered / pieceSize
236 largePieces = MaxLarge / pieceSize
237 smallPieces = SmallPage / pieceSize
238)
239
240// take takes a response's piece i from the budget. A response's first
241// smallPieces pieces take from the budget alone. The piece that takes it
242// past them takes from the large budget too, for itself and for every
243// piece before it, and each piece after that takes one more. So responses
244// larger than SmallPage hold at most MaxLarge in all, counting their
245// first SmallPage bytes, and the rest of the budget is left to the
246// others. take takes nothing and is false when either budget has too
247// little left.
248func (s *Server) take(i int) bool {
249 large := 0
250 switch {
251 case i == smallPieces:
252 large = smallPieces + 1
253 case i > smallPieces:
254 large = 1
255 }
256 s.pieces.Lock()
257 defer s.pieces.Unlock()
258 if s.held == budgetPieces || s.large+large > largePieces {
259 return false
260 }
261 s.held++
262 s.large += large
263 return true
264}
265
266// give gives back the n pieces a response took.
267func (s *Server) give(n int) {
268 s.pieces.Lock()
269 defer s.pieces.Unlock()
270 s.held -= n
271 if n > smallPieces {
272 s.large -= n
273 }
274}
275
276// freshness is when the export's plan was collected, and when the
277// publisher last finished a check of the policy, with that check's age as
278// of the request. The pages are stale once that check is older than
279// StaleAfter: the publisher checks the policy on every pass, whether or
280// not the content changed, so a page goes stale only once the publisher
281// stops reaching the edge. The collection time is shown apart, and says
282// how old the content is; a recent check does not make old content new.
283type freshness struct {
284 Collected string
285 Checked string
286 Age string
287 Stale bool
288}
289
290func freshnessOf(collected string, checked, now time.Time) *freshness {
291 f := &freshness{Collected: stampOf(collected), Checked: stamp(checked)}
292 age := now.Sub(checked)
293 f.Age, f.Stale = ago(age), age > StaleAfter
294 return f
295}
296
297// stamp is a time as the pages show it, to the minute, in UTC.
298func stamp(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") }
299
300func parseTime(s string) (time.Time, error) { return time.Parse(time.RFC3339, s) }
301
302// stampOf is stamp of an RFC 3339 time, or the text as it is when it is
303// not one.
304func stampOf(s string) string {
305 t, err := parseTime(s)
306 if err != nil {
307 return s
308 }
309 return stamp(t)
310}
311
312// ago is an age in words. A negative age, from a clock behind the
313// publisher's, reads as the youngest.
314func ago(d time.Duration) string {
315 switch {
316 case d < time.Minute:
317 return "less than a minute ago"
318 case d < time.Hour:
319 return count(int(d/time.Minute), "minute") + " ago"
320 case d < 48*time.Hour:
321 return count(int(d/time.Hour), "hour") + " ago"
322 }
323 return count(int(d/(24*time.Hour)), "day") + " ago"
324}
325
326// trimEnd is text without the line ends that close it, which a
327// preformatted block would show as blank lines.
328func trimEnd(s string) string { return strings.TrimRight(s, "\r\n") }
329
330func count(n int, noun string) string {
331 if n == 1 {
332 return "1 " + noun
333 }
334 return strconv.Itoa(n) + " " + noun + "s"
335}
336
337// The derived states valley-plan/v1 gives a knot, and the words the pages
338// show for each. ready is shown as free to start.
339var stateWords = map[string]string{
340 "ready": "free to start",
341 "in-progress": "in progress",
342 "blocked": "blocked",
343 "active": "question or idea",
344 "done": "done",
345 "abandoned": "abandoned",
346}
347
348// glyphClass is the class of a state's glyph. A state the pages do not
349// know is drawn as active.
350func glyphClass(state string) string {
351 if _, ok := stateWords[state]; ok {
352 return state
353 }
354 return "active"
355}
356
357func stateLabel(state string) string {
358 if w, ok := stateWords[state]; ok {
359 return w
360 }
361 return state
362}