You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.0 KiB
83 lines
2.0 KiB
4 years ago
|
use warp::{
|
||
4 years ago
|
Filter,
|
||
|
Rejection,
|
||
|
Reply,
|
||
4 years ago
|
body
|
||
4 years ago
|
};
|
||
|
use std::{
|
||
|
collections::HashMap,
|
||
4 years ago
|
sync::Arc
|
||
4 years ago
|
};
|
||
|
use env_logger;
|
||
|
use tokio::sync::Mutex;
|
||
4 years ago
|
use uuid::Uuid;
|
||
4 years ago
|
use tokio::join;
|
||
4 years ago
|
use u_lib::{
|
||
|
MASTER_PORT,
|
||
4 years ago
|
contracts::*,
|
||
4 years ago
|
client::*
|
||
4 years ago
|
};
|
||
|
|
||
|
|
||
4 years ago
|
fn get_content() -> impl Filter<Extract = (Message<'static, ClientInfo>,),
|
||
|
Error = Rejection> + Clone {
|
||
4 years ago
|
body::content_length_limit(1024*64).and(body::json::<Message<ClientInfo>>())
|
||
|
}
|
||
|
|
||
4 years ago
|
async fn add_client(msg: Message<'_, ClientInfo>,
|
||
|
db: SharedStorage) -> Result<impl Reply, Rejection> {
|
||
4 years ago
|
let new_cli = msg.item;
|
||
|
let mut clients = db.lock().await;
|
||
|
if clients.contains_key(&new_cli.id) {
|
||
|
Ok(warp::reply::json(
|
||
4 years ago
|
&RawMsg("Already exist".to_string()).into_message()
|
||
4 years ago
|
))
|
||
|
} else {
|
||
4 years ago
|
clients.insert(
|
||
|
new_cli.id.clone(),
|
||
|
UClient::new(new_cli.into_owned())
|
||
|
);
|
||
4 years ago
|
Ok(warp::reply::json(
|
||
4 years ago
|
&RawMsg("Added".to_string()).into_message()
|
||
|
))
|
||
4 years ago
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
async fn listing(db: SharedStorage) -> Result<impl Reply, Rejection> {
|
||
4 years ago
|
let clients = db.lock().await;
|
||
4 years ago
|
let mut result: Vec<ClientInfo> = Vec::with_capacity(clients.len());
|
||
|
for cli in clients.values() {
|
||
4 years ago
|
result.push(cli.client_info.clone());
|
||
4 years ago
|
}
|
||
4 years ago
|
Ok(warp::reply::json(
|
||
4 years ago
|
&Message::new_owned(result)
|
||
4 years ago
|
))
|
||
|
}
|
||
4 years ago
|
|
||
|
|
||
|
#[tokio::main]
|
||
|
async fn main() {
|
||
|
env_logger::init();
|
||
4 years ago
|
let base_db: SharedStorage = Arc::new(
|
||
4 years ago
|
Mutex::new(HashMap::<Uuid, UClient>::new())
|
||
4 years ago
|
);
|
||
|
let db = warp::any().map(move || Arc::clone(&base_db));
|
||
|
|
||
|
let new_client = warp::post()
|
||
|
.and(warp::path("new"))
|
||
|
.and(get_content())
|
||
|
.and(db.clone())
|
||
|
.and_then(add_client);
|
||
|
|
||
|
let ls = warp::get()
|
||
|
.and(warp::path("ls"))
|
||
|
.and(db.clone())
|
||
|
.and_then(listing);
|
||
4 years ago
|
|
||
4 years ago
|
let routes = new_client
|
||
4 years ago
|
.or(ls)
|
||
4 years ago
|
.with(warp::log("warp"));
|
||
4 years ago
|
warp::serve(routes)
|
||
4 years ago
|
.run(([0,0,0,0], MASTER_PORT)).await;
|
||
4 years ago
|
}
|