Skip to content

Commit

Permalink
chore:fix spell error and make code more elegant (#678)
Browse files Browse the repository at this point in the history
* chore:fix spell error

* update

* update

* cargo fix spi-all

* update
  • Loading branch information
RWDai authored Apr 2, 2024
1 parent 771c6d1 commit 4c17c74
Show file tree
Hide file tree
Showing 45 changed files with 300 additions and 326 deletions.
8 changes: 4 additions & 4 deletions basic/src/helper/bios_ctx_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub fn unsafe_fill_ctx(request: &Request, funs: &TardisFunsInst, ctx: &mut Tardi
)
}

pub fn unsfae_fill_owner_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
pub fn unsafe_fill_owner_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
Expand All @@ -94,7 +94,7 @@ pub fn unsfae_fill_owner_only(request: &Request, funs: &TardisFunsInst, ctx: &mu
)
}

pub fn unsfae_fill_own_paths_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
pub fn unsafe_fill_own_paths_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
Expand All @@ -106,7 +106,7 @@ pub fn unsfae_fill_own_paths_only(request: &Request, funs: &TardisFunsInst, ctx:
)
}

pub fn unsfae_fill_roles_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
pub fn unsafe_fill_roles_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
Expand All @@ -125,7 +125,7 @@ pub fn unsfae_fill_roles_only(request: &Request, funs: &TardisFunsInst, ctx: &mu
)
}

