From de93a90d7480cc4c9299571ec73c88960e12e267 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:50:19 -0600 Subject: [PATCH] examples: capability-dependent demo library + app with both negative tests (#5957) Greeter (pkgs/id/examples/roc-cap-demo/lib) is a Roc package whose library depends on the platform records.read capability via RocCap; main.roc is the demo app importing it. Negative tests: the same app+library against the reduced platform-no-caps.roc must fail over the missing pf.RocCap (A), and a wrong-signature schedule_at_request call must fail with a type mismatch (B). Both are wired into scripts/roc-test.sh so they run in the roc-test flake check. --- pkgs/id/examples/roc-cap-demo/README.md | 44 +++++ .../roc-cap-demo/lib-no-caps/Greeter.roc | 151 ++++++++++++++++++ .../roc-cap-demo/lib-no-caps/main.roc | 6 + pkgs/id/examples/roc-cap-demo/lib/Greeter.roc | 151 ++++++++++++++++++ pkgs/id/examples/roc-cap-demo/lib/main.roc | 8 + .../roc-cap-demo/main-missing-cap.roc | 116 ++++++++++++++ .../roc-cap-demo/main-wrong-usage.roc | 121 ++++++++++++++ pkgs/id/examples/roc-cap-demo/main.roc | 112 +++++++++++++ .../roc-cap-demo/roc-cap-demo-test.sh | 67 ++++++++ .../examples/roc-world/platform-no-caps.roc | 68 ++++++++ pkgs/id/scripts/roc-test.sh | 4 +- 11 files changed, 847 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/examples/roc-cap-demo/README.md create mode 100644 pkgs/id/examples/roc-cap-demo/lib-no-caps/Greeter.roc create mode 100644 pkgs/id/examples/roc-cap-demo/lib-no-caps/main.roc create mode 100644 pkgs/id/examples/roc-cap-demo/lib/Greeter.roc create mode 100644 pkgs/id/examples/roc-cap-demo/lib/main.roc create mode 100644 pkgs/id/examples/roc-cap-demo/main-missing-cap.roc create mode 100644 pkgs/id/examples/roc-cap-demo/main-wrong-usage.roc create mode 100644 pkgs/id/examples/roc-cap-demo/main.roc create mode 100755 pkgs/id/examples/roc-cap-demo/roc-cap-demo-test.sh create mode 100644 pkgs/id/examples/roc-world/platform-no-caps.roc diff --git a/pkgs/id/examples/roc-cap-demo/README.md b/pkgs/id/examples/roc-cap-demo/README.md new file mode 100644 index 0000000000..8085bd2b77 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/README.md @@ -0,0 +1,44 @@ +# roc-cap-demo — a capability-dependent demo library + app (#5957) + +A small worked example of the Roc library import model for worlds: +a **library that is not pure** (it depends on a platform capability) +and an **app** that imports it and runs on a platform providing that +capability. + +- `lib/` — the demo library, a Roc package. `lib/Greeter.roc` greets + world participants by name. The names live in the world records, so + the library issues a `records.read` capability request through the + platform's `RocCap` protocol helpers: it cannot do its job on a + platform that does not provide that capability. `lib/main.roc` is + the package root and binds the library to + `../roc-world/platform.roc`. +- `main.roc` — the demo app. On init it asks for the names through + the library; its view greets every participant once the result + arrives. All protocol handling (issuing, announcing in `wants`, + routing the result by id, retiring it, snapshot/restore of the + session) lives in the library. + +## Tests + +`roc-cap-demo-test.sh` (wired into `scripts/roc-test.sh`, i.e. the `roc-test` +just recipe and flake check) runs: + +1. The library's `expect` tests (`roc test lib/main.roc`) and a + typecheck of the demo app (`roc check main.roc`) — the positive + path. +2. **Negative test A** — `main-missing-cap.roc`, the same app and + library bound to the reduced platform + `../roc-world/platform-no-caps.roc`, which does not expose + `RocCap`. Compilation must fail, and the failure must name the + missing `pf.RocCap` module. (`lib-no-caps/` is the library package + bound to the reduced platform; its `Greeter.roc` is a + byte-identical copy of `lib/Greeter.roc` — Roc package modules + cannot be symlinked in from outside the package root — and + `roc-cap-demo-test.sh` fails if the copies drift.) +3. **Negative test B** — `main-wrong-usage.roc`, the app against the + full platform but calling `RocCap.schedule_at_request` with a + wrong signature. Compilation must fail with a type mismatch at + that call. + +Each negative test pins *why* it fails (asserted error content), not +just that it fails. diff --git a/pkgs/id/examples/roc-cap-demo/lib-no-caps/Greeter.roc b/pkgs/id/examples/roc-cap-demo/lib-no-caps/Greeter.roc new file mode 100644 index 0000000000..6b96c4fb2c --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/lib-no-caps/Greeter.roc @@ -0,0 +1,151 @@ +## Demo library: greet world participants by name. +## +## The names live in the world records, not in this library, so the +## library is NOT pure: it depends on the platform providing the +## records.read capability (through the RocCap protocol helpers) to +## fetch them. A platform without that capability cannot host this +## library at all — see the negative tests in ../roc-cap-demo-test.sh, which are +## wired into scripts/roc-test.sh (#5957). +import pf.RocCap +import pf.RocJson + +Greeter := { + session : RocCap, + names : List(Str), +}.{ + ## A greeter that has not asked for names yet. + new : Greeter + new = { session: RocCap.empty, names: [] } + + ## Ask the platform for the participant-name records (prefix + ## "names/"). Returns the updated greeter and the request id; the + ## app announces the greeter requests (see wants) and routes the + ## result back through absorb_result. + ask_for_names : Greeter -> { greeter : Greeter, id : Str } + ask_for_names = |greeter| { + issued = RocCap.issue(greeter.session, "records.read") + { + greeter: { session: RocCap.attach(issued.session, issued.id, RocCap.records_request(issued.id, "names/", "")), names: greeter.names }, + id: issued.id, + } + } + + ## Absorb one decoded {"cap":"result",...} event. A records.read + ## answer teaches the greeter the participant names; any other + ## outstanding request is simply retired. Results for ids this + ## greeter never issued are ignored, so journal replay and stale + ## answers cannot corrupt the model. + absorb_result : Greeter, RocJson -> Greeter + absorb_result = |greeter, event| { + id = string_field(event, "id") + answered = RocCap.answered(greeter.session, id) + if answered == "records.read" and bool_field(event, "ok") { + { session: RocCap.done(greeter.session, id), names: names_from_page(field(event, "value")) } + } else if answered != "" { + { session: RocCap.done(greeter.session, id), names: greeter.names } + } else { + greeter + } + } + + ## The wants document announcing the outstanding requests, in the + ## shape the world host expects (compare roc-chat). + wants : Greeter -> Str + wants = |greeter| encode_or_crash( + RocJson.Object([ + { key: "v", value: RocJson.Number("1") }, + { key: "requests", value: RocJson.Array(RocCap.requests(greeter.session)) }, + ]), + ) + + ## The greeting for every participant name learned so far. + greetings : Greeter -> List(Str) + greetings = |greeter| List.map(greeter.names, greet) + + ## The greeting for one participant name. + greet : Str -> Str + greet = |name| Str.concat("hello, ", name) + + ## The participant names from a records.read result page: each + ## record entry carries its name as the string value. + names_from_page : RocJson -> List(Str) + names_from_page = |page| + List.fold(RocCap.records_page(page), [], |names, entry| + match RocJson.as_string(field(entry, "value")) { + Ok(name) => List.append(names, name) + Err(_) => names + }) + + ## The names learned so far. + known_names : Greeter -> List(Str) + known_names = |greeter| greeter.names + + ## The session request counter, for snapshotting. + counter : Greeter -> U64 + counter = |greeter| RocCap.counter(greeter.session) + + ## The outstanding request documents, for snapshotting. + pending_documents : Greeter -> List(RocJson) + pending_documents = |greeter| RocCap.requests(greeter.session) + + ## Rebuild a greeter from its snapshot parts (compare + ## RocCap.from_pending). + from_parts : U64, List(RocJson), List(Str) -> Greeter + from_parts = |next, documents, names| { session: RocCap.from_pending(next, documents), names: names } + + field : RocJson, Str -> RocJson + field = |value, key| match RocJson.get(value, key) { + Ok(found) => found + Err(_) => RocJson.Null + } + + string_field : RocJson, Str -> Str + string_field = |value, key| match RocJson.as_string(field(value, key)) { + Ok(text) => text + Err(_) => "" + } + + bool_field : RocJson, Str -> Bool + bool_field = |value, key| match RocJson.as_bool(field(value, key)) { + Ok(flag) => flag + Err(_) => Bool.False + } + + encode_or_crash : RocJson -> Str + encode_or_crash = |value| match RocJson.encode(value) { + Ok(text) => text + Err(_) => crash "Greeter attempted to encode an invalid or oversized JSON value" + } +} + +sample_page : RocJson +sample_page = RocJson.Object([ + { + key: "records", + value: RocJson.Array([ + RocJson.Object([ + { key: "key", value: RocJson.String("names/1") }, + { key: "value", value: RocJson.String("ada") }, + ]), + RocJson.Object([ + { key: "key", value: RocJson.String("names/2") }, + { key: "value", value: RocJson.String("grace") }, + ]), + ]), + }, + { key: "next_after", value: RocJson.String("") }, +]) + +sample_result : RocJson +sample_result = RocJson.Object([ + { key: "cap", value: RocJson.String("result") }, + { key: "id", value: RocJson.String("r0") }, + { key: "ok", value: RocJson.Bool(Bool.True) }, + { key: "value", value: sample_page }, +]) + +expect Greeter.greet("ada") == "hello, ada" +expect Greeter.ask_for_names(Greeter.new).id == "r0" +expect Greeter.names_from_page(sample_page) == ["ada", "grace"] +expect Greeter.greetings(Greeter.absorb_result(Greeter.ask_for_names(Greeter.new).greeter, sample_result)) == ["hello, ada", "hello, grace"] +expect Str.contains(Greeter.wants(Greeter.ask_for_names(Greeter.new).greeter), "records.read") == Bool.True diff --git a/pkgs/id/examples/roc-cap-demo/lib-no-caps/main.roc b/pkgs/id/examples/roc-cap-demo/lib-no-caps/main.roc new file mode 100644 index 0000000000..461d53b580 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/lib-no-caps/main.roc @@ -0,0 +1,6 @@ +## The roc-cap-demo library bound to the reduced platform +## (roc-world/platform-no-caps.roc), which does NOT provide the +## RocCap capability module. Negative test A (#5957): Greeter.roc +## imports pf.RocCap, so anything using this package must fail to +## compile — the capability is not on the platform. +package [Greeter] { pf: platform "../../roc-world/platform-no-caps.roc" } diff --git a/pkgs/id/examples/roc-cap-demo/lib/Greeter.roc b/pkgs/id/examples/roc-cap-demo/lib/Greeter.roc new file mode 100644 index 0000000000..6b96c4fb2c --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/lib/Greeter.roc @@ -0,0 +1,151 @@ +## Demo library: greet world participants by name. +## +## The names live in the world records, not in this library, so the +## library is NOT pure: it depends on the platform providing the +## records.read capability (through the RocCap protocol helpers) to +## fetch them. A platform without that capability cannot host this +## library at all — see the negative tests in ../roc-cap-demo-test.sh, which are +## wired into scripts/roc-test.sh (#5957). +import pf.RocCap +import pf.RocJson + +Greeter := { + session : RocCap, + names : List(Str), +}.{ + ## A greeter that has not asked for names yet. + new : Greeter + new = { session: RocCap.empty, names: [] } + + ## Ask the platform for the participant-name records (prefix + ## "names/"). Returns the updated greeter and the request id; the + ## app announces the greeter requests (see wants) and routes the + ## result back through absorb_result. + ask_for_names : Greeter -> { greeter : Greeter, id : Str } + ask_for_names = |greeter| { + issued = RocCap.issue(greeter.session, "records.read") + { + greeter: { session: RocCap.attach(issued.session, issued.id, RocCap.records_request(issued.id, "names/", "")), names: greeter.names }, + id: issued.id, + } + } + + ## Absorb one decoded {"cap":"result",...} event. A records.read + ## answer teaches the greeter the participant names; any other + ## outstanding request is simply retired. Results for ids this + ## greeter never issued are ignored, so journal replay and stale + ## answers cannot corrupt the model. + absorb_result : Greeter, RocJson -> Greeter + absorb_result = |greeter, event| { + id = string_field(event, "id") + answered = RocCap.answered(greeter.session, id) + if answered == "records.read" and bool_field(event, "ok") { + { session: RocCap.done(greeter.session, id), names: names_from_page(field(event, "value")) } + } else if answered != "" { + { session: RocCap.done(greeter.session, id), names: greeter.names } + } else { + greeter + } + } + + ## The wants document announcing the outstanding requests, in the + ## shape the world host expects (compare roc-chat). + wants : Greeter -> Str + wants = |greeter| encode_or_crash( + RocJson.Object([ + { key: "v", value: RocJson.Number("1") }, + { key: "requests", value: RocJson.Array(RocCap.requests(greeter.session)) }, + ]), + ) + + ## The greeting for every participant name learned so far. + greetings : Greeter -> List(Str) + greetings = |greeter| List.map(greeter.names, greet) + + ## The greeting for one participant name. + greet : Str -> Str + greet = |name| Str.concat("hello, ", name) + + ## The participant names from a records.read result page: each + ## record entry carries its name as the string value. + names_from_page : RocJson -> List(Str) + names_from_page = |page| + List.fold(RocCap.records_page(page), [], |names, entry| + match RocJson.as_string(field(entry, "value")) { + Ok(name) => List.append(names, name) + Err(_) => names + }) + + ## The names learned so far. + known_names : Greeter -> List(Str) + known_names = |greeter| greeter.names + + ## The session request counter, for snapshotting. + counter : Greeter -> U64 + counter = |greeter| RocCap.counter(greeter.session) + + ## The outstanding request documents, for snapshotting. + pending_documents : Greeter -> List(RocJson) + pending_documents = |greeter| RocCap.requests(greeter.session) + + ## Rebuild a greeter from its snapshot parts (compare + ## RocCap.from_pending). + from_parts : U64, List(RocJson), List(Str) -> Greeter + from_parts = |next, documents, names| { session: RocCap.from_pending(next, documents), names: names } + + field : RocJson, Str -> RocJson + field = |value, key| match RocJson.get(value, key) { + Ok(found) => found + Err(_) => RocJson.Null + } + + string_field : RocJson, Str -> Str + string_field = |value, key| match RocJson.as_string(field(value, key)) { + Ok(text) => text + Err(_) => "" + } + + bool_field : RocJson, Str -> Bool + bool_field = |value, key| match RocJson.as_bool(field(value, key)) { + Ok(flag) => flag + Err(_) => Bool.False + } + + encode_or_crash : RocJson -> Str + encode_or_crash = |value| match RocJson.encode(value) { + Ok(text) => text + Err(_) => crash "Greeter attempted to encode an invalid or oversized JSON value" + } +} + +sample_page : RocJson +sample_page = RocJson.Object([ + { + key: "records", + value: RocJson.Array([ + RocJson.Object([ + { key: "key", value: RocJson.String("names/1") }, + { key: "value", value: RocJson.String("ada") }, + ]), + RocJson.Object([ + { key: "key", value: RocJson.String("names/2") }, + { key: "value", value: RocJson.String("grace") }, + ]), + ]), + }, + { key: "next_after", value: RocJson.String("") }, +]) + +sample_result : RocJson +sample_result = RocJson.Object([ + { key: "cap", value: RocJson.String("result") }, + { key: "id", value: RocJson.String("r0") }, + { key: "ok", value: RocJson.Bool(Bool.True) }, + { key: "value", value: sample_page }, +]) + +expect Greeter.greet("ada") == "hello, ada" +expect Greeter.ask_for_names(Greeter.new).id == "r0" +expect Greeter.names_from_page(sample_page) == ["ada", "grace"] +expect Greeter.greetings(Greeter.absorb_result(Greeter.ask_for_names(Greeter.new).greeter, sample_result)) == ["hello, ada", "hello, grace"] +expect Str.contains(Greeter.wants(Greeter.ask_for_names(Greeter.new).greeter), "records.read") == Bool.True diff --git a/pkgs/id/examples/roc-cap-demo/lib/main.roc b/pkgs/id/examples/roc-cap-demo/lib/main.roc new file mode 100644 index 0000000000..bdadcae825 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/lib/main.roc @@ -0,0 +1,8 @@ +## Package root for the roc-cap-demo demo library. +## +## The library (Greeter.roc) depends on the world platform: it uses +## the platform-provided RocCap/RocJson modules, so this package can +## only be used with a platform that provides them. ../main.roc is +## the demo app that imports it; ../lib-no-caps is the same library +## bound to a reduced platform, for the negative tests. +package [Greeter] { pf: platform "../../roc-world/platform.roc" } diff --git a/pkgs/id/examples/roc-cap-demo/main-missing-cap.roc b/pkgs/id/examples/roc-cap-demo/main-missing-cap.roc new file mode 100644 index 0000000000..0579fa95a6 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/main-missing-cap.roc @@ -0,0 +1,116 @@ +app [program] { pf: platform "../roc-world/platform-no-caps.roc", caplib: "./lib-no-caps/main.roc" } + +import pf.RocJson +import caplib.Greeter + +# NEGATIVE TEST A (#5957): the demo app compiled against the reduced +# platform (platform-no-caps.roc), which does not provide the RocCap +# capability module the Greeter library depends on. This file must +# FAIL to compile; roc-cap-demo-test.sh pins the failure to the missing RocCap. +# A demo app for the Greeter library (lib/): on init it asks the +# platform for the participant-name records through the library, and +# its view greets every participant by name once the records.read +# result arrives. All capability protocol handling — issuing the +# request, announcing it in wants, routing the result, retiring it — +# lives in the library; this app only decodes host events and renders. + +Model : { greeter : Greeter } + +program = { init, update, view, layout, records, wants, snapshot, restore } + +init : U64 -> Model +init = |_seed| { greeter: Greeter.ask_for_names(Greeter.new).greeter } + +update : Model, U64, Str -> Model +update = |model, pid, ev| + if pid == 0 { host(model, ev) } else { model } + +## Host events (participant 0): capability results are routed by the +## library, keyed on the request id it issued. +host : Model, Str -> Model +host = |model, ev| match RocJson.decode(ev) { + Err(_) => model + Ok(event) => if string_field(event, "cap") == "result" { + { greeter: Greeter.absorb_result(model.greeter, event) } + } else { + model + } +} + +view : Model -> Str +view = |model| { + greetings = Greeter.greetings(model.greeter) + if List.is_empty(greetings) { + "cap-demo: awaiting participant names" + } else { + Str.concat("cap-demo: ", Str.join_with(greetings, ", ")) + } +} + +## This program renders the same layout at any viewport. +layout : Model, U64, U64 -> Str +layout = |model, _width, _height| view(model) + +records : Model -> Str +records = |model| encode_or_crash( + RocJson.Object([{ key: "greeted", value: RocJson.Number(List.len(Greeter.known_names(model.greeter)).to_str()) }]), +) + +## The library announces its outstanding capability requests. +wants : Model -> Str +wants = |model| Greeter.wants(model.greeter) + +snapshot : Model -> Str +snapshot = |model| { + documents = Str.join_with(List.map(Greeter.pending_documents(model.greeter), encode_or_crash), "\n") + names = encode_or_crash(RocJson.Array(List.map(Greeter.known_names(model.greeter), |name| RocJson.String(name)))) + "${Greeter.counter(model.greeter).to_str()}\n${names}\n${documents}" +} + +restore : Str -> Model +restore = |text| { + parts = Str.split_on(text, "\n") + documents = List.fold(List.drop_first(parts, 2), [], |acc, line| match RocJson.decode(line) { + Ok(value) => List.append(acc, value) + Err(_) => acc + }) + { greeter: Greeter.from_parts(num(parts, 0), documents, names_from_line(part(parts, 1))) } +} + +# --- helpers --------------------------------------------------------------- + +encode_or_crash = |value| match RocJson.encode(value) { + Ok(text) => text + Err(_) => crash "roc-cap-demo attempted to encode an invalid or oversized JSON value" +} + +field = |value, key| match RocJson.get(value, key) { + Ok(found) => found + Err(_) => RocJson.Null +} + +string_field = |value, key| match RocJson.as_string(field(value, key)) { + Ok(text) => text + Err(_) => "" +} + +part = |fields, index| match List.get(fields, index) { + Ok(found) => found + Err(_) => "" +} + +num = |fields, index| match U64.from_str(part(fields, index)) { + Ok(value) => value + Err(_) => 0 +} + +names_from_line = |line| match RocJson.decode(line) { + Ok(value) => match RocJson.as_array(value) { + Ok(items) => List.fold(items, [], |names, item| match RocJson.as_string(item) { + Ok(name) => List.append(names, name) + Err(_) => names + }) + Err(_) => [] + } + Err(_) => [] +} diff --git a/pkgs/id/examples/roc-cap-demo/main-wrong-usage.roc b/pkgs/id/examples/roc-cap-demo/main-wrong-usage.roc new file mode 100644 index 0000000000..f6d58ac8c9 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/main-wrong-usage.roc @@ -0,0 +1,121 @@ +app [program] { pf: platform "../roc-world/platform.roc", caplib: "./lib/main.roc" } + +import pf.RocJson +import caplib.Greeter +import pf.RocCap + +# A demo app for the Greeter library (lib/): on init it asks the +# platform for the participant-name records through the library, and +# its view greets every participant by name once the records.read +# result arrives. All capability protocol handling — issuing the +# request, announcing it in wants, routing the result, retiring it — +# lives in the library; this app only decodes host events and renders. + +Model : { greeter : Greeter } + +program = { init, update, view, layout, records, wants, snapshot, restore } + +init : U64 -> Model +init = |_seed| { greeter: Greeter.ask_for_names(Greeter.new).greeter } + +update : Model, U64, Str -> Model +update = |model, pid, ev| + if pid == 0 { host(model, ev) } else { model } + +## Host events (participant 0): capability results are routed by the +## library, keyed on the request id it issued. +host : Model, Str -> Model +host = |model, ev| match RocJson.decode(ev) { + Err(_) => model + Ok(event) => if string_field(event, "cap") == "result" { + { greeter: Greeter.absorb_result(model.greeter, event) } + } else { + model + } +} + +view : Model -> Str +view = |model| { + greetings = Greeter.greetings(model.greeter) + if List.is_empty(greetings) { + "cap-demo: awaiting participant names" + } else { + Str.concat("cap-demo: ", Str.join_with(greetings, ", ")) + } +} + +## This program renders the same layout at any viewport. +layout : Model, U64, U64 -> Str +layout = |model, _width, _height| view(model) + +records : Model -> Str +records = |model| encode_or_crash( + RocJson.Object([{ key: "greeted", value: RocJson.Number(List.len(Greeter.known_names(model.greeter)).to_str()) }]), +) + +## The library announces its outstanding capability requests. +wants : Model -> Str +wants = |model| Greeter.wants(model.greeter) + +snapshot : Model -> Str +snapshot = |model| { + documents = Str.join_with(List.map(Greeter.pending_documents(model.greeter), encode_or_crash), "\n") + names = encode_or_crash(RocJson.Array(List.map(Greeter.known_names(model.greeter), |name| RocJson.String(name)))) + "${Greeter.counter(model.greeter).to_str()}\n${names}\n${documents}" +} + +restore : Str -> Model +restore = |text| { + parts = Str.split_on(text, "\n") + documents = List.fold(List.drop_first(parts, 2), [], |acc, line| match RocJson.decode(line) { + Ok(value) => List.append(acc, value) + Err(_) => acc + }) + { greeter: Greeter.from_parts(num(parts, 0), documents, names_from_line(part(parts, 1))) } +} + +# --- helpers --------------------------------------------------------------- + +encode_or_crash = |value| match RocJson.encode(value) { + Ok(text) => text + Err(_) => crash "roc-cap-demo attempted to encode an invalid or oversized JSON value" +} + +field = |value, key| match RocJson.get(value, key) { + Ok(found) => found + Err(_) => RocJson.Null +} + +string_field = |value, key| match RocJson.as_string(field(value, key)) { + Ok(text) => text + Err(_) => "" +} + +part = |fields, index| match List.get(fields, index) { + Ok(found) => found + Err(_) => "" +} + +num = |fields, index| match U64.from_str(part(fields, index)) { + Ok(value) => value + Err(_) => 0 +} + +names_from_line = |line| match RocJson.decode(line) { + Ok(value) => match RocJson.as_array(value) { + Ok(items) => List.fold(items, [], |names, item| match RocJson.as_string(item) { + Ok(name) => List.append(names, name) + Err(_) => names + }) + Err(_) => [] + } + Err(_) => [] +} + +## NEGATIVE TEST B (#5957): deliberate misuse of the platform +## capability API. RocCap.schedule_at_request takes +## (id : Str, schedule_id : Str, at_ms : U64); this call passes a +## number for the id and a string for the timestamp — a wrong +## signature. This file must FAIL to compile; roc-cap-demo-test.sh pins the +## failure to this call. +misused_schedule = RocCap.schedule_at_request(42, "wake", "soon") diff --git a/pkgs/id/examples/roc-cap-demo/main.roc b/pkgs/id/examples/roc-cap-demo/main.roc new file mode 100644 index 0000000000..59a7d4f684 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/main.roc @@ -0,0 +1,112 @@ +app [program] { pf: platform "../roc-world/platform.roc", caplib: "./lib/main.roc" } + +import pf.RocJson +import caplib.Greeter + +# A demo app for the Greeter library (lib/): on init it asks the +# platform for the participant-name records through the library, and +# its view greets every participant by name once the records.read +# result arrives. All capability protocol handling — issuing the +# request, announcing it in wants, routing the result, retiring it — +# lives in the library; this app only decodes host events and renders. + +Model : { greeter : Greeter } + +program = { init, update, view, layout, records, wants, snapshot, restore } + +init : U64 -> Model +init = |_seed| { greeter: Greeter.ask_for_names(Greeter.new).greeter } + +update : Model, U64, Str -> Model +update = |model, pid, ev| + if pid == 0 { host(model, ev) } else { model } + +## Host events (participant 0): capability results are routed by the +## library, keyed on the request id it issued. +host : Model, Str -> Model +host = |model, ev| match RocJson.decode(ev) { + Err(_) => model + Ok(event) => if string_field(event, "cap") == "result" { + { greeter: Greeter.absorb_result(model.greeter, event) } + } else { + model + } +} + +view : Model -> Str +view = |model| { + greetings = Greeter.greetings(model.greeter) + if List.is_empty(greetings) { + "cap-demo: awaiting participant names" + } else { + Str.concat("cap-demo: ", Str.join_with(greetings, ", ")) + } +} + +## This program renders the same layout at any viewport. +layout : Model, U64, U64 -> Str +layout = |model, _width, _height| view(model) + +records : Model -> Str +records = |model| encode_or_crash( + RocJson.Object([{ key: "greeted", value: RocJson.Number(List.len(Greeter.known_names(model.greeter)).to_str()) }]), +) + +## The library announces its outstanding capability requests. +wants : Model -> Str +wants = |model| Greeter.wants(model.greeter) + +snapshot : Model -> Str +snapshot = |model| { + documents = Str.join_with(List.map(Greeter.pending_documents(model.greeter), encode_or_crash), "\n") + names = encode_or_crash(RocJson.Array(List.map(Greeter.known_names(model.greeter), |name| RocJson.String(name)))) + "${Greeter.counter(model.greeter).to_str()}\n${names}\n${documents}" +} + +restore : Str -> Model +restore = |text| { + parts = Str.split_on(text, "\n") + documents = List.fold(List.drop_first(parts, 2), [], |acc, line| match RocJson.decode(line) { + Ok(value) => List.append(acc, value) + Err(_) => acc + }) + { greeter: Greeter.from_parts(num(parts, 0), documents, names_from_line(part(parts, 1))) } +} + +# --- helpers --------------------------------------------------------------- + +encode_or_crash = |value| match RocJson.encode(value) { + Ok(text) => text + Err(_) => crash "roc-cap-demo attempted to encode an invalid or oversized JSON value" +} + +field = |value, key| match RocJson.get(value, key) { + Ok(found) => found + Err(_) => RocJson.Null +} + +string_field = |value, key| match RocJson.as_string(field(value, key)) { + Ok(text) => text + Err(_) => "" +} + +part = |fields, index| match List.get(fields, index) { + Ok(found) => found + Err(_) => "" +} + +num = |fields, index| match U64.from_str(part(fields, index)) { + Ok(value) => value + Err(_) => 0 +} + +names_from_line = |line| match RocJson.decode(line) { + Ok(value) => match RocJson.as_array(value) { + Ok(items) => List.fold(items, [], |names, item| match RocJson.as_string(item) { + Ok(name) => List.append(names, name) + Err(_) => names + }) + Err(_) => [] + } + Err(_) => [] +} diff --git a/pkgs/id/examples/roc-cap-demo/roc-cap-demo-test.sh b/pkgs/id/examples/roc-cap-demo/roc-cap-demo-test.sh new file mode 100755 index 0000000000..162e2eb7f9 --- /dev/null +++ b/pkgs/id/examples/roc-cap-demo/roc-cap-demo-test.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Tests for the roc-cap-demo example (#5957): a demo library (Greeter, +# in lib/) that depends on a platform capability (records.read, via the +# platform's RocCap module), a demo app (main.roc) importing it, and +# BOTH negative tests the issue requires: +# +# A. main-missing-cap.roc — the same app + library compiled against +# the reduced platform (roc-world/platform-no-caps.roc), which +# does not provide RocCap. Must FAIL, and the failure must name +# the missing pf.RocCap module. +# B. main-wrong-usage.roc — the app against the full platform, but +# calling RocCap.schedule_at_request with a wrong signature. +# Must FAIL, and the failure must be a type mismatch at that call. +# +# The positive path (library expect tests + app typecheck) runs first. +# Invoked from scripts/roc-test.sh (the roc-test just recipe / flake +# check), so these tests are part of the normal test flow and cannot +# silently rot. A negative test that starts compiling, or that fails +# for a different reason, fails this script. +set -euo pipefail + +cd "$(dirname "$0")" + +if ! command -v roc >/dev/null 2>&1; then + echo "roc-cap-demo test: the pinned Roc compiler is not on PATH; refusing to skip silently." >&2 + exit 1 +fi + +fail() { echo "roc-cap-demo test FAILED: $*" >&2; exit 1; } + +echo "=== roc-cap-demo: library expect tests (roc test lib/main.roc) ===" +roc test lib/main.roc + +echo "=== roc-cap-demo: demo app typechecks (roc check main.roc) ===" +roc check main.roc + +# The negative-A package binds a byte-identical copy of the library to +# the reduced platform (Roc resolves package modules only inside the +# package root, so a symlink out of lib-no-caps/ is not allowed). Keep +# the copy honest: any drift between the two copies fails here. +diff lib/Greeter.roc lib-no-caps/Greeter.roc >/dev/null \ + || fail "lib-no-caps/Greeter.roc has drifted from lib/Greeter.roc; re-copy it" + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +echo "=== roc-cap-demo: negative test A (capability not on the platform) ===" +if roc check main-missing-cap.roc >"$TMP/neg-a.log" 2>&1; then + fail "main-missing-cap.roc compiled, but the reduced platform must not satisfy the library" +fi +grep -q "pf.RocCap" "$TMP/neg-a.log" \ + || { cat "$TMP/neg-a.log" >&2; fail "negative A failed, but not over the missing pf.RocCap module"; } +grep -q "does not exist" "$TMP/neg-a.log" \ + || { cat "$TMP/neg-a.log" >&2; fail "negative A failed, but the error does not say pf.RocCap is missing"; } +echo "negative A failed as required: pf.RocCap is not provided by the reduced platform" + +echo "=== roc-cap-demo: negative test B (platform used wrong) ===" +if roc check main-wrong-usage.roc >"$TMP/neg-b.log" 2>&1; then + fail "main-wrong-usage.roc compiled, but the wrong-signature capability call must not typecheck" +fi +grep -q "schedule_at_request" "$TMP/neg-b.log" \ + || { cat "$TMP/neg-b.log" >&2; fail "negative B failed, but not at the schedule_at_request call"; } +grep -qi "type mismatch" "$TMP/neg-b.log" \ + || { cat "$TMP/neg-b.log" >&2; fail "negative B failed, but not with a type mismatch"; } +echo "negative B failed as required: type mismatch at the schedule_at_request call" + +echo "✓ roc-cap-demo tests passed (positive path + both negative tests)" diff --git a/pkgs/id/examples/roc-world/platform-no-caps.roc b/pkgs/id/examples/roc-world/platform-no-caps.roc new file mode 100644 index 0000000000..a17e24adf9 --- /dev/null +++ b/pkgs/id/examples/roc-world/platform-no-caps.roc @@ -0,0 +1,68 @@ +## Reduced world platform WITHOUT the capability protocol module +## (RocCap): a test fixture for roc-cap-demo negative test A (#5957). +## It is platform.roc with RocCap removed from exposes/imports, so a +## program or library that depends on platform capabilities fails to +## compile against it. Do not build real worlds on this platform. + +platform "" + requires { + [Model : model] for program : { + init : U64 -> model, + update : model, U64, Str -> model, + view : model -> Str, + layout : model, U64, U64 -> Str, + records : model -> Str, + wants : model -> Str, + snapshot : model -> Str, + restore : Str -> model, + } + } + exposes [Screen, Key, RocJson, RocGrid, RocText] + packages {} + provides { + "roc_init": init_for_host, + "roc_update": update_for_host, + "roc_view": view_for_host, + "roc_layout": layout_for_host, + "roc_records": records_for_host, + "roc_wants": wants_for_host, + "roc_snapshot": snapshot_for_host, + "roc_restore": restore_for_host, + } + targets: { + inputs_dir: "targets/", + x64musl: { inputs: ["crt1.o", "libhost.a", app, "libc.a", "libzigc.a", "libcompiler_rt.a"] }, + wasm32: { inputs: ["host.wasm", app], output: Shared, exports: ["plaza_abi_version", "plaza_alloc", "plaza_free", "plaza_init", "plaza_update", "plaza_view", "plaza_layout", "plaza_records", "plaza_wants", "plaza_snapshot", "plaza_restore", "plaza_out_len", "plaza_error_ptr", "plaza_error_len"] }, + } + +import Screen +import Key +import RocJson +import RocGrid +import RocText + +init_for_host : U64 -> Box(Model) +init_for_host = |seed| Box.box((program.init)(seed)) + +update_for_host : Box(Model), U64, Str -> Box(Model) +update_for_host = |boxed, pid, ev| Box.box((program.update)(Box.unbox(boxed), pid, ev)) + +view_for_host : Box(Model) -> Str +view_for_host = |boxed| (program.view)(Box.unbox(boxed)) + +layout_for_host : Box(Model), U64, U64 -> Str +layout_for_host = |boxed, width, height| (program.layout)(Box.unbox(boxed), width, height) + +records_for_host : Box(Model) -> Str +records_for_host = |boxed| (program.records)(Box.unbox(boxed)) + +## What the program wants from the server: subscriptions and one-shot +## requests, as the JSON document of the world's capability protocol. +wants_for_host : Box(Model) -> Str +wants_for_host = |boxed| (program.wants)(Box.unbox(boxed)) + +snapshot_for_host : Box(Model) -> Str +snapshot_for_host = |boxed| (program.snapshot)(Box.unbox(boxed)) + +restore_for_host : Str -> Box(Model) +restore_for_host = |text| Box.box((program.restore)(text)) diff --git a/pkgs/id/scripts/roc-test.sh b/pkgs/id/scripts/roc-test.sh index bd453e70c8..531545a22b 100755 --- a/pkgs/id/scripts/roc-test.sh +++ b/pkgs/id/scripts/roc-test.sh @@ -17,4 +17,6 @@ for module in RocJson Screen Key; do echo "=== roc test examples/roc-world/${module}.roc ===" roc test "examples/roc-world/${module}.roc" done -echo "✓ Roc library expectations passed (RocJson, Screen, Key)" +echo "=== roc-cap-demo: capability-dependent library + app, both negative tests (#5957) ===" +bash examples/roc-cap-demo/roc-cap-demo-test.sh +echo "✓ Roc library expectations passed (RocJson, Screen, Key; roc-cap-demo positive + negative tests)"