client.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. /// * Connection aborted: The client did not have a chance to send the
  15. /// request, or will not receive a reply because the network is down.
  16. /// * Not connected: The network does not allow the client to send requests.
  17. /// * Broken pipe: The network no longer allows the client to send requests.
  18. /// * Not found: The network could not find the target server.
  19. /// * Invalid input: The server could not find the service / method to call.
  20. /// * Connection reset: The server received the request, but decided to stop
  21. /// responding.
  22. pub async fn call_rpc(
  23. &self,
  24. service_method: String,
  25. request: RequestMessage,
  26. ) -> Result<ReplyMessage> {
  27. let (tx, rx) = futures::channel::oneshot::channel();
  28. let rpc = RpcOnWire {
  29. client: self.client.clone(),
  30. server: self.server.clone(),
  31. service_method,
  32. request,
  33. reply_channel: tx,
  34. };
  35. self.request_bus.send(rpc).map_err(|e| {
  36. // The receiving end has been closed. Network connection is broken.
  37. std::io::Error::new(
  38. std::io::ErrorKind::ConnectionAborted,
  39. format!(
  40. "Cannot send rpc, client {} is disconnected. {}",
  41. self.client.clone(),
  42. e
  43. ),
  44. )
  45. })?;
  46. rx.await.map_err(|e| {
  47. std::io::Error::new(
  48. // The network closed our connection. The server might not even
  49. // get a chance to see the request.
  50. std::io::ErrorKind::ConnectionAborted,
  51. format!("Network request is dropped: {}", e),
  52. )
  53. })?
  54. }
  55. }