pub fn unsfae_fill_groups_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
pub fn unsafe_fill_groups_only(request: &Request, funs: &TardisFunsInst, ctx: &mut TardisContext) -> TardisResult<()> {
unsafe_check_ctx(
request,
|bios_ctx, ctx| {
Expand Down
2 changes: 1 addition & 1 deletion basic/src/helper/request_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub async fn add_remote_ip(request: &Request, ctx: &TardisContext) -> TardisResu
}

pub async fn get_ip(request: &Request) -> TardisResult<Option<String>> {
let back_ip = request.remote_addr().as_socket_addr().map(|socert_addr| socert_addr.ip().to_string());
let back_ip = request.remote_addr().as_socket_addr().map(|socket_addr| socket_addr.ip().to_string());
let ip = if let Some(real_ips) = request.headers().get("X-Forwarded-For") {
if let Some(real_ip) = real_ips.to_str().ok().and_then(|ips| ips.split(',').collect::<Vec<_>>().first().map(|ip| ip.to_string())) {
Some(real_ip)
Expand Down
2 changes: 1 addition & 1 deletion gateway/spacegate-lib/src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl From<String> for ExtensionPackEnum {
}
}
impl ExtensionPackEnum {
pub fn to_value(&self, ext: &Extensions) -> Result<Option<Value>, BoxError> {
pub fn _to_value(&self, ext: &Extensions) -> Result<Option<Value>, BoxError> {
match self {
ExtensionPackEnum::LogParamContent() => {
if let Some(ext) = LogParamContent::get(ext) {
Expand Down
4 changes: 2 additions & 2 deletions gateway/spacegate-lib/src/plugin/auth/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ async fn test_auth_plugin_crypto() {

let test_body_value = r#"test_body_value!@#$%^&*():"中文测试"#;

//========dont need to decrypt======
log::info!("========dont need to decrypt=====");
//========don't need to decrypt======
log::info!("========don't need to decrypt=====");
let req = Request::builder()
.method(Method::POST)
.uri(Uri::from_static("http://sg.idealworld.group/test1"))
Expand Down
4 changes: 2 additions & 2 deletions gateway/spacegate-lib/src/plugin/ip_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::sync::Arc;
use ipnet::IpNet;
use serde::{Deserialize, Serialize};
use spacegate_shell::hyper::{Request, Response, StatusCode};
use spacegate_shell::kernel::extension::PeerAddr;
use spacegate_shell::kernel::helper_layers::function::Inner;
use spacegate_shell::kernel::{extension::PeerAddr};
use spacegate_shell::plugin::Plugin;

use spacegate_shell::{BoxError, SgBody, SgResponseExt};
Expand Down Expand Up @@ -78,7 +78,7 @@ pub struct IpTimePlugin {
// - segment list
// - ban: Set {}
// - allow: Set {}
// - pointer to the lastest segment
// - pointer to the latest segment
pub mode: SgFilterIpTimeMode,
pub rules: Arc<[(IpNet, IpTimeRule)]>,
}
Expand Down
11 changes: 4 additions & 7 deletions gateway/spacegate-lib/src/plugin/op_redis_publisher.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use std::{
str::FromStr as _,
time::{Duration, Instant},
};
use std::{str::FromStr as _, time::Instant};

use http::Response;
use jsonpath_rust::JsonPathInst;
Expand Down Expand Up @@ -142,7 +139,7 @@ impl RedisPublisherPlugin {
};

let Some(param) = resp.extensions().get::<AuditLogParam>() else {
warn!("[Plugin.OpRedisPubilsher] missing audit log param");
warn!("[Plugin.OpRedisPublisher] missing audit log param");
return Ok((resp, None));
};

Expand Down Expand Up @@ -192,7 +189,7 @@ impl RedisPublisherPlugin {
ip: param.request_ip.clone(),
path: param.request_path.clone(),
scheme: param.request_scheme.clone(),
server_timing: start_time.map(|st| end_time - st),
server_timing: start_time.map(|st| (end_time - st).as_nanos()),
resp_status: resp.status().as_u16().to_string(),
success,
own_paths: resp.extensions().get::<CertInfo>().and_then(|info| info.own_paths.clone()),
Expand All @@ -211,7 +208,7 @@ struct OpLogContent {
pub ip: String,
pub path: String,
pub scheme: String,
pub server_timing: Option<Duration>,
pub server_timing: Option<u128>,
pub resp_status: String,
//Indicates whether the business operation was successful.
pub success: bool,
Expand Down
105 changes: 49 additions & 56 deletions gateway/spacegate-lib/src/plugin/rewrite_ns_b_ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@ use ipnet::IpNet;
use serde::{Deserialize, Serialize};

use spacegate_shell::extension::k8s_service::K8sService;
use spacegate_shell::hyper::Request;
use spacegate_shell::hyper::{http::uri, Response};
use spacegate_shell::kernel::extension::PeerAddr;
use spacegate_shell::kernel::helper_layers::function::Inner;
use spacegate_shell::kernel::SgRequest;
use spacegate_shell::plugin::{Plugin, PluginConfig, PluginError};
use spacegate_shell::{BoxError, SgBody};
use std::net::IpAddr;
use std::str::FromStr;
use std::sync::Arc;

use tardis::{log, serde_json};
// def_plugin!("rewrite_ns", RewriteNsPlugin, SgFilterRewriteNs);

/// Kube available only!
#[derive(Clone)]
Expand Down Expand Up @@ -86,7 +85,13 @@ impl Plugin for RewriteNsPlugin {
target_ns: config.target_ns,
})
}
async fn call(&self, mut req: Request<SgBody>, inner: Inner) -> Result<Response<SgBody>, BoxError> {
async fn call(&self, mut req: SgRequest, inner: Inner) -> Result<Response<SgBody>, BoxError> {
self.req(&mut req)?;
Ok(inner.call(req).await)
}
}
impl RewriteNsPlugin {
fn req(&self, req: &mut SgRequest) -> Result<(), BoxError> {
'change_ns: {
if let Some(k8s_service) = req.extensions().get::<K8sService>().cloned() {
let Some(ref ns) = k8s_service.0.namespace else { break 'change_ns };
Expand All @@ -106,63 +111,51 @@ impl Plugin for RewriteNsPlugin {
}
}
}
Ok(inner.call(req).await)
Ok(())
}
}

// #[cfg(test)]
// mod test {
// use crate::plugin::rewrite_ns_b_ip::SgFilterRewriteNs;
// use spacegate_shell::config::gateway_dto::SgParameters;
// use spacegate_shell::http::{HeaderMap, Method, Uri, Version};
// use spacegate_shell::hyper::Body;
// use spacegate_shell::instance::SgBackendInst;
// use spacegate_shell::plugins::context::SgRoutePluginContext;
// use spacegate_shell::plugins::filters::{SgPluginFilter, SgPluginFilterInitDto};
// use tardis::tokio;
#[cfg(test)]
mod test {

use http::{Method, Request, Uri, Version};
use spacegate_shell::{
config::K8sServiceData,
extension::k8s_service::K8sService,
kernel::extension::PeerAddr,
plugin::{Plugin as _, PluginConfig},
SgBody,
};
use tardis::{serde_json::json, tokio};

// #[tokio::test]
// async fn test() {
// let mut filter_rens = SgFilterRewriteNs {
// ip_list: vec!["198.168.1.0/24".to_string()],
// target_ns: "target".to_string(),
// ..Default::default()
// };
use crate::plugin::rewrite_ns_b_ip::RewriteNsPlugin;

// filter_rens
// .init(&SgPluginFilterInitDto {
// gateway_name: "".to_string(),
// gateway_parameters: SgParameters {
// redis_url: None,
// log_level: None,
// lang: None,
// ignore_tls_verification: None,
// },
// http_route_rules: vec![],
// attached_level: spacegate_shell::plugins::filters::SgAttachedLevel::Gateway,
// })
// .await
// .unwrap();
#[tokio::test]
async fn test() {
let plugin = RewriteNsPlugin::create(PluginConfig {
code: "rewrite-ns".into(),
spec: json!({"ip_list":["198.168.1.0/24"],"target_ns":"target"}),
name: None,
})
.unwrap();

let mut req = Request::builder()
.method(Method::POST)
.uri(Uri::from_static("http://sg.idealworld:80/test"))
.version(Version::HTTP_11)
.extension(K8sService(
K8sServiceData {
name: "sg".to_string(),
namespace: Some("idealworld".to_string()),
}
.into(),
))
.extension(PeerAddr("198.168.1.1:8080".parse().unwrap()))
.body(SgBody::full("test"))
.unwrap();

// let mut ctx = SgRoutePluginContext::new_http(
// Method::POST,
// Uri::from_static("http://sg.idealworld.group/test1"),
// Version::HTTP_11,
// HeaderMap::new(),
// Body::from("test"),
// "198.168.1.1:8080".parse().unwrap(),
// "".to_string(),
// None,
// );
// let back_inst = SgBackendInst {
// name_or_host: "test".to_string(),
// namespace: Some("Anamspace".to_string()),
// port: 80,
// ..Default::default()
// };
// ctx.set_chose_backend_inst(&back_inst);
plugin.req(&mut req).unwrap();

// let (_, ctx) = filter_rens.req_filter("", ctx).await.unwrap();
// assert_eq!(ctx.request.uri.get().host().unwrap(), format!("test.target"))
// }
// }
assert_eq!(req.uri().host(), Some("sg.target"));
}
}
2 changes: 1 addition & 1 deletion spi/spi-search/src/serv/es/search_es_item_serv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ pub async fn delete_by_ownership(tag: &str, onw_paths: &str, funs: &TardisFunsIn
cond_by_or: None,
},
query: SearchItemQueryReq {
own_paths: Some(vec![onw_paths.to_string().into()]),
own_paths: Some(vec![onw_paths.to_string()]),
..Default::default()
},
sort: None,
Expand Down
Loading

0 comments on commit 4c17c74

Please sign in to comment.