client.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use std::sync::mpsc::Sender;
  2. use crate::{
  3. ClientIdentifier, ReplyMessage, RequestMessage, Result, RpcOnWire,
  4. ServerIdentifier,
  5. };
  6. // Client interface, used by the RPC client.
  7. pub struct Client {
  8. pub(crate) client: ClientIdentifier,
  9. pub(crate) server: ServerIdentifier,
  10. pub(crate) request_bus: Sender<RpcOnWire>,
  11. }
  12. impl Client {
  13. /// Error type and meaning
  14. /// * Not connected: The client did not have a chance to send the request
  15. /// because the network is down.
  16. /// * Permission denied: The network does not allow the client to send
  17. /// requests.
  18. /// * Broken pipe: The network no longer allows the client to send requests.
  19. /// * Not found: The network could not find the target server.
  20. /// * Invalid input: The server could not find the service / method to call.
  21. /// * Connection reset: The server received the request, but decided to stop
  22. /// responding.
  23. /// * Connection aborted: The client will not receive a reply because the
  24. /// the connection is closed by the network.
  25. pub async fn call_rpc(
  26. &self,
  27. service_method: String,
  28. request: RequestMessage,
  29. ) -> Result<ReplyMessage> {
  30. let (tx, rx) = futures::channel::oneshot::channel();
  31. let rpc = RpcOnWire {
  32. client: self.client.clone(),
  33. server: self.server.clone(),
  34. service_method,
  35. request,
  36. reply_channel: tx,
  37. };
  38. self.request_bus.send(rpc).map_err(|e| {
  39. // The receiving end has been closed. Network connection is broken.
  40. std::io::Error::new(
  41. std::io::ErrorKind::NotConnected,
  42. format!(
  43. "Cannot send rpc, client {} is disconnected. {}",
  44. self.client.clone(),
  45. e
  46. ),
  47. )
  48. })?;
  49. rx.await.map_err(|e| {
  50. std::io::Error::new(
  51. // The network closed our connection. The server might not even
  52. // get a chance to see the request.
  53. std::io::ErrorKind::ConnectionAborted,
  54. format!("Network request is dropped: {}", e),
  55. )
  56. })?
  57. }
  58. }