Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tower & Warp server error #763

Open
ghost opened this issue Feb 11, 2024 · 0 comments
Open

Tower & Warp server error #763

ghost opened this issue Feb 11, 2024 · 0 comments

Comments

@ghost
Copy link

ghost commented Feb 11, 2024

I donot understand anything...

Code:

use crate:: {
  log::log::*,
  response::create_response::create_response,
  env::env:: {
    Env,
    EnvT
  },
  response::response:: {
    Response,
    ResponseTrait
  },
  entry::entry:: {
    Entry,
    EntryTrait
  },
};
use std:: {
  collections::HashMap,
  net::SocketAddr,
  process,
  sync::Arc
};
use warp::Filter;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct RequestParams {
  query: String,
}

pub struct Server;

pub trait ServerT {
  fn check_variables(env_vars: &HashMap<String, String>);
  fn run();
}

impl ServerT for Server {
  fn check_variables(env_vars: &HashMap<String, String>) {
    if env_vars["BIND"].is_empty() {
      println!("[{}] BIND cannot be empty! Specify it using --bind <bind> or set SQUARE_BIND in the enviroment", Log::error("ERR"));
      process::exit(1);
    }

    if env_vars["ENDPOINT"].is_empty() {
      println!("[{}] Endpoint cannot be empty! Specify it using --endpoint <endpoint> or set SQUARE_ENDPOINT in the enviroment", Log::error("ERR"));
      process::exit(1);
    }

    if env_vars["DATA_FOLDER"].is_empty() {
      println!("[{}] DATA_FOLDER cannot be empty! Specify it using --file <data folder> or set SQUARE_DATA_FOLDER in the enviroment", Log::error("ERR"));
      process::exit(1);
    }

    if env_vars["WEB_CRT"].is_empty() && !env_vars["WEB_KEY"].is_empty() || !env_vars["WEB_CRT"].is_empty() && env_vars["WEB_KEY"].is_empty() {
      println!(
        "[{}] {} is empty, but {} is not.",
        Log::info("INFO"),
        Log::info("WEB_CRT"),
        Log::info("WEB_KEY")
      );
    }
  }

  #[tokio::main(flavor = "multi_thread", worker_threads = 10)]
  async fn run() {
    let env_vars: HashMap<String,
    String> = Env.get_env_vars_from_session();
    Self::check_variables(&env_vars);

    let endpoint = &env_vars["ENDPOINT"];
    let max_connections: usize = env_vars["MAX_CONNECTIONS"].parse().unwrap_or_else(|_| {
      eprintln!("Error: MAX_CONNECTIONS must be a valid positive integer.");
      process::exit(1);
    });

    let api = warp::post()
    .and(warp::path(endpoint.clone()))
    .and(warp::body::json())
    .and(warp::header::optional("Authorization"))
    .and(warp::addr::remote())
    .map(
      move |params: RequestParams, auth_header: Option<String>, addr: Option<SocketAddr>| {
        println!("-------------------------");
        if let Some(auth_header) = auth_header {
          println!("[{}] {}", Log::info(addr.unwrap()), Log::info(&params.query));
          return Response::respond(Entry::new().handle_cmd(&params.query));
        } else {
          println!("[{}] No Authorization header found", Log::info(addr.unwrap()));
          return Response::respond(create_response(
            "403",
            "Authentication Required",
            None,
            Some("No data was found in the Authorization header!"),
          ));
        }
      },
    );

    // Convert the api filter into a service
    let api_service = warp::service(api);

    // Apply the Tower concurrency limit
    let api_service = api_service.with(tower::limit::concurrency::ConcurrencyLimit::new(max_connections));

    // Build the service with the Tower middleware
    let svc = ServiceBuilder::new()
    .layer(TraceLayer::new_for_http())
    .service(api_service);
    
    let socket_addr: SocketAddr = env_vars["BIND"].parse().expect("Failed to parse Socket Address");

    println!(
      "[{}] Server runned on on {}/{}",
      Log::success("SUCCESS"),
      Log::success(socket_addr),
      Log::success(&env_vars["ENDPOINT"])
    );

    if !env_vars["WEB_CRT"].is_empty() && !env_vars["WEB_KEY"].is_empty() {
      println!("[{}] TLS used...", Log::info("INFO"));
      warp::serve(svc)
      .tls()
      .cert_path(&env_vars["WEB_CRT"])
      .key_path(&env_vars["WEB_KEY"])
      .run(socket_addr)
      .await;
    } else {
      warp::serve(svc).run(socket_addr).await;
    }
  }
}

Error:

