Files
nym/sdk/rust/nym-sdk/examples/control_requests.rs
mfahampshire 9db748e8dd Max/sdk docrs (#6566)
* Improve SDK rustdoc and add ARCHITECTURE.md files

- Rewrite lib.rs module docs with quick-start example and module overview
- Add stream example and include_str! ARCHITECTURE.md to mixnet module
- Add ARCHITECTURE.md for mixnet, client_pool, and stream modules
- Add rustdoc to MixnetClientBuilder, MixnetClientSender, MixnetMessageSender
- Add cancel safety and drop behavior annotations to async methods
- Add TcpProxy deprecation notice pointing to stream module

* Fix rustdoc errors and add stepwise comments to remaining examples

Rustdoc fixes:
- Add missing .unwrap() on connect_new example
- Replace broken turbofish intra-doc link in MixnetClientBuilder
- Fix NymProxyServer::new args in tcp_proxy example
- Wrap BandwidthImporter example in scoped block to fix borrow-then-move
- Change misleading "5-hop routing" to "multi-hop routing"
- Fix copy-paste "forget me" in send_remember_me error message
- Fix wrong cargo run command in stream_simple_read_write
- Fix DecayWrapper description

* Cut down doc comment length

* Trimmed down SDK ARCHITECTURE files

* Slim Rust SDK docs and rename opener to dialer

- Merge tour page into SDK landing page, delete tour.mdx
- Trim all three tutorials: cut boilerplate, duplicated code, and misplaced content
- Make FFI page evergreen with Go and C++ snippets, link to repo examples
- Rename "opener" to "dialer" in stream docs, source ARCHITECTURE.md, and rustdoc
- Add reply-to-open arrow in stream mermaid diagram
- Replace remaining Unicode dashes in mermaid flowchart

* - elevate streams in rustdoc: examples on lib.rs, MixnetClient, open_stream, listener
- add stream quick reference to mixnet ARCHITECTURE.md
- add stream types to key types list in ARCHITECTURE.md
- add docs.rs links for AsyncRead/AsyncWrite and stream submodule
- tcp_proxy: replace bold deprecation with warning box

* - replace individual example doc pages with GitHub-linked tables
- add step-by-step inline comments to all SDK example source files
- add doc comments to examples missing them (simple, surb_reply, builder, etc.)
- expand mixnet tutorial with persistent identity and split_sender sections
- add tcpproxy tutorial
- rename "API Reference" to "TypeDoc Reference" in TS SDK sidebar
- rename "Misc" to "Extras" in developer sidebar, move VPN CLI up
- remove echo server from tools
- update message-queue callout to reference actual modules
- fix mixnet/examples redirect collision

* Add missing mut to example code

* Update ARCHITECTURE.md with LP Framing + stream examples with sequencing

* Update doc comment in utils.rs

* Standardise commenting style across Rust SDK examples

* Fix inline doc examples and trim re-export boilerplate

* Update sdk/rust/nym-sdk/examples/bandwidth.rs

Co-authored-by: Simon Wicky <simon@nymtech.net>

* Fix review comments

---------

Co-authored-by: Simon Wicky <simon@nymtech.net>
2026-04-10 10:51:38 +00:00

97 lines
3.6 KiB
Rust

// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
//! Sending control requests to a service provider via the mixnet.
//!
//! Demonstrates `send_message` with explicit SURB counts and the
//! `nym-service-providers-common` request/response protocol. Sends
//! Health, BinaryInfo, and SupportedRequestVersions queries.
//!
//! Run with: cargo run --example control_requests
use nym_sdk::mixnet::{
IncludedSurbs, MixnetClient, MixnetMessageSender, Recipient, ReconstructedMessage,
};
use nym_service_providers_common::interface::{
ControlRequest, ControlResponse, ProviderInterfaceVersion, Request, Response, ResponseContent,
};
fn parse_control_response(received: Vec<ReconstructedMessage>) -> ControlResponse {
assert_eq!(received.len(), 1);
let response: Response = Response::try_from_bytes(&received[0].message).unwrap();
match response.content {
ResponseContent::Control(control) => control,
ResponseContent::ProviderData(_) => {
panic!("received provider data even though we sent control request!")
}
}
}
async fn wait_for_control_response(client: &mut MixnetClient) -> ControlResponse {
loop {
let next = client.wait_for_messages().await.unwrap();
if !next.is_empty() {
return parse_control_response(next);
}
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Connect an ephemeral client.
let mut client = MixnetClient::connect_new().await.unwrap();
let provider: Recipient = "8YF6f8x17j3fviBdU87EGD9g9MAgn9DARxunwLEVM7Bm.4ydfpjbTjCmzj58hWdQjxU2gT6CRVnTbnKajr2hAGBBM@2xU4CBE6QiiYt6EyBXSALwxkNvM7gqJfjHXaMkjiFmYW".parse().unwrap();
// Build control requests using the service-provider interface.
let request_health = ControlRequest::Health;
let request_binary_info = ControlRequest::BinaryInfo;
let request_versions = ControlRequest::SupportedRequestVersions;
let full_request_health: Request =
Request::new_control(ProviderInterfaceVersion::new_current(), request_health);
let full_request_binary_info: Request =
Request::new_control(ProviderInterfaceVersion::new_current(), request_binary_info);
let full_request_versions: Request =
Request::new_control(ProviderInterfaceVersion::new_current(), request_versions);
// Send a Health request with 10 reply SURBs and wait for the response.
println!("Sending 'Health' request...");
client
.send_message(
provider,
full_request_health.into_bytes(),
IncludedSurbs::new(10),
)
.await?;
let response = wait_for_control_response(&mut client).await;
println!("response to 'Health' request: {response:#?}");
// Send a BinaryInfo request (no SURBs — the SP reuses SURBs from previous messages).
println!("Sending 'BinaryInfo' request...");
client
.send_message(
provider,
full_request_binary_info.into_bytes(),
IncludedSurbs::none(),
)
.await?;
let response = wait_for_control_response(&mut client).await;
println!("response to 'BinaryInfo' request: {response:#?}");
// Send a SupportedRequestVersions request.
println!("Sending 'SupportedRequestVersions' request...");
client
.send_message(
provider,
full_request_versions.into_bytes(),
IncludedSurbs::none(),
)
.await?;
let response = wait_for_control_response(&mut client).await;
println!("response to 'SupportedRequestVersions' request: {response:#?}");
// Disconnect for clean shutdown.
client.disconnect().await;
Ok(())
}