rewrite using actix

actix supports websocket, which iron does not.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2019-01-10 21:15:33 +08:00
parent 0f9110b36c
commit 881599d031
3 changed files with 901 additions and 276 deletions

1037
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,22 +4,10 @@ version = "0.1.0"
authors = ["Sean Cross <sean@xobs.io>"]
edition = "2018"
#[dependencies]
#clap = "2.25"
#error-type = "0.1"
#futures = "0.1"
#futures-cpupool = "0.1"
#git2 = "0.8"
#http = "0.1"
#hyper = "0.12"
##hyper-staticfile = "0.3"
#serde_json = "1.0"
#websocket = "0.22"
[dependencies]
actix = "0.7"
actix-web = "0.7"
env_logger = "0.5"
git2 = "0.8"
iron = "0.6"
mount = "0.4"
serde_json = "1.0"
staticfile = "0.5"
websocket = "0.22"
http = "0.1"
serde_json = "1.0"

View File

@ -1,8 +1,11 @@
extern crate actix;
extern crate actix_web;
extern crate git2;
extern crate iron;
extern crate mount;
extern crate http;
extern crate serde_json;
extern crate staticfile;
extern crate env_logger;
// This example serves the docs from target/doc/staticfile at /doc/
//
@ -11,12 +14,12 @@ extern crate staticfile;
use std::path::{Path, PathBuf};
use std::error::Error;
use std::env;
use std::sync::{Arc, Mutex};
use iron::prelude::{Chain, Request, Response};
use iron::{status, Iron, IronResult};
use mount::Mount;
use staticfile::Static;
use actix_web::{
fs, middleware, server, App, HttpMessage, HttpRequest, HttpResponse
};
use git2::Repository;
struct WebHookConfig {
@ -42,44 +45,61 @@ fn redeploy_repo(url: &str, path: &Path, name: &str) -> Result<(), git2::Error>
};
repo.set_head("FETCH_HEAD")?;
// repo.checkout_tree(&branch.into_reference(), Some(git2::build::CheckoutBuilder::new().force().use_theirs(true)))?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force().use_theirs(true)))?;
Ok(())
}
fn webhook(req: &mut Request, config: &WebHookConfig) -> IronResult<Response> {
eprintln!("Webhook Request: {:?}", req);
let wh: serde_json::Value = serde_json::from_reader(&mut req.body).unwrap();
fn webhook_handler((contents, req): (String, HttpRequest<Arc<Mutex<WebHookConfig>>>)) -> HttpResponse {
let config = req.state().lock().unwrap();
// Ensure there's a "Push" event
if let Some(v) = req.headers().get("X-GitHub-Event") {
match v.to_str() {
Err(_) => return HttpResponse::BadRequest().body("invalid X-Github-Event header"),
Ok(o) => {
if o != "push" {
return HttpResponse::Ok().body("Ok");
}
}
}
} else {
return HttpResponse::Ok().body("Ok");
}
// Parse the JSON
let wh: serde_json::Value = match serde_json::from_str(&contents) {
Ok(o) => o,
Err(e) => return HttpResponse::BadRequest().body(format!("invalid json data: {}", e.description())),
};
// Ensure we have a "Secret" parameter, and that it matches the config.
let found_secret = wh.get("secret");
if found_secret.is_none() {
return Ok(Response::with(status::Unauthorized));
return HttpResponse::Unauthorized().body("invalid secret");
}
let found_secret = found_secret.unwrap();
if found_secret != &config.secret {
return Ok(Response::with(status::Unauthorized));
return HttpResponse::Unauthorized().body("invalid secret");
}
// Ensure the repo is valid.
let repository = wh.get("repository");
if repository.is_none() {
eprintln!("No 'repository' key found");
return Ok(Response::with(status::PreconditionRequired));
return HttpResponse::PreconditionFailed().body("no 'repository' key found");
}
let repository = repository.unwrap();
// Ensure there's an HTML URL that's a valid string
let html_url = match repository.get("html_url") {
None => {
eprintln!("No HTML URL found");
return Ok(Response::with(status::PreconditionRequired));
return HttpResponse::PreconditionFailed().body("no repository html_url found");
}
Some(s) => match s.as_str() {
None => {
eprintln!("HTML URL isn't a string");
return Ok(Response::with(status::PreconditionRequired));
return HttpResponse::PreconditionFailed().body("html_url is not a string");
}
Some(s) => s,
},
@ -95,32 +115,32 @@ fn webhook(req: &mut Request, config: &WebHookConfig) -> IronResult<Response> {
}
if !found_match {
eprintln!("URL doesn't start with match");
return Ok(Response::with(status::PreconditionRequired));
return HttpResponse::PreconditionFailed().body("url doesn't start with a recognized prefix");
}
// And ensure the URL is a string
let website_url = match repository.get("website") {
let website_url: http::uri::Uri = match repository.get("website") {
None => {
eprintln!("The website isn't configured for this repo");
return Ok(Response::with(status::PreconditionRequired));
return HttpResponse::PreconditionFailed().body("this repo has no website configured");
}
Some(s) => match s.as_str() {
None => {
eprintln!("Website URL isn't a string");
return Ok(Response::with(status::PreconditionRequired));
return HttpResponse::PreconditionFailed().body("repo's website url is not a string");
}
Some(s) => match iron::Url::parse(s) {
Some(s) => match s.parse() {
Ok(u) => u,
Err(e) => {
eprintln!("Unable to parse URL: {:?}", e);
return Ok(Response::with(status::PreconditionFailed));
return HttpResponse::PreconditionFailed().body("repo's url is unparseable");
}
},
},
};
let target_path = match website_url.path().last() {
let target_path = match website_url.path().split("/").last() {
Some(s) => {
if s.is_empty() {
if s.is_empty() || s == "." || s == ".." {
eprintln!("No website URL path was found -- defaulting to \"current\"");
"current".to_owned()
} else {
@ -129,21 +149,24 @@ fn webhook(req: &mut Request, config: &WebHookConfig) -> IronResult<Response> {
}
None => {
eprintln!("No website URL path was found");
return Ok(Response::with(status::PreconditionFailed));
return HttpResponse::PreconditionFailed().body("no website url path could be found");
}
};
eprintln!("Final path: {:?} / {:?}", config.repo_root, target_path);
if let Err(e) = redeploy_repo(html_url, &config.repo_root, &target_path) {
eprintln!("unable to clone/update repo: {}", e.description());
return Ok(Response::with(status::NotModified));
return HttpResponse::NotModified().body("unable to clone/update repo");
}
Ok(Response::with(status::Ok))
HttpResponse::Ok().body("Ok") // <- send response
}
fn main() {
let mut mount = Mount::new();
env::set_var("RUST_LOG", "actix_web=debug");
env::set_var("RUST_BACKTRACE", "1");
env_logger::init();
let hostaddr = "0.0.0.0:9119".to_owned();
let config = WebHookConfig {
secret: "1234".to_owned(),
@ -151,16 +174,31 @@ fn main() {
repo_prefixes: vec!["https://git.xobs.io/xobs".to_owned()],
};
// Serve the shared JS/CSS at /
mount.mount("/", Static::new(config.repo_root.clone()));
// Listen for calls to "/webhook" and process accordingly
mount.mount(
"/webhook",
Chain::new(move |req: &mut Request| webhook(req, &config)),
);
println!("Doc server running on http://{}", hostaddr);
Iron::new(mount).http(hostaddr).unwrap();
let repo_root_copy = Arc::new(Mutex::new(config.repo_root.clone()));
let config = Arc::new(Mutex::new(config));
let sys = actix::System::new("basic-example");
server::new(move || {
App::with_state(config.clone())
// enable logger
.middleware(middleware::Logger::default())
// Our webhook
.resource("/webhook", |r|
r.method(actix_web::http::Method::POST)
.with_config(webhook_handler, |((cfg, _),)| {
cfg.limit(16384);
})
)
// static files
.handler("/", fs::StaticFiles::new(&*repo_root_copy.lock().unwrap().clone()).unwrap().index_file("index.html"))
})
.bind(hostaddr.clone()).expect(&format!("Can not bind to {}", hostaddr))
.shutdown_timeout(0) // <- Set shutdown timeout to 0 seconds (default 60s)
.start();
let _ = sys.run();
}