Browse Source

use actix and maintain queue

Steven Jacobs 11 months ago
parent
commit
5edfd4ef94
5 changed files with 1073 additions and 346 deletions
  1. 1000 228
      Cargo.lock
  2. 7 3
      Cargo.toml
  3. 0 69
      src/client.rs
  4. 66 0
      src/main.rs
  5. 0 46
      src/server.rs

File diff suppressed because it is too large
+ 1000 - 228
Cargo.lock


+ 7 - 3
Cargo.toml

@@ -5,6 +5,10 @@ authors = ["Steven Jacobs <stjacobs@fastmail.fm>"]
 edition = "2018"
 
 [dependencies]
-hyper = "0.12"
-hyper-tls = "0.3.2"
-futures = "0.1"
+http = "0.1"
+actix-web = "1.0.0-alpha.6"
+
+log = "0.4.0"
+env_logger = "0.6.1"
+
+rand = "0.6"

+ 0 - 69
src/client.rs

@@ -1,69 +0,0 @@
-extern crate hyper;
-extern crate hyper_tls;
-
-use hyper::rt::{self, Future, Stream};
-use hyper::{Body, Client, Method, Request};
-use hyper_tls::HttpsConnector;
-// use std::io::{self, Write};
-
-fn main() {
-    rt::run(rt::lazy(|| {
-        let https = HttpsConnector::new(4).expect("TLS initialization failed");
-
-        let client = Client::builder().build::<_, hyper::Body>(https);
-
-        // let uri = "http://httbin.org/ip".parse().unwrap();
-        let uri: hyper::Uri = "http://httpbin.org/post".parse().unwrap();
-
-        let json = r#"{"library":"hyper"}"#;
-        let mut req = Request::new(Body::from(json));
-        *req.method_mut() = Method::POST;
-        *req.uri_mut() = uri.clone();
-        req.headers_mut().insert(
-            hyper::header::CONTENT_TYPE,
-            hyper::header::HeaderValue::from_static("application/json"),
-        );
-
-        //client
-        //    .get(uri)
-        //    .and_then(|res| {
-        //        println!("Response: {}", res.status());
-        //        res
-        //            .into_body()
-        //            .for_each(|chunk| {
-        //                io::stdout()
-        //                    .write_all(&chunk)
-        //                    .map_err(|e| {
-        //                        panic!("example expects stdout is open, error={}", e)
-        //                    })
-        //            })
-        //    })
-        //    .map_err(|err| {
-        //        println!("Error: {}", err);
-        //    })
-
-        let post = client.request(req).and_then(|res| {
-            println!("POST: {}", res.status());
-
-            res.into_body().concat2()
-        });
-
-        let get = client
-            .get("http://httpbin.org/headers".parse().unwrap())
-            .and_then(|res| {
-                println!("GET: {}", res.status());
-
-                res.into_body().concat2()
-            });
-
-        let work = post.join(get);
-
-        work.map(|(posted, got)| {
-            println!("GET: {:?}", got);
-            println!("POST: {:?}", posted);
-        })
-        .map_err(|err| {
-            println!("Error: {}", err);
-        })
-    }))
-}

+ 66 - 0
src/main.rs

@@ -0,0 +1,66 @@
+#[macro_use]
+extern crate log;
+extern crate env_logger;
+
+use rand::prelude::*;
+
+use std::collections::BTreeMap;
+use std::io;
+use std::sync::{Arc, Mutex};
+
+use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
+
+#[derive(Debug)]
+enum Resource {
+    Linode,
+}
+
+#[derive(Debug)]
+struct Job {
+    resource: Resource,
+    uri: http::Uri,
+    id: u32,
+    method: http::Method,
+}
+
+fn print_job(id: u32, state: &Arc<BTreeMap<u32, Job>>) {
+    println!("job: {:?}", state[&id])
+}
+
+fn job_from(req: HttpRequest) -> Job {
+    Job{
+        id: 3,
+        uri: req.uri().clone(),
+        resource: Resource::Linode,
+        method: req.method().clone(),
+    }
+}
+
+/// simple handle
+fn index(state: web::Data<Arc<Mutex<BTreeMap<u32, Job>>>>, req: HttpRequest) -> HttpResponse {
+    println!("{:?}", req);
+    let mut rng = rand::thread_rng();
+    let mut map = state.lock().unwrap();
+    map.insert(rng.gen::<u32>(), job_from(req));
+
+    HttpResponse::Ok().body(format!("Num of jobs: {}. Current jobs: {:?}", map.len(), map.values()))
+}
+
+fn main() -> io::Result<()> {
+    std::env::set_var("RUST_LOG", "actix_web=info");
+    env_logger::init();
+
+    let state = Arc::new(Mutex::new(BTreeMap::<u32, Job>::new()));
+
+    //move is necessary to give closure below ownership of counter
+    HttpServer::new(move || {
+        App::new()
+            .data(state.clone()) // <- create app with shared state
+            // enable logger
+            .wrap(middleware::Logger::default())
+            // register simple handler, handle all methods
+            .service(web::resource("/").to(index))
+    })
+    .bind("127.0.0.1:8080")?
+    .run()
+}

+ 0 - 46
src/server.rs

@@ -1,46 +0,0 @@
-extern crate futures;
-extern crate hyper;
-
-use futures::future;
-use hyper::rt::Future;
-use hyper::service::service_fn;
-use hyper::{Body, Method, Request, Response, Server, StatusCode};
-
-type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>;
-
-fn echo(req: Request<Body>) -> BoxFut {
-    let mut response = Response::new(Body::empty());
-
-    match (req.method(), req.uri().path()) {
-        (&Method::GET, "/") => {
-            *response.body_mut() = Body::from("Try POSTing data to /echo");
-        }
-        (&Method::POST, "/debug") => {
-            let mapping = req
-                .headers()
-                .iter()
-                .map(|(name, value)| {
-                    format!("{}: \"{}\"\n", name.as_str(), value.to_str().unwrap())
-                })
-                .collect::<Vec<_>>()
-                .concat();
-
-            *response.body_mut() = Body::from(mapping);
-        }
-        _ => {
-            *response.status_mut() = StatusCode::NOT_FOUND;
-        }
-    };
-
-    Box::new(future::ok(response))
-}
-
-fn main() {
-    let addr = ([127, 0, 0, 1], 3000).into();
-
-    let server = Server::bind(&addr)
-        .serve(|| service_fn(echo))
-        .map_err(|e| eprintln!("server error: {}", e));
-
-    hyper::rt::run(server);
-}