Robust proxying with retry

Also includes upgraded hyper-reverse-proxy, hyper, and futures.

This is looking and feeling way more ergonomic.
This commit is contained in:
Brandon Thomas committed 2020-09-10 04:18:08 -04:00
1 parent 74de16f952
commit e1c39e65de
5 files changed
+556 -449

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
use anyhow::Result as AnyhowResult;
use futures::TryStreamExt;
use hyper::http::HeaderValue;
use hyper::{Body, Request, HeaderMap, Response, StatusCode};
use hyper::body::Bytes;
/// NB: This much match the shape of SpeakRequest in the 'voder/tts_service' code.
/// This is used for both /speak and /speak_spectrogram requests.
#[derive(Deserialize, Debug)]
pub struct ExternalSpeakRequest {
/// Slug for the speaker
pub speaker: String,
/// Raw text to be spoken
pub text: String,
}
/// The full request
pub struct ExternalHttpRequest {
pub headers: HeaderMap<HeaderValue>,
pub speak_request: ExternalSpeakRequest,
}
#[derive(Serialize, Debug)]
pub struct InternalSpeakRequest {
/// Slug for the speaker
pub speaker: String,
/// Raw text to be spoken
pub text: String,
/// Retry attempt.
/// The first request is "0", and all subsequent requests are incremented.
/// Subsequent requests do not trigger the rate limiter.
pub retry_attempt_number: u8,
/// Admin/debug requests get to skip the rate limiter.
pub skip_rate_limiter: bool,
}
pub enum ErrorType {
/// The proxy couldn't find a healthy host (or it died mid-connection)
ProxyError,
// The backend server reported a 500
ServerError,
/// Client is rate limited
RateLimitError,
}
pub struct ErrorResponse {
/// The type of error
pub error_type: ErrorType,
/// Description of the error
pub error_description: String,
}
impl ExternalHttpRequest {
pub async fn decode_request(request: Request<Body>) -> AnyhowResult<Self> {
let headers = request.headers().clone();
let (_parts, body) = request.into_parts();
let body_bytes = body_to_bytes(body).await?;
let speak_request = serde_json::from_slice::<ExternalSpeakRequest>(&body_bytes)?;
Ok(ExternalHttpRequest {
headers: headers,
speak_request: speak_request,
})
}
}
impl ErrorType {
pub fn status_code(&self) -> StatusCode {
match *self {
ErrorType::ProxyError =>StatusCode::INTERNAL_SERVER_ERROR,
ErrorType::ServerError => StatusCode::INTERNAL_SERVER_ERROR,
ErrorType::RateLimitError => StatusCode::TOO_MANY_REQUESTS,
}
}
}
impl ErrorResponse {
pub fn to_response(&self) -> Response<Body> {
let status_code = self.error_type.status_code();
let body = Body::from(self.error_description.clone());
Response::builder()
.status(status_code)
.body(body)
.unwrap()
}
}
async fn body_to_bytes(body: Body) -> AnyhowResult<Vec<u8>> {
// Also: let body_bytes = hyper::body::to_bytes(body)
let bytes = body.try_fold(Vec::new(), |mut data, chunk| async move {
data.extend_from_slice(&chunk);
Ok(data)
}).await?;
Ok(bytes)
}
+84 -52
View File
@@ -1,32 +1,33 @@
#![feature(toowned_clone_into)]
#[macro_use] extern crate anyhow;
#[macro_use] extern crate log;
#[macro_use] extern crate serde_derive;
pub mod api;
pub mod newrelic_logger;
pub mod speak_proxy;
use anyhow::Result as AnyhowResult;
use crate::newrelic_logger::{NewRelicLogger, MaybeNewRelicTransaction};
use crate::speak_proxy::{speak_proxy, speak_proxy_with_retry};
use crate::speak_proxy::speak_proxy_with_retry;
use futures::future::{self, Future};
use hyper::Method;
use hyper::header::HeaderValue;
use hyper::http::header::HeaderName;
use hyper::rt::Stream;
use hyper::server::conn::AddrStream;
use hyper::service::{service_fn, make_service_fn};
use hyper::{Body, Request, Response, Server};
use hyper::{Method, StatusCode};
use rand::seq::IteratorRandom;
use std::collections::HashMap;
use std::convert::Infallible;
use std::env;
use std::fmt::Debug;
use std::fmt::Display;
use std::net::SocketAddr;
use std::net::{SocketAddr, IpAddr};
use std::str::FromStr;
use std::sync::Arc;
type BoxFut = Box<dyn Future<Item=Response<Body>, Error=hyper::Error> + Send>;
const ENV_DEFAULT_ROUTE : &'static str = "DEFAULT_ROUTE";
const ENV_NEWRELIC_API_KEY : &'static str = "NEWRELIC_API_KEY";
const ENV_PROXY_CONFIG_FILE : &'static str = "PROXY_CONFIG_FILE";
@@ -88,17 +89,6 @@ fn get_env_num<T>(env_name: &str, default: T) -> AnyhowResult<T>
}
}
fn _debug_request(req: Request<Body>) -> BoxFut {
let body_str = format!("{:?}", req);
let response = Response::new(Body::from(body_str));
Box::new(future::ok(response))
}
fn health_check_response(_req: Request<Body>) -> BoxFut {
let response = Response::new(Body::from("healthy"));
Box::new(future::ok(response))
}
pub struct Router {
pub routes: HashMap<String, String>,
pub default_route: String,
@@ -120,7 +110,66 @@ impl Router {
}
}
fn main() -> AnyhowResult<()> {
fn debug_request(req: Request<Body>) -> Result<Response<Body>, Infallible> {
let body_str = format!("{:?}", req);
Ok(Response::new(Body::from(body_str)))
}
fn health_check_response(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("healthy")))
}
pub async fn handle(
client_ip: IpAddr,
req: Request<Body>,
router: Arc<Router>,
newrelic_logger: Arc<NewRelicLogger>) -> Result<Response<Body>, Infallible>
{
match req.uri().path() {
"/speak" => {
let nr_transaction = newrelic_logger.web_transaction("/speak");
let result = speak_proxy_with_retry(client_ip, req, router, nr_transaction, "/speak").await;
match result {
Ok(response) => Ok(response),
Err(error) => Ok(error.to_response()),
}
},
"/speak_spectrogram" => {
let nr_transaction = newrelic_logger.web_transaction("/speak_spectrogram");
let result = speak_proxy_with_retry(client_ip, req, router, nr_transaction, "/speak_spectrogram").await;
match result {
Ok(response) => Ok(response),
Err(error) => Ok(error.to_response()),
}
},
"/proxy_health" => {
let _droppable_transaction = newrelic_logger.web_transaction("/proxy_health");
health_check_response(req)
},
_ => {
let _droppable_transaction = newrelic_logger
.web_transaction("unmatched endpoint");
let forward = router.get_random_host();
info!("Forwarding to `{}` random host: {}", &forward, req.uri());
match hyper_reverse_proxy::call(client_ip, &forward, req).await {
Ok(response) => {
Ok(response)
},
Err(_) => {
Ok(Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from("unknown proxy error"))
.unwrap())
}
}
},
}
}
#[tokio::main]
async fn main() {
if env::var(ENV_RUST_LOG)
.as_ref()
.ok()
@@ -134,7 +183,8 @@ fn main() -> AnyhowResult<()> {
env_logger::init();
let default_route = get_env_string(ENV_DEFAULT_ROUTE, DEFAULT_DEFAULT_ROUTE);
let service_port = get_env_num::<u16>(ENV_SERVICE_PORT, DEFAULT_SERVICE_PORT)?;
let service_port = get_env_num::<u16>(ENV_SERVICE_PORT, DEFAULT_SERVICE_PORT)
.expect("should have env var");
let newrelic_api_key = get_env_string(ENV_NEWRELIC_API_KEY, DEFAULT_NEWRELIC_API_KEY);
info!("Default route: {}", default_route);
@@ -142,7 +192,8 @@ fn main() -> AnyhowResult<()> {
let proxy_configs_file = get_env_string(ENV_PROXY_CONFIG_FILE, DEFAULT_PROXY_CONFIG_FILE);
info!("Proxy config file: {}", proxy_configs_file);
let proxy_configs = ProxyConfigs::load_from_file(&proxy_configs_file)?;
let proxy_configs = ProxyConfigs::load_from_file(&proxy_configs_file)
.expect("should have configs");
info!("Proxy configs: {:?}", proxy_configs);
let mut route_map = HashMap::new();
@@ -165,49 +216,30 @@ fn main() -> AnyhowResult<()> {
let newrelic_logger = Arc::new(newrelic_logger);
let make_service = make_service_fn(move |socket: &AddrStream| {
let remote_addr = socket.remote_addr();
info!("Got a request from: {:?}", remote_addr);
let make_service = make_service_fn(move |conn: &AddrStream| {
let remote_addr = conn.remote_addr().ip();
let router2 = router.clone();
let newrelic_logger2 = newrelic_logger.clone();
service_fn(move |req: Request<Body>| {
async move {
let router3 = router2.clone();
let newrelic_logger3 = newrelic_logger2.clone();
match (req.method(), req.uri().path()) {
(&Method::POST, "/speak") => {
let nr_transaction = newrelic_logger3.web_transaction("/speak");
speak_proxy_with_retry(req, remote_addr.clone(), router3, nr_transaction, "/speak")
},
(&Method::POST, "/speak_spectrogram") => {
let nr_transaction = newrelic_logger3.web_transaction("/speak_spectrogram");
speak_proxy(req, remote_addr.clone(), router3, nr_transaction, "/speak_spectrogram")
},
(&Method::GET, "/proxy_health") => {
let _droppable_transaction = newrelic_logger3.web_transaction("/proxy_health");
health_check_response(req)
},
_ => {
let _droppable_transaction = newrelic_logger3.web_transaction("unmatched endpoint");
let forward = router3.get_random_host();
info!("Forwarding to `{}` random host: {}", &forward, req.uri());
hyper_reverse_proxy::call(remote_addr.ip(), &forward, req)
}
}
})
Ok::<_, Infallible>(service_fn(move |req| {
let router4 = router3.clone();
let newrelic_logger4 = newrelic_logger3.clone();
handle(remote_addr, req, router4, newrelic_logger4)
}))
}
});
let addr = ([0, 0, 0, 0], service_port).into();
info!("Running server on {:?}", addr);
let server = Server::bind(&addr)
.serve(make_service)
.map_err(|e| eprintln!("server error: {}", e));
let server = Server::bind(&addr).serve(make_service);
hyper::rt::run(server);
Ok(())
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}
+94 -74
View File
@@ -1,72 +1,45 @@
use anyhow::Result as AnyhowResult;
use crate::{BoxFut, Router};
use crate::Router;
use crate::api::{ExternalSpeakRequest, ExternalHttpRequest, InternalSpeakRequest, ErrorResponse, ErrorType};
use crate::newrelic_logger::{NewRelicLogger, MaybeNewRelicTransaction};
use futures::TryStreamExt;
use futures::future::{self, Future};
use hyper::Method;
use hyper::header::HeaderValue;
use hyper::http::header::HeaderName;
use hyper::rt::Stream;
use hyper::server::conn::AddrStream;
use hyper::service::{service_fn, make_service_fn};
use hyper::{Body, Request, Response, Server};
use hyper::{Body, Request, Response, Server, HeaderMap};
use hyper::{Method, StatusCode};
use hyper_reverse_proxy::ProxyError;
use rand::seq::IteratorRandom;
use std::collections::HashMap;
use std::env;
use std::convert::Infallible;
use std::fmt::Debug;
use std::fmt::Display;
use std::net::SocketAddr;
use std::net::{SocketAddr, IpAddr};
use std::str::FromStr;
use std::sync::Arc;
use futures::IntoFuture;
use std::time::Duration;
use std::{env, thread};
/// NB: This much match the shape of SpeakRequest in the 'voder/tts_service' code.
/// This is used for both /speak and /speak_spectrogram requests.
#[derive(Serialize, Deserialize, Debug)]
pub struct SpeakRequest {
/// Slug for the speaker
speaker: String,
/// Raw text to be spoken
text: String,
}
struct RequestDetails {
pub request_bytes: Vec<u8>,
pub speaker: String,
}
pub fn speak_proxy_with_retry(
req: Request<Body>,
remote_addr: SocketAddr,
pub async fn speak_proxy_with_retry(
ip_addr: IpAddr,
request: Request<Body>,
router: Arc<Router>,
transaction: MaybeNewRelicTransaction,
endpoint: &'static str) -> BoxFut
_transaction: MaybeNewRelicTransaction,
endpoint: &'static str) -> Result<Response<Body>, ErrorResponse>
{
speak_proxy(req, remote_addr, router, transaction, endpoint)
.then(|result| {
match result {
Ok(t) => future::ok(t),
Err(t) => future::err(t),
}
})
.boxed()
}
let mut attempt : u8 = 0;
pub fn speak_proxy(
req: Request<Body>,
remote_addr: SocketAddr,
router: Arc<Router>,
transaction: MaybeNewRelicTransaction,
endpoint: &'static str) -> BoxFut
{
let mut headers = req.headers().clone();
let external_http_request = ExternalHttpRequest::decode_request(request).await.unwrap();
// This is the IP of the Digital Ocean load balancer.
let gateway_ip = HeaderValue::from_str(&remote_addr.ip().to_string())
let gateway_ip = HeaderValue::from_str(&ip_addr.to_string())
.ok()
.unwrap_or(HeaderValue::from_static(""));
// This is the IP of the upstream client browser.
let upstream_client_ip = req.headers().get(HeaderName::from_static("x-forwarded-for"))
let upstream_client_ip = external_http_request.headers.get(HeaderName::from_static("x-forwarded-for"))
.map(|ip| ip.to_str().unwrap_or(""))
.unwrap_or("");
@@ -74,42 +47,89 @@ pub fn speak_proxy(
.ok()
.unwrap_or(HeaderValue::from_static(""));
headers.insert(HeaderName::from_static("forwarded"), upstream_client_ip.clone());
headers.insert(HeaderName::from_static("x-forwarded-for"), upstream_client_ip.clone());
let mut headers_to_proxy = external_http_request.headers.clone();
headers_to_proxy.insert(HeaderName::from_static("forwarded"), upstream_client_ip.clone());
headers_to_proxy.insert(HeaderName::from_static("x-forwarded-for"), upstream_client_ip.clone());
// Unfortunately it looks like this middleware trounces the standard headers, so
// here we put it somewhere it won't be overwritten.
headers.insert(HeaderName::from_static("x-voder-proxy-for"), upstream_client_ip.clone());
headers.insert(HeaderName::from_static("x-gateway-ip"), gateway_ip);
headers_to_proxy.insert(HeaderName::from_static("x-voder-proxy-for"), upstream_client_ip.clone());
headers_to_proxy.insert(HeaderName::from_static("x-gateway-ip"), gateway_ip);
Box::new(req.into_body().concat2().map(move |b| { // Builds a BoxedFut to return
let request_bytes = b.as_ref();
// We're going to be changing the request body length, so remove the reported value
// so Hyper doesn't choke on any mismatch.
headers_to_proxy.remove(HeaderName::from_static("content-length"));
let request = serde_json::from_slice::<SpeakRequest>(request_bytes)
.unwrap();
// The proxy host is a Kubernetes load balancer. We're not doing the round robin magic here,
// so it makes sense to reuse the same value for each retry.
let load_balancer_hostname = router.get_speaker_host(&external_http_request.speak_request.speaker);
RequestDetails {
request_bytes: request_bytes.to_vec(),
speaker: request.speaker,
}
}).and_then(move |request_details: RequestDetails| {
let proxy_host = router.get_speaker_host(&request_details.speaker);
loop {
let internal_speak_request = InternalSpeakRequest {
speaker: external_http_request.speak_request.speaker.clone(),
text: external_http_request.speak_request.text.clone(),
retry_attempt_number: attempt,
skip_rate_limiter: false,
};
info!("Routing {} for {} to {}", endpoint, &request_details.speaker, &proxy_host);
let result = speak_proxy(
ip_addr,
internal_speak_request,
headers_to_proxy.clone(),
&load_balancer_hostname,
endpoint).await;
transaction.add_attribute("speaker", &request_details.speaker);
let mut request_builder = Request::builder();
request_builder.method(Method::POST)
.uri(endpoint);
for (k, v) in headers.iter() {
request_builder.header(k, v);
match result {
Ok(good_response) => return Ok(good_response),
Err(_) => {},
}
let new_req = request_builder
.body(Body::from(request_details.request_bytes))
.unwrap();
attempt += 1;
hyper_reverse_proxy::call(remote_addr.ip(), &proxy_host, new_req)
}))
thread::sleep(Duration::from_millis(400)); // TODO: Needs backoff + jitter
if attempt > 2 {
return Err(ErrorResponse {
error_type: ErrorType::ProxyError,
error_description: "max internal retry attempts reached".to_string(),
});
}
}
}
#[derive(Serialize, Debug)]
pub struct ResponseError {
pub reason: String,
}
async fn speak_proxy(
ip_addr: IpAddr,
internal_speak_request: InternalSpeakRequest,
headers: HeaderMap<HeaderValue>,
load_balancer_hostname: &str,
endpoint: &'static str) -> Result<Response<Body>, ()>
{
info!("Routing {} for {} to {} (attempt # {})", endpoint, &internal_speak_request.speaker,
&load_balancer_hostname, internal_speak_request.retry_attempt_number);
let mut request_builder = Request::builder()
.method(Method::POST)
.uri(endpoint);
for (k, v) in headers.iter() {
// NB: Handling move because of builder class
request_builder = request_builder.header(k, v);
}
let json_speak_request = serde_json::to_string(&internal_speak_request).unwrap();
let request = request_builder
.body(Body::from(json_speak_request))
.unwrap();
match hyper_reverse_proxy::call(ip_addr, &load_balancer_hostname, request).await {
Ok(result) => Ok(result),
Err(_result) => Err(()), // TODO: Surface this?
}
}