gunk-dev/the-valley

render.go

sourceecbe8599c29dmain's published tip history
5.4 KiB
1package server
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "embed"
7 "encoding/base64"
8 "fmt"
9 "html/template"
10 "net/http"
11 "strconv"
12 "strings"
13 "time"
14)
15
16// The pages' templates, and the one stylesheet and one script they carry
17// inline. Nothing else is served: no font, image or script is fetched.
18var (
19 //go:embed templates/*.tmpl
20 templateFiles embed.FS
21 //go:embed assets/style.css
22 styleCSS string
23 //go:embed assets/plan.js
24 planJS string
25)
26
27// csp is every response's Content-Security-Policy. The inline stylesheet
28// and script are admitted by their SHA-256 hashes alone, and every other
29// fetch is held to the server's own origin.
30var csp = "default-src 'self'; script-src " + inlineHash(planJS) + "; style-src " + inlineHash(styleCSS) +
31 "; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
32
33func inlineHash(s string) string {
34 sum := sha256.Sum256([]byte(s))
35 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
36}
37
38var pages = parsePages("plan", "knot", "tree", "blob", "log", "error")
39
40// parsePages parses each page's template over the shared layout.
41func parsePages(names ...string) map[string]*template.Template {
42 funcs := template.FuncMap{"glyph": glyphClass, "label": stateLabel, "inc": func(i int) int { return i + 1 }}
43 base := template.Must(template.New("layout").Funcs(funcs).ParseFS(templateFiles, "templates/layout.tmpl"))
44 m := map[string]*template.Template{}
45 for _, name := range names {
46 m[name] = template.Must(template.Must(base.Clone()).ParseFS(templateFiles, "templates/"+name+".tmpl"))
47 }
48 return m
49}
50
51// layout is what every page shares: its title, the inline stylesheet, the
52// script on the plan page alone, the links to the plan and to each
53// project's source, and the export's age.
54type layout struct {
55 Title string
56 Style template.CSS
57 Script template.JS
58 Nav []link
59 Fresh *freshness
60 Content any
61}
62
63// errorPage is a page that answers a request with no content of its own.
64type errorPage struct {
65 Heading string
66 Text string
67}
68
69// link is one link: its text and where it goes.
70type link struct {
71 Text string
72 URL string
73}
74
75// page renders the page called name with content as the response, to be
76// written with status. A page is rendered whole before anything is
77// written, so a failure to render answers 500 rather than half a page.
78func (q *request) page(status int, name, title string, content any) {
79 data := layout{Title: title, Style: template.CSS(styleCSS), Content: content}
80 if name == "plan" {
81 data.Script = template.JS(planJS)
82 }
83 if q.e != nil {
84 data.Nav = append(data.Nav, link{"Plan", "/"})
85 for _, name := range q.idx.public {
86 p := q.idx.projects[name]
87 data.Nav = append(data.Nav, link{name + " source", treeURL(name, p.SourceTip, nil)})
88 }
89 data.Fresh = freshnessOf(q.e.Collected, q.now)
90 }
91 var b bytes.Buffer
92 if err := pages[name].ExecuteTemplate(&b, "layout", data); err != nil {
93 q.s.log(fmt.Errorf("rendering %s: %w", name, err))
94 q.status, q.ctype, q.body = http.StatusInternalServerError, "text/plain; charset=utf-8",
95 []byte("The server could not render this page.\n")
96 return
97 }
98 q.status, q.ctype, q.body = status, "text/html; charset=utf-8", b.Bytes()
99}
100
101// freshness is the export's collection time and its age, as of the
102// request. An export is stale once it is older than StaleAfter.
103type freshness struct {
104 Collected string
105 Age string
106 Stale bool
107}
108
109func freshnessOf(collected string, now time.Time) *freshness {
110 at, err := parseTime(collected)
111 if err != nil {
112 return &freshness{Collected: collected, Age: "of unknown age", Stale: true}
113 }
114 age := now.Sub(at)
115 return &freshness{Collected: stamp(at), Age: ago(age), Stale: age > StaleAfter}
116}
117
118// stamp is a time as the pages show it, to the minute, in UTC.
119func stamp(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") }
120
121func parseTime(s string) (time.Time, error) { return time.Parse(time.RFC3339, s) }
122
123// stampOf is stamp of an RFC 3339 time, or the text as it is when it is
124// not one.
125func stampOf(s string) string {
126 t, err := parseTime(s)
127 if err != nil {
128 return s
129 }
130 return stamp(t)
131}
132
133// ago is an age in words. A negative age, from a clock behind the
134// publisher's, reads as the youngest.
135func ago(d time.Duration) string {
136 switch {
137 case d < time.Minute:
138 return "less than a minute ago"
139 case d < time.Hour:
140 return count(int(d/time.Minute), "minute") + " ago"
141 case d < 48*time.Hour:
142 return count(int(d/time.Hour), "hour") + " ago"
143 }
144 return count(int(d/(24*time.Hour)), "day") + " ago"
145}
146
147// trimEnd is text without the line ends that close it, which a
148// preformatted block would show as blank lines.
149func trimEnd(s string) string { return strings.TrimRight(s, "\r\n") }
150
151func count(n int, noun string) string {
152 if n == 1 {
153 return "1 " + noun
154 }
155 return strconv.Itoa(n) + " " + noun + "s"
156}
157
158// The derived states valley-plan/v1 gives a knot, and the words the pages
159// show for each. ready is shown as free to start.
160var stateWords = map[string]string{
161 "ready": "free to start",
162 "in-progress": "in progress",
163 "blocked": "blocked",
164 "active": "question or idea",
165 "done": "done",
166 "abandoned": "abandoned",
167}
168
169// glyphClass is the class of a state's glyph. A state the pages do not
170// know is drawn as active.
171func glyphClass(state string) string {
172 if _, ok := stateWords[state]; ok {
173 return state
174 }
175 return "active"
176}
177
178func stateLabel(state string) string {
179 if w, ok := stateWords[state]; ok {
180 return w
181 }
182 return state
183}