19. Show me how
Every exhibit shows the code that makes it work.
An app's code is plain files in its repo; apps shows any commit of it, and the zoo links each exhibit to the files it was built from, so what you read is what runs.
This is the code serving the zoo right now: the bytes this very program was built from (each file is embedded when the zoo is compiled), at commit
55c71513c5 (staging). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.
e19_show_me_how.odin sha256 55cfef2bdbf1 · raw
1package main 2 3// Exhibit 19. Every card's "how" link opens the exhibit's source, the files the zoo is running. Each 4// is embedded in the program when the zoo is compiled (#load), so /how/<n> shows exactly the bytes the 5// running build was made from; with page.odin's switch on, the links open them on apps instead, at the 6// commit this zoo runs (root's mirror of the zoo's repo; `source = public` lets anyone read it there). 7// The check fetches every one of those files over HTTPS, from wherever the links point, and compares 8// it byte for byte with the file the zoo was built from. 9 10import "core:fmt" 11import "ratcloud:rc" 12 13e19 :: proc() -> Exhibit { 14 return { 15 n = 19, wing = "Building", 16 title = "Show me how", 17 promise = "Every exhibit shows the code that makes it work.", 18 block = "An app's code is plain files in its repo; apps shows any commit of it, and the zoo links each exhibit to the files it was built from, so what you read is what runs.", 19 src = {"e19_show_me_how.odin", #load("e19_show_me_how.odin", string)}, 20 files = srcs({"page.odin", #load("page.odin", string)}, {"zoo.odin", #load("zoo.odin", string)}), 21 show = proc(me: ^rc.User) -> string { 22 where_ := "the actual file this program was built from, with its sha256" 23 if how_on_apps() do where_ = fmt.tprintf(`on <a href="%s">apps</a>, at commit <code>%s</code>, the one running here`, h(how_apps_url("files", "")), h(short(how_commit(), 10))) 24 e10, _ := exhibit(10) 25 e9, _ := exhibit(9) 26 return fmt.tprintf(`<p>Every card has a <b>how</b> link. Try <a href="%s">the counter's</a> or <a href="%s">the doors'</a>: %s.</p>`, h(how_url(e10)), h(how_url(e9)), where_) 27 }, 28 check = proc() -> Check { 29 b := new_browser() // a visitor: no sign-in 30 n := 0 31 apps := how_on_apps() 32 if apps && how_commit() == "" do return fail("the fact deploy.json names no commit for this zoo, so there is nothing to link to on apps") 33 for &e in exhibits() { 34 for f in how_files(&e) { 35 url := how_apps_url("raw", f.path) if apps else self_url(fmt.tprintf("/how/%d?raw=%s", e.n, rc.percent_encode(f.path))) 36 r := get(b, url) 37 if r.status != 200 do return fail(fmt.tprintf("how for exhibit %d (%s) answered %d at %s", e.n, f.path, r.status, url)) 38 if r.body != f.text do return fail(fmt.tprintf("how for exhibit %d shows a %s that differs from the running one (%s)", e.n, f.path, url)) 39 n += 1 40 } 41 } 42 return pass(fmt.tprintf("%d files fetched over HTTPS from %s each identical to the file the running build was made from", n, cat("apps, at commit ", short(how_commit(), 10), ",") if apps else "the zoo's own how pages,")) 43 }, 44 } 45}
page.odin sha256 6b4723523a00 · raw
1package main 2 3// The front page (the row of lights, then every exhibit by wing) and "how" (exhibit 19: an 4// exhibit's source, the very bytes this program was built from). 5 6import "core:crypto/hash" 7import "core:fmt" 8import "core:strings" 9import "ratcloud:rc" 10 11PAGE_HTML :: #load("web/page.html", string) 12HOW_HTML :: #load("web/how.html", string) 13ZOO_CSS :: #load("public/zoo.css", string) // served by nginx from public/; here only for its version 14ZOO_JS :: #load("public/zoo.js", string) 15 16// The first 8 hex of a file's sha256: its version in a URL, so a new file is a new address. 17version_of :: proc(s: string) -> string { 18 out: [32]u8 19 hash.hash_string_to_buffer(.SHA256, s, out[:]) 20 return hex(out[:4]) 21} 22 23light_html :: proc(l: Light) -> string { 24 when_ := cat(" ", ago(l.at)) if l.at > 0 else "" 25 // A red light says what is wrong, then when it last worked, or that it never has. 26 text: string 27 if l.prefix != "" { 28 pre := cat(h(l.prefix), when_) if when_ != "" else "never worked yet" 29 text = fmt.tprintf(`%s <span class="muted">(%s)</span>`, h(l.text), pre) 30 } else { 31 text = cat(h(l.text), when_) 32 } 33 return fmt.tprintf(`<span class="light %s"><i></i><span>%s</span></span>`, l.color, text) 34} 35 36KIND_WORDS :: proc(kind: string) -> string { 37 switch kind { 38 case "self": return "checks itself" 39 case "human": return "a person checks this" 40 } 41 return "not built yet" 42} 43 44page :: proc(w: ^rc.Response, me: ^rc.User) { 45 all := exhibits() 46 lights := make([]Light, len(all)) 47 count: map[string]int 48 for &e, i in all {lights[i] = light(&e); count[lights[i].color] += 1} 49 e := env() 50 deploy := jget(fact("deploy.json"), e.env) 51 52 dots := strings.builder_make() 53 tries := strings.builder_make() 54 scripts := strings.builder_make() 55 for &x, i in all { 56 rc.render_to(&dots, `<a href="#e{{1}}" class="dot {{2}}" title="{{3}}">{{4}}</a>`, {{"1", x.n}, {"2", lights[i].color}, {"3", fmt.tprintf("%d. %s: %s", x.n, x.title, lights[i].text)}, {"4", x.n}}) 57 if x.try_ != "" && me != nil { 58 if strings.builder_len(tries) > 0 do strings.write_string(&tries, " · ") 59 rc.render_to(&tries, `<a href="#e{{1}}">{{2}}</a>`, {{"1", x.n}, {"2", x.try_}}) 60 } 61 } 62 wings := strings.builder_make() 63 for wing in WINGS { 64 rc.render_to(&wings, " <section class=\"wing\">\n <h2>{{1}}</h2>\n <div class=\"cards\">\n", {{"1", wing}}) 65 for &x, i in all { 66 if x.wing != wing do continue 67 rc.render_to(&wings, ` <article class="card {{1}}" id="e{{2}}"{{3}}><header><span class="num">{{4}}</span><h3>{{5}}</h3></header>`, {{"1", lights[i].color}, {"2", x.n}, {"3", rc.raw(" data-try" if x.try_ != "" else "")}, {"4", x.n}, {"5", x.title}}) 68 rc.render_to(&wings, `{{1}}<p class="promise">{{2}}</p><details class="more" open><summary>See it working</summary>`, {{"1", rc.raw(light_html(lights[i]))}, {"2", x.promise}}) 69 if x.show != nil do rc.render_to(&wings, `<div class="live">{{1}}</div>`, {{"1", rc.raw(x.show(me))}}) 70 rc.render_to(&wings, `<p class="block">{{1}}</p></details><footer><a href="{{2}}">how</a>`, {{"1", x.block}, {"2", how_url(&x)}}) 71 if x.check != nil do rc.render_to(&wings, ` <button class="link" data-check="{{1}}">check now</button>`, {{"1", x.n}}) 72 rc.render_to(&wings, ` <span class="kind">{{1}}</span></footer></article>` + "\n", {{"1", KIND_WORDS(x.kind)}}) 73 if x.script.text != "" {strings.write_string(&scripts, x.script.text); strings.write_byte(&scripts, '\n')} 74 } 75 strings.write_string(&wings, " </div>\n </section>\n") 76 } 77 tries_html := fmt.tprintf(`<p class="try">Things to try: %s.</p>`, strings.to_string(tries)) if me != nil && strings.builder_len(tries) > 0 else "" 78 legend := `<p class="legend"><b>A red light is a promise broken right now.</b> The zoo shows it rather than hiding it, and the card says what is wrong; the green ones still work.</p>` if count["red"] > 0 else "" 79 80 rc.set_header(w, "Content-Type", "text/html; charset=utf-8") 81 rc.set_header(w, "Cache-Control", "no-store") 82 rc.render(w, PAGE_HTML, { 83 {"env_title", "" if e.env == "live" else fmt.tprintf(" (%s)", e.env)}, 84 {"head", rc.raw(rc_head())}, 85 {"css_v", version_of(ZOO_CSS)}, 86 {"js_v", version_of(ZOO_JS)}, 87 {"me_id", itoa(me.id) if me != nil else ""}, 88 {"header", rc.raw(rc_header("Zoo", me, "/api/3/signout", false))}, 89 {"home", home_url()}, 90 {"checked", rc.raw(ago(meta_int("checked_at")))}, 91 {"green", count["green"]}, {"red", count["red"]}, {"amber", count["amber"]}, {"grey", count["grey"]}, 92 {"legend", rc.raw(legend)}, 93 {"tries", rc.raw(tries_html)}, 94 {"dots", rc.raw(strings.to_string(dots))}, 95 {"alerts", rc.raw(alerts_card(me))}, 96 {"wings", rc.raw(strings.to_string(wings))}, 97 {"commit", short(jstr(deploy, "commit") or_else "unknown", 10)}, 98 {"env", e.env}, 99 {"by", jstr(deploy, "by") or_else "?"}, 100 {"arrived", rc.raw(ago(parse_time(jstr(deploy, "at"))))}, 101 {"other_host", other_env_host()}, 102 {"other_name", "the staging zoo" if e.env == "live" else "the live zoo"}, 103 {"apps", rc.app_url("apps")}, 104 {"scripts", rc.raw(strings.to_string(scripts))}, 105 }) 106} 107 108// ---- how (exhibit 19) ---- 109// 110// The switch: where a card's "how" link opens. false: /how/<n>, the zoo's own page. true: apps's file 111// view of the commit this zoo runs (https://apps.<domain>/zoo/files/<commit>/<path>), from root's 112// mirror of the zoo's repo. apps shows an app's source to everyone only under `source = public` in 113// its ratcloud.conf, a key root does not know yet. Flip a line once it does. 114how_on_apps :: proc() -> bool { 115 switch env().env { 116 case "live": return false 117 case "staging": return false 118 } 119 return false 120} 121how_commit :: proc() -> string {return jstr(fact("deploy.json"), env().env, "commit")} 122how_apps_url :: proc(kind, file: string) -> string { 123 apps := rc.app_url("apps") 124 if i := strings.index(apps, "-staging."); i >= 0 do apps = cat(apps[:i], apps[i + 8:]) 125 parts := strings.split(file, "/") 126 for &p in parts do p = rc.percent_encode(p) 127 return fmt.tprintf("%s/%s/%s/%s/%s", apps, env().app, kind, how_commit(), strings.join(parts, "/")) 128} 129// A card's "how" link: apps's view of the exhibit's own file when the switch is on, else /how/<n>. 130how_url :: proc(e: ^Exhibit) -> string { 131 if how_on_apps() && how_commit() != "" do return how_apps_url("files", e.src.path) 132 return fmt.tprintf("/how/%d", e.n) 133} 134 135how_page :: proc(r: ^rc.Request, w: ^rc.Response, n: int, me: ^rc.User) { 136 e, ok := exhibit(n) 137 if !ok {rc.status(w, 404); rc.write(w, "no such exhibit\n"); return} 138 files := how_files(e) 139 rc.set_header(w, "Cache-Control", "no-store") 140 if raw, has := rc.query(r)["raw"]; has { 141 // Only the files this exhibit names: never anything else. 142 for f in files { 143 if f.path != raw do continue 144 rc.set_header(w, "Content-Type", "text/plain; charset=utf-8") 145 rc.write(w, f.text) 146 return 147 } 148 rc.status(w, 404) 149 rc.write(w, "not one of this exhibit's files\n") 150 return 151 } 152 b := strings.builder_make() 153 for f in files { 154 sum: [32]u8 155 hash.hash_string_to_buffer(.SHA256, f.text, sum[:]) 156 rc.render_to(&b, `<section class="src"><h2><code>{{1}}</code> <small class="muted">sha256 {{2}} · <a href="/how/{{3}}?raw={{4}}">raw</a>`, {{"1", f.path}, {"2", hex(sum[:6])}, {"3", n}, {"4", rc.percent_encode(f.path)}}) 157 if how_on_apps() do rc.render_to(&b, ` · <a href="{{1}}">on apps</a>`, {{"1", how_apps_url("files", f.path)}}) 158 strings.write_string(&b, "</small></h2>\n<pre>") 159 lines := strings.split(strings.trim_right(f.text, "\n"), "\n") 160 for line, i in lines do rc.render_to(&b, "<span class=\"ln\">{{1}}</span>{{2}}\n", {{"1", i + 1}, {"2", line}}) 161 strings.write_string(&b, "</pre></section>\n") 162 } 163 rc.set_header(w, "Content-Type", "text/html; charset=utf-8") 164 rc.render(w, HOW_HTML, { 165 {"title", e.title}, {"n", n}, {"promise", e.promise}, {"block", e.block}, 166 {"head", rc.raw(rc_head())}, {"css_v", version_of(ZOO_CSS)}, 167 {"header", rc.raw(rc_header("Zoo", me, "/api/3/signout", false))}, 168 {"commit", short(how_commit() if how_commit() != "" else "unknown", 10)}, {"env", env().env}, 169 {"files", rc.raw(strings.to_string(b))}, 170 }) 171} 172 173how_txt :: proc(w: ^rc.Response, n: int) { 174 rc.set_header(w, "Content-Type", "text/plain; charset=utf-8") 175 rc.set_header(w, "Cache-Control", "no-store") 176 e, ok := exhibit(n) 177 if !ok {rc.status(w, 404); rc.write(w, "no such exhibit\n"); return} 178 rc.write(w, fmt.tprintf("Exhibit %d: %s\nPromise: %s\nBlock: %s\n", e.n, e.title, e.promise, e.block)) 179 for f in how_files(e) { 180 rc.write(w, fmt.tprintf("\n=== %s ===\n", f.path)) 181 rc.write(w, f.text) 182 } 183}
zoo.odin sha256 b41cb7634455 · raw
1package main 2 3// The zoo's shared parts: its database, its exhibits and their lights, and a few helpers. 4// 5// Every address comes from the platform (rc.env(), rc.app_url, the facts root publishes); nothing 6// is typed out. The zoo is one fresh wasm instance per request and per job run, so a global here 7// lives for exactly one of those. 8 9import "core:crypto" 10import "core:encoding/json" 11import "core:fmt" 12import "core:strings" 13import "core:time" 14import "ratcloud:rc" 15 16WINGS :: []string{"Identity", "Deploy", "Isolation", "Realtime", "Storage", "Sealed", "Intelligence", "Notifications", "Building", "Operations"} 17HUMAN_FRESH_DAYS :: 30 // a human-only exhibit goes amber after this 18CHECK_STALE_MIN :: 15 // the self-check runs every 5 minutes 19// Root's back-of-house check (rc check) runs hourly and lands in RC_FACTS/platform.json. Older than 20// 2 hours means a run was missed: root's own minute tick says so past 2 hours (tools lib/facts.php), 21// and exhibit 22 and the owner alerts use this same number. Root does not publish it, so it is 22// matched here; if root ever does, read that instead. 23ROOT_CHECK_MAX_HOURS :: 2 24 25// ---- one instance's context ---------------------------------------------------------------------- 26 27Env :: struct { 28 app, env, host, accounts, domain: string, 29} 30g_env: Env 31g_env_ok: bool 32 33env :: proc() -> Env { 34 if !g_env_ok { 35 e := rc.env() 36 g_env = {e.app, e.env, e.host, e.accounts, domain_of(e.host)} 37 g_env_ok = true 38 } 39 return g_env 40} 41 42// "zoo-staging.ratcloud.club" -> "ratcloud.club" 43domain_of :: proc(host: string) -> string { 44 if i := strings.index_byte(host, '.'); i >= 0 do return host[i + 1:] 45 return host 46} 47 48// The other environment's address: zoo <-> zoo-staging, derived from our own. 49other_env_host :: proc() -> string { 50 h := env().host 51 dot := strings.index_byte(h, '.') 52 label := h[:dot] 53 label = label[:len(label) - 8] if strings.has_suffix(label, "-staging") else strings.concatenate({label, "-staging"}) 54 return strings.concatenate({label, h[dot:]}) 55} 56 57self_url :: proc(path := "/") -> string {return strings.concatenate({"https://", env().host, path})} 58home_url :: proc() -> string {return strings.concatenate({"https://", env().domain, "/"})} 59 60// ---- the database: zoo.db in the zoo's data, the only place it writes ---------------------------- 61 62g_db: rc.DB 63g_db_ok: bool 64 65db :: proc() -> rc.DB { 66 if g_db_ok do return g_db 67 d, ok := rc.db("zoo") 68 if !ok do panic("zoo.db did not open") 69 g_db, g_db_ok = d, true 70 for sql in ([]string { 71 "CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)", 72 "CREATE TABLE IF NOT EXISTS guestbook (user_id INTEGER PRIMARY KEY, note TEXT NOT NULL, at INTEGER NOT NULL)", 73 "CREATE TABLE IF NOT EXISTS lights (n INTEGER PRIMARY KEY, ok INTEGER NOT NULL, detail TEXT NOT NULL, data TEXT, at INTEGER NOT NULL, last_ok INTEGER)", 74 "CREATE TABLE IF NOT EXISTS seen (id INTEGER PRIMARY KEY AUTOINCREMENT, n INTEGER NOT NULL, user_id INTEGER NOT NULL, at INTEGER NOT NULL)", 75 "CREATE TABLE IF NOT EXISTS alerts (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, kind TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, results TEXT NOT NULL)", 76 }) { 77 must(sql) 78 } 79 // Which database this is. Live and staging each make their own, so comparing them proves the two 80 // environments share no data (exhibit 7). 81 if _, has := meta("instance"); !has do meta_set("instance", random_hex(8)) 82 return d 83} 84 85must :: proc(sql: string, args: ..any) -> i64 { 86 n, err := rc.exec(db(), sql, ..args) 87 if err != "" do panic(fmt.tprintf("zoo.db: %s: %s", err, sql)) 88 return n 89} 90 91meta :: proc(k: string) -> (string, bool) { 92 rows := rc.query_rows(db(), "SELECT v FROM meta WHERE k = ?", k) 93 v, ok := "", false 94 for rc.next(&rows) {v = strings.clone(rc.col_text(&rows, 0)); ok = !rc.col_is_null(&rows, 0)} 95 return v, ok 96} 97meta_int :: proc(k: string) -> i64 { 98 v, _ := meta(k) 99 return atoi(v) 100} 101meta_set :: proc(k, v: string) { 102 must("INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v", k, v) 103} 104 105// ---- facts: what root tells the zoo, read-only --------------------------------------------------- 106 107fact :: proc(name: string) -> json.Value { 108 text, ok := rc.fact(name) 109 if !ok do return nil 110 v, err := json.parse_string(text, parse_integers = true) 111 if err != nil do return nil 112 return v 113} 114 115// A preview's data in words, from its preview.json `data`: root's {op, from, at, by, note}. 116preview_data_words :: proc(d: json.Value) -> string { 117 if s, ok := d.(json.String); ok do return string(s) 118 if _, ok := d.(json.Object); !ok do return "nothing said" 119 at := parse_time(jstr(d, "at")) 120 when_ := fmt.tprintf(" %s UTC", day_hm(at)) if at > 0 else "" 121 by := jstr(d, "by") 122 s: string 123 by_ := cat(" by ", by) if by != "" else "" 124 switch jstr(d, "op") { 125 case "load": s = fmt.tprintf("a copy of %s's data, loaded%s%s", jstr(d, "from") or_else "?", when_, by_) 126 case "empty": s = fmt.tprintf("emptied%s%s", when_, by_) 127 case "push", "put": s = fmt.tprintf("what %s put in,%s", by if by != "" else "someone", when_) 128 case: s = jstr(d, "note") or_else "as the preview's own code left it" 129 } 130 return strings.concatenate({s, ", kept across branches"}) 131} 132 133// ---- JSON helpers: read values by path, with defaults --------------------------------------------- 134 135jget :: proc(v: json.Value, keys: ..string) -> json.Value { 136 cur := v 137 for k in keys { 138 o, ok := cur.(json.Object) 139 if !ok do return nil 140 cur = o[k] or_else nil 141 } 142 return cur 143} 144jstr :: proc(v: json.Value, keys: ..string) -> (string, bool) #optional_ok { 145 #partial switch x in jget(v, ..keys) { 146 case json.String: return string(x), true 147 case json.Integer: return fmt.tprintf("%d", x), true 148 case json.Float: return fmt.tprintf("%v", x), true 149 } 150 return "", false 151} 152jint :: proc(v: json.Value, keys: ..string) -> (i64, bool) #optional_ok { 153 #partial switch x in jget(v, ..keys) { 154 case json.Integer: return x, true 155 case json.Float: return i64(x), true 156 case json.String: return atoi(string(x)), true 157 case json.Boolean: return 1 if x else 0, true 158 } 159 return 0, false 160} 161jbool :: proc(v: json.Value, keys: ..string) -> bool { 162 #partial switch x in jget(v, ..keys) { 163 case json.Boolean: return x 164 case json.Integer: return x != 0 165 case json.String: return x != "" && x != "0" 166 case json.Array: return len(x) > 0 167 case json.Object: return len(x) > 0 168 } 169 return false 170} 171jarr :: proc(v: json.Value, keys: ..string) -> json.Array { 172 a, _ := jget(v, ..keys).(json.Array) 173 return a 174} 175jhas :: proc(v: json.Value, keys: ..string) -> bool { 176 x := jget(v, ..keys) 177 _, null := x.(json.Null) 178 return x != nil && !null 179} 180parse :: proc(s: string) -> json.Value { 181 v, err := json.parse_string(s, parse_integers = true) 182 if err != nil do return nil 183 return v 184} 185// Any value as JSON text (a struct, a json.Value, a map); "null" for nil. 186to_json :: proc(v: any) -> string { 187 if v == nil do return "null" 188 b, err := json.marshal(v) 189 if err != nil do return "null" 190 return string(b) 191} 192// A JSON string literal. 193jq :: proc(s: string) -> string { 194 b, _ := json.marshal(s) 195 return string(b) 196} 197 198// ---- exhibits ------------------------------------------------------------------------------------ 199// 200// One file per exhibit (eNN_*.odin), each with a proc returning its Exhibit: 201// n, wing, title, promise the exhibit as ZOO.md states it 202// block what the building block is and how an app uses it, in a sentence 203// kind "self" (the self-check proves it), "human" (a person presses and 204// looks) or "waiting" (its building block does not exist yet) 205// show(me) -> HTML the live part of the card 206// api(a) -> bool JSON at /api/<n>/<do> (CSRF-checked before it runs); false: no such call 207// check() -> Check self-running exhibits: what the self-check runs 208// src, files its own source and the other files "how" shows (#load: what runs) 209// script the card's JS 210 211Src :: struct { 212 path, text: string, 213} 214 215Exhibit :: struct { 216 n: int, 217 wing: string, 218 title: string, 219 promise: string, 220 block: string, 221 kind: string, 222 try_: string, 223 waiting_on: string, 224 src: Src, 225 files: []Src, 226 script: Src, 227 show: proc(me: ^rc.User) -> string, 228 api: proc(a: ^Api) -> bool, 229 check: proc() -> Check, 230 channel: proc(name, id: string, me: ^rc.User) -> (allow: bool, mine: bool), 231} 232 233Check :: struct { 234 ok: bool, 235 detail: string, 236 data: string, // JSON text 237} 238 239pass :: proc(detail: string, data: any = nil) -> Check {return {true, detail, to_json(data)}} 240fail :: proc(detail: string, data: any = nil) -> Check {return {false, detail, to_json(data)}} 241 242g_all: []Exhibit 243 244exhibits :: proc() -> []Exhibit { 245 if g_all != nil do return g_all 246 list := []proc() -> Exhibit { 247 e01, e02, e03, e04, e05, e06, e07, e08, e30, e09, e10, e11, e12, e13, e26, e27, e14, e15, e16, 248 e17, e18, e19, e20, e21, e25, e29, e22, e23, e24, 249 } 250 out := make([dynamic]Exhibit) 251 for f in list { 252 e := f() 253 if e.kind == "" do e.kind = "self" 254 append(&out, e) 255 } 256 // by number 257 for i in 1 ..< len(out) { 258 for j := i; j > 0 && out[j - 1].n > out[j].n; j -= 1 do out[j - 1], out[j] = out[j], out[j - 1] 259 } 260 g_all = out[:] 261 return g_all 262} 263 264exhibit :: proc(n: int) -> (^Exhibit, bool) { 265 for &e in exhibits() do if e.n == n do return &e, true 266 return nil, false 267} 268 269// A slice of sources that outlives the call (a compound literal would live in the caller's frame). 270srcs :: proc(xs: ..Src) -> []Src { 271 out := make([]Src, len(xs)) 272 copy(out, xs) 273 return out 274} 275 276// The files "how" shows for an exhibit: its own, then the others it names (a file once). 277how_files :: proc(e: ^Exhibit) -> []Src { 278 out := make([dynamic]Src) 279 add :: proc(out: ^[dynamic]Src, s: Src) { 280 if s.path == "" do return 281 for x in out do if x.path == s.path do return 282 append(out, s) 283 } 284 add(&out, e.src) 285 for f in e.files do add(&out, f) 286 add(&out, e.script) 287 return out[:] 288} 289 290// ---- lights -------------------------------------------------------------------------------------- 291 292Stored :: struct { 293 ok: bool, 294 detail: string, 295 data: string, 296 at: i64, 297 last_ok: i64, 298} 299 300stored :: proc(n: int) -> (s: Stored, found: bool) { 301 rows := rc.query_rows(db(), "SELECT ok, detail, data, at, last_ok FROM lights WHERE n = ?", n) 302 for rc.next(&rows) { 303 s = {rc.col_int(&rows, 0) != 0, strings.clone(rc.col_text(&rows, 1)), strings.clone(rc.col_text(&rows, 2)), rc.col_int(&rows, 3), rc.col_int(&rows, 4)} 304 found = true 305 } 306 return 307} 308 309// The stored light's data, parsed into T (zero if none). 310stored_data :: proc(n: int, $T: typeid) -> (v: T, s: Stored, found: bool) { 311 s, found = stored(n) 312 if found && s.data != "" && s.data != "null" do json.unmarshal_string(s.data, &v) 313 return 314} 315 316Light :: struct { 317 color: string, 318 text: string, 319 at: i64, // 0: no time 320 prefix: string, // a red light's "last worked" 321} 322 323light :: proc(e: ^Exhibit) -> Light { 324 if e.kind == "waiting" do return {color = "grey", text = strings.concatenate({"not built yet: waiting on ", e.waiting_on})} 325 if e.kind == "human" { 326 rows := rc.query_rows(db(), "SELECT user_id, at FROM seen WHERE n = ? ORDER BY at DESC LIMIT 1", e.n) 327 uid, at: i64 328 found := false 329 for rc.next(&rows) {uid, at, found = rc.col_int(&rows, 0), rc.col_int(&rows, 1), true} 330 if !found do return {color = "amber", text = "nobody has seen this work yet"} 331 who := "a deleted account" 332 if u, ok := rc.users({uid})[uid]; ok do who = u.username 333 fresh := now() - at < HUMAN_FRESH_DAYS * 86400 334 return {color = "green" if fresh else "amber", text = strings.concatenate({"last seen working by ", who}), at = at} 335 } 336 s, found := stored(e.n) 337 if !found do return {color = "grey", text = "not checked yet"} 338 if now() - s.at > CHECK_STALE_MIN * 60 do return {color = "red", text = "not checked since", at = s.at} 339 // A check may pass with a warning (data.amber): its detail says what is getting old. 340 if s.ok && jbool(parse(s.data), "amber") do return {color = "amber", text = s.detail, at = s.at} 341 if s.ok do return {color = "green", text = "last worked", at = s.at} 342 return {color = "red", text = s.detail, at = s.last_ok, prefix = "last worked"} 343} 344 345// Run one exhibit's check and store the result as its light. The light is data: the page reads it, 346// it never makes live requests to draw itself. 347Ran :: struct { 348 n: int, 349 ok: bool, 350 detail: string, 351 ms: i64, 352} 353 354run_check :: proc(e: ^Exhibit) -> Ran { 355 t0 := time.tick_now() 356 // One run of an exhibit's check at a time. The five-minute job and a "check now" can meet, and 357 // two runs of a check that writes (26's keyring, 13's postcards) trip over each other. If a run is 358 // under way, wait for it: its result is the answer. 359 lk := lock_open(fmt.tprintf("check-%d.lock", e.n)) 360 if !lock_try(lk) { 361 lock_wait(lk, 300_000) 362 lock_close(lk) 363 s, _ := stored(e.n) 364 return {e.n, s.ok, s.detail, i64(time.duration_milliseconds(time.tick_since(t0)))} 365 } 366 defer lock_close(lk) 367 r := e.check() 368 t := now() 369 last_ok: any = nil 370 if r.ok do last_ok = t 371 must(`INSERT INTO lights (n, ok, detail, data, at, last_ok) VALUES (?, ?, ?, ?, ?, ?) 372 ON CONFLICT(n) DO UPDATE SET ok = excluded.ok, detail = excluded.detail, data = excluded.data, 373 at = excluded.at, last_ok = COALESCE(excluded.last_ok, lights.last_ok)`, 374 e.n, 1 if r.ok else 0, r.detail, r.data if r.data != "" else "null", t, last_ok) 375 return {e.n, r.ok, r.detail, i64(time.duration_milliseconds(time.tick_since(t0)))} 376} 377 378// True for exactly one caller per `every` seconds per exhibit (an upsert that only wins when the last 379// claim is old enough). 380claim_check :: proc(n: int, every: i64) -> bool { 381 t := now() 382 return must(`INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v 383 WHERE CAST(meta.v AS INTEGER) <= ?`, fmt.tprintf("check-claim.%d", n), fmt.tprintf("%d", t), t - every) == 1 384} 385 386// A human-only exhibit's "this worked for me". 387seen :: proc(n: int, uid: i64) { 388 must("INSERT INTO seen (n, user_id, at) VALUES (?, ?, ?)", n, uid, now()) 389} 390 391// ---- locks: a byte-range lock on a file in the zoo's data, held by this instance ----------------- 392 393Lock :: struct { 394 h: i32, 395} 396 397lock_open :: proc(name: string) -> Lock { 398 p, l := rc.sptr(name) 399 return {rc.file_open(p, l, rc.FILE_READ | rc.FILE_WRITE | rc.FILE_CREATE)} 400} 401lock_try :: proc(l: Lock) -> bool {return l.h > 0 && rc.file_lock(l.h, 2, 0, 1) == 0} 402// Wait for the lock (the host never blocks: -EAGAIN, so we retry), at most `ms`. 403lock_wait :: proc(l: Lock, ms: int) -> bool { 404 for waited := 0; waited < ms; waited += 50 { 405 if lock_try(l) do return true 406 rc.sleep(50) 407 } 408 return false 409} 410lock_close :: proc(l: Lock) {if l.h > 0 do rc.file_close(l.h)} 411 412// ---- time ---------------------------------------------------------------------------------------- 413 414now :: proc() -> i64 {return time.time_to_unix(time.now())} 415now_ms :: proc() -> i64 {return time.time_to_unix_nano(time.now()) / 1e6} 416 417// "2026-11-27T21:15:37+00:00", as PHP's gmdate("c") wrote it. 418iso :: proc(t: i64) -> string { 419 tt := time.unix(t, 0) 420 y, mo, d := time.date(tt) 421 hh, mm, ss := time.clock(tt) 422 return fmt.tprintf("%04d-%02d-%02dT%02d:%02d:%02d+00:00", y, int(mo), d, hh, mm, ss) 423} 424// An ISO 8601 / RFC 3339 time as unix seconds; 0 if it is none. 425parse_time :: proc(s: string) -> i64 { 426 if len(s) < 19 do return 0 427 t, n := time.rfc3339_to_time_utc(s) 428 if n == 0 { 429 // "2026-11-27 21:15:37" (no zone): UTC 430 t2, n2 := time.rfc3339_to_time_utc(strings.concatenate({s[:10], "T", s[11:19], "Z"})) 431 if n2 == 0 do return 0 432 t = t2 433 } 434 return time.time_to_unix(t) 435} 436hm :: proc(t: i64) -> string {h, m, _ := time.clock(time.unix(t, 0)); return fmt.tprintf("%02d:%02d", h, m)} 437hms :: proc(t: i64) -> string {h, m, s := time.clock(time.unix(t, 0)); return fmt.tprintf("%02d:%02d:%02d", h, m, s)} 438MONTHS := [12]string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} 439// "27 Nov 21:15" 440day_hm :: proc(t: i64) -> string { 441 _, mo, d := time.date(time.unix(t, 0)) 442 return fmt.tprintf("%d %s %s", d, MONTHS[int(mo) - 1], hm(t)) 443} 444// "2026-11-27 21:15" 445ymd_hm :: proc(t: i64) -> string { 446 y, mo, d := time.date(time.unix(t, 0)) 447 return fmt.tprintf("%04d-%02d-%02d %s", y, int(mo), d, hm(t)) 448} 449ymd :: proc(t: i64) -> string { 450 y, mo, d := time.date(time.unix(t, 0)) 451 return fmt.tprintf("%04d%02d%02d", y, int(mo), d) 452} 453 454// "3 minutes ago", as a <time>. 455ago :: proc(t: i64) -> string { 456 if t <= 0 do return "never" 457 d := max(0, now() - t) 458 s: string 459 switch { 460 case d < 60: s = "just now" 461 case d < 3600: s = fmt.tprintf("%d minute%s ago", d / 60, "" if d / 60 == 1 else "s") 462 case d < 172800: s = fmt.tprintf("%d hour%s ago", d / 3600, "" if d / 3600 == 1 else "s") 463 case: s = fmt.tprintf("%d days ago", d / 86400) 464 } 465 return fmt.tprintf(`<time datetime="%s">%s</time>`, iso(t), s) 466} 467 468// ---- small helpers ------------------------------------------------------------------------------- 469 470h :: rc.esc 471cat :: proc(parts: ..string) -> string {return strings.concatenate(parts)} 472 473atoi :: proc(s: string) -> i64 { 474 n: i64 = 0 475 neg := false 476 for ch, i in transmute([]u8)s { 477 if i == 0 && ch == '-' {neg = true; continue} 478 if ch < '0' || ch > '9' do break 479 n = n * 10 + i64(ch - '0') 480 } 481 return -n if neg else n 482} 483itoa :: proc(n: i64) -> string {return fmt.tprintf("%d", n)} 484 485random_bytes :: proc(n: int) -> []u8 { 486 b := make([]u8, n) 487 crypto.rand_bytes(b) 488 return b 489} 490random_hex :: proc(n: int) -> string {return hex(random_bytes(n))} 491random_int :: proc(lo, hi: int) -> int { 492 b := random_bytes(4) 493 x := int(b[0]) | int(b[1]) << 8 | int(b[2]) << 16 | int(b[3] & 0x7f) << 24 494 return lo + x % (hi - lo + 1) 495} 496hex :: proc(b: []u8) -> string { 497 DIG := "0123456789abcdef" 498 out := make([]u8, len(b) * 2) 499 for x, i in b {out[2 * i] = DIG[x >> 4]; out[2 * i + 1] = DIG[x & 15]} 500 return string(out) 501} 502short :: proc(s: string, n: int) -> string {return s[:min(n, len(s))]} 503// At most n characters (runes), with "…" when cut. 504clip :: proc(s: string, n: int) -> string { 505 count := 0 506 for _, i in s { 507 if count == n - 1 && i + 1 < len(s) do return strings.concatenate({s[:i], "…"}) 508 count += 1 509 } 510 return s 511} 512// The first line. 513first_line :: proc(s: string) -> string { 514 t := strings.trim_space(s) 515 if i := strings.index_byte(t, '\n'); i >= 0 do return t[:i] 516 return t 517} 518 519// One user's card: picture, name, username. Pictures are account's URLs, cached forever by the 520// browser, and always the current one (exhibit 4). 521person :: proc(u: ^rc.User, class := "") -> string { 522 b := strings.builder_make() 523 if u == nil { 524 rc.render_to(&b, `<div class="person {{1}}"><span class="pic none">?</span><span><b>visitor</b><small>not signed in</small></span></div>`, {{"1", class}}) 525 } else if u.picture == "" { 526 rc.render_to(&b, `<div class="person {{1}}"><span class="pic none">?</span><span><b>{{2}}</b><small>no longer here</small></span></div>`, {{"1", class}, {"2", u.name}}) 527 } else { 528 rc.render_to(&b, `<div class="person {{1}}"><img class="pic" src="{{2}}" alt=""><span><b>{{3}}</b><small>@{{4}} · #{{5}}</small></span></div>`, {{"1", class}, {"2", u.picture}, {"3", u.name}, {"4", u.username}, {"5", u.id}}) 529 } 530 return strings.to_string(b) 531} 532 533// A card's "this worked for me" button, for human-only exhibits. 534seen_button :: proc(n: int, me: ^rc.User, what := "This worked for me") -> string { 535 if me == nil do return `<p class="muted">Sign in to record that this worked for you.</p>` 536 return fmt.tprintf(`<button class="seen" data-seen="%d">%s</button>`, n, h(what)) 537} 538 539signin_line :: proc(what: string) -> string { 540 return fmt.tprintf(`<p class="muted"><a href="%s">Sign in</a> %s</p>`, h(rc.signin_url()), what) 541} 542 543// Publish on one of our declared channels: the host prefixes the channel with the app and the 544// environment, so the zoo can only ever reach its own streams. 545publish :: proc(channel, id: string, msg: string) -> bool { 546 return rc.publish(channel, id, msg) == "" 547} 548 549// Call another app the way any app does: HTTPS, with account's assertion (rc.app_headers). as_user: 550// for this request's signed-in person. The status (0: no answer) and the body. 551App_Answer :: struct { 552 status: int, 553 body: string, 554 err: string, 555} 556 557call_app :: proc(app, path: string, as_user: bool, method := "GET", body := "", content_type := "", timeout_ms := 0) -> App_Answer { 558 hs, err := rc.app_headers(app, as_user) 559 if err != "" do return {0, "", strings.concatenate({"no assertion for ", app, ": ", err})} 560 if content_type != "" do hs["Content-Type"] = content_type 561 res := rc.fetch({method = method, url = strings.concatenate({rc.app_url(app), path}), headers = hs, body = transmute([]u8)body, timeout_ms = timeout_ms}) 562 return {res.status, string(res.body), res.err} 563} 564 565json_into :: proc(text: string, v: ^$T) -> bool {return json.unmarshal_string(text, v) == nil}