gunk-dev/the-valley

render.go

source927567a46a59main's published tip history
10.2 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. Once a body grows past its first SmallPage bytes, all of its
169// pieces are held against the large budget too. A static page is one
170// piece of its own, and its body has no server.
171type body struct {
172 s *Server
173 ctx context.Context
174 pieces [][]byte
175 n int
176}
177
178// Write appends p to the body. It writes nothing of p that would take the
179// body past the server's maxResponse, and fails with errTooLarge, and
180// nothing once ctx is done. It fails with errNoBudget when the budget, or
181// for a body past its first SmallPage bytes the large budget, has no room
182// left for the rest of p.
183func (b *body) Write(p []byte) (int, error) {
184 if err := b.ctx.Err(); err != nil {
185 return 0, err
186 }
187 if len(p) > b.s.maxResponse-b.n {
188 return 0, errTooLarge
189 }
190 written := 0
191 for written < len(p) {
192 last := len(b.pieces) - 1
193 if last < 0 || len(b.pieces[last]) == cap(b.pieces[last]) {
194 if !b.s.take(len(b.pieces)) {
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 b.s.give(len(b.pieces))
213 }
214 b.pieces, b.n = nil, 0
215}
216
217// The budget in pieces: all of it, the large budget, and how many of a
218// response's pieces SmallPage is.
219const (
220 budgetPieces = MaxBuffered / pieceSize
221 largePieces = MaxLarge / pieceSize
222 smallPieces = SmallPage / pieceSize
223)
224
225// take takes a response's piece i from the budget. A response's first
226// smallPieces pieces take from the budget alone. The piece that takes it
227// past them takes from the large budget too, for itself and for every
228// piece before it, and each piece after that takes one more. So responses
229// larger than SmallPage hold at most MaxLarge in all, counting their
230// first SmallPage bytes, and the rest of the budget is left to the
231// others. take takes nothing and is false when either budget has too
232// little left.
233func (s *Server) take(i int) bool {
234 large := 0
235 switch {
236 case i == smallPieces:
237 large = smallPieces + 1
238 case i > smallPieces:
239 large = 1
240 }
241 s.pieces.Lock()
242 defer s.pieces.Unlock()
243 if s.held == budgetPieces || s.large+large > largePieces {
244 return false
245 }
246 s.held++
247 s.large += large
248 return true
249}
250
251// give gives back the n pieces a response took.
252func (s *Server) give(n int) {
253 s.pieces.Lock()
254 defer s.pieces.Unlock()
255 s.held -= n
256 if n > smallPieces {
257 s.large -= n
258 }
259}
260
261// freshness is the export's collection time and its age, as of the
262// request. An export is stale once it is older than StaleAfter.
263type freshness struct {
264 Collected string
265 Age string
266 Stale bool
267}
268
269func freshnessOf(collected string, now time.Time) *freshness {
270 at, err := parseTime(collected)
271 if err != nil {
272 return &freshness{Collected: collected, Age: "of unknown age", Stale: true}
273 }
274 age := now.Sub(at)
275 return &freshness{Collected: stamp(at), Age: ago(age), Stale: age > StaleAfter}
276}
277
278// stamp is a time as the pages show it, to the minute, in UTC.
279func stamp(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") }
280
281func parseTime(s string) (time.Time, error) { return time.Parse(time.RFC3339, s) }
282
283// stampOf is stamp of an RFC 3339 time, or the text as it is when it is
284// not one.
285func stampOf(s string) string {
286 t, err := parseTime(s)
287 if err != nil {
288 return s
289 }
290 return stamp(t)
291}
292
293// ago is an age in words. A negative age, from a clock behind the
294// publisher's, reads as the youngest.
295func ago(d time.Duration) string {
296 switch {
297 case d < time.Minute:
298 return "less than a minute ago"
299 case d < time.Hour:
300 return count(int(d/time.Minute), "minute") + " ago"
301 case d < 48*time.Hour:
302 return count(int(d/time.Hour), "hour") + " ago"
303 }
304 return count(int(d/(24*time.Hour)), "day") + " ago"
305}
306
307// trimEnd is text without the line ends that close it, which a
308// preformatted block would show as blank lines.
309func trimEnd(s string) string { return strings.TrimRight(s, "\r\n") }
310
311func count(n int, noun string) string {
312 if n == 1 {
313 return "1 " + noun
314 }
315 return strconv.Itoa(n) + " " + noun + "s"
316}
317
318// The derived states valley-plan/v1 gives a knot, and the words the pages
319// show for each. ready is shown as free to start.
320var stateWords = map[string]string{
321 "ready": "free to start",
322 "in-progress": "in progress",
323 "blocked": "blocked",
324 "active": "question or idea",
325 "done": "done",
326 "abandoned": "abandoned",
327}
328
329// glyphClass is the class of a state's glyph. A state the pages do not
330// know is drawn as active.
331func glyphClass(state string) string {
332 if _, ok := stateWords[state]; ok {
333 return state
334 }
335 return "active"
336}
337
338func stateLabel(state string) string {
339 if w, ok := stateWords[state]; ok {
340 return w
341 }
342 return state
343}