Skip to content

Commit

Permalink
Replace all unwraps
Browse files Browse the repository at this point in the history
Signed-off-by: Adam Cattermole <[email protected]>
  • Loading branch information
adam-cattermole committed Nov 20, 2024
1 parent e88f73e commit 5c3ea61
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 24 deletions.
10 changes: 5 additions & 5 deletions src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,7 @@ impl TryFrom<PluginConfiguration> for FilterConfig {
.expect("Predicates must not be compiled yet!");

for datum in &action.data {
let result = datum.item.compile();
if result.is_err() {
return Err(result.err().unwrap());
}
datum.item.compile()?;
}
}

Expand Down Expand Up @@ -204,7 +201,10 @@ impl<'de> Visitor<'de> for TimeoutVisitor {
E: Error,
{
match duration(Arc::new(string)) {
Ok(Value::Duration(duration)) => Ok(Timeout(duration.to_std().unwrap())),
Ok(Value::Duration(duration)) => duration
.to_std()
.map(Timeout)
.map_err(|e| E::custom(e.to_string())),
Err(e) => Err(E::custom(e)),
_ => Err(E::custom("Unsupported Duration Value")),
}
Expand Down
5 changes: 4 additions & 1 deletion src/data/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,10 @@ fn process_metadata(s: &Struct, prefix: String) -> Vec<(String, String)> {
let nested_struct = value.get_struct_value();
result.extend(process_metadata(nested_struct, current_prefix));
} else if let Some(v) = json {
result.push((current_prefix, serde_json::to_string(&v).unwrap()));
match serde_json::to_string(&v) {
Ok(ser) => result.push((current_prefix, ser)),
Err(e) => error!("failed to serialize json Value: {e:?}"),
}
}
}
result
Expand Down
38 changes: 31 additions & 7 deletions src/data/cel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ use cel_parser::{parse, Expression as CelExpression, Member, ParseError};
use chrono::{DateTime, FixedOffset};
#[cfg(feature = "debug-host-behaviour")]
use log::debug;
use log::warn;
use proxy_wasm::types::{Bytes, Status};
use serde_json::Value as JsonValue;
use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter};
Expand Down Expand Up @@ -87,7 +89,7 @@ impl Expression {

/// Decodes the query string and returns a Map where the key is the parameter's name and
/// the value is either a [`Value::String`] or a [`Value::List`] if the parameter's name is repeated
/// and the second arg is set not set to `false`.
/// and the second arg is not set to `false`.
/// see [`tests::decodes_query_string`]
fn decode_query_string(This(s): This<Arc<String>>, Arguments(args): Arguments) -> ResolveResult {
let allow_repeats = if args.len() == 2 {
Expand All @@ -102,8 +104,22 @@ fn decode_query_string(This(s): This<Arc<String>>, Arguments(args): Arguments) -
for part in s.split('&') {
let mut kv = part.split('=');
if let (Some(key), Some(value)) = (kv.next(), kv.next().or(Some(""))) {
let new_v: Value = decode(value).unwrap().into_owned().into();
match map.entry(decode(key).unwrap().into_owned().into()) {
let new_v: Value = decode(value)
.unwrap_or_else(|e| {
warn!("failed to decode query value, using default: {e:?}");
Cow::from(value)
})
.into_owned()
.into();
match map.entry(
decode(key)
.unwrap_or_else(|e| {
warn!("failed to decode query key, using default: {e:?}");
Cow::from(key)
})
.into_owned()
.into(),
) {
Entry::Occupied(mut e) => {
if allow_repeats {
if let Value::List(ref mut list) = e.get_mut() {
Expand All @@ -118,7 +134,15 @@ fn decode_query_string(This(s): This<Arc<String>>, Arguments(args): Arguments) -
}
}
Entry::Vacant(e) => {
e.insert(decode(value).unwrap().into_owned().into());
e.insert(
decode(value)
.unwrap_or_else(|e| {
warn!("failed to decode query value, using default: {e:?}");
Cow::from(value)
})
.into_owned()
.into(),
);
}
}
}
Expand Down Expand Up @@ -296,11 +320,11 @@ fn json_to_cel(json: &str) -> Value {
JsonValue::Bool(b) => b.into(),
JsonValue::Number(n) => {
if n.is_u64() {
n.as_u64().unwrap().into()
n.as_u64().expect("Unreachable: number must be u64").into()
} else if n.is_i64() {
n.as_i64().unwrap().into()
n.as_i64().expect("Unreachable: number must be i64").into()
} else {
n.as_f64().unwrap().into()
n.as_f64().expect("Unreachable: number must be f64").into()
}
}
JsonValue::String(str) => str.into(),
Expand Down
3 changes: 2 additions & 1 deletion src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ extern "C" fn start() {

proxy_wasm::set_log_level(LogLevel::Trace);
std::panic::set_hook(Box::new(|panic_info| {
proxy_wasm::hostcalls::log(LogLevel::Critical, &panic_info.to_string()).unwrap();
proxy_wasm::hostcalls::log(LogLevel::Critical, &panic_info.to_string())
.expect("failed to log panic_info");
}));
proxy_wasm::set_root_context(|context_id| -> Box<dyn RootContext> {
info!("#{} set_root_context", context_id);
Expand Down
18 changes: 12 additions & 6 deletions src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::service::TracingHeader::{Baggage, Traceparent, Tracestate};
use log::warn;
use protobuf::Message;
use proxy_wasm::hostcalls;
use proxy_wasm::types::Status::SerializationFailure;
use proxy_wasm::types::{BufferType, Bytes, MapType, Status};
use std::cell::OnceCell;
use std::rc::Rc;
Expand Down Expand Up @@ -56,8 +57,8 @@ impl GrpcService {
resp_size: usize,
) -> Result<GrpcResult, StatusCode> {
let failure_mode = operation.get_failure_mode();
if let Some(res_body_bytes) =
hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, 0, resp_size).unwrap()
if let Ok(Some(res_body_bytes)) =
hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, 0, resp_size)
{
match GrpcMessageResponse::new(operation.get_service_type(), &res_body_bytes) {
Ok(res) => match operation.get_service_type() {
Expand All @@ -75,7 +76,7 @@ impl GrpcService {
}
}
} else {
warn!("grpc response body is empty!");
warn!("failed to get grpc buffer or return data is null!");
GrpcService::handle_error_on_grpc_response(failure_mode);
Err(StatusCode::InternalServerError)
}
Expand All @@ -85,9 +86,11 @@ impl GrpcService {
match failure_mode {
FailureMode::Deny => {
hostcalls::send_http_response(500, vec![], Some(b"Internal Server Error.\n"))
.unwrap();
.expect("failed to send_http_response 500");
}
FailureMode::Allow => {
hostcalls::resume_http_request().expect("failed to resume_http_request")
}
FailureMode::Allow => hostcalls::resume_http_request().unwrap(),
}
}
}
Expand Down Expand Up @@ -140,7 +143,10 @@ impl GrpcServiceHandler {
message: GrpcMessageRequest,
timeout: Duration,
) -> Result<u32, Status> {
let msg = Message::write_to_bytes(&message).unwrap();
let msg = Message::write_to_bytes(&message).map_err(|e| {
warn!("Failed to write protobuf message to bytes: {e:?}");
SerializationFailure
})?;
let metadata = self
.header_resolver
.get(get_map_values_bytes_fn)
Expand Down
6 changes: 3 additions & 3 deletions src/service/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl AuthService {
let mut request = AttributeContext_Request::default();
let mut http = AttributeContext_HttpRequest::default();
let headers: HashMap<String, String> = hostcalls::get_map(MapType::HttpRequestHeaders)
.unwrap()
.expect("failed to retrieve HttpRequestHeaders from host")
.into_iter()
.collect();

Expand Down Expand Up @@ -151,7 +151,7 @@ impl AuthService {
header.get_header().get_key(),
header.get_header().get_value(),
)
.unwrap()
.expect("failed to add_map_value to HttpRequestHeaders")
});
Ok(GrpcResult::default())
}
Expand All @@ -170,7 +170,7 @@ impl AuthService {
response_headers,
Some(denied_response.get_body().as_ref()),
)
.unwrap();
.expect("failed to send_http_response");
Err(status_code)
}
None => {
Expand Down
2 changes: 1 addition & 1 deletion src/service/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl RateLimitService {
response_headers.push((header.get_key(), header.get_value()));
}
hostcalls::send_http_response(429, response_headers, Some(b"Too Many Requests\n"))
.unwrap();
.expect("failed to send_http_response 429 while OVER_LIMIT");
Err(StatusCode::TooManyRequests)
}
GrpcMessageResponse::RateLimit(RateLimitResponse {
Expand Down

0 comments on commit 5c3ea61

Please sign in to comment.