gunk-dev/the-valley

render.go

source43d938c6651fmain's published tip history
8.9 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.
84func (q *request) page(status int, name, title string, content any) {
85 data := layout{Title: title, Style: template.CSS(styleCSS), Content: content}
86 if name == "plan" {
87 data.Script = template.JS(planJS)
88 }
89 if q.e != nil {
90 data.Nav = append(data.Nav, link{"Plan", "/"})
91 for _, name := range q.idx.public {
92 p := q.idx.projects[name]
93 data.Nav = append(data.Nav, link{name + " source", treeURL(name, p.SourceTip, nil)})
94 }
95 data.Fresh = freshnessOf(q.e.Collected, q.now)
96 }
97 q.drop()
98 b := &body{s: q.s, ctx: q.ctx}
99 err := pages[name].ExecuteTemplate(b, "layout", data)
100 if err == nil {
101 q.status, q.ctype, q.body = status, htmlType, b
102 return
103 }
104 b.free()
105 switch {
106 case errors.Is(err, errNoBudget):
107 q.busy()
108 case errors.Is(err, errTooLarge):
109 q.s.log(fmt.Errorf("rendering %q: the page is larger than %d bytes", q.r.URL.EscapedPath(), q.s.maxResponse))
110 q.static(http.StatusInternalServerError, htmlType, tooLargePage)
111 case q.ctx.Err() != nil:
112 q.fail(fmt.Errorf("rendering %s: %w", name, err))
113 default:
114 q.s.log(fmt.Errorf("rendering %s: %w", name, err))
115 q.static(http.StatusInternalServerError, "text/plain; charset=utf-8", notRendered)
116 }
117}
118
119const htmlType = "text/html; charset=utf-8"
120
121// static answers with a response made once, when the server starts. It
122// shows no export, and takes nothing from the budget.
123func (q *request) static(status int, ctype string, page []byte) {
124 q.drop()
125 q.status, q.ctype, q.body = status, ctype, &body{pieces: [][]byte{page}, n: len(page)}
126}
127
128// drop gives back the pieces of the response the request rendered, if it
129// rendered one.
130func (q *request) drop() {
131 if q.body != nil {
132 q.body.free()
133 q.body = nil
134 }
135}
136
137// The responses made once: two pages, and the text that answers a page
138// that failed to render.
139var (
140 busyPage = staticPage("Busy", errorPage{
141 Heading: "Busy", Text: "The server is serving too many pages at once. Try again in a few seconds.",
142 })
143 tooLargePage = staticPage("Page too large", errorPage{
144 Heading: "Page too large", Text: "This page is larger than the server sends.",
145 })
146 notRendered = []byte("The server could not render this page.\n")
147)
148
149func staticPage(title string, content errorPage) []byte {
150 var b bytes.Buffer
151 data := layout{Title: title, Style: template.CSS(styleCSS), Content: content}
152 if err := pages["error"].ExecuteTemplate(&b, "layout", data); err != nil {
153 panic(err)
154 }
155 return b.Bytes()
156}
157
158// The errors a body's Write fails with: the page is larger than the
159// server sends, or the response budget has no piece left for it.
160var (
161 errTooLarge = errors.New("the page is larger than the server sends")
162 errNoBudget = errors.New("the response budget is spent")
163)
164
165// body is a response's body: the pieces it is held in, and their length.
166// A page is rendered into pieces of pieceSize, each taken from the
167// server's budget and given back by free, until its request's ctx is
168// done. A static page is one piece of its own, and its body has no
169// server.
170type body struct {
171 s *Server
172 ctx context.Context
173 pieces [][]byte
174 n int
175}
176
177// Write appends p to the body. It writes nothing of p that would take the
178// body past the server's maxResponse, and fails with errTooLarge, and
179// nothing once ctx is done. It fails with errNoBudget when the budget has
180// no piece left for the rest of p.
181func (b *body) Write(p []byte) (int, error) {
182 if err := b.ctx.Err(); err != nil {
183 return 0, err
184 }
185 if len(p) > b.s.maxResponse-b.n {
186 return 0, errTooLarge
187 }
188 written := 0
189 for written < len(p) {
190 last := len(b.pieces) - 1
191 if last < 0 || len(b.pieces[last]) == cap(b.pieces[last]) {
192 select {
193 case b.s.budget <- struct{}{}:
194 default:
195 return written, errNoBudget
196 }
197 b.pieces = append(b.pieces, make([]byte, 0, pieceSize))
198 last++
199 }
200 piece := b.pieces[last]
201 k := copy(piece[len(piece):cap(piece)], p[written:])
202 b.pieces[last] = piece[:len(piece)+k]
203 written += k
204 b.n += k
205 }
206 return written, nil
207}
208
209// free gives the body's pieces back to the budget, once.
210func (b *body) free() {
211 if b.s != nil {
212 for range b.pieces {
213 <-b.s.budget
214 }
215 }
216 b.pieces, b.n = nil, 0
217}
218
219// freshness is the export's collection time and its age, as of the
220// request. An export is stale once it is older than StaleAfter.
221type freshness struct {
222 Collected string
223 Age string
224 Stale bool
225}
226
227func freshnessOf(collected string, now time.Time) *freshness {
228 at, err := parseTime(collected)
229 if err != nil {
230 return &freshness{Collected: collected, Age: "of unknown age", Stale: true}
231 }
232 age := now.Sub(at)
233 return &freshness{Collected: stamp(at), Age: ago(age), Stale: age > StaleAfter}
234}
235
236// stamp is a time as the pages show it, to the minute, in UTC.
237func stamp(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") }
238
239func parseTime(s string) (time.Time, error) { return time.Parse(time.RFC3339, s) }
240
241// stampOf is stamp of an RFC 3339 time, or the text as it is when it is
242// not one.
243func stampOf(s string) string {
244 t, err := parseTime(s)
245 if err != nil {
246 return s
247 }
248 return stamp(t)
249}
250
251// ago is an age in words. A negative age, from a clock behind the
252// publisher's, reads as the youngest.
253func ago(d time.Duration) string {
254 switch {
255 case d < time.Minute:
256 return "less than a minute ago"
257 case d < time.Hour:
258 return count(int(d/time.Minute), "minute") + " ago"
259 case d < 48*time.Hour:
260 return count(int(d/time.Hour), "hour") + " ago"
261 }
262 return count(int(d/(24*time.Hour)), "day") + " ago"
263}
264
265// trimEnd is text without the line ends that close it, which a
266// preformatted block would show as blank lines.
267func trimEnd(s string) string { return strings.TrimRight(s, "\r\n") }
268
269func count(n int, noun string) string {
270 if n == 1 {
271 return "1 " + noun
272 }
273 return strconv.Itoa(n) + " " + noun + "s"
274}
275
276// The derived states valley-plan/v1 gives a knot, and the words the pages
277// show for each. ready is shown as free to start.
278var stateWords = map[string]string{
279 "ready": "free to start",
280 "in-progress": "in progress",
281 "blocked": "blocked",
282 "active": "question or idea",
283 "done": "done",
284 "abandoned": "abandoned",
285}
286
287// glyphClass is the class of a state's glyph. A state the pages do not
288// know is drawn as active.
289func glyphClass(state string) string {
290 if _, ok := stateWords[state]; ok {
291 return state
292 }
293 return "active"
294}
295
296func stateLabel(state string) string {
297 if w, ok := stateWords[state]; ok {
298 return w
299 }
300 return state
301}