Preview a drag with duplex
It is Red's turn again. Alice drags red7 across squares 18, 19 and 11. A duplex exchange lets her send positions while receiving allowed-square and capture previews. It starts without initial data, just like the push exchange.
For each position, the rules worker queries the legal candidates and replies with landing, allowed and a captures map. The worker allows squares 18 and 19 in this position. It rejects square 11 because that choice would move a non-king Red piece backward. None of these previews moves a stored piece.
Alice finishes her sending direction after the final position. She can still read responses until the worker finishes its direction. The example reads both finish notices and checks that the board remains at revision two. Cancellation would end the whole exchange instead of closing only one direction.
Use a request or completed push turn to confirm a choice. A preview can become stale between a query and the later commit. Check the expected revision in the commit mutation.
The preview for square 18 is:
landing 18
allowed true
captures {}
Define the messages
The game data installs duplex/checkers/drag in the events definition folder:
request {type object
required [piece landing]
additionalProperties false
properties {piece {type string}
landing {type integer
minimum 0
maximum 31}}}
response {type object
required [landing allowed captures]
additionalProperties false
properties {landing {type integer
minimum 0
maximum 31}
allowed {type boolean}
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 preview_a_drag(
game: &Game<'_>,
alice: &events::Owner<'_>,
rules: &events::Owner<'_>,
) -> Outcome {
let worker = events::serve_checkers_drag(rules)?;
let caller = events::open_checkers_drag(alice)?;
let exchange = worker.accept(WAIT)?;
for landing in [18, 19, 11] {
caller.send(&events::CheckersDragRequest {
piece: "red7".into(),
landing,
})?;
let update = match exchange.read(WAIT)? {
Notice::Message(data) => data,
_ => return Err("drag ended early".into()),
};
let moves = game.rows("checkers/legal", json!({"?piece":update.piece}))?;
let choice = moves.iter().find(|row| row["landing"] == update.landing);
let captures = choice
.and_then(|row| row.get("captures"))
.cloned()
.unwrap_or(json!({}));
exchange.send(&events::CheckersDragResponse {
landing: update.landing,
allowed: choice.is_some(),
captures: serde_json::from_value(captures)?,
})?;
let preview = match caller.read(WAIT)? {
Notice::Message(data) => data,
_ => return Err("drag ended early".into()),
};
assert_eq!(preview.allowed, landing != 11);
}
caller.finish()?;
assert_eq!(exchange.read(WAIT)?, Notice::Finished);
exchange.finish()?;
assert_eq!(caller.read(WAIT)?, Notice::Finished);
assert_eq!(game.board()?["revision"], 2);
worker.close()?;
Ok(())
}