Skip to content

Commit

Permalink
refactor: adjust http cache mod
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Mar 23, 2024
1 parent 1775a79 commit 285de17
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 51 deletions.
34 changes: 34 additions & 0 deletions src/cache/http_header.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use crate::utils::split_to_two_trim;
use http::{HeaderName, HeaderValue};
use snafu::{ResultExt, Snafu};
use std::str::FromStr;

#[derive(Debug, Snafu)]
pub enum Error {
InvalidHeaderValue {
value: String,
source: http::header::InvalidHeaderValue,
},
#[snafu(display("Invalid header name {source}, {value}"))]
InvalidHeaderName {
value: String,
source: http::header::InvalidHeaderName,
},
}
type Result<T, E = Error> = std::result::Result<T, E>;

pub type HttpHeader = (HeaderName, HeaderValue);

pub fn convert_headers(header_values: &[String]) -> Result<Vec<HttpHeader>> {
let mut arr = vec![];
for item in header_values {
if let Some([k, v]) = split_to_two_trim(item, ":") {
let name =
HeaderName::from_str(&k).context(InvalidHeaderNameSnafu { value: k.clone() })?;
let value =
HeaderValue::from_str(&v).context(InvalidHeaderValueSnafu { value: v.clone() })?;
arr.push((name, value));
}
}
Ok(arr)
}
9 changes: 5 additions & 4 deletions src/proxy/response_data.rs → src/cache/http_response.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
use super::HttpHeader;
use bytes::Bytes;
use http::{HeaderName, HeaderValue, StatusCode};
use http::StatusCode;
use pingora::{http::ResponseHeader, proxy::Session};

