-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.rs
79 lines (73 loc) · 2.39 KB
/
server.rs
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
use crate::proto::{
action_server::{Action, ActionServer},
Acknowledgement, GetRequest, GetResponse, RemoveRequest, SetRequest,
};
use crate::KvStore;
use crate::KvsEngine;
use std::{net::SocketAddr, sync::Arc};
use tracing::info;
/// Server implementation which has no awareness of other server stores. It simply
/// services requests from its own internal [`KvStore`].
#[derive(Clone)]
pub struct StandaloneServer {
pub store: Arc<KvStore>,
pub addr: SocketAddr,
}
impl StandaloneServer {
pub fn new<P>(path: P, addr: SocketAddr) -> anyhow::Result<Self>
where
P: Into<std::path::PathBuf>,
{
let store = Arc::new(KvStore::open(path)?);
Ok(Self { store, addr })
}
pub async fn run(&self) -> anyhow::Result<()> {
info!("Listening on {}", self.addr);
info!(
"sqrl-server version: {}, engine: sqrl",
env!("CARGO_PKG_VERSION"),
);
tonic::transport::Server::builder()
.add_service(ActionServer::new(self.clone()))
.serve(self.addr)
.await?;
Ok(())
}
}
#[tonic::async_trait]
impl Action for StandaloneServer {
async fn get(
&self,
req: tonic::Request<GetRequest>,
) -> tonic::Result<tonic::Response<GetResponse>, tonic::Status> {
let req = req.into_inner();
match self.store.get(req.key).await.unwrap() {
Some(v) => Ok(tonic::Response::new(GetResponse {
value: v.value,
timestamp: v.timestamp,
})),
None => Ok(tonic::Response::new(GetResponse {
value: None,
timestamp: 0,
})),
}
}
async fn set(
&self,
req: tonic::Request<SetRequest>,
) -> tonic::Result<tonic::Response<Acknowledgement>, tonic::Status> {
let req = req.into_inner();
self.store.set(req.key, req.value).await.unwrap();
Ok(tonic::Response::new(Acknowledgement { success: true }))
}
async fn remove(
&self,
req: tonic::Request<RemoveRequest>,
) -> tonic::Result<tonic::Response<Acknowledgement>, tonic::Status> {
let req = req.into_inner();
match self.store.remove(req.key).await {
Ok(_) => Ok(tonic::Response::new(Acknowledgement { success: true })),
Err(_) => Ok(tonic::Response::new(Acknowledgement { success: false })),
}
}
}