Skip to content

Commit

Permalink
fixup! fixup! fixup! fixup! fixup! fixup! wip
Browse files Browse the repository at this point in the history
  • Loading branch information
eguzki committed Nov 15, 2024
1 parent 0c48320 commit 24fd5f0
Show file tree
Hide file tree
Showing 12 changed files with 270 additions and 198 deletions.
7 changes: 1 addition & 6 deletions src/configuration/action.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
use crate::configuration::{DataItem, DataType};
use crate::data::Predicate;
use crate::envoy::{RateLimitDescriptor, RateLimitDescriptor_Entry};
use cel_interpreter::Value;
use log::error;
use crate::configuration::DataItem;
use serde::Deserialize;
use std::cell::OnceCell;

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
Expand Down
4 changes: 0 additions & 4 deletions src/configuration/action_set.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
use crate::configuration::action::Action;
use crate::data::Predicate;
use serde::Deserialize;
use std::cell::OnceCell;

#[derive(Deserialize, Debug, Clone, Default)]
pub struct RouteRuleConditions {
pub hostnames: Vec<String>,
#[serde(default)]
pub predicates: Vec<String>,
#[serde(skip_deserializing)]
pub compiled_predicates: OnceCell<Vec<Predicate>>,
}

#[derive(Default, Deserialize, Debug, Clone)]
Expand Down
13 changes: 4 additions & 9 deletions src/filter/http_context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::configuration::action_set::ActionSet;
use crate::configuration::FailureMode;
use crate::internal::filter_config::FilterConfig;
use crate::internal::merged_actions::MergedActionSet;
use crate::internal::grpc_action_set::GRPCActionSet;
use crate::operation_dispatcher::{OperationDispatcher, OperationError};
use crate::service::GrpcService;
use log::{debug, warn};
Expand Down Expand Up @@ -32,16 +31,12 @@ impl Filter {
}