error[E0599]: the method `with` exists for struct `FilteredService<Map<..., ...>>`, but its trait bounds were not satisfied        --> src/server/server.rs:105:35                                  |                                                           105 | ...vice = api_service.with(tower::limit::concurrency::C...    |                       ^^^^ method cannot be called on `FilteredService<Map<..., ...>>` due to unsatisfied trait bounds        |                                                              ::: /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/warp-0.3.6/src/filter/service.rs:62:1                             |                                                           62  | pub struct FilteredService<F> {                               | -----------------------------
    | |
    | doesn't satisfy `_: FilterBase`                               | doesn't satisfy `_: Filter`
    |
    = note: the full type name has been written to '/root/square-db/target/debug/deps/squaredb-566fdeb758a9156b.long-type-9237493750586144620.txt'
    = note: the following trait bounds were not satisfied:
            `warp::filter::service::FilteredService<warp::filter::map::Map<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<impl warp::Filter + warp::filter::FilterBase<Extract = (), Error = Rejection> + Copy, Exact<warp::path::internal::Opaque<std::string::String>>>, impl warp::Filter + warp::filter::FilterBase<Extract = (RequestParams,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::string::String>,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::net::SocketAddr>,), Error = Infallible> + Copy>, {closure@src/server/server.rs:84:7: 84:90}>>: warp::filter::FilterBase`
            which is required by `warp::filter::service::FilteredService<warp::filter::map::Map<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<impl warp::Filter + warp::filter::FilterBase<Extract = (), Error = Rejection> + Copy, Exact<warp::path::internal::Opaque<std::string::String>>>, impl warp::Filter + warp::filter::FilterBase<Extract = (RequestParams,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::string::String>,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::net::SocketAddr>,), Error = Infallible> + Copy>, {closure@src/server/server.rs:84:7: 84:90}>>: warp::Filter`
            `&warp::filter::service::FilteredService<warp::filter::map::Map<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<impl warp::Filter + warp::filter::FilterBase<Extract = (), Error = Rejection> + Copy, Exact<warp::path::internal::Opaque<std::string::String>>>, impl warp::Filter + warp::filter::FilterBase<Extract = (RequestParams,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::string::String>,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::net::SocketAddr>,), Error = Infallible> + Copy>, {closure@src/server/server.rs:84:7: 84:90}>>: warp::filter::FilterBase`
            which is required by `&warp::filter::service::FilteredService<warp::filter::map::Map<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<impl warp::Filter + warp::filter::FilterBase<Extract = (), Error = Rejection> + Copy, Exact<warp::path::internal::Opaque<std::string::String>>>, impl warp::Filter + warp::filter::FilterBase<Extract = (RequestParams,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::string::String>,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::net::SocketAddr>,), Error = Infallible> + Copy>, {closure@src/server/server.rs:84:7: 84:90}>>: warp::Filter`
            `&mut warp::filter::service::FilteredService<warp::filter::map::Map<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<impl warp::Filter + warp::filter::FilterBase<Extract = (), Error = Rejection> + Copy, Exact<warp::path::internal::Opaque<std::string::String>>>, impl warp::Filter + warp::filter::FilterBase<Extract = (RequestParams,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::string::String>,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::net::SocketAddr>,), Error = Infallible> + Copy>, {closure@src/server/server.rs:84:7: 84:90}>>: warp::filter::FilterBase`
            which is required by `&mut warp::filter::service::FilteredService<warp::filter::map::Map<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<warp::filter::and::And<impl warp::Filter + warp::filter::FilterBase<Extract = (), Error = Rejection> + Copy, Exact<warp::path::internal::Opaque<std::string::String>>>, impl warp::Filter + warp::filter::FilterBase<Extract = (RequestParams,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::string::String>,), Error = Rejection> + Copy>, impl warp::Filter + warp::filter::FilterBase<Extract = (std::option::Option<std::net::SocketAddr>,), Error = Infallible> + Copy>, {closure@src/server/server.rs:84:7: 84:90}>>: warp::Filter`

error[E0061]: this function takes 2 arguments but 1 argument was supplied
   --> src/server/server.rs:105:40
    |
105 | ...th(tower::limit::concurrency::ConcurrencyLimit::new(max_connections...
    |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----------------- an argument of type `usize` is missing
    |
note: associated function defined here
   --> /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tower-0.4.13/src/limit/concurrency/service.rs:28:12
    |
28  |     pub fn new(inner: T, max: usize) -> Self {
    |            ^^^
help: provide the argument
    |
105 |     let api_service = api_service.with(tower::limit::concurrency::ConcurrencyLimit::new(max_connections, /* usize */));
    |                                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some errors have detailed explanations: E0061, E0599.
For more information about an error, try `rustc --explain E0061`.
warning: `squaredb` (bin "squaredb") generated 2 warnings
error: could not compile `squaredb` (bin "squaredb") due to 2 previous errors; 2 warnings emitted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants