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
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use std::net::ToSocketAddrs;
use std::error::Error;
use std::sync::Arc;

use tokio;
use tokio::net::{TcpStream, TcpListener};
use tokio::prelude::*;
use tokio::codec::Framed;

use thruster_app::app::App;
use thruster_core::context::Context;
use thruster_core::http::Http;
use thruster_core::response::Response;
use thruster_core::request::Request;

// use std::thread;
// use num_cpus;
// use net2::TcpBuilder;
// #[cfg(not(windows))]
// use net2::unix::UnixTcpBuilderExt;

use crate::thruster_server::ThrusterServer;

pub struct Server<T: 'static + Context<Response = Response> + Send> {
  app: App<Request, T>
}

// impl<T: 'static + Context<Response = Response> + Send> Server<T> {
//   ///
//   /// Starts the app with the default tokio runtime execution model
//   ///
//   pub fn start_work_stealing_optimized(self, host: &str, port: u16) {
//     self.start(host, port);
//   }

//   ///
//   /// Starts the app with a thread pool optimized for small requests and quick timeouts. This
//   /// is done internally by spawning a separate thread for each reactor core. This is valuable
//   /// if all server endpoints are similar in their load, as work is divided evenly among threads.
//   /// As seanmonstar points out though, this is a very specific use case and might not be useful
//   /// for everyday work loads.alloc
//   ///
//   /// See the discussion here for more information:
//   ///
//   /// https://users.rust-lang.org/t/getting-tokio-to-match-actix-web-performance/18659/7
//   ///
//   pub fn start_small_load_optimized(mut self, host: &str, port: u16) {
//     let addr = (host, port).to_socket_addrs().unwrap().next().unwrap();
//     let mut threads = Vec::new();
//     self.app._route_parser.optimize();
//     let arc_app = Arc::new(self.app);

//     for _ in 0..num_cpus::get() {
//       let arc_app = arc_app.clone();
//       threads.push(thread::spawn(move || {
//         let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap();

//         let server = async || {
//           let listener = {
//             let builder = TcpBuilder::new_v4().unwrap();
//             #[cfg(not(windows))]
//             builder.reuse_address(true).unwrap();
//             #[cfg(not(windows))]
//             builder.reuse_port(true).unwrap();
//             builder.bind(addr).unwrap();
//             builder.listen(2048).unwrap()
//           };
//           let listener = TcpListener::from_std(listener, &tokio::reactor::Handle::default()).unwrap();

//           listener.incoming().for_each(move |socket| {
//             process(Arc::clone(&arc_app), socket);
//             Ok(())
//           })
//           .map_err(|err| eprintln!("accept error = {:?}", err))
//         };

//         runtime.spawn(server);
//         runtime.run().unwrap();
//       }));
//     }

//     println!("Server running on {}", addr);

//     for thread in threads {
//       thread.join().unwrap();
//     }

//     fn process<T: Context<Response = Response> + Send>(app: Arc<App<Request, T>>, socket: TcpStream) {
//       let framed = Framed::new(socket, Http);
//       let (tx, rx) = framed.split();

//       let task = tx.send_all(rx.and_then(move |request: Request| {
//             let matched = app.resolve_from_method_and_path(request.method(), request.path());
//             app.resolve(request, matched)
//           }));

//       // Spawn the task that handles the connection.
//       tokio::spawn(task);
//     }
//   }
// }

impl<T: Context<Response = Response> + Send> ThrusterServer for Server<T> {
  type Context = T;
  type Response = Response;
  type Request = Request;

  fn new(app: App<Self::Request, T>) -> Self {
    Server {
      app
    }
  }

  ///
  /// Alias for start_work_stealing_optimized
  ///
  fn start(mut self, host: &str, port: u16) {
    let rt = tokio::runtime::Runtime::new().unwrap();
    let _ = rt.block_on(async {
      let addr = (host, port).to_socket_addrs().unwrap().next().unwrap();

      self.app._route_parser.optimize();

      let listener = TcpListener::bind(&addr).await.unwrap();
      let mut incoming = listener.incoming();
      let arc_app = Arc::new(self.app);

      while let Some(Ok(stream)) = incoming.next().await {
          let cloned = arc_app.clone();
          tokio::spawn(async move {
              if let Err(e) = process(cloned, stream).await {
                  println!("failed to process connection; error = {}", e);
              }
          });
      }
    });

    async fn process<T: Context<Response = Response> + Send>(app: Arc<App<Request, T>>, socket: TcpStream) -> Result<(), Box<dyn Error>> {
      let mut framed = Framed::new(socket, Http);

      while let Some(request) = framed.next().await {
        match request {
            Ok(request) => {
              let matched = app.resolve_from_method_and_path(request.method(), request.path());
              let response = app.resolve(request, matched).await?;
              framed.send(response).await?;
            }
            Err(e) => return Err(e.into()),
        }
      }

      Ok(())
    }
  }
}