gunk-dev/the-valley

render.go

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