package main // The zoo's shared parts: its database, its exhibits and their lights, and a few helpers. // // Every address comes from the platform (rc.env(), rc.app_url, the facts root publishes); nothing // is typed out. The zoo is one fresh wasm instance per request and per job run, so a global here // lives for exactly one of those. import "core:crypto" import "core:encoding/json" import "core:fmt" import "core:strings" import "core:time" import "ratcloud:rc" WINGS :: []string{"Identity", "Deploy", "Isolation", "Realtime", "Storage", "Sealed", "Intelligence", "Notifications", "Building", "Operations"} HUMAN_FRESH_DAYS :: 30 // a human-only exhibit goes amber after this CHECK_STALE_MIN :: 15 // the self-check runs every 5 minutes // Root's back-of-house check (rc check) runs hourly and lands in RC_FACTS/platform.json. Older than // 2 hours means a run was missed: root's own minute tick says so past 2 hours (tools lib/facts.php), // and exhibit 22 and the owner alerts use this same number. Root does not publish it, so it is // matched here; if root ever does, read that instead. ROOT_CHECK_MAX_HOURS :: 2 // ---- one instance's context ---------------------------------------------------------------------- Env :: struct { app, env, host, accounts, domain: string, } g_env: Env g_env_ok: bool env :: proc() -> Env { if !g_env_ok { e := rc.env() g_env = {e.app, e.env, e.host, e.accounts, domain_of(e.host)} g_env_ok = true } return g_env } // "zoo-staging.ratcloud.club" -> "ratcloud.club" domain_of :: proc(host: string) -> string { if i := strings.index_byte(host, '.'); i >= 0 do return host[i + 1:] return host } // The other environment's address: zoo <-> zoo-staging, derived from our own. other_env_host :: proc() -> string { h := env().host dot := strings.index_byte(h, '.') label := h[:dot] label = label[:len(label) - 8] if strings.has_suffix(label, "-staging") else strings.concatenate({label, "-staging"}) return strings.concatenate({label, h[dot:]}) } self_url :: proc(path := "/") -> string {return strings.concatenate({"https://", env().host, path})} home_url :: proc() -> string {return strings.concatenate({"https://", env().domain, "/"})} // ---- the database: zoo.db in the zoo's data, the only place it writes ---------------------------- g_db: rc.DB g_db_ok: bool db :: proc() -> rc.DB { if g_db_ok do return g_db d, ok := rc.db("zoo") if !ok do panic("zoo.db did not open") g_db, g_db_ok = d, true for sql in ([]string { "CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)", "CREATE TABLE IF NOT EXISTS guestbook (user_id INTEGER PRIMARY KEY, note TEXT NOT NULL, at INTEGER NOT NULL)", "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)", "CREATE TABLE IF NOT EXISTS seen (id INTEGER PRIMARY KEY AUTOINCREMENT, n INTEGER NOT NULL, user_id INTEGER NOT NULL, at INTEGER NOT NULL)", "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)", }) { must(sql) } // Which database this is. Live and staging each make their own, so comparing them proves the two // environments share no data (exhibit 7). if _, has := meta("instance"); !has do meta_set("instance", random_hex(8)) return d } must :: proc(sql: string, args: ..any) -> i64 { n, err := rc.exec(db(), sql, ..args) if err != "" do panic(fmt.tprintf("zoo.db: %s: %s", err, sql)) return n } meta :: proc(k: string) -> (string, bool) { rows := rc.query_rows(db(), "SELECT v FROM meta WHERE k = ?", k) v, ok := "", false for rc.next(&rows) {v = strings.clone(rc.col_text(&rows, 0)); ok = !rc.col_is_null(&rows, 0)} return v, ok } meta_int :: proc(k: string) -> i64 { v, _ := meta(k) return atoi(v) } meta_set :: proc(k, v: string) { must("INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v", k, v) } // ---- facts: what root tells the zoo, read-only --------------------------------------------------- fact :: proc(name: string) -> json.Value { text, ok := rc.fact(name) if !ok do return nil v, err := json.parse_string(text, parse_integers = true) if err != nil do return nil return v } // A preview's data in words, from its preview.json `data`: root's {op, from, at, by, note}. preview_data_words :: proc(d: json.Value) -> string { if s, ok := d.(json.String); ok do return string(s) if _, ok := d.(json.Object); !ok do return "nothing said" at := parse_time(jstr(d, "at")) when_ := fmt.tprintf(" %s UTC", day_hm(at)) if at > 0 else "" by := jstr(d, "by") s: string by_ := cat(" by ", by) if by != "" else "" switch jstr(d, "op") { case "load": s = fmt.tprintf("a copy of %s's data, loaded%s%s", jstr(d, "from") or_else "?", when_, by_) case "empty": s = fmt.tprintf("emptied%s%s", when_, by_) case "push", "put": s = fmt.tprintf("what %s put in,%s", by if by != "" else "someone", when_) case: s = jstr(d, "note") or_else "as the preview's own code left it" } return strings.concatenate({s, ", kept across branches"}) } // ---- JSON helpers: read values by path, with defaults --------------------------------------------- jget :: proc(v: json.Value, keys: ..string) -> json.Value { cur := v for k in keys { o, ok := cur.(json.Object) if !ok do return nil cur = o[k] or_else nil } return cur } jstr :: proc(v: json.Value, keys: ..string) -> (string, bool) #optional_ok { #partial switch x in jget(v, ..keys) { case json.String: return string(x), true case json.Integer: return fmt.tprintf("%d", x), true case json.Float: return fmt.tprintf("%v", x), true } return "", false } jint :: proc(v: json.Value, keys: ..string) -> (i64, bool) #optional_ok { #partial switch x in jget(v, ..keys) { case json.Integer: return x, true case json.Float: return i64(x), true case json.String: return atoi(string(x)), true case json.Boolean: return 1 if x else 0, true } return 0, false } jbool :: proc(v: json.Value, keys: ..string) -> bool { #partial switch x in jget(v, ..keys) { case json.Boolean: return x case json.Integer: return x != 0 case json.String: return x != "" && x != "0" case json.Array: return len(x) > 0 case json.Object: return len(x) > 0 } return false } jarr :: proc(v: json.Value, keys: ..string) -> json.Array { a, _ := jget(v, ..keys).(json.Array) return a } jhas :: proc(v: json.Value, keys: ..string) -> bool { x := jget(v, ..keys) _, null := x.(json.Null) return x != nil && !null } parse :: proc(s: string) -> json.Value { v, err := json.parse_string(s, parse_integers = true) if err != nil do return nil return v } // Any value as JSON text (a struct, a json.Value, a map); "null" for nil. to_json :: proc(v: any) -> string { if v == nil do return "null" b, err := json.marshal(v) if err != nil do return "null" return string(b) } // A JSON string literal. jq :: proc(s: string) -> string { b, _ := json.marshal(s) return string(b) } // ---- exhibits ------------------------------------------------------------------------------------ // // One file per exhibit (eNN_*.odin), each with a proc returning its Exhibit: // n, wing, title, promise the exhibit as ZOO.md states it // block what the building block is and how an app uses it, in a sentence // kind "self" (the self-check proves it), "human" (a person presses and // looks) or "waiting" (its building block does not exist yet) // show(me) -> HTML the live part of the card // api(a) -> bool JSON at /api// (CSRF-checked before it runs); false: no such call // check() -> Check self-running exhibits: what the self-check runs // src, files its own source and the other files "how" shows (#load: what runs) // script the card's JS Src :: struct { path, text: string, } Exhibit :: struct { n: int, wing: string, title: string, promise: string, block: string, kind: string, try_: string, waiting_on: string, src: Src, files: []Src, script: Src, show: proc(me: ^rc.User) -> string, api: proc(a: ^Api) -> bool, check: proc() -> Check, channel: proc(name, id: string, me: ^rc.User) -> (allow: bool, mine: bool), } Check :: struct { ok: bool, detail: string, data: string, // JSON text } pass :: proc(detail: string, data: any = nil) -> Check {return {true, detail, to_json(data)}} fail :: proc(detail: string, data: any = nil) -> Check {return {false, detail, to_json(data)}} g_all: []Exhibit exhibits :: proc() -> []Exhibit { if g_all != nil do return g_all list := []proc() -> Exhibit { e01, e02, e03, e04, e05, e06, e07, e08, e30, e09, e10, e11, e12, e13, e26, e27, e14, e15, e16, e17, e18, e19, e20, e21, e25, e29, e22, e23, e24, } out := make([dynamic]Exhibit) for f in list { e := f() if e.kind == "" do e.kind = "self" append(&out, e) } // by number for i in 1 ..< len(out) { 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] } g_all = out[:] return g_all } exhibit :: proc(n: int) -> (^Exhibit, bool) { for &e in exhibits() do if e.n == n do return &e, true return nil, false } // A slice of sources that outlives the call (a compound literal would live in the caller's frame). srcs :: proc(xs: ..Src) -> []Src { out := make([]Src, len(xs)) copy(out, xs) return out } // The files "how" shows for an exhibit: its own, then the others it names (a file once). how_files :: proc(e: ^Exhibit) -> []Src { out := make([dynamic]Src) add :: proc(out: ^[dynamic]Src, s: Src) { if s.path == "" do return for x in out do if x.path == s.path do return append(out, s) } add(&out, e.src) for f in e.files do add(&out, f) add(&out, e.script) return out[:] } // ---- lights -------------------------------------------------------------------------------------- Stored :: struct { ok: bool, detail: string, data: string, at: i64, last_ok: i64, } stored :: proc(n: int) -> (s: Stored, found: bool) { rows := rc.query_rows(db(), "SELECT ok, detail, data, at, last_ok FROM lights WHERE n = ?", n) for rc.next(&rows) { 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)} found = true } return } // The stored light's data, parsed into T (zero if none). stored_data :: proc(n: int, $T: typeid) -> (v: T, s: Stored, found: bool) { s, found = stored(n) if found && s.data != "" && s.data != "null" do json.unmarshal_string(s.data, &v) return } Light :: struct { color: string, text: string, at: i64, // 0: no time prefix: string, // a red light's "last worked" } light :: proc(e: ^Exhibit) -> Light { if e.kind == "waiting" do return {color = "grey", text = strings.concatenate({"not built yet: waiting on ", e.waiting_on})} if e.kind == "human" { rows := rc.query_rows(db(), "SELECT user_id, at FROM seen WHERE n = ? ORDER BY at DESC LIMIT 1", e.n) uid, at: i64 found := false for rc.next(&rows) {uid, at, found = rc.col_int(&rows, 0), rc.col_int(&rows, 1), true} if !found do return {color = "amber", text = "nobody has seen this work yet"} who := "a deleted account" if u, ok := rc.users({uid})[uid]; ok do who = u.username fresh := now() - at < HUMAN_FRESH_DAYS * 86400 return {color = "green" if fresh else "amber", text = strings.concatenate({"last seen working by ", who}), at = at} } s, found := stored(e.n) if !found do return {color = "grey", text = "not checked yet"} if now() - s.at > CHECK_STALE_MIN * 60 do return {color = "red", text = "not checked since", at = s.at} // A check may pass with a warning (data.amber): its detail says what is getting old. if s.ok && jbool(parse(s.data), "amber") do return {color = "amber", text = s.detail, at = s.at} if s.ok do return {color = "green", text = "last worked", at = s.at} return {color = "red", text = s.detail, at = s.last_ok, prefix = "last worked"} } // Run one exhibit's check and store the result as its light. The light is data: the page reads it, // it never makes live requests to draw itself. Ran :: struct { n: int, ok: bool, detail: string, ms: i64, } run_check :: proc(e: ^Exhibit) -> Ran { t0 := time.tick_now() // One run of an exhibit's check at a time. The five-minute job and a "check now" can meet, and // two runs of a check that writes (26's keyring, 13's postcards) trip over each other. If a run is // under way, wait for it: its result is the answer. lk := lock_open(fmt.tprintf("check-%d.lock", e.n)) if !lock_try(lk) { lock_wait(lk, 300_000) lock_close(lk) s, _ := stored(e.n) return {e.n, s.ok, s.detail, i64(time.duration_milliseconds(time.tick_since(t0)))} } defer lock_close(lk) r := e.check() t := now() last_ok: any = nil if r.ok do last_ok = t must(`INSERT INTO lights (n, ok, detail, data, at, last_ok) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(n) DO UPDATE SET ok = excluded.ok, detail = excluded.detail, data = excluded.data, at = excluded.at, last_ok = COALESCE(excluded.last_ok, lights.last_ok)`, e.n, 1 if r.ok else 0, r.detail, r.data if r.data != "" else "null", t, last_ok) return {e.n, r.ok, r.detail, i64(time.duration_milliseconds(time.tick_since(t0)))} } // True for exactly one caller per `every` seconds per exhibit (an upsert that only wins when the last // claim is old enough). claim_check :: proc(n: int, every: i64) -> bool { t := now() return must(`INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v WHERE CAST(meta.v AS INTEGER) <= ?`, fmt.tprintf("check-claim.%d", n), fmt.tprintf("%d", t), t - every) == 1 } // A human-only exhibit's "this worked for me". seen :: proc(n: int, uid: i64) { must("INSERT INTO seen (n, user_id, at) VALUES (?, ?, ?)", n, uid, now()) } // ---- locks: a byte-range lock on a file in the zoo's data, held by this instance ----------------- Lock :: struct { h: i32, } lock_open :: proc(name: string) -> Lock { p, l := rc.sptr(name) return {rc.file_open(p, l, rc.FILE_READ | rc.FILE_WRITE | rc.FILE_CREATE)} } lock_try :: proc(l: Lock) -> bool {return l.h > 0 && rc.file_lock(l.h, 2, 0, 1) == 0} // Wait for the lock (the host never blocks: -EAGAIN, so we retry), at most `ms`. lock_wait :: proc(l: Lock, ms: int) -> bool { for waited := 0; waited < ms; waited += 50 { if lock_try(l) do return true rc.sleep(50) } return false } lock_close :: proc(l: Lock) {if l.h > 0 do rc.file_close(l.h)} // ---- time ---------------------------------------------------------------------------------------- now :: proc() -> i64 {return time.time_to_unix(time.now())} now_ms :: proc() -> i64 {return time.time_to_unix_nano(time.now()) / 1e6} // "2026-11-27T21:15:37+00:00", as PHP's gmdate("c") wrote it. iso :: proc(t: i64) -> string { tt := time.unix(t, 0) y, mo, d := time.date(tt) hh, mm, ss := time.clock(tt) return fmt.tprintf("%04d-%02d-%02dT%02d:%02d:%02d+00:00", y, int(mo), d, hh, mm, ss) } // An ISO 8601 / RFC 3339 time as unix seconds; 0 if it is none. parse_time :: proc(s: string) -> i64 { if len(s) < 19 do return 0 t, n := time.rfc3339_to_time_utc(s) if n == 0 { // "2026-11-27 21:15:37" (no zone): UTC t2, n2 := time.rfc3339_to_time_utc(strings.concatenate({s[:10], "T", s[11:19], "Z"})) if n2 == 0 do return 0 t = t2 } return time.time_to_unix(t) } hm :: proc(t: i64) -> string {h, m, _ := time.clock(time.unix(t, 0)); return fmt.tprintf("%02d:%02d", h, m)} hms :: proc(t: i64) -> string {h, m, s := time.clock(time.unix(t, 0)); return fmt.tprintf("%02d:%02d:%02d", h, m, s)} MONTHS := [12]string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} // "27 Nov 21:15" day_hm :: proc(t: i64) -> string { _, mo, d := time.date(time.unix(t, 0)) return fmt.tprintf("%d %s %s", d, MONTHS[int(mo) - 1], hm(t)) } // "2026-11-27 21:15" ymd_hm :: proc(t: i64) -> string { y, mo, d := time.date(time.unix(t, 0)) return fmt.tprintf("%04d-%02d-%02d %s", y, int(mo), d, hm(t)) } ymd :: proc(t: i64) -> string { y, mo, d := time.date(time.unix(t, 0)) return fmt.tprintf("%04d%02d%02d", y, int(mo), d) } // "3 minutes ago", as a