Zoo

staging

← back to the zoo

21. Jobs on a clock

An app can run a script every few minutes.

Add `cron = tick every 5m` to ratcloud.conf and a job proc to rc.serve: the host runs it in a fresh instance on that clock, never two at once, with its output in the fact log.txt.

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.

e21_jobs.odin sha256 4dd6a2de1e11 · raw

1package main
2
3// Exhibit 21. `cron = tick every 5m` in ratcloud.conf: the host runs the zoo's `tick` job (main.odin's
4// job proc) every five minutes, in a fresh instance of its own, never two at once. It writes the time
5// here.
6
7import "core:fmt"
8import "ratcloud:rc"
9
10e21 :: proc() -> Exhibit {
11	return {
12		n = 21, wing = "Building",
13		title = "Jobs on a clock",
14		promise = "An app can run a script every few minutes.",
15		block = "Add `cron = tick every 5m` to ratcloud.conf and a job proc to rc.serve: the host runs it in a fresh instance on that clock, never two at once, with its output in the fact log.txt.",
16		src = {"e21_jobs.odin", #load("e21_jobs.odin", string)},
17		files = srcs(SELF_SRC, {"ratcloud.conf", #load("ratcloud.conf", string)}),
18		show = proc(me: ^rc.User) -> string {
19			return fmt.tprintf("<p>Last tick: <b>%s</b>, written by the zoo's own five-minute job.</p>", ago(meta_int("last_tick")))
20		},
21		check = proc() -> Check {
22			t := meta_int("last_tick")
23			if t == 0 do return fail("the job has never ticked")
24			m := (now() - t) / 60
25			if m > 10 do return fail(fmt.tprintf("the last tick was %d minutes ago", m))
26			return pass(fmt.tprintf("the last tick was %s ago", fmt.tprintf("%d minute(s)", m) if m > 0 else "under a minute"))
27		},
28	}
29}

main.odin sha256 0eb573c11997 · raw

1package main
2
3// The zoo: every promise in ZOO.md as an exhibit, working live, with a light. Odin on the wasm
4// runtime: one fresh instance per request and per job run.
5//
6//   /                    every exhibit and its light
7//   /api/<n>/<do>        an exhibit's JSON (check: run its check now; seen: "this worked for me")
8//   /how/<n>             the exhibit's source, the bytes this very program was built from (exhibit 19)
9//   /lights.json         every light, for tests and anyone curious
10//   /index.txt           one line per exhibit (promise and building block), for a model's brief
11//   /how/<n>.txt         exhibit n's files as plain text
12//   /platform.md         what an app gets: root's PLATFORM.md, the running version, for anyone
13//
14// nginx also asks whether a browser may listen on an `auth` channel (channel_ok); and the host runs
15// the jobs of ratcloud.conf's `cron` (job): tick, selfcheck, nightly, workbench.
16
17import "core:encoding/json"
18import "core:fmt"
19import "core:strings"
20import "core:time"
21import "ratcloud:rc"
22
23main :: proc() {
24	rc.serve(handle, channel_ok, job)
25}
26
27SELF_SRC :: Src{"main.odin", #load("main.odin", string)}
28
29channel_ok :: proc(r: ^rc.Request, channel, id: string) -> bool {
30	u, signed := rc.me()
31	me := &u if signed else nil
32	for &e in exhibits() {
33		if e.channel == nil do continue
34		if allow, mine := e.channel(channel, id, me); mine do return allow
35	}
36	return false
37}
38
39g_req: ^rc.Request
40
41handle :: proc(r: ^rc.Request, w: ^rc.Response) {
42	g_req = r
43	defer robot_done()
44	u, signed := rc.me()
45	me := &u if signed else nil
46	path := r.path
47
48	if strings.has_prefix(path, "/api/") {
49		api(r, w, me)
50		return
51	}
52	if strings.has_prefix(path, "/how/") {
53		rest := path[5:]
54		if strings.has_suffix(rest, ".txt") {how_txt(w, int(atoi(rest[:len(rest) - 4]))); return}
55		how_page(r, w, int(atoi(rest)), me)
56		return
57	}
58	switch path {
59	case "/": page(w, me); return
60	case "/lights.json": lights_json(w); return
61	case "/index.txt":
62		// A model's brief lists the exhibits, one line each.
63		rc.set_header(w, "Content-Type", "text/plain; charset=utf-8")
64		rc.set_header(w, "Cache-Control", "max-age=300")
65		for e in exhibits() do rc.write(w, fmt.tprintf("%d. %s (%s%s): %s\n", e.n, e.title, e.wing, ", not built yet" if e.kind == "waiting" else "", e.block))
66		return
67	case "/platform.md":
68		// Root publishes PLATFORM.md into every app's facts; the zoo, being the documentation, serves
69		// its copy so a model working in a clone (no facts there) reads the version that is running.
70		doc, ok := rc.fact("PLATFORM.md")
71		rc.status(w, 200 if ok else 404)
72		rc.set_header(w, "Content-Type", "text/markdown; charset=utf-8")
73		rc.set_header(w, "Cache-Control", "max-age=300")
74		rc.write(w, doc if ok else "PLATFORM.md is not published here yet.\n")
75		return
76	}
77	rc.status(w, 404)
78	rc.set_header(w, "Cache-Control", "no-store")
79	rc.render(w, NOT_FOUND_HTML, {{"head", rc.raw(rc_head())}, {"header", rc.raw(rc_header("Zoo", me, "/api/3/signout", false))}})
80}
81
82NOT_FOUND_HTML :: `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Not found · Zoo</title>{{head}}</head><body>{{header}}<main class="rc-main"><div class="rc-empty"><b>Nothing here</b><p>The zoo has no page at this address.</p><a class="button primary" href="/">Go to the zoo</a></div></main></body></html>`
83
84// ---- /api/<n>/<do> ----
85
86Api :: struct {
87	r:    ^rc.Request,
88	w:    ^rc.Response,
89	do_:  string,
90	me:   ^rc.User,
91	post: bool,
92	in_:  json.Value, // the POST's JSON body, or the query as an object of strings
93}
94
95reply :: proc(a: ^Api, v: any, status := 200) {
96	rc.status(a.w, status)
97	rc.set_header(a.w, "Cache-Control", "no-store")
98	rc.set_header(a.w, "Content-Type", "application/json")
99	rc.write(a.w, to_json(v))
100	rc.write(a.w, "\n")
101}
102reply_raw :: proc(a: ^Api, json_text: string, status := 200) {
103	rc.status(a.w, status)
104	rc.set_header(a.w, "Cache-Control", "no-store")
105	rc.set_header(a.w, "Content-Type", "application/json")
106	rc.write(a.w, json_text)
107	rc.write(a.w, "\n")
108}
109reply_err :: proc(a: ^Api, status: int, msg: string) {
110	reply_raw(a, fmt.tprintf(`{{"error":%s}}`, jq(msg)), status)
111}
112in_str :: proc(a: ^Api, k: string) -> string {return jstr(a.in_, k)}
113in_int :: proc(a: ^Api, k: string) -> i64 {return jint(a.in_, k)}
114
115api :: proc(r: ^rc.Request, w: ^rc.Response, me: ^rc.User) {
116	a := Api{r = r, w = w, me = me, post = r.method == "POST"}
117	rest := r.path[5:]
118	slash := strings.index_byte(rest, '/')
119	if slash < 0 {reply_err(&a, 404, "no such exhibit"); return}
120	n := int(atoi(rest[:slash]))
121	a.do_ = rest[slash + 1:]
122	e, ok := exhibit(n)
123	if !ok || itoa(i64(n)) != rest[:slash] {reply_err(&a, 404, "no such exhibit"); return}
124	if !rc.csrf_ok(r) {reply_err(&a, 403, "refused: not from the zoo's own page"); return}
125	if a.post {
126		body, _ := rc.body(r)
127		if v, err := json.parse(body, parse_integers = true); err == nil do a.in_ = v
128	} else {
129		o := make(json.Object)
130		for k, v in rc.query(r) do o[k] = json.String(v)
131		a.in_ = o
132	}
133	if a.do_ == "check" && e.check != nil {
134		// POST runs it now, unless it ran (or started) in the last 15 seconds: anyone can press this,
135		// and a run costs a robot sign-in, a model call, B2 and push. The slot is taken atomically, so
136		// a burst runs it once. GET (an <img> anywhere) only reads the light.
137		if a.post && claim_check(e.n, 15) do run_check(e)
138		s, found := stored(e.n)
139		if !found {
140			reply_raw(&a, fmt.tprintf(`{{"n":%d,"title":%s,"ok":false,"detail":"not checked yet","at":null,"data":null}}`, e.n, jq(e.title)))
141			return
142		}
143		reply_raw(&a, fmt.tprintf(`{{"n":%d,"title":%s,"ok":%v,"detail":%s,"at":%s,"data":%s}}`, e.n, jq(e.title), s.ok, jq(s.detail), jq(iso(s.at)), s.data if s.data != "" else "null"))
144		return
145	}
146	if a.do_ == "seen" && a.post && e.kind == "human" {
147		if me == nil {reply_err(&a, 401, "sign in first, so the zoo can say who saw it work"); return}
148		seen(e.n, me.id)
149		l := light(e)
150		reply_raw(&a, fmt.tprintf(`{{"ok":true,"light":{{"color":%s,"text":%s}}}}`, jq(l.color), jq(l.text)))
151		return
152	}
153	if e.api != nil && e.api(&a) do return
154	reply_err(&a, 404, fmt.tprintf("exhibit %d has no '%s'", e.n, a.do_))
155}
156
157// ---- /lights.json ----
158
159lights_json :: proc(w: ^rc.Response) {
160	b := strings.builder_make()
161	checked := meta_int("checked_at")
162	fmt.sbprintf(&b, `{{"env":%s,"checked":%s,"lights":[`, jq(env().env), jq(iso(checked)) if checked > 0 else "null")
163	for &e, i in exhibits() {
164		l := light(&e)
165		if i > 0 do strings.write_byte(&b, ',')
166		fmt.sbprintf(&b, `{{"n":%d,"title":%s,"kind":%s,"color":%s,"text":%s,"at":%s}}`, e.n, jq(e.title), jq(e.kind), jq(l.color), jq(l.text), jq(iso(l.at)) if l.at > 0 else "null")
167	}
168	strings.write_string(&b, `],"alerts":[`)
169	for x, i in alerts_recent(10) {
170		if i > 0 do strings.write_byte(&b, ',')
171		fmt.sbprintf(&b, `{{"at":%s,"kind":%s,"title":%s,"body":%s,"results":%s}}`, jq(iso(x.at)), jq(x.kind), jq(x.title), jq(x.body), x.results)
172	}
173	strings.write_string(&b, "]}\n")
174	rc.set_header(w, "Content-Type", "application/json")
175	rc.set_header(w, "Cache-Control", "no-store")
176	rc.write(w, strings.to_string(b))
177}
178
179// ---- the jobs (ratcloud.conf `cron`): the host runs each in a fresh instance on its schedule ----
180
181job :: proc(name: string, w: ^rc.Response) {
182	defer robot_done()
183	switch name {
184	case "tick":
185		// Exhibit 21: write the time. That is all.
186		meta_set("last_tick", itoa(now()))
187	case "selfcheck":
188		selfcheck(w)
189	case "nightly":
190		// Exhibit 8's upkeep: if a valid push replaced zoo-broken's deliberate typo, put it back.
191		res := broken_reassert()
192		res.at = now()
193		meta_set("broken.nightly", to_json(res))
194		rc.write(w, fmt.tprintf("exhibit 8 upkeep (%s): %s: %s\n", res.branch, res.result, res.detail))
195		if res.result != "still refused" && res.result != "put back" do rc.status(w, 500)
196	case "workbench":
197		// Exhibit 25's run in the robot's workbench: at most once a day, live only.
198		if said, did := e25_job(); did {
199			rc.write(w, said)
200			rc.write(w, "\n")
201			if strings.contains(said, "FAILED") do rc.status(w, 500)
202		}
203	case:
204		rc.status(w, 404)
205		rc.write(w, fmt.tprintf("no job %q\n", name))
206	}
207}
208
209// Exhibit 22's job: every five minutes, run every self-running exhibit's check and store the results
210// as lights. Exhibit 22 runs last, since it judges the others.
211selfcheck :: proc(w: ^rc.Response) {
212	t0 := time.tick_now()
213	g_in_job = true
214	last: ^Exhibit
215	for &e in exhibits() {
216		if e.n == 22 {last = &e; continue}
217		if e.check == nil || e.kind != "self" do continue
218		r := run_check(&e)
219		if !r.ok do rc.write(w, fmt.tprintf("exhibit %d: %s\n", r.n, r.detail))
220	}
221	if last != nil {
222		r := run_check(last)
223		if !r.ok do rc.write(w, fmt.tprintf("exhibit %d: %s\n", r.n, r.detail))
224	}
225	alerts_run(w)
226	meta_set("checked_at", itoa(now()))
227	meta_set("checked_ms", itoa(i64(time.duration_milliseconds(time.tick_since(t0)))))
228	rc.write(w, fmt.tprintf("checked in %d ms, memory %d KiB\n", i64(time.duration_milliseconds(time.tick_since(t0))), rc.bump_top() / 1024))
229}
230
231// The five-minute job, not a "check now" from the page (PHP's PHP_SAPI === "cli"): the rounds that
232// take minutes (18, 29, 30) start only here, where the job's own time allows them.
233g_in_job: bool

ratcloud.conf sha256 da8f09e08292 · raw

1# The zoo's settings. rc builds the app and renders nginx and the jobs from this; a mistake refuses the push.
2name = Zoo
3description = See every building block working
4# Odin compiled to wasm (main.odin and the exhibits, e*.odin), built on the box at every push.
5runtime = wasm
6# 10: anyone may listen to the counter. 11: `auth` makes nginx ask the zoo first (channel_ok).
7channels = counter, mine auth
8# 21: the clock. 22: the self-check that turns every self-running exhibit into a light. 8: the nightly
9# job puts zoo-broken's deliberate typo back if a valid push cleared it. 25: once a day the robot asks
10# its workbench for a change (the job looks every half hour). Each is a name main.odin's job answers.
11cron = tick every 5m, selfcheck every 5m, nightly every 1d, workbench every 30m
12# The robot's tools (8, 18, 30): git and ssh as zoo-robot, granted by root (rc cap zoo git ssh --as zoo-robot).
13capabilities = git, ssh
14max_body = 1M
15# 23: after each nightly backup, root counts the guestbook in the backup copy.
16backup_check = zoo.db guestbook
17smoke = tests/smoke.odin