d2m_ping_pong.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //! Example for usage of the Device to Mediator Protocol state machine, doing a real handshake with the
  2. //! mediator server and an exemplary payload flow loop.
  3. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  4. #![expect(
  5. clippy::integer_division_remainder_used,
  6. reason = "Some internal of tokio::select triggers this"
  7. )]
  8. use core::time::Duration;
  9. use anyhow::{Result, anyhow, bail};
  10. use clap::{ArgAction, Parser};
  11. use futures_util::{SinkExt as _, TryStreamExt as _};
  12. use libthreema::{
  13. cli::config::{FullIdentityConfig, FullIdentityConfigOptions},
  14. d2m::{
  15. D2mContext, D2mProtocol, D2mStateUpdate,
  16. payload::{BeginTransaction, IncomingPayload, OutgoingPayload, Reflect, ReflectFlags},
  17. },
  18. https::cli::https_client_builder,
  19. utils::logging::init_stderr_logging,
  20. };
  21. use libthreema_dependencies::rand;
  22. use tokio::{net::TcpStream, signal, sync::mpsc, time};
  23. use tokio_tungstenite::{
  24. MaybeTlsStream, WebSocketStream, connect_async,
  25. tungstenite::protocol::{CloseFrame, Message, frame::coding::CloseCode},
  26. };
  27. use tracing::{Level, debug, error, info, trace, warn};
  28. #[derive(Parser)]
  29. #[command()]
  30. struct D2mPingPongCommand {
  31. #[command(flatten)]
  32. config: FullIdentityConfigOptions,
  33. /// Turn on debugging information.
  34. /// Use -v -vv to control log level.
  35. #[arg(short, action = ArgAction::Count)]
  36. verbose: u8,
  37. }
  38. /// Payload queues for the main process.
  39. struct PayloadQueuesForD2mPingPong {
  40. incoming: mpsc::Receiver<IncomingPayload>,
  41. outgoing: mpsc::Sender<OutgoingPayload>,
  42. }
  43. /// Payload queues for the protocol flow runner.
  44. struct PayloadQueuesForProtocol {
  45. incoming: mpsc::Sender<IncomingPayload>,
  46. outgoing: mpsc::Receiver<OutgoingPayload>,
  47. }
  48. struct D2mProtocolRunner {
  49. /// The WebSocket stream.
  50. stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
  51. /// An instance of the [`D2mProtocol`] state machine.
  52. protocol: D2mProtocol,
  53. }
  54. impl D2mProtocolRunner {
  55. /// Initiate a D2M protocol connection
  56. #[tracing::instrument(skip_all)]
  57. async fn new(context: D2mContext) -> Result<Self> {
  58. // Create the protocol
  59. let (d2m_protocol, url) = D2mProtocol::new(context);
  60. // Connect via WebSocket
  61. debug!(?url, "Establishing WebSocket connection to mediator server");
  62. let (stream, response) = connect_async(url).await?;
  63. if response.status() != reqwest::StatusCode::SWITCHING_PROTOCOLS {
  64. bail!(
  65. "Expected response to switch protocols ({expected}), got {actual}",
  66. expected = reqwest::StatusCode::SWITCHING_PROTOCOLS,
  67. actual = response.status(),
  68. );
  69. }
  70. Ok(Self {
  71. stream,
  72. protocol: d2m_protocol,
  73. })
  74. }
  75. /// Do the handshake with the mediator server by exchanging the following messages:
  76. ///
  77. /// ```txt
  78. /// C -- client-info --> S (was already sent as part of the URL's path)
  79. /// C <- server-hello -- S
  80. /// C -- client-hello -> S
  81. /// C <- server-info --- S
  82. /// ```
  83. async fn run_handshake_flow(&mut self) -> Result<()> {
  84. for iteration in 1_usize.. {
  85. trace!("Iteration #{iteration}");
  86. // Receive datagram and add it
  87. let datagram = self.receive().await?;
  88. self.protocol.add_datagrams(vec![datagram])?;
  89. // Handle instruction
  90. let Some(instruction) = self.protocol.poll()? else {
  91. continue;
  92. };
  93. // We do not expect an incoming payload at this stage
  94. if let Some(incoming_payload) = instruction.incoming_payload {
  95. let message = "Unexpected incoming payload during handshake";
  96. error!(?incoming_payload, message);
  97. bail!(message)
  98. }
  99. // Send any outgoing datagram
  100. if let Some(datagram) = instruction.outgoing_datagram {
  101. self.send(datagram.0).await?;
  102. }
  103. // Check if we've completed the handshake
  104. if let Some(D2mStateUpdate::PostHandshake(server_info)) = instruction.state_update {
  105. info!(?server_info, "Handshake completed");
  106. break;
  107. }
  108. }
  109. Ok(())
  110. }
  111. /// Run the payload exchange flow until stopped.
  112. #[tracing::instrument(skip_all)]
  113. async fn run_payload_flow(&mut self, mut queues: PayloadQueuesForProtocol) -> Result<()> {
  114. for iteration in 1_usize.. {
  115. trace!("Payload flow iteration #{iteration}");
  116. // Poll for any pending instruction
  117. let mut instruction = self.protocol.poll()?;
  118. if instruction.is_none() {
  119. // No pending instruction left, wait for more input
  120. instruction = tokio::select! {
  121. // Forward any incoming datagrams from the WebSocket transport
  122. datagram = self.receive() => {
  123. // Add datagram (poll in the next iteration)
  124. self.protocol.add_datagrams(vec![datagram?])?;
  125. None
  126. },
  127. // Forward any outgoing payloads
  128. Some(outgoing_payload) = queues.outgoing.recv() => {
  129. debug!(?outgoing_payload, "Sending payload");
  130. let instruction = self.protocol.create_payload(outgoing_payload)?;
  131. Some(instruction)
  132. }
  133. }
  134. }
  135. let Some(instruction) = instruction else {
  136. continue;
  137. };
  138. // We do not expect any state updates at this stage
  139. if let Some(state_update) = instruction.state_update {
  140. let message = "Unexpected state update after handshake";
  141. error!(?state_update, message);
  142. bail!(message)
  143. }
  144. // Log any incoming payload
  145. if let Some(incoming_payload) = instruction.incoming_payload {
  146. debug!(?incoming_payload, "Received payload");
  147. queues.incoming.send(incoming_payload).await?;
  148. }
  149. // Send any outgoing datagram
  150. if let Some(datagram) = instruction.outgoing_datagram {
  151. self.send(datagram.0).await?;
  152. }
  153. }
  154. Ok(())
  155. }
  156. #[tracing::instrument(skip_all)]
  157. async fn shutdown(mut self) -> Result<()> {
  158. info!("Shutting down WebSocket connection");
  159. // Normal closure, e.g. when the user is explicitly disconnecting
  160. Ok(self
  161. .stream
  162. .close(Some(CloseFrame {
  163. code: CloseCode::Normal,
  164. reason: "Bye".into(),
  165. }))
  166. .await?)
  167. }
  168. #[tracing::instrument(skip_all)]
  169. async fn send(&mut self, datagram: Vec<u8>) -> Result<()> {
  170. trace!(length = datagram.len(), "Sending datagram");
  171. self.stream.send(Message::Binary(datagram.into())).await?;
  172. Ok(())
  173. }
  174. #[tracing::instrument(skip_all)]
  175. async fn receive(&mut self) -> Result<Vec<u8>> {
  176. let datagram = loop {
  177. let message = self
  178. .stream
  179. .try_next()
  180. .await?
  181. .ok_or(anyhow!("WebSocket reading end closed"))?;
  182. match message {
  183. Message::Binary(bytes) => break bytes.to_vec(),
  184. Message::Text(text) => {
  185. bail!("Received unexpected text message: {}", text.as_str())
  186. },
  187. Message::Ping(bytes) => {
  188. // WARNING: There's a slight chance that the pong is lost when this is cancelled!
  189. debug!(ping_length = bytes.len(), "Received ping, responding with a pong");
  190. self.stream.feed(Message::Pong(bytes)).await?;
  191. debug!("Pong sent");
  192. },
  193. Message::Pong(bytes) => {
  194. debug!(pong_length = bytes.len(), "Received pong");
  195. },
  196. Message::Close(close_frame) => {
  197. info!(?close_frame, "Received close");
  198. },
  199. Message::Frame(_) => {
  200. bail!("Received unexpected raw frame");
  201. },
  202. }
  203. };
  204. debug!(datagram_length = datagram.len(), "Received datagram");
  205. Ok(datagram)
  206. }
  207. }
  208. #[derive(Debug, PartialEq)]
  209. enum TransactionState {
  210. None,
  211. Blocked,
  212. AwaitingBeginAck,
  213. Running,
  214. AwaitingCommitAck,
  215. }
  216. struct D2mPingPongFlowRunner {
  217. queues: PayloadQueuesForD2mPingPong,
  218. transaction_state: TransactionState,
  219. reflect_id_counter: u32,
  220. }
  221. impl D2mPingPongFlowRunner {
  222. fn new(queues: PayloadQueuesForD2mPingPong) -> Self {
  223. Self {
  224. queues,
  225. transaction_state: TransactionState::None,
  226. reflect_id_counter: 0,
  227. }
  228. }
  229. async fn run(mut self) -> Result<()> {
  230. // Create a timer that will periodically trigger an outgoing payload
  231. let mut payload_timer = time::interval_at(
  232. time::Instant::now()
  233. .checked_add(Duration::from_secs(10))
  234. .expect("Oops, apocalypse is near"),
  235. Duration::from_secs(10),
  236. );
  237. // Enter ping-pong flow loop
  238. loop {
  239. let outgoing_payload = tokio::select! {
  240. // Create an outgoing payload when the timer fires
  241. _ = payload_timer.tick() => {
  242. self.create_outgoing_payload()
  243. },
  244. // Process incoming payload
  245. incoming_payload = self.queues.incoming.recv() => {
  246. if let Some(incoming_payload) = incoming_payload {
  247. info!(?incoming_payload, "Received payload");
  248. self.handle_incoming_payload(&incoming_payload)
  249. } else {
  250. break
  251. }
  252. }
  253. };
  254. // Send any outgoing payload
  255. if let Some(outgoing_payload) = outgoing_payload {
  256. info!(?outgoing_payload, "Sending payload");
  257. self.queues.outgoing.send(outgoing_payload).await?;
  258. }
  259. }
  260. Ok(())
  261. }
  262. #[tracing::instrument(skip_all)]
  263. fn handle_incoming_payload(&mut self, incoming_payload: &IncomingPayload) -> Option<OutgoingPayload> {
  264. match incoming_payload {
  265. // Transaction acknowledged: Now running
  266. IncomingPayload::BeginTransactionAck => {
  267. self.transaction_state = TransactionState::Running;
  268. None
  269. },
  270. // Transaction committed: Now none ongoing
  271. IncomingPayload::CommitTransactionAck => {
  272. self.transaction_state = TransactionState::None;
  273. None
  274. },
  275. // Transaction rejected: Retry beginning once we're unblocked
  276. IncomingPayload::TransactionRejected(_) => {
  277. self.transaction_state = TransactionState::Blocked;
  278. None
  279. },
  280. // Another transaction ended: Retry if we were blocked
  281. IncomingPayload::TransactionEnded(_) => {
  282. if self.transaction_state == TransactionState::Blocked {
  283. self.transaction_state = TransactionState::None;
  284. Some(OutgoingPayload::BeginTransaction(BeginTransaction {
  285. encrypted_scope: b"encrypted_scope".to_vec(),
  286. ttl: None,
  287. }))
  288. } else {
  289. None
  290. }
  291. },
  292. _ => None,
  293. }
  294. }
  295. #[tracing::instrument(skip_all)]
  296. fn create_outgoing_payload(&mut self) -> Option<OutgoingPayload> {
  297. trace!(state = ?self.transaction_state);
  298. match self.transaction_state {
  299. // No transaction: Occasionally begin a transaction
  300. TransactionState::None if rand::random::<bool>() => {
  301. self.transaction_state = TransactionState::AwaitingBeginAck;
  302. Some(OutgoingPayload::BeginTransaction(BeginTransaction {
  303. encrypted_scope: b"encrypted_scope".to_vec(),
  304. ttl: None,
  305. }))
  306. },
  307. // Transaction running: Commit.
  308. TransactionState::Running => {
  309. self.transaction_state = TransactionState::AwaitingCommitAck;
  310. Some(OutgoingPayload::CommitTransaction)
  311. },
  312. // No transaction running: Reflect.
  313. TransactionState::None
  314. | TransactionState::Blocked
  315. | TransactionState::AwaitingBeginAck
  316. | TransactionState::AwaitingCommitAck => {
  317. self.reflect_id_counter = self.reflect_id_counter.checked_add(1)?;
  318. Some(OutgoingPayload::Reflect(Reflect {
  319. flags: ReflectFlags(ReflectFlags::EPHEMERAL_MARKER),
  320. reflect_id: self.reflect_id_counter,
  321. envelope: b"envelope".to_vec(),
  322. }))
  323. },
  324. }
  325. }
  326. }
  327. #[tokio::main]
  328. async fn main() -> Result<()> {
  329. // Parse command
  330. let arguments = D2mPingPongCommand::parse();
  331. // Configure logging
  332. let log_level = match arguments.verbose {
  333. 1 => Level::DEBUG,
  334. 2 => Level::TRACE,
  335. _ => Level::INFO,
  336. };
  337. init_stderr_logging(log_level);
  338. // Create HTTP client
  339. let http_client = https_client_builder().build()?;
  340. let config = FullIdentityConfig::from_options(&http_client, arguments.config).await?;
  341. // Create payload queues
  342. let (app_queues, protocol_queues) = {
  343. let incoming_payload = mpsc::channel(4);
  344. let outgoing_payload = mpsc::channel(4);
  345. (
  346. PayloadQueuesForD2mPingPong {
  347. incoming: incoming_payload.1,
  348. outgoing: outgoing_payload.0,
  349. },
  350. PayloadQueuesForProtocol {
  351. incoming: incoming_payload.0,
  352. outgoing: outgoing_payload.1,
  353. },
  354. )
  355. };
  356. // Create D2M protocol and establish a connection
  357. let mut d2m_connection = D2mProtocolRunner::new(
  358. config
  359. .d2m_context()
  360. .expect("Configuration must include D2X configuration"),
  361. )
  362. .await?;
  363. // Create protocol flow runner
  364. let ping_pong_flow_runner = D2mPingPongFlowRunner::new(app_queues);
  365. // Run the handshake flow
  366. d2m_connection.run_handshake_flow().await?;
  367. // Run the protocols
  368. tokio::select! {
  369. _ = d2m_connection.run_payload_flow(protocol_queues) => {}
  370. _ = ping_pong_flow_runner.run() => {}
  371. _ = signal::ctrl_c() => {},
  372. };
  373. // Shut down
  374. d2m_connection.shutdown().await?;
  375. Ok(())
  376. }
  377. #[test]
  378. fn verify_cli() {
  379. use clap::CommandFactory;
  380. D2mPingPongCommand::command().debug_assert();
  381. }