1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
pub use libqaul_types::*;
pub use qrpc_sdk::{
default_socket_path,
error::{RpcError, RpcResult},
io::Message,
RpcSocket, Service,
};
pub use std::{str, sync::Arc};
use rpc::{Capabilities, Reply, UserCapabilities, UserReply, ADDRESS};
use users::UserAuth;
pub struct QaulRpc {
socket: Arc<RpcSocket>,
addr: String,
}
impl QaulRpc {
pub fn connect(service: &Service) -> RpcResult<Self> {
let socket = service.get_socket();
let addr = service.name.clone();
Ok(Self { socket, addr })
}
pub fn users<'q>(&'q self) -> UserRpc<'q> {
UserRpc { rpc: self }
}
async fn send(&self, cap: Capabilities) -> RpcResult<Reply> {
let json = cap.to_json();
let msg = Message::to_addr(ADDRESS, &self.addr, json.as_bytes().to_vec());
self.socket
.send(msg, |Message { data, .. }| {
match str::from_utf8(data.as_slice())
.ok()
.and_then(|json| Reply::from_json(json))
{
Some(Reply::Error(e)) => Err(RpcError::Other(e.to_string())),
None => Err(RpcError::EncoderFault("Invalid json payload!".into())),
Some(r) => Ok(r),
}
})
.await
}
}
pub struct UserRpc<'q> {
rpc: &'q QaulRpc,
}
impl<'q> UserRpc<'q> {
pub async fn create<S: Into<String>>(&'q self, pw: S) -> RpcResult<UserAuth> {
if let Reply::Users(UserReply::Auth(auth)) = self
.rpc
.send(Capabilities::Users(UserCapabilities::Create {
pw: pw.into(),
}))
.await?
{
Ok(auth)
} else {
Err(RpcError::EncoderFault("Invalid reply payload!".into()))
}
}
}