Skip to content

Commit

Permalink
feat: add GET /session endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
DefiCake committed Dec 1, 2023
1 parent ba88406 commit 30b53b3
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ serde_json = { version = "1.0" }
tokio = { version = "1.0", features = ["full"] }
tower = { version = "0.4", features = ["buffer", "limit", "load-shed", "util", "timeout"] }
tower-http = { version = "0.2.5", features = ["cors", "trace", "set-header", "fs"] }
rand = "0.8.5"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
rand = "0.8.5"

[dev-dependencies]
fuel-core = { version = "0.21.0", default-features = false }
Expand Down
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ pub async fn start_server(
)
.into_inner(),
)
.route("/session", get(routes::get_session))
.layer(Extension(sessions.clone()))
.route("/session", post(routes::create_session))
.layer(
ServiceBuilder::new()
Expand All @@ -201,7 +203,7 @@ pub async fn start_server(
.concurrency_limit(MAX_CONCURRENT_REQUESTS)
.timeout(Duration::from_secs(60))
.layer(TraceLayer::new_for_http())
.layer(Extension(sessions))
.layer(Extension(sessions.clone()))
.into_inner(),
);

Expand Down
66 changes: 59 additions & 7 deletions src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
CoinOutput, SharedConfig, SharedFaucetState, SharedNetworkConfig, SharedWallet,
};
use axum::{
extract::Query,
response::{Html, IntoResponse, Response},
routing::{get_service, MethodRouter},
Extension, Json,
Expand All @@ -23,8 +24,10 @@ use fuels_core::types::{
};
use fuels_core::types::{input::Input, transaction_builders::ScriptTransactionBuilder};
use handlebars::Handlebars;
use hex::FromHexError;
use reqwest::StatusCode;
use secrecy::ExposeSecret;
use serde::Deserialize;
use serde_json::json;
use std::sync::{Arc, Mutex};
use std::{
Expand Down Expand Up @@ -67,13 +70,11 @@ pub fn serve_worker() -> MethodRouter {
let template = concat!(env!("OUT_DIR"), "/worker.js");

async fn handle_error(_err: io::Error) -> impl IntoResponse {
dbg!(_err);
(
StatusCode::INTERNAL_SERVER_ERROR,
"Could not serve worker.js",
)
}
dbg!(template);
get_service(ServeFile::new(template)).handle_error(handle_error)
}

Expand Down Expand Up @@ -335,20 +336,71 @@ pub async fn create_session(
} else {
return Err(CreateSessionError {
status: StatusCode::BAD_REQUEST,
error: "invalid address".to_string(),
error: "invalid address".to_owned(),
});
}?;

// Access and modify the session map within the handler
let mut map = sessions.lock().unwrap();
let mut map = match sessions.lock() {
Ok(val) => val,
Err(_) => {
return Err(CreateSessionError {
status: StatusCode::INTERNAL_SERVER_ERROR,
error: "Could not acquire sessions lock".to_owned(),
})
}
};
let salt = Salt::random();

map.insert(salt.clone(), address);

dbg!(map.get(&salt));

Ok(CreateSessionResponse {
status: "Success".to_owned(),
salt: hex::encode(salt.as_bytes()),
})
}

#[derive(Deserialize)]
pub struct SessionQuery {
salt: String,
}

pub async fn get_session(
query: Query<SessionQuery>,
Extension(sessions): Extension<Arc<Mutex<SessionMap>>>,
) -> Response {
let salt: Result<[u8; 32], _> = hex::decode(&query.salt).and_then(|value| {
value
.try_into()
.map_err(|_| FromHexError::InvalidStringLength)
});

match salt {
Ok(value) => value,
Err(_) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "Invalid salt"})),
)
.into_response()
}
};

let map = match sessions.lock() {
Ok(val) => val,
Err(_) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "Could not acquire sessions lock"})),
)
.into_response()
}
};

let result = map.get(&Salt::new(salt.unwrap()));

match result {
Some(address) => (StatusCode::OK, Json(json!({"address": address}))),
None => (StatusCode::NOT_FOUND, Json(json!({}))),
}
.into_response()
}
4 changes: 4 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ use std::collections::HashMap;
pub struct Salt([u8; 32]);

impl Salt {
pub fn new(bytes: [u8; 32]) -> Self {
Salt(bytes)
}

pub fn random() -> Self {
let mut rng = rand::thread_rng();
let mut bytes = [0u8; 32];
Expand Down

0 comments on commit 30b53b3

Please sign in to comment.