#[derive(Default)]
pub struct ResponseData {
pub struct HttpResponse {
pub status: StatusCode,
pub body: Bytes,
pub max_age: Option<u32>,
pub created_at: Option<u64>,
pub headers: Option<Vec<(HeaderName, HeaderValue)>>,
pub headers: Option<Vec<HttpHeader>>,
}

impl ResponseData {
impl HttpResponse {
pub async fn send(&self, session: &mut Session) -> pingora::Result<usize> {
let mut resp = ResponseHeader::build(self.status, Some(4))?;
resp.insert_header(http::header::CONTENT_LENGTH, self.body.len().to_string())?;
Expand Down
5 changes: 5 additions & 0 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod http_header;
mod http_response;

pub use http_header::*;
pub use http_response::*;
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::error::Error;
use std::io::Write;
use std::sync::Arc;

mod cache;
mod config;
mod proxy;
mod utils;
Expand Down
20 changes: 10 additions & 10 deletions src/proxy/location.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::Upstream;
use crate::{config::LocationConf, utils};
use http::{HeaderName, HeaderValue};
use crate::cache::{convert_headers, HttpHeader};
use crate::config::LocationConf;
use regex::Regex;
use snafu::{ResultExt, Snafu};
use std::sync::Arc;
Expand Down Expand Up @@ -58,14 +58,14 @@ pub struct Location {
path_selector: PathSelector,
host: String,
reg_rewrite: Option<(Regex, String)>,
headers: Option<Vec<(HeaderName, HeaderValue)>>,
proxy_headers: Option<Vec<(HeaderName, HeaderValue)>>,
headers: Option<Vec<HttpHeader>>,
proxy_headers: Option<Vec<HttpHeader>>,
pub upstream: Arc<Upstream>,
}

fn convert_headers(values: &Option<Vec<String>>) -> Result<Option<Vec<(HeaderName, HeaderValue)>>> {
fn format_headers(values: &Option<Vec<String>>) -> Result<Option<Vec<HttpHeader>>> {
if let Some(header_values) = values {
let arr = utils::convert_headers(header_values).map_err(|err| Error::Invalid {
let arr = convert_headers(header_values).map_err(|err| Error::Invalid {
message: err.to_string(),
})?;
Ok(Some(arr))
Expand Down Expand Up @@ -103,8 +103,8 @@ impl Location {
host: conf.host.clone().unwrap_or_default(),
upstream: up.clone(),
reg_rewrite,
headers: convert_headers(&conf.headers)?,
proxy_headers: convert_headers(&conf.proxy_headers)?,
headers: format_headers(&conf.headers)?,
proxy_headers: format_headers(&conf.proxy_headers)?,
})
}
#[inline]
Expand Down Expand Up @@ -134,11 +134,11 @@ impl Location {
None
}
#[inline]
pub fn get_proxy_headers(&self) -> Option<Vec<(HeaderName, HeaderValue)>> {
pub fn get_proxy_headers(&self) -> Option<Vec<HttpHeader>> {
self.proxy_headers.clone()
}
#[inline]
pub fn get_header(&self) -> Option<Vec<(HeaderName, HeaderValue)>> {
pub fn get_header(&self) -> Option<Vec<HttpHeader>> {
self.headers.clone()
}
}
1 change: 0 additions & 1 deletion src/proxy/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod location;
mod logger;
mod response_data;
mod server;
mod state;
mod upstream;
Expand Down
8 changes: 4 additions & 4 deletions src/proxy/server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::logger::Parser;
use super::response_data::ResponseData;
use super::state::State;
use super::{Location, Upstream};
use crate::cache::{convert_headers, HttpResponse};
use crate::config::{LocationConf, PingapConf, UpstreamConf};
use crate::utils;
use async_trait::async_trait;
Expand Down Expand Up @@ -272,20 +272,20 @@ impl Server {
}
Ok(ServerServices { lb, bg_services })
}
fn get_stats_response(&self) -> ResponseData {
fn get_stats_response(&self) -> HttpResponse {
let buf = serde_json::to_vec(&ServerStats {
accepted: self.accepted.load(Ordering::Relaxed),
processing: self.processing.load(Ordering::Relaxed),
hostname: HOST_NAME.to_string(),
})
.unwrap_or_default();
let headers = utils::convert_headers(&[
let headers = convert_headers(&[
"Content-Type: application/json; charset=utf-8".to_string(),
"Cache-Control: private, no-store".to_string(),
])
.unwrap_or_default();

ResponseData {
HttpResponse {
status: StatusCode::OK,
body: Bytes::from(buf),
headers: Some(headers),
Expand Down
32 changes: 0 additions & 32 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,3 @@
use http::{HeaderName, HeaderValue};
use snafu::{ResultExt, Snafu};
use std::str::FromStr;

#[derive(Debug, Snafu)]
pub enum Error {
InvalidHeaderValue {
value: String,
source: http::header::InvalidHeaderValue,
},
#[snafu(display("Invalid header name {source}, {value}"))]
InvalidHeaderName {
value: String,
source: http::header::InvalidHeaderName,
},
}
type Result<T, E = Error> = std::result::Result<T, E>;

pub fn split_to_two_trim(value: &str, pat: &str) -> Option<[String; 2]> {
let arr: Vec<&str> = value.split(pat).collect();
if arr.len() < 2 {
Expand All @@ -26,20 +8,6 @@ pub fn split_to_two_trim(value: &str, pat: &str) -> Option<[String; 2]> {
Some([arr[0].trim().to_string(), value])
}

pub fn convert_headers(header_values: &[String]) -> Result<Vec<(HeaderName, HeaderValue)>> {
let mut arr = vec![];
for item in header_values {
if let Some([k, v]) = split_to_two_trim(item, ":") {
let name =
HeaderName::from_str(&k).context(InvalidHeaderNameSnafu { value: k.clone() })?;
let value =
HeaderValue::from_str(&v).context(InvalidHeaderValueSnafu { value: v.clone() })?;
arr.push((name, value));
}
}
Ok(arr)
}

const NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");

Expand Down

0 comments on commit 285de17

Please sign in to comment.