Skip to content

Commit

Permalink
refactor: adjust proxy plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed May 12, 2024
1 parent 131813c commit c118ccc
Show file tree
Hide file tree
Showing 23 changed files with 200 additions and 203 deletions.
4 changes: 2 additions & 2 deletions docs/plugin_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ Pingap中通过Locaton添加各种插件支持更多的应用场景,如鉴权
```rust
#[async_trait]
pub trait ProxyPlugin: Sync + Send {
fn category(&self) -> ProxyPluginCategory;
fn step(&self) -> ProxyPluginStep;
fn category(&self) -> PluginCategory;
fn step(&self) -> PluginStep;
async fn handle(
&self,
_session: &mut Session,
Expand Down
21 changes: 10 additions & 11 deletions src/config/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub const CATEGORY_PROXY_PLUGIN: &str = "proxy_plugin";

#[derive(PartialEq, Debug, Default, Clone, EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum ProxyPluginCategory {
pub enum PluginCategory {
#[default]
Stats,
Limit,
Expand All @@ -52,7 +52,7 @@ pub enum ProxyPluginCategory {
ResponseHeaders,
}

impl Serialize for ProxyPluginCategory {
impl Serialize for PluginCategory {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
Expand All @@ -61,28 +61,27 @@ impl Serialize for ProxyPluginCategory {
}
}

impl<'de> Deserialize<'de> for ProxyPluginCategory {
impl<'de> Deserialize<'de> for PluginCategory {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: String = serde::Deserialize::deserialize(deserializer)?;
let category =
ProxyPluginCategory::from_str(&value).unwrap_or(ProxyPluginCategory::default());
let category = PluginCategory::from_str(&value).unwrap_or(PluginCategory::default());

Ok(category)
}
}

#[derive(PartialEq, Debug, Default, Clone, Copy, EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum ProxyPluginStep {
pub enum PluginStep {
#[default]
RequestFilter,
ProxyUpstreamFilter,
}

impl Serialize for ProxyPluginStep {
impl Serialize for PluginStep {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
Expand All @@ -91,13 +90,13 @@ impl Serialize for ProxyPluginStep {
}
}

impl<'de> Deserialize<'de> for ProxyPluginStep {
impl<'de> Deserialize<'de> for PluginStep {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: String = serde::Deserialize::deserialize(deserializer)?;
let category = ProxyPluginStep::from_str(&value).unwrap_or(ProxyPluginStep::default());
let category = PluginStep::from_str(&value).unwrap_or(PluginStep::default());

Ok(category)
}
Expand All @@ -106,8 +105,8 @@ impl<'de> Deserialize<'de> for ProxyPluginStep {
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
pub struct ProxyPluginConf {
pub value: Option<String>,
pub category: ProxyPluginCategory,
pub step: Option<ProxyPluginStep>,
pub category: PluginCategory,
pub step: Option<PluginStep>,
pub remark: Option<String>,
}

Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::acme::LetsEncryptService;
use crate::config::ETCD_PROTOCOL;
use crate::state::AutoRestart;
use clap::Parser;
use config::{PingapConf, ProxyPluginCategory, ProxyPluginConf};
use config::{PingapConf, PluginCategory, ProxyPluginConf};
use crossbeam_channel::Sender;
use log::{error, info};
use pingora::server;
Expand Down Expand Up @@ -159,7 +159,7 @@ fn parse_admin_proxy_plugin(addr: &str) -> (ServerConf, String, ProxyPluginConf)
util::ADMIN_SERVER_PLUGIN.clone(),
ProxyPluginConf {
value: Some(format!("/ {authorization}")),
category: ProxyPluginCategory::Admin,
category: PluginCategory::Admin,
remark: Some("Admin serve".to_string()),
step: None,
},
Expand Down
14 changes: 7 additions & 7 deletions src/plugin/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

use super::{ProxyPlugin, Result};
use crate::config::{
self, save_config, BasicConf, LocationConf, ProxyPluginCategory, ProxyPluginConf,
ProxyPluginStep, ServerConf, UpstreamConf,
self, save_config, BasicConf, LocationConf, PluginCategory, PluginStep, ProxyPluginConf,
ServerConf, UpstreamConf,
};
use crate::config::{
PingapConf, CATEGORY_LOCATION, CATEGORY_PROXY_PLUGIN, CATEGORY_SERVER, CATEGORY_UPSTREAM,
Expand Down Expand Up @@ -90,11 +90,11 @@ impl From<EmbeddedStaticFile> for HttpResponse {
pub struct AdminServe {
pub path: String,
pub authorization: String,
pub proxy_step: ProxyPluginStep,
pub proxy_step: PluginStep,
ip_fail_limit: TtlLruLimit,
}
impl AdminServe {
pub fn new(value: &str, proxy_step: ProxyPluginStep) -> Result<Self> {
pub fn new(value: &str, proxy_step: PluginStep) -> Result<Self> {
debug!("new admin server proxy plugin, {value}, {proxy_step:?}");
let arr: Vec<&str> = value.split(' ').collect();
let mut authorization = "".to_string();
Expand Down Expand Up @@ -255,12 +255,12 @@ fn get_method_path(session: &Session) -> (Method, String) {
#[async_trait]
impl ProxyPlugin for AdminServe {
#[inline]
fn step(&self) -> ProxyPluginStep {
fn step(&self) -> PluginStep {
self.proxy_step
}
#[inline]
fn category(&self) -> ProxyPluginCategory {
ProxyPluginCategory::Admin
fn category(&self) -> PluginCategory {
PluginCategory::Admin
}
async fn handle(
&self,
Expand Down
19 changes: 9 additions & 10 deletions src/plugin/basic_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

use super::ProxyPlugin;
use super::{Error, Result};
use crate::config::ProxyPluginCategory;
use crate::config::ProxyPluginStep;
use crate::config::PluginCategory;
use crate::config::PluginStep;
use crate::http_extra::HttpResponse;
use crate::state::State;
use async_trait::async_trait;
Expand All @@ -27,14 +27,14 @@ use log::debug;
use pingora::proxy::Session;

pub struct BasicAuth {
proxy_step: ProxyPluginStep,
proxy_step: PluginStep,
authorizations: Vec<Vec<u8>>,
miss_authorization_resp: HttpResponse,
unauthorized_resp: HttpResponse,
}

impl BasicAuth {
pub fn new(value: &str, proxy_step: ProxyPluginStep) -> Result<Self> {
pub fn new(value: &str, proxy_step: PluginStep) -> Result<Self> {
debug!("new basic auth proxy plugin, {value}, {proxy_step:?}");
let mut authorizations = vec![];
for item in value.split(',') {
Expand Down Expand Up @@ -75,12 +75,12 @@ impl BasicAuth {
#[async_trait]
impl ProxyPlugin for BasicAuth {
#[inline]
fn step(&self) -> ProxyPluginStep {
fn step(&self) -> PluginStep {
self.proxy_step
}
#[inline]
fn category(&self) -> ProxyPluginCategory {
ProxyPluginCategory::BasicAuth
fn category(&self) -> PluginCategory {
PluginCategory::BasicAuth
}
#[inline]
async fn handle(
Expand All @@ -103,16 +103,15 @@ impl ProxyPlugin for BasicAuth {
mod tests {
use super::BasicAuth;
use crate::state::State;
use crate::{config::ProxyPluginStep, plugin::ProxyPlugin};
use crate::{config::PluginStep, plugin::ProxyPlugin};
use http::StatusCode;
use pingora::proxy::Session;
use pretty_assertions::assert_eq;
use tokio_test::io::Builder;

#[tokio::test]
async fn test_basic_auth() {
let auth =
BasicAuth::new("YWRtaW46MTIzMTIz", ProxyPluginStep::ProxyUpstreamFilter).unwrap();
let auth = BasicAuth::new("YWRtaW46MTIzMTIz", PluginStep::ProxyUpstreamFilter).unwrap();

// auth success
let headers = ["Authorization: Basic YWRtaW46MTIzMTIz"].join("\r\n");
Expand Down
12 changes: 6 additions & 6 deletions src/plugin/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

use super::ProxyPlugin;
use super::{Error, Result};
use crate::config::{get_current_config, ProxyPluginCategory, ProxyPluginStep};
use crate::config::{get_current_config, PluginCategory, PluginStep};
use crate::http_extra::HttpResponse;
use crate::state::State;
use async_trait::async_trait;
Expand Down Expand Up @@ -53,7 +53,7 @@ static CACHE_LOCK_THREE_SECONDS: Lazy<CacheLock> =
Lazy::new(|| CacheLock::new(std::time::Duration::from_secs(3)));

pub struct Cache {
proxy_step: ProxyPluginStep,
proxy_step: PluginStep,
eviction: bool,
predictor: bool,
lock: u8,
Expand All @@ -64,7 +64,7 @@ pub struct Cache {
}

impl Cache {
pub fn new(value: &str, proxy_step: ProxyPluginStep) -> Result<Self> {
pub fn new(value: &str, proxy_step: PluginStep) -> Result<Self> {
debug!("new cache storage proxy plugin, {value}, {proxy_step:?}");
let url_info = Url::parse(value).map_err(|e| Error::Invalid {
message: e.to_string(),
Expand Down Expand Up @@ -119,12 +119,12 @@ impl Cache {
#[async_trait]
impl ProxyPlugin for Cache {
#[inline]
fn step(&self) -> ProxyPluginStep {
fn step(&self) -> PluginStep {
self.proxy_step
}
#[inline]
fn category(&self) -> ProxyPluginCategory {
ProxyPluginCategory::Cache
fn category(&self) -> PluginCategory {
PluginCategory::Cache
}
#[inline]
async fn handle(
Expand Down
16 changes: 8 additions & 8 deletions src/plugin/compression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

use super::ProxyPlugin;
use super::{Error, Result};
use crate::config::{ProxyPluginCategory, ProxyPluginStep};
use crate::config::{PluginCategory, PluginStep};
use crate::http_extra::HttpResponse;
use crate::state::State;
use async_trait::async_trait;
Expand All @@ -32,11 +32,11 @@ pub struct Compression {
br_level: u32,
zstd_level: u32,
support_compression: bool,
proxy_step: ProxyPluginStep,
proxy_step: PluginStep,
}

impl Compression {
pub fn new(value: &str, proxy_step: ProxyPluginStep) -> Result<Self> {
pub fn new(value: &str, proxy_step: PluginStep) -> Result<Self> {
debug!("new compresson proxy plugin, {value}, {proxy_step:?}");

let mut levels: [u32; 3] = [0, 0, 0];
Expand Down Expand Up @@ -66,12 +66,12 @@ impl Compression {
#[async_trait]
impl ProxyPlugin for Compression {
#[inline]
fn step(&self) -> ProxyPluginStep {
fn step(&self) -> PluginStep {
self.proxy_step
}
#[inline]
fn category(&self) -> ProxyPluginCategory {
ProxyPluginCategory::Compression
fn category(&self) -> PluginCategory {
PluginCategory::Compression
}
#[inline]
async fn handle(
Expand Down Expand Up @@ -113,14 +113,14 @@ impl ProxyPlugin for Compression {
mod tests {
use super::Compression;
use crate::state::State;
use crate::{config::ProxyPluginStep, plugin::ProxyPlugin};
use crate::{config::PluginStep, plugin::ProxyPlugin};
use pingora::proxy::Session;
use pretty_assertions::assert_eq;
use tokio_test::io::Builder;

#[tokio::test]
async fn test_basic_auth() {
let compression = Compression::new("9 8 7", ProxyPluginStep::ProxyUpstreamFilter).unwrap();
let compression = Compression::new("9 8 7", PluginStep::ProxyUpstreamFilter).unwrap();

// gzip
let headers = ["Accept-Encoding: gzip"].join("\r\n");
Expand Down
16 changes: 8 additions & 8 deletions src/plugin/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// limitations under the License.

use super::{ProxyPlugin, Result};
use crate::config::{ProxyPluginCategory, ProxyPluginStep};
use crate::config::{PluginCategory, PluginStep};
use crate::http_extra::{HttpChunkResponse, HttpHeader, HttpResponse};
use crate::state::State;
use crate::util;
Expand Down Expand Up @@ -95,7 +95,7 @@ pub struct Directory {
cache_private: Option<bool>,
// charset for text file
charset: Option<String>,
proxy_step: ProxyPluginStep,
proxy_step: PluginStep,
}

async fn get_data(file: &PathBuf) -> std::io::Result<(std::fs::Metadata, fs::File)> {
Expand Down Expand Up @@ -142,7 +142,7 @@ fn get_cacheable_and_headers_from_meta(

impl Directory {
/// Creates a new directory upstream, which will serve static file of directory.
pub fn new(value: &str, proxy_step: ProxyPluginStep) -> Result<Self> {
pub fn new(value: &str, proxy_step: PluginStep) -> Result<Self> {
debug!("new serve static file proxy plugin, {value}, {proxy_step:?}");
let mut new_path = value.to_string();
let mut chunk_size = None;
Expand Down Expand Up @@ -242,12 +242,12 @@ fn get_autoindex_html(path: &Path) -> Result<String, String> {
#[async_trait]
impl ProxyPlugin for Directory {
#[inline]
fn step(&self) -> ProxyPluginStep {
fn step(&self) -> PluginStep {
self.proxy_step
}
#[inline]
fn category(&self) -> ProxyPluginCategory {
ProxyPluginCategory::Directory
fn category(&self) -> PluginCategory {
PluginCategory::Directory
}
async fn handle(
&self,
Expand Down Expand Up @@ -325,15 +325,15 @@ impl ProxyPlugin for Directory {
#[cfg(test)]
mod tests {
use super::{get_cacheable_and_headers_from_meta, get_data, Directory};
use crate::config::ProxyPluginStep;
use crate::config::PluginStep;
use pretty_assertions::{assert_eq, assert_ne};
use std::{os::unix::fs::MetadataExt, path::Path};

#[test]
fn test_new_directory() {
let dir = Directory::new(
"~/Downloads?chunk_size=1024&max_age=3600&private&index=pingap/index.html",
ProxyPluginStep::RequestFilter,
PluginStep::RequestFilter,
)
.unwrap();
assert_eq!(1024, dir.chunk_size.unwrap_or_default());
Expand Down
Loading

0 comments on commit c118ccc

Please sign in to comment.