Stream legal landings with pull
It is now Black's turn. Bob selects black1, and a pull exchange sends that one selection to the rules worker. The worker runs checkers/legal against the current revision and sends each candidate as a response message. It calls finish after the last candidate.
Bob reads until he receives kind: finish. The candidate for this position lands on 13 and captures red2. Bob collects candidates in a map keyed by landing square. The collection has no order, even though the transport delivers messages in sequence.
This fixture has one candidate for Black's first jump. A larger result can use the same send-and-finish pattern without changing the request. Treat the result as a preview of the queried revision. The commit mutation must still check the board because another turn could change it before Bob acts.
The streamed candidate is:
landing 13
captures {red2 true}
Define the messages
The game data installs pull/checkers/legal in the events definition folder:
request {type object
required [piece]
additionalProperties false
properties {piece {type string}}}
response {type object
required [landing captures]
additionalProperties false
properties {landing {type integer
minimum 0
maximum 31}
captures {type object
additionalProperties {type boolean}}}}
The SDK plugin derives the payload types and route helpers from this definition. The Events plugin validates each message against its stored schema. The example below imports the generated SDK.
Code
fn list_legal_moves(
game: &Game<'_>,
bob: &events::Owner<'_>,
rules: &events::Owner<'_>,
) -> Outcome {
let worker = events::serve_checkers_legal(rules)?;
let caller = events::open_checkers_legal(
bob,
&events::CheckersLegalRequest {
piece: "black1".into(),
},
)?;
let exchange = worker.accept(WAIT)?;
for row in game.rows(
"checkers/legal",
json!({"?piece": exchange.request().piece}),
)? {
let response: events::CheckersLegalResponse = serde_json::from_value(row)?;
exchange.send(&response)?;
}
exchange.finish()?;
let mut moves = Vec::new();
loop {
match caller.read(WAIT)? {
Notice::Message(data) => moves.push(serde_json::to_value(data)?),
Notice::Finished => break,
Notice::Cancelled => return Err("legal-move stream cancelled".into()),
}
}
assert_eq!(moves, vec![json!({"landing":13,"captures":{"red2":true}})]);
worker.close()?;
Ok(())
}