Admit and fold a thread in Rust
This Rust receiver gets a vote before it gets the proposal. It checks each act. It calculates the tally after it accepts the two acts.
Start in the Cargo project from Install a dialect in Rust. Save the poll dialect as lunch-vote.cbcl beside Cargo.toml. Run cargo add serde_json@1 to read verdicts and state by field. Copy the complete receiver into src/main.rs.
On this page
Complete receiver
use cbcl_parser::state_exports::{admit_str, fold_str, intend_str};
use serde_json::Value;
fn main() -> Result<(), String> {
let dialect = include_str!("../lunch-vote.cbcl");
let opener = r#"(lang lunch-vote (propose @team :question "Lunch?"
:options ("Sushi" "Pizza") :caused-by begin :thread "friday" :from @alice))"#;
let alice = format!("(@alice {opener})");
let history = format!("(acts {alice})");
let vote = intend_str(&format!(
r#"(intend {dialect} friday {history} @bob vote
(:choice "Sushi" :clock "hlc-0000000000000001-00000000"))"#
))?;
let bob = format!("(@bob {vote})");
let admit = |accepted: &str, candidate: &str| -> Result<String, String> {
let frame = format!("(admit {dialect} friday {accepted} {candidate})");
let json = admit_str(&frame)?;
let result: Value = serde_json::from_str(&json).map_err(|e| e.to_string())?;
Ok(result["verdict"].as_str().ok_or("missing verdict")?.to_owned())
};
assert_eq!(admit("(acts)", &bob)?, "pending");
assert_eq!(admit("(acts)", &alice)?, "accepted");
assert_eq!(admit(&history, &bob)?, "accepted");
let json = fold_str(&format!("(fold {dialect} friday (acts {alice} {bob}))"))?;
let state: Value = serde_json::from_str(&json).map_err(|e| e.to_string())?;
println!("{}", state["tally"]);
Ok(())
}
Build the sender’s intent
Each record contains the authenticated signer and the complete message. The sender has the opener. It can make a vote that refers to the opener.
The example uses fixed text and canonical output to construct frames. For application input, construct S-expression values. Use cbcl_core::serializer::serialize to keep the correct types and quotation marks.
Admit at the receiver
Run cargo run. The program checks three verdicts. It prints {"Sushi":1}. The first verdict is pending because the receiver does not have the predecessor. When the receiver accepts the opener, it can retry the same vote.
Handle the two result channels
If a frame is unreadable or installation fails, admit_str returns a Rust error. For a valid frame, the function gives the admission verdict in JSON. Check the verdict before you add a record to the history for fold_str.
If the verdict is rejected, record the reason and the message address. If the verdict is pending, record the missing predecessor. Retry the candidate when the predecessor arrives.
The native fold takes the accepted history supplied by its caller. The JavaScript runtime also offers an read operation that checks admission for the records in the inbox.