async fn run(
    opts: Arc<Opts>,
    tx: Sender<String>,
    req: Request<Body>,
) -> Result<Response<Body>, Error> {
    match (req.method(), req.uri().path()) {
        (&Method::GET, "/bench") => {
            // FIXME: this is terrible
            let connection = establish_connection();
            let mut res: Vec<Benchmark> = benchmarks
                .order(created_at.desc())
                .limit(100)
                .load(&connection)?;
            res.reverse();
            let res = serde_json::to_string(&res)?;
            Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, "application/json")
                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
                .body(Body::from(res))
                .map_err(|_| Error::Other("response error"))
        }
        // Simply echo the body back to the client.
        (&Method::POST, "/bench") => {
            //
            let sig = req
                .headers()
                .get("X-Hub-Signature-256")
                .and_then(|v| v.to_str().ok())
                .map(ToString::to_string);

            let event = req
                .headers()
                .get("X-GitHub-Event")
                .and_then(|v| v.to_str().ok())
                .map(ToString::to_string)
                .ok_or_else(|| Error::BadRequest("missing X-GitHub-Event header".into()))?;

            if event != "push" {
                return Err(Error::BadRequest(format!(
                    "Only runs on `push` but got {}",
                    event
                )));
            };

            let body = hyper::body::to_bytes(req.into_body()).await?;

            if let Some(key) = &opts.key {
                let mut mac = HmacSha256::new_from_slice(key.as_bytes())?;
                mac.update(&body);
                let result = format!(
                    "sha256={}",
                    base16::encode_lower(&mac.finalize().into_bytes())
                );
                if sig != Some(result) {
                    //FIXME: Error
                    let mut error = Response::new(Body::from("bad hmac"));
                    *error.status_mut() = StatusCode::FORBIDDEN;
                    return Ok(error);
                };
            };

            let body = serde_json::from_slice::<Value>(&body)?;

            let ghref = body
                .get("ref")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::BadRequest("`ref` is missing".into()))?
                .to_string();

            if ghref != "refs/heads/main" {
                return Ok(Response::new(Body::from(format!(
                    r#"{{"branch": "{}"}}"#,
                    ghref
                ))));
            }

            let hash = body
                .get("after")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::BadRequest("`after` is missing".into()))?
                .to_string();

            tx.send(hash.clone()).await?;

            Ok(Response::new(Body::from(format!(
                r#"{{"hash": "{}"}}"#,
                hash
            ))))
        }

        // Return the 404 Not Found for other routes.
        _ => {
            let mut error = Response::new(Body::from("not found"));
            *error.status_mut() = StatusCode::NOT_FOUND;
            Ok(error)
        }
    }
}
/// This is our service handler. It receives a Request, routes on its
/// path, and returns a Future of a Response.
This is our service handler. It receives a Request, routes on its
path, and returns a Future of a Response.
This is our service handler . It receives a Request routes on its path and returns a Future of a Response .
async fn run(
    opts: Arc<Opts>,
    tx: Sender<String>,
    req: Request<Body>,
) -> Result<Response<Body>, Error> {
    match (req.method(), req.uri().path()) {
        (&Method::GET, "/bench") => {
            // FIXME: this is terrible
            let connection = establish_connection();
            let mut res: Vec<Benchmark> = benchmarks
                .order(created_at.desc())
                .limit(100)
                .load(&connection)?;
            res.reverse();
            let res = serde_json::to_string(&res)?;
            Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, "application/json")
                .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
                .body(Body::from(res))
                .map_err(|_| Error::Other("response error"))
        }
        // Simply echo the body back to the client.
        (&Method::POST, "/bench") => {
            //
            let sig = req
                .headers()
                .get("X-Hub-Signature-256")
                .and_then(|v| v.to_str().ok())
                .map(ToString::to_string);
            let event = req
                .headers()
                .get("X-GitHub-Event")
                .and_then(|v| v.to_str().ok())
                .map(ToString::to_string)
                .ok_or_else(|| Error::BadRequest("missing X-GitHub-Event header".into()))?;
            if event != "push" {
                return Err(Error::BadRequest(format!(
                    "Only runs on `push` but got {}",
                    event
                )));
            };
            let body = hyper::body::to_bytes(req.into_body()).await?;
            if let Some(key) = &opts.key {
                let mut mac = HmacSha256::new_from_slice(key.as_bytes())?;
                mac.update(&body);
                let result = format!(
                    "sha256={}",
                    base16::encode_lower(&mac.finalize().into_bytes())
                );
                if sig != Some(result) {
                    //FIXME: Error
                    let mut error = Response::new(Body::from("bad hmac"));
                    *error.status_mut() = StatusCode::FORBIDDEN;
                    return Ok(error);
                };
            };
            let body = serde_json::from_slice::<Value>(&body)?;
            let ghref = body
                .get("ref")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::BadRequest("`ref` is missing".into()))?
                .to_string();
            if ghref != "refs/heads/main" {
                return Ok(Response::new(Body::from(format!(
                    r#"{{"branch": "{}"}}"#,
                    ghref
                ))));
            }
            let hash = body
                .get("after")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::BadRequest("`after` is missing".into()))?
                .to_string();
            tx.send(hash.clone()).await?;
            Ok(Response::new(Body::from(format!(
                r#"{{"hash": "{}"}}"#,
                hash
            ))))
        }
        // Return the 404 Not Found for other routes.
        _ => {
            let mut error = Response::new(Body::from("not found"));
            *error.status_mut() = StatusCode::NOT_FOUND;
            Ok(error)
        }
    }
}
async fn run ( opts : Arc < Opts > , tx : Sender < String > , req : Request < Body > , ) -> Result < Response < Body > , Error > { match ( req . method ( ) , req . uri ( ) . path ( ) ) { ( & Method :: GET , " " ) => { // FIXME: this is terrible let connection = establish_connection ( ) ; let mut res : Vec < Benchmark > = benchmarks . order ( created_at . desc ( ) ) . limit ( 100 ) . load ( & connection ) ? ; res . reverse ( ) ; let res = serde_json :: to_string ( & res ) ? ; Response :: builder ( ) . status ( StatusCode :: OK ) . header ( header :: CONTENT_TYPE , " " ) . header ( header :: ACCESS_CONTROL_ALLOW_ORIGIN , " " ) . body ( Body :: from ( res ) ) . map_err ( | _ | Error :: Other ( " " ) ) } // Simply echo the body back to the client. ( & Method :: POST , " " ) => { // let sig = req . headers ( ) . get ( " " ) . and_then ( | v | v . to_str ( ) . ok ( ) ) . map ( ToString :: to_string ) ; let event = req . headers ( ) . get ( " " ) . and_then ( | v | v . to_str ( ) . ok ( ) ) . map ( ToString :: to_string ) . ok_or_else ( | | Error :: BadRequest ( " " . into ( ) ) ) ? ; if event != " " { return Err ( Error :: BadRequest ( format ! ( " " event ) ) ) ; } ; let body = hyper :: body :: to_bytes ( req . into_body ( ) ) . await ? ; if let Some ( key ) = & opts . key { let mut mac = HmacSha256 :: new_from_slice ( key . as_bytes ( ) ) ? ; mac . update ( & body ) ; let result = format ! ( " " base16 encode_lower ( mac finalize ( ) into_bytes ( ) ) ) ; if sig != Some ( result ) { //FIXME: Error let mut error = Response :: new ( Body :: from ( " " ) ) ; * error . status_mut ( ) = StatusCode :: FORBIDDEN ; return Ok ( error ) ; } ; } ; let body = serde_json :: from_slice :: < Value > ( & body ) ? ; let ghref = body . get ( " " ) . and_then ( Value :: as_str ) . ok_or_else ( | | Error :: BadRequest ( " " . into ( ) ) ) ? . to_string ( ) ; if ghref != " " { return Ok ( Response :: new ( Body :: from ( format ! ( r#"{{"branch": "{}"}}"# ghref ) ) ) ) ; } let hash = body . get ( " " ) . and_then ( Value :: as_str ) . ok_or_else ( | | Error :: BadRequest ( " " . into ( ) ) ) ? . to_string ( ) ; tx . send ( hash . clone ( ) ) . await ? ; Ok ( Response :: new ( Body :: from ( format ! ( r#"{{"hash": "{}"}}"# hash ) ) ) ) } // Return the 404 Not Found for other routes. _ => { let mut error = Response :: new ( Body :: from ( " " ) ) ; * error . status_mut ( ) = StatusCode :: NOT_FOUND ; Ok ( error ) } } }
This is our service handler.
This is our service handler .
opts
Arc<Opts>
tx
Sender<String>
req
Request<Body>