#[allow(unknown_lints, clippy::manual_inspect)]
fn process_action_sets(&self, m_set_list: &[Rc<MergedActionSet>]) -> Action {
fn process_action_sets(&self, m_set_list: &[Rc<GRPCActionSet>]) -> Action {
if let Some(m_set) = m_set_list.iter().find(|m_set| m_set.conditions_apply()) {
debug!("#{} action_set selected {}", self.context_id, m_set.name);
if let Err(op_err) = self
.operation_dispatcher
self.operation_dispatcher
.borrow_mut()
.build_operations(&m_set.merged_actions)
{
self.send_http_response(500, vec![], Some(format!("{op_err}").as_ref()));
}
.build_operations(&m_set.grpc_actions)
} else {
debug!(
"#{} process_action_sets: no action_set with conditions applies",
Expand Down
17 changes: 1 addition & 16 deletions src/filter/root_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ use crate::configuration::PluginConfiguration;
use crate::filter::http_context::Filter;
use crate::internal::filter_config::FilterConfig;
use crate::operation_dispatcher::OperationDispatcher;
use crate::service::{GrpcServiceHandler, HeaderResolver};
use const_format::formatcp;
use log::{debug, error, info};
use proxy_wasm::traits::{Context, HttpContext, RootContext};
use proxy_wasm::types::ContextType;
use std::collections::HashMap;
use std::rc::Rc;

const WASM_SHIM_VERSION: &str = env!("CARGO_PKG_VERSION");
Expand Down Expand Up @@ -36,24 +34,11 @@ impl RootContext for FilterRoot {

fn create_http_context(&self, context_id: u32) -> Option<Box<dyn HttpContext>> {
debug!("#{} create_http_context", context_id);
let mut service_handlers: HashMap<String, Rc<GrpcServiceHandler>> = HashMap::new();
let header_resolver = Rc::new(HeaderResolver::new());
self.config
.services
.iter()
.for_each(|(service_name, grpc_service)| {
service_handlers
.entry(service_name.clone())
.or_insert(Rc::from(GrpcServiceHandler::new(
Rc::clone(grpc_service),
Rc::clone(&header_resolver),
)));
});
Some(Box::new(Filter {
context_id,
config: Rc::clone(&self.config),
response_headers_to_add: Vec::default(),
operation_dispatcher: OperationDispatcher::new(service_handlers).into(),
operation_dispatcher: OperationDispatcher::new().into(),
}))
}

Expand Down
63 changes: 60 additions & 3 deletions src/internal/auth_action.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,67 @@
use crate::configuration::action::Action;
use crate::configuration::Service;
use crate::configuration::{FailureMode, Service};
use crate::data::Predicate;
use crate::service::GrpcService;
use log::error;
use std::cell::OnceCell;
use std::rc::Rc;

pub struct AuthAction {}
#[derive(Clone, Debug)]
pub struct AuthAction {
grpc_service: Rc<GrpcService>,
scope: String,
predicates: OnceCell<Vec<Predicate>>,
}

impl AuthAction {
pub fn new(action: &Action, service: &Service) -> Result<Self, String> {
todo!()
let mut predicates = Vec::default();
for predicate in &action.predicates {
predicates.push(Predicate::new(predicate).map_err(|e| e.to_string())?);
}

let auth_action = AuthAction {
grpc_service: Rc::new(GrpcService::new(Rc::new(service.clone()))),
scope: action.scope.clone(),
predicates: OnceCell::new(),
};

auth_action
.predicates
.set(predicates)
.expect("Predicates must not be compiled yet!");

Ok(auth_action)
}

pub fn get_grpcservice(&self) -> Rc<GrpcService> {
Rc::clone(&self.grpc_service)
}

pub fn service(&self) -> &str {
self.grpc_service.name()
}

pub fn scope(&self) -> &str {
self.scope.as_str()
}

pub fn conditions_apply(&self) -> bool {
let predicates = self
.predicates
.get()
.expect("predicates must be compiled by now");
predicates.is_empty()
|| predicates.iter().all(|predicate| match predicate.test() {
Ok(b) => b,
Err(err) => {
error!("Failed to evaluate {:?}: {}", predicate, err);
panic!("Err out of this!")
}
})
}

pub fn get_failure_mode(&self) -> FailureMode {
self.grpc_service.get_failure_mode()
}
}
5 changes: 0 additions & 5 deletions src/internal/filter_config.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
use crate::configuration::PluginConfiguration;
use crate::internal::action_set_index::ActionSetIndex;
use crate::internal::grpc_action_set::GRPCActionSet;
use crate::service::GrpcService;
use std::collections::HashMap;
use std::rc::Rc;

pub(crate) struct FilterConfig {
pub index: ActionSetIndex,
//pub services: Rc<HashMap<String, Rc<GrpcService>>>,
}

impl TryFrom<PluginConfiguration> for FilterConfig {
Expand All @@ -29,7 +25,6 @@ impl Default for FilterConfig {
fn default() -> Self {
Self {
index: ActionSetIndex::new(),
// services: Rc::new(HashMap::new()),
}
}
}
127 changes: 48 additions & 79 deletions src/internal/grpc_action.rs
Original file line number Diff line number Diff line change
@@ -1,60 +1,13 @@
use crate::configuration::action::Action;
use crate::configuration::{DataType, Service, ServiceType};
use crate::data::Predicate;
use crate::envoy::{RateLimitDescriptor, RateLimitDescriptor_Entry};
use crate::configuration::{FailureMode, Service, ServiceType};
use crate::internal::auth_action::AuthAction;
use crate::internal::ratelimit_action::RateLimitAction;
use log::error;
use protobuf::RepeatedField;
use std::cell::OnceCell;
use crate::service::GrpcService;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;

impl MergedAction {
pub fn build_descriptor(&self) -> Option<RateLimitDescriptor> {
let mut entries = RepeatedField::default();

// iterate over data items to allow any data item to skip the entire descriptor
for data in self.data.iter() {
let (key, value) = match &data.item {
DataType::Static(static_item) => {
(static_item.key.to_owned(), static_item.value.to_owned())
}
DataType::Expression(cel) => (
cel.key.clone(),
match cel
.compiled
.get()
.expect("Expression must be compiled by now")
.eval()
{
Ok(value) => match value {
Value::Int(n) => format!("{n}"),
Value::UInt(n) => format!("{n}"),
Value::Float(n) => format!("{n}"),
// todo this probably should be a proper string literal!
Value::String(s) => (*s).clone(),
Value::Bool(b) => format!("{b}"),
Value::Null => "null".to_owned(),
_ => panic!("Only scalar values can be sent as data"),
},
Err(err) => {
error!("Failed to evaluate {}: {}", cel.value, err);
panic!("Err out of this!")
}
},
),
};
let mut descriptor_entry = RateLimitDescriptor_Entry::new();
descriptor_entry.set_key(key);
descriptor_entry.set_value(value);
entries.push(descriptor_entry);
}
let mut res = RateLimitDescriptor::new();
res.set_entries(entries);
Some(res)
}
}

#[derive(Clone, Debug)]
pub enum GRPCAction {
Auth(AuthAction),
RateLimit(RateLimitAction),
Expand All @@ -70,41 +23,57 @@ impl GRPCAction {
ServiceType::RateLimit => Ok(Self::RateLimit(RateLimitAction::new(action, service)?)),
ServiceType::Auth => Ok(Self::Auth(AuthAction::new(action, service)?)),
}
}

pub fn service(&self) -> &str {
match self {
Self::Auth(auth_action) => auth_action.service(),
Self::RateLimit(rl_action) => rl_action.service(),
}
}

pub fn scope(&self) -> &str {
match self {
Self::Auth(auth_action) => auth_action.scope(),
Self::RateLimit(rl_action) => rl_action.scope(),
}
}

//let mut predicates = Vec::default();
//for predicate in &action.predicates {
// predicates.push(Predicate::new(predicate).map_err(|e| e.to_string())?);
//}
pub fn grpc_service(&self) -> Rc<GrpcService> {
match self {
Self::Auth(auth_action) => auth_action.get_grpcservice(),
Self::RateLimit(rl_action) => rl_action.get_grpcservice(),
}
}

//let mut data_exp_list = Vec::default();
//for datum in &action.data {
// data_exp_list.push(datum.item.clone().try_into()?);
//}
//let conditional_data = ConditionalData {
// data: OnceCell::new(),
// predicates: OnceCell::new(),
//};
//conditional_data
// .predicates
// .set(predicates)
// .expect("Predicates must not be compiled yet!");
pub fn merge(&mut self, other: &GRPCAction) {
// only makes sense for rate limiting actions
if let Self::RateLimit(self_rl_action) = self {
if let Self::RateLimit(other_rl_action) = other {
self_rl_action.merge(other_rl_action)
}
}
}

//conditional_data
// .data
// .set(data_exp_list)
// .expect("Data expressions must not be compiled yet!");
//Ok(conditional_data)
pub fn conditions_apply(&self) -> bool {
match self {
Self::Auth(auth_action) => auth_action.conditions_apply(),
Self::RateLimit(rl_action) => rl_action.conditions_apply(),
}
}

pub fn service(&self) -> String {
todo!()
pub fn get_failure_mode(&self) -> FailureMode {
match self {
Self::Auth(auth_action) => auth_action.get_failure_mode(),
Self::RateLimit(rl_action) => rl_action.get_failure_mode(),
}
}

pub fn scope(&self) -> String {
todo!()
pub fn get_timeout(&self) -> Duration {
self.grpc_service().get_timeout()
}

pub fn merge(&mut self, other: GRPCAction) {
todo!()
pub fn get_service_type(&self) -> ServiceType {
self.grpc_service().get_service_type()
}
}
2 changes: 1 addition & 1 deletion src/internal/grpc_action_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl GRPCActionSet {
if existing.service() == grpc_action.service()
&& existing.scope() == grpc_action.scope()
{
existing.merge(grpc_action);
existing.merge(&grpc_action);
} else {
self.grpc_actions.push(grpc_action);
}
Expand Down
Loading

0 comments on commit 24fd5f0

Please sign in to comment.