package main // Exhibit 10. A channel is declared in ratcloud.conf (`channels = counter, ...`). Browsers listen at // /rc/sub/counter/ with EventSource; the app publishes with rc.publish("counter", id, data). That // is the whole of realtime. import "core:encoding/json" import "core:fmt" import "core:time" import "ratcloud:rc" e10 :: proc() -> Exhibit { return { n = 10, try_ = "press the shared counter", wing = "Realtime", title = "Live for everyone", promise = "A change one person makes appears on everyone's open page within a second, without a reload.", block = "Declare a channel in ratcloud.conf; browsers listen with EventSource at /rc/sub//, the app sends with rc.publish(name, id, data).", src = {"e10_counter.odin", #load("e10_counter.odin", string)}, script = {"web/e10.js", #load("web/e10.js", string)}, show = proc(me: ^rc.User) -> string { return fmt.tprintf(`
%d

Open this page in two tabs and press in one.

`, meta_int("counter")) }, api = proc(a: ^Api) -> bool { if a.do_ != "press" || !a.post do return false must("BEGIN IMMEDIATE") n := meta_int("counter") + 1 meta_set("counter", itoa(n)) must("COMMIT") ok := publish("counter", "main", fmt.tprintf(`{{"n":%d,"at":%.3f}}`, n, f64(now_ms()) / 1000)) reply_raw(a, fmt.tprintf(`{{"n":%d,"published":%v}}`, n, ok)) return true }, // Two listeners, one press: both must see the new number within a second. check = proc() -> Check { sub := self_url("/rc/sub/counter/main") b := new_browser() l := listen_open(b, {sub, sub}, 2000) defer listen_close(&l) t0 := time.tick_now() r := post(b, self_url("/api/10/press")) n, has := jint(r.j, "n") if !has do return fail("pressing the counter failed") if l.status[0] != 200 || l.status[1] != 200 do return fail(fmt.tprintf("the listeners were answered %d, %d", l.status[0], l.status[1])) want :: proc(v: json.Value, arg: rawptr) -> bool {return jint(v, "n") == (^i64)(arg)^} seen, ms := listen_wait(&l, t0, want, &n) if seen < 2 do return fail(fmt.tprintf("pressed to %d; only %d of 2 listeners saw it within 2 seconds", n, seen)) if ms > 1000 do return fail(fmt.tprintf("both listeners saw %d, but after %dms", n, ms)) return pass(fmt.tprintf("pressed to %d; both listeners saw it %dms later (press included)", n, ms)) }, } }