fire_stream_api/
client.rs1use crate::message::{Action, Message, IntoMessage, FromMessage};
2use crate::request::{Request};
3use crate::error::ApiError;
4
5use stream::util::ByteStream;
6use stream::client::Connection;
7pub use stream::client::{Config, ReconStrat};
8use stream::packet::{Packet, PacketBytes};
9pub use stream::packet::PlainBytes;
10use stream::error::TaskError;
11
12#[cfg(feature = "encrypted")]
13pub use stream::packet::EncryptedBytes;
14#[cfg(feature = "encrypted")]
15use crypto::signature::PublicKey;
16
17
18pub struct Client<A, B> {
19 inner: Connection<Message<A, B>>
20}
21
22impl<A> Client<A, PlainBytes>
23where A: Action + Send + 'static {
24 pub fn new<S>(
26 stream: S,
27 cfg: Config,
28 recon_strat: Option<ReconStrat<S>>
29 ) -> Self
30 where S: ByteStream {
31 Self {
32 inner: Connection::new(stream, cfg, recon_strat)
33 }
34 }
35}
36
37#[cfg(feature = "encrypted")]
38#[cfg_attr(docsrs, doc(cfg(feature = "encrypted")))]
39impl<A> Client<A, EncryptedBytes>
40where A: Action + Send + 'static {
41 pub fn new_encrypted<S>(
42 stream: S,
43 cfg: Config,
44 recon_strat: Option<ReconStrat<S>>,
45 pub_key: PublicKey
46 ) -> Self
47 where S: ByteStream {
48 Self {
49 inner: Connection::new_encrypted(stream, cfg, recon_strat, pub_key)
50 }
51 }
52}
53
54impl<A, B> Client<A, B>
55where
56 A: Action,
57 B: PacketBytes
58{
59 pub async fn request<R>(&self, req: R) -> Result<R::Response, R::Error>
60 where
61 R: Request<Action=A>,
62 R: IntoMessage<A, B>,
63 R::Response: FromMessage<A, B>,
64 R::Error: FromMessage<A, B>
65 {
66 let mut msg = req.into_message()
67 .map_err(R::Error::from_message_error)?;
68 msg.header_mut().set_action(R::ACTION);
69
70 let res = self.inner.request(msg).await
71 .map_err(R::Error::from_request_error)?;
72
73 if res.is_success() {
75 R::Response::from_message(res)
76 .map_err(R::Error::from_message_error)
77 } else {
78 R::Error::from_message(res)
79 .map(Err)
80 .map_err(R::Error::from_message_error)?
81 }
82 }
83}
84
85impl<A, B> Client<A, B> {
86 pub async fn close(self) -> Result<(), TaskError> {
87 self.inner.close().await
88 }
89}