diff --git a/Cargo.toml b/Cargo.toml index f2375fdd..88749627 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,3 +17,13 @@ unused = "deny" [workspace.lints.clippy] as_conversions = "deny" + +[workspace.dependencies] +hyper = "0.13.9" +tokio = { version = "0.2", features = ["macros"] } +thiserror = "1.0" +starknet_api = "0.8.0" +serde = { version = "1.0.193", features = ["derive"] } +serde_json = "1.0" +assert_matches = "1.5.0" + diff --git a/crates/gateway/Cargo.toml b/crates/gateway/Cargo.toml index 3875d7e5..556af0fa 100644 --- a/crates/gateway/Cargo.toml +++ b/crates/gateway/Cargo.toml @@ -6,6 +6,13 @@ repository.workspace = true license.workspace = true [dependencies] +hyper.workspace = true +tokio.workspace = true +thiserror.workspace = true +serde.workspace = true +serde_json.workspace = true +starknet_api.workspace = true +assert_matches.workspace = true [lints] workspace = true diff --git a/crates/gateway/src/errors.rs b/crates/gateway/src/errors.rs new file mode 100644 index 00000000..b08a50f7 --- /dev/null +++ b/crates/gateway/src/errors.rs @@ -0,0 +1,19 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum GatewayError { + #[error(transparent)] + ConfigError(#[from] GatewayConfigError), + #[error(transparent)] + HTTPError(#[from] hyper::http::Error), + #[error("Internal server error")] + InternalServerError, + #[error("Error while starting the server")] + ServerStartError(#[from] hyper::Error), +} + +#[derive(Debug, Error)] +pub enum GatewayConfigError { + #[error("Server address is not an bind IP address: {0}")] + InvalidServerBindAddress(String), +} diff --git a/crates/gateway/src/gateway.rs b/crates/gateway/src/gateway.rs new file mode 100644 index 00000000..4996db4f --- /dev/null +++ b/crates/gateway/src/gateway.rs @@ -0,0 +1,57 @@ +use crate::errors::{GatewayConfigError, GatewayError}; +use hyper::service::{make_service_fn, service_fn}; +use hyper::{Body, Method, Request, Response, Server, StatusCode}; +use std::convert::Infallible; +use std::net::SocketAddr; +use std::str::FromStr; + +#[cfg(test)] +#[path = "gateway_test.rs"] +pub mod gateway_test; + +const NOT_FOUND_RESPONSE: &str = "Not found."; +type RequestBody = Request
; +type ResponseBody = Response; +pub type GatewayResult = Result<(), GatewayError>; + +pub struct Gateway { + pub gateway_config: GatewayConfig, +} + +impl Gateway { + pub async fn build_server(&self) -> GatewayResult { + let addr = SocketAddr::from_str(&self.gateway_config.bind_address).map_err(|_| { + GatewayConfigError::InvalidServerBindAddress(self.gateway_config.bind_address.clone()) + })?; + + let make_service = + make_service_fn(|_conn| async { Ok::<_, Infallible>(service_fn(handle_request)) }); + + Server::bind(&addr).serve(make_service).await?; + + Ok(()) + } +} + +pub struct GatewayConfig { + pub bind_address: String, +} + +async fn handle_request(request: RequestBody) -> Result