weirdnet_service/
client.rs1use std::sync::Arc;
2
3use serde::Serialize;
4use serde::de::DeserializeOwned;
5
6use crate::{Credentials, Dialer, Live, ProtocolId, ServiceError, Session, State, Subscription, Topic};
7
8#[derive(Clone)]
11pub struct Client {
12 dialer: Arc<dyn Dialer>,
13 credentials: Credentials,
14}
15
16impl Client {
17 pub fn new(dialer: Arc<dyn Dialer>) -> Self {
18 Self { dialer, credentials: Credentials::default() }
19 }
20
21 pub fn with_credentials(mut self, credentials: Credentials) -> Self {
22 self.credentials = credentials;
23 self
24 }
25
26 pub fn credentials(&self) -> &Credentials {
27 &self.credentials
28 }
29
30 pub async fn session<Req: Serialize + Sync, Resp: DeserializeOwned>(
32 &self,
33 node: &str,
34 protocol: &ProtocolId,
35 ) -> Result<Session<Req, Resp>, ServiceError> {
36 let ch = self.dialer.open(node, protocol.as_str()).await?;
37 Session::start(ch, self.credentials.clone()).await
38 }
39
40 pub async fn session_any<Req: Serialize + Sync, Resp: DeserializeOwned>(
43 &self,
44 node: &str,
45 protocols: &[ProtocolId],
46 ) -> Result<(ProtocolId, Session<Req, Resp>), ServiceError> {
47 let mut last = ServiceError::unsupported("no protocol given");
48 for p in protocols {
49 match self.session(node, p).await {
50 Ok(s) => return Ok((p.clone(), s)),
51 Err(e @ ServiceError::Unsupported { .. }) => last = e,
52 Err(e) => return Err(e),
53 }
54 }
55 Err(last)
56 }
57
58 pub async fn subscribe<T: Topic, S: State>(
60 &self,
61 node: &str,
62 protocol: &ProtocolId,
63 topic: T,
64 resume: Option<crate::Position>,
65 ) -> Result<Subscription<T, S>, ServiceError> {
66 let ch = self.dialer.open(node, protocol.as_str()).await?;
67 Subscription::start(ch, self.credentials.clone(), topic, resume).await
68 }
69
70 pub fn live<T: Topic, S: State>(&self, node: &str, protocol: &ProtocolId, topic: T) -> Live<T, S> {
72 Live::new(self.clone(), node, protocol.clone(), topic)
73 }
74}