diff --git a/src/dispatcher.rs b/src/dispatcher.rs index 671ef0f3..bde160bf 100644 --- a/src/dispatcher.rs +++ b/src/dispatcher.rs @@ -16,7 +16,7 @@ use crate::hostcalls; use crate::traits::*; use crate::types::*; use hashbrown::HashMap; -use log::trace; +use log::{error, trace}; use std::cell::{Cell, RefCell}; thread_local! { @@ -100,7 +100,7 @@ impl Dispatcher { .insert(token_id, self.active_id.get()) .is_some() { - panic!("duplicate token_id") + error!("duplicate token_id") } } @@ -111,7 +111,7 @@ impl Dispatcher { .insert(token_id, self.active_id.get()) .is_some() { - panic!("duplicate token_id") + error!("duplicate token_id") } } @@ -122,7 +122,7 @@ impl Dispatcher { .insert(token_id, self.active_id.get()) .is_some() { - panic!("duplicate token_id") + error!("duplicate token_id") } } @@ -137,7 +137,7 @@ impl Dispatcher { .insert(context_id, new_context) .is_some() { - panic!("duplicate context_id") + error!("duplicate context_id") } } @@ -147,10 +147,16 @@ impl Dispatcher { Some(f) => f(context_id, root_context_id), None => match root_context.create_stream_context(context_id) { Some(stream_context) => stream_context, - None => panic!("create_stream_context returned None"), + None => { + error!("create_stream_context returned None"); + return; + }, }, }, - None => panic!("invalid root_context_id"), + None => { + error!("invalid root_context_id"); + return; + }, }; if self .streams @@ -158,7 +164,7 @@ impl Dispatcher { .insert(context_id, new_context) .is_some() { - panic!("duplicate context_id") + error!("duplicate context_id") } } @@ -168,10 +174,16 @@ impl Dispatcher { Some(f) => f(context_id, root_context_id), None => match root_context.create_http_context(context_id) { Some(stream_context) => stream_context, - None => panic!("create_http_context returned None"), + None => { + error!("create_http_context returned None"); + return; + }, }, }, - None => panic!("invalid root_context_id"), + None => { + error!("invalid root_context_id"); + return; + }, }; if self .http_streams @@ -179,7 +191,7 @@ impl Dispatcher { .insert(context_id, new_context) .is_some() { - panic!("duplicate context_id") + error!("duplicate context_id") } } @@ -198,10 +210,13 @@ impl Dispatcher { Some(ContextType::StreamContext) => { self.create_stream_context(context_id, root_context_id) } - None => panic!("missing ContextType on root_context"), + None => { + error!("missing ContextType on root_context"); + return; + }, } } else { - panic!("invalid root_context_id and missing constructors"); + error!("invalid root_context_id and missing constructors"); } } @@ -216,7 +231,8 @@ impl Dispatcher { self.active_id.set(context_id); root.on_done() } else { - panic!("invalid context_id") + error!("invalid context_id"); + return true } } @@ -231,7 +247,7 @@ impl Dispatcher { self.active_id.set(context_id); root.on_log() } else { - panic!("invalid context_id") + error!("invalid context_id") } } @@ -240,7 +256,7 @@ impl Dispatcher { || self.streams.borrow_mut().remove(&context_id).is_some() || self.roots.borrow_mut().remove(&context_id).is_some()) { - panic!("invalid context_id") + error!("invalid context_id") } } @@ -249,7 +265,8 @@ impl Dispatcher { self.active_id.set(context_id); root.on_vm_start(vm_configuration_size) } else { - panic!("invalid context_id") + error!("invalid context_id"); + true } } @@ -258,7 +275,8 @@ impl Dispatcher { self.active_id.set(context_id); root.on_configure(plugin_configuration_size) } else { - panic!("invalid context_id") + error!("invalid context_id"); + true } } @@ -267,7 +285,7 @@ impl Dispatcher { self.active_id.set(context_id); root.on_tick() } else { - panic!("invalid context_id") + error!("invalid context_id") } } @@ -276,7 +294,7 @@ impl Dispatcher { self.active_id.set(context_id); root.on_queue_ready(queue_id) } else { - panic!("invalid context_id") + error!("invalid context_id") } } @@ -285,7 +303,8 @@ impl Dispatcher { self.active_id.set(context_id); stream.on_new_connection() } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -294,7 +313,8 @@ impl Dispatcher { self.active_id.set(context_id); stream.on_downstream_data(data_size, end_of_stream) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -303,7 +323,7 @@ impl Dispatcher { self.active_id.set(context_id); stream.on_downstream_close(peer_type) } else { - panic!("invalid context_id") + error!("invalid context_id") } } @@ -312,7 +332,8 @@ impl Dispatcher { self.active_id.set(context_id); stream.on_upstream_data(data_size, end_of_stream) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -321,7 +342,7 @@ impl Dispatcher { self.active_id.set(context_id); stream.on_upstream_close(peer_type) } else { - panic!("invalid context_id") + error!("invalid context_id") } } @@ -335,7 +356,8 @@ impl Dispatcher { self.active_id.set(context_id); http_stream.on_http_request_headers(num_headers, end_of_stream) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -349,7 +371,8 @@ impl Dispatcher { self.active_id.set(context_id); http_stream.on_http_request_body(body_size, end_of_stream) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -358,7 +381,8 @@ impl Dispatcher { self.active_id.set(context_id); http_stream.on_http_request_trailers(num_trailers) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -372,7 +396,8 @@ impl Dispatcher { self.active_id.set(context_id); http_stream.on_http_response_headers(num_headers, end_of_stream) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -386,7 +411,8 @@ impl Dispatcher { self.active_id.set(context_id); http_stream.on_http_response_body(body_size, end_of_stream) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -395,7 +421,8 @@ impl Dispatcher { self.active_id.set(context_id); http_stream.on_http_response_trailers(num_trailers) } else { - panic!("invalid context_id") + error!("invalid context_id"); + Action::Continue } } @@ -414,15 +441,24 @@ impl Dispatcher { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_http_call_response(token_id, num_headers, body_size, num_trailers) } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id) { + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_http_call_response(token_id, num_headers, body_size, num_trailers) } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id) { + error!("set_effective_context failed: {:?}", e); + return; + } root.on_http_call_response(token_id, num_headers, body_size, num_trailers) } } @@ -439,15 +475,24 @@ impl Dispatcher { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_grpc_stream_initial_metadata(token_id, headers); } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_grpc_stream_initial_metadata(token_id, headers); } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } root.on_grpc_stream_initial_metadata(token_id, headers); } } @@ -457,15 +502,24 @@ impl Dispatcher { if let Some(context_id) = context_id { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_grpc_call_response(token_id, 0, response_size); } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_grpc_call_response(token_id, 0, response_size); } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id) { + error!("set_effective_context failed: {:?}", e); + return; + } root.on_grpc_call_response(token_id, 0, response_size); } } else { @@ -473,15 +527,24 @@ impl Dispatcher { if let Some(context_id) = context_id { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_grpc_stream_message(token_id, response_size); } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_grpc_stream_message(token_id, response_size); } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } root.on_grpc_stream_message(token_id, response_size); } } else { @@ -503,15 +566,24 @@ impl Dispatcher { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_grpc_stream_trailing_metadata(token_id, trailers); } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_grpc_stream_trailing_metadata(token_id, trailers); } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } root.on_grpc_stream_trailing_metadata(token_id, trailers); } } @@ -521,15 +593,24 @@ impl Dispatcher { if let Some(context_id) = context_id { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_grpc_call_response(token_id, status_code, 0); } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_grpc_call_response(token_id, status_code, 0); } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } root.on_grpc_call_response(token_id, status_code, 0); } } else { @@ -537,15 +618,24 @@ impl Dispatcher { if let Some(context_id) = context_id { if let Some(http_stream) = self.http_streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } http_stream.on_grpc_stream_close(token_id, status_code) } else if let Some(stream) = self.streams.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } stream.on_grpc_stream_close(token_id, status_code) } else if let Some(root) = self.roots.borrow_mut().get_mut(&context_id) { self.active_id.set(context_id); - hostcalls::set_effective_context(context_id).unwrap(); + if let Err(e) = hostcalls::set_effective_context(context_id){ + error!("set_effective_context failed: {:?}", e); + return; + } root.on_grpc_stream_close(token_id, status_code) } } else { diff --git a/src/hostcalls.rs b/src/hostcalls.rs index 15687888..682b4977 100644 --- a/src/hostcalls.rs +++ b/src/hostcalls.rs @@ -16,6 +16,7 @@ use crate::dispatcher; use crate::types::*; use std::ptr::{null, null_mut}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use log::error; extern "C" { fn proxy_log(level: LogLevel, message_data: *const u8, message_size: usize) -> Status; @@ -25,7 +26,10 @@ pub fn log(level: LogLevel, message: &str) -> Result<(), Status> { unsafe { match proxy_log(level, message.as_ptr(), message.len()) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[log] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -39,7 +43,10 @@ pub fn get_log_level() -> Result { unsafe { match proxy_get_log_level(&mut return_level) { Status::Ok => Ok(return_level), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[get_log_level] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -53,7 +60,10 @@ pub fn get_current_time() -> Result { unsafe { match proxy_get_current_time_nanoseconds(&mut return_time) { Status::Ok => Ok(UNIX_EPOCH + Duration::from_nanos(return_time)), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[get_current_time] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -66,7 +76,10 @@ pub fn set_tick_period(period: Duration) -> Result<(), Status> { unsafe { match proxy_set_tick_period_milliseconds(period.as_millis() as u32) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_tick_period] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -108,7 +121,10 @@ pub fn get_buffer( } } Status::NotFound => Ok(None), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -132,7 +148,10 @@ pub fn set_buffer( unsafe { match proxy_set_buffer_bytes(buffer_type, start, size, value.as_ptr(), value.len()) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_buffer] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -158,7 +177,10 @@ pub fn get_map(map_type: MapType) -> Result, Status> { Ok(Vec::new()) } } - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[get_map] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -176,7 +198,10 @@ pub fn get_map_bytes(map_type: MapType) -> Result, Status> Ok(Vec::new()) } } - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -194,7 +219,10 @@ pub fn set_map(map_type: MapType, map: Vec<(&str, &str)>) -> Result<(), Status> unsafe { match proxy_set_header_map_pairs(map_type, serialized_map.as_ptr(), serialized_map.len()) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_map] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -204,7 +232,10 @@ pub fn set_map_bytes(map_type: MapType, map: Vec<(&str, &[u8])>) -> Result<(), S unsafe { match proxy_set_header_map_pairs(map_type, serialized_map.as_ptr(), serialized_map.len()) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_map_bytes] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -220,8 +251,9 @@ extern "C" { } pub fn get_map_value(map_type: MapType, key: &str) -> Result, Status> { - let mut return_data: *mut u8 = null_mut(); + let mut return_data: *mut u8 = std::ptr::null_mut(); let mut return_size: usize = 0; + unsafe { match proxy_get_header_map_value( map_type, @@ -232,20 +264,24 @@ pub fn get_map_value(map_type: MapType, key: &str) -> Result, Sta ) { Status::Ok => { if !return_data.is_null() { - Ok(Some( - String::from_utf8(Vec::from_raw_parts( - return_data, - return_size, - return_size, - )) - .unwrap(), - )) + // Try to convert raw bytes to UTF-8 string + let vec = Vec::from_raw_parts(return_data, return_size, return_size); + match String::from_utf8(vec) { + Ok(string) => Ok(Some(string)), // Successfully converted to String + Err(e) => { + error!("[get_map_value] Failed to convert to UTF-8 string: {}", e); + Err(Status::SerializationFailure) // Return an appropriate error + } + } } else { Ok(None) } } Status::NotFound => Ok(None), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -273,7 +309,10 @@ pub fn get_map_value_bytes(map_type: MapType, key: &str) -> Result } } Status::NotFound => Ok(None), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -307,12 +346,18 @@ pub fn set_map_value(map_type: MapType, key: &str, value: Option<&str>) -> Resul value.len(), ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_map_value] unexpected status: {}", status as u32); + Err(status) + }, } } else { match proxy_remove_header_map_value(map_type, key.as_ptr(), key.len()) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_map_value] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -333,12 +378,18 @@ pub fn set_map_value_bytes( value.len(), ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_map_value_bytes] unexpected status: {}", status as u32); + Err(status) + }, } } else { match proxy_remove_header_map_value(map_type, key.as_ptr(), key.len()) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_map_value_bytes] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -364,7 +415,10 @@ pub fn add_map_value(map_type: MapType, key: &str, value: &str) -> Result<(), St value.len(), ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[add_map_value] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -379,7 +433,10 @@ pub fn add_map_value_bytes(map_type: MapType, key: &str, value: &[u8]) -> Result value.len(), ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[add_map_value_bytes] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -418,7 +475,10 @@ pub fn get_property(path: Vec<&str>) -> Result, Status> { Status::NotFound => Ok(None), Status::SerializationFailure => Err(Status::SerializationFailure), Status::InternalFailure => Err(Status::InternalFailure), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[get_property] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -442,7 +502,10 @@ pub fn set_property(path: Vec<&str>, value: Option<&[u8]>) -> Result<(), Status> value.map_or(0, |value| value.len()), ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_property] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -484,7 +547,10 @@ pub fn get_shared_data(key: &str) -> Result<(Option, Option), Status } } Status::NotFound => Ok((None, None)), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[get_shared_data] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -510,7 +576,10 @@ pub fn set_shared_data(key: &str, value: Option<&[u8]>, cas: Option) -> Res ) { Status::Ok => Ok(()), Status::CasMismatch => Err(Status::CasMismatch), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_shared_data] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -528,7 +597,10 @@ pub fn register_shared_queue(name: &str) -> Result { let mut return_id: u32 = 0; match proxy_register_shared_queue(name.as_ptr(), name.len(), &mut return_id) { Status::Ok => Ok(return_id), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[register_shared_queue] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -555,7 +627,10 @@ pub fn resolve_shared_queue(vm_id: &str, name: &str) -> Result, Stat ) { Status::Ok => Ok(Some(return_id)), Status::NotFound => Ok(None), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[resolve_shared_queue] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -586,7 +661,10 @@ pub fn dequeue_shared_queue(queue_id: u32) -> Result, Status> { } Status::Empty => Ok(None), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[dequeue_shared_queue] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -608,7 +686,10 @@ pub fn enqueue_shared_queue(queue_id: u32, value: Option<&[u8]>) -> Result<(), S ) { Status::Ok => Ok(()), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[enqueue_shared_queue] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -621,7 +702,10 @@ pub fn resume_downstream() -> Result<(), Status> { unsafe { match proxy_continue_stream(StreamType::Downstream) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status =>{ + error!("[resume_downstream] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -630,7 +714,10 @@ pub fn resume_upstream() -> Result<(), Status> { unsafe { match proxy_continue_stream(StreamType::Upstream) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[resume_upstream] unexpected status: {}", status as u32); + Err(status) + } } } } @@ -639,7 +726,10 @@ pub fn resume_http_request() -> Result<(), Status> { unsafe { match proxy_continue_stream(StreamType::HttpRequest) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[resume_http_request] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -648,7 +738,10 @@ pub fn resume_http_response() -> Result<(), Status> { unsafe { match proxy_continue_stream(StreamType::HttpResponse) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[resume_http_response] unexpected status: {}", status as u32); + Err(status) + } } } } @@ -661,7 +754,10 @@ pub fn close_downstream() -> Result<(), Status> { unsafe { match proxy_close_stream(StreamType::Downstream) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status =>{ + error!("[close_downstream] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -669,7 +765,10 @@ pub fn close_upstream() -> Result<(), Status> { unsafe { match proxy_close_stream(StreamType::Upstream) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[close_upstream] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -678,7 +777,10 @@ pub fn reset_http_request() -> Result<(), Status> { unsafe { match proxy_close_stream(StreamType::HttpRequest) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[reset_http_request] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -687,7 +789,10 @@ pub fn reset_http_response() -> Result<(), Status> { unsafe { match proxy_close_stream(StreamType::HttpResponse) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[reset_http_response] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -723,7 +828,10 @@ pub fn send_http_response( -1, ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[send_http_response] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -746,7 +854,10 @@ pub fn send_grpc_response( grpc_status as i32, ) { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[send_grpc_response] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -795,7 +906,10 @@ pub fn dispatch_http_call( } Status::BadArgument => Err(Status::BadArgument), Status::InternalFailure => Err(Status::InternalFailure), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -848,7 +962,10 @@ pub fn dispatch_grpc_call( } Status::ParseFailure => Err(Status::ParseFailure), Status::InternalFailure => Err(Status::InternalFailure), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -893,7 +1010,10 @@ pub fn open_grpc_stream( } Status::ParseFailure => Err(Status::ParseFailure), Status::InternalFailure => Err(Status::InternalFailure), - status => panic!("unexpected status: {}", status as u32), + status =>{ + error!("[open_grpc_stream] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -922,7 +1042,10 @@ pub fn send_grpc_stream_message( Status::Ok => Ok(()), Status::BadArgument => Err(Status::BadArgument), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[send_grpc_stream_message] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -936,7 +1059,10 @@ pub fn cancel_grpc_call(token_id: u32) -> Result<(), Status> { match proxy_grpc_cancel(token_id) { Status::Ok => Ok(()), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -946,7 +1072,10 @@ pub fn cancel_grpc_stream(token_id: u32) -> Result<(), Status> { match proxy_grpc_cancel(token_id) { Status::Ok => Ok(()), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -960,7 +1089,10 @@ pub fn close_grpc_stream(token_id: u32) -> Result<(), Status> { match proxy_grpc_close(token_id) { Status::Ok => Ok(()), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[proxy_grpc_close] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -981,22 +1113,25 @@ pub fn get_grpc_status() -> Result<(u32, Option), Status> { match proxy_get_status(&mut return_code, &mut return_data, &mut return_size) { Status::Ok => { if !return_data.is_null() { - Ok(( - return_code, - Some( - String::from_utf8(Vec::from_raw_parts( - return_data, - return_size, - return_size, - )) - .unwrap(), - ), - )) + match String::from_utf8(Vec::from_raw_parts( + return_data, + return_size, + return_size, + )) { + Ok(return_data) => Ok((return_code, Some(return_data))), + Err(e) => { + error!("failed to parse grpc_status: {}", e); + Err(Status::InternalFailure) + } + } } else { Ok((return_code, None)) } } - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1010,7 +1145,10 @@ pub fn set_effective_context(context_id: u32) -> Result<(), Status> { match proxy_set_effective_context(context_id) { Status::Ok => Ok(()), Status::BadArgument => Err(Status::BadArgument), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[set_effective_context] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1056,7 +1194,10 @@ pub fn call_foreign_function( Status::BadArgument => Err(Status::BadArgument), Status::SerializationFailure => Err(Status::SerializationFailure), Status::InternalFailure => Err(Status::InternalFailure), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[call_foreign_function] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1069,7 +1210,10 @@ pub fn done() -> Result<(), Status> { unsafe { match proxy_done() { Status::Ok => Ok(()), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[done] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1088,7 +1232,10 @@ pub fn define_metric(metric_type: MetricType, name: &str) -> Result unsafe { match proxy_define_metric(metric_type, name.as_ptr(), name.len(), &mut return_id) { Status::Ok => Ok(return_id), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[define_metric] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1104,7 +1251,10 @@ pub fn get_metric(metric_id: u32) -> Result { Status::Ok => Ok(return_value), Status::NotFound => Err(Status::NotFound), Status::BadArgument => Err(Status::BadArgument), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[get_metric] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1118,7 +1268,10 @@ pub fn record_metric(metric_id: u32, value: u64) -> Result<(), Status> { match proxy_record_metric(metric_id, value) { Status::Ok => Ok(()), Status::NotFound => Err(Status::NotFound), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1133,7 +1286,10 @@ pub fn increment_metric(metric_id: u32, offset: i64) -> Result<(), Status> { Status::Ok => Ok(()), Status::NotFound => Err(Status::NotFound), Status::BadArgument => Err(Status::BadArgument), - status => panic!("unexpected status: {}", status as u32), + status => { + error!("[increment_metric] unexpected status: {}", status as u32); + Err(status) + }, } } } @@ -1141,6 +1297,7 @@ pub fn increment_metric(metric_id: u32, offset: i64) -> Result<(), Status> { mod utils { use crate::types::Bytes; use std::convert::TryFrom; + use log::error; pub(super) fn serialize_property_path(path: Vec<&str>) -> Bytes { if path.is_empty() { @@ -1199,48 +1356,189 @@ mod utils { bytes } + pub(super) fn deserialize_map(bytes: &[u8]) -> Vec<(String, String)> { let mut map = Vec::new(); + + // 如果数据为空,直接返回空的 Vec if bytes.is_empty() { return map; } - let size = u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[0..4]).unwrap()) as usize; + + // 确保数据至少有 4 个字节来读取大小信息 + if bytes.len() < 4 { + error!("[deserialize_map] Insufficient bytes to extract size"); + return map; // 数据不足,返回空的 Vec + } + + // 尝试读取前 4 个字节作为大小信息 + let size = match <[u8; 4]>::try_from(&bytes[0..4]) { + Ok(byte_array) => u32::from_le_bytes(byte_array) as usize, + Err(_) => { + error!("Failed to convert bytes to array when extracting size."); + return map; // 转换失败,返回空的 Vec + }, + }; + + // 计算出初始偏移量 `p` let mut p = 4 + size * 8; + + // 遍历每个键值对 for n in 0..size { let s = 4 + n * 8; - let size = u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[s..s + 4]).unwrap()) as usize; - let key = bytes[p..p + size].to_vec(); - p += size + 1; - let size = - u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[s + 4..s + 8]).unwrap()) as usize; - let value = bytes[p..p + size].to_vec(); - p += size + 1; - map.push(( - String::from_utf8(key).unwrap(), - String::from_utf8(value).unwrap(), - )); + + // 确保有足够的数据来处理当前条目 + if bytes.len() < s + 8 || bytes.len() < p { + error!("Insufficient bytes to read key-value pair."); + return map; + } + + // 读取 key 的大小 + let key_size = match <[u8; 4]>::try_from(&bytes[s..s + 4]) { + Ok(byte_array) => u32::from_le_bytes(byte_array) as usize, + Err(_) => { + error!("Failed to convert bytes to array when extracting key size."); + return map; + }, + }; + + // 确保有足够的字节用于 key + if bytes.len() < p + key_size { + error!("Insufficient bytes to read the key."); + return map; + } + + // 提取 key 的字节数组 + let key = bytes[p..p + key_size].to_vec(); + p += key_size + 1; // 跳过 key 后的 '\0' 字节 + + // 读取 value 的大小 + let value_size = match <[u8; 4]>::try_from(&bytes[s + 4..s + 8]) { + Ok(byte_array) => u32::from_le_bytes(byte_array) as usize, + Err(_) => { + error!("Failed to convert bytes to array when extracting value size."); + return map; + }, + }; + + // 确保有足够的字节用于 value + if bytes.len() < p + value_size { + error!("Insufficient bytes to read the value."); + return map; + } + + // 提取 value 的字节数组 + let value = bytes[p..p + value_size].to_vec(); + p += value_size + 1; // 跳过 value 后的 '\0' 字节 + + // 尝试将 key 和 value 转换为 String,处理转换失败的情况 + let key_string = String::from_utf8(key).unwrap_or_else(|e| { + error!("Failed to convert key to String: {}", e); + String::new() // 或者根据你的需求返回默认值 + }); + + let value_string = String::from_utf8(value).unwrap_or_else(|e| { + error!("Failed to convert value to String: {}", e); + String::new() // 或者根据你的需求返回默认值 + }); + + // 将成功转换的键值对推入 map + map.push((key_string, value_string)); } map } pub(super) fn deserialize_map_bytes(bytes: &[u8]) -> Vec<(String, Bytes)> { let mut map = Vec::new(); + + // 如果输入字节为空,直接返回空的 Vec if bytes.is_empty() { return map; } - let size = u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[0..4]).unwrap()) as usize; + + // 尝试读取前 4 个字节作为大小信息 + let size = match <[u8; 4]>::try_from(&bytes[0..4]) { + Ok(byte_array) => u32::from_le_bytes(byte_array) as usize, + Err(_) => { + error!("Failed to read map size from bytes."); + return map; + } + }; + let mut p = 4 + size * 8; + + // 遍历每个键值对 for n in 0..size { let s = 4 + n * 8; - let size = u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[s..s + 4]).unwrap()) as usize; - let key = bytes[p..p + size].to_vec(); - p += size + 1; - let size = - u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[s + 4..s + 8]).unwrap()) as usize; - let value = bytes[p..p + size].to_vec(); - p += size + 1; - map.push((String::from_utf8(key).unwrap(), value)); + + // 尝试读取键的大小 + let key_size = match <[u8; 4]>::try_from(&bytes[s..s + 4]) { + Ok(byte_array) => u32::from_le_bytes(byte_array) as usize, + Err(_) => { + error!("Failed to read key size from bytes."); + return map; + } + }; + + // 确保有足够的字节来读取 key + if p + key_size > bytes.len() { + error!("Insufficient bytes to read key."); + return map; + } + + let key = bytes[p..p + key_size].to_vec(); + p += key_size + 1; // 跳过 key 后的 '\0' 字符 + + // 尝试读取值的大小 + let value_size = match <[u8; 4]>::try_from(&bytes[s + 4..s + 8]) { + Ok(byte_array) => u32::from_le_bytes(byte_array) as usize, + Err(_) => { + error!("Failed to read value size from bytes."); + return map; + } + }; + + // 确保有足够的字节来读取 value + if p + value_size > bytes.len() { + error!("Insufficient bytes to read value."); + return map; + } + + let value = bytes[p..p + value_size].to_vec(); + p += value_size + 1; // 跳过 value 后的 '\0' 字符 + + // 尝试将 key 从字节转换为 UTF-8 字符串 + match String::from_utf8(key) { + Ok(key_string) => map.push((key_string, Bytes::from(value))), + Err(e) => { + error!("Failed to convert key to String: {}", e); + return map; + } + } } + map } + + // + // pub(super) fn deserialize_map_bytes(bytes: &[u8]) -> Vec<(String, Bytes)> { + // let mut map = Vec::new(); + // if bytes.is_empty() { + // return map; + // } + // let size = u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[0..4]).unwrap()) as usize; + // let mut p = 4 + size * 8; + // for n in 0..size { + // let s = 4 + n * 8; + // let size = u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[s..s + 4]).unwrap()) as usize; + // let key = bytes[p..p + size].to_vec(); + // p += size + 1; + // let size = + // u32::from_le_bytes(<[u8; 4]>::try_from(&bytes[s + 4..s + 8]).unwrap()) as usize; + // let value = bytes[p..p + size].to_vec(); + // p += size + 1; + // map.push((String::from_utf8(key).unwrap(), value)); + // } + // map + // } } diff --git a/src/lib.rs b/src/lib.rs index a8f42651..d576c782 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,7 +55,7 @@ macro_rules! main { } pub fn set_log_level(level: types::LogLevel) { - logger::set_log_level(level); + let _ = logger::set_log_level(level); } pub fn set_root_context(callback: types::NewRootContext) { diff --git a/src/logger.rs b/src/logger.rs index 050a356d..6cb2e30d 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -22,17 +22,24 @@ struct Logger; static LOGGER: Logger = Logger; static INITIALIZED: AtomicBool = AtomicBool::new(false); -pub(crate) fn set_log_level(level: LogLevel) { +pub(crate) fn set_log_level(level: LogLevel) -> Result<(), Box> { if !INITIALIZED.load(Ordering::Relaxed) { - log::set_logger(&LOGGER).unwrap(); + log::set_logger(&LOGGER) + .map_err(|e| format!("Failed to set logger: {}", e))?; + panic::set_hook(Box::new(|panic_info| { - hostcalls::log(LogLevel::Critical, &panic_info.to_string()).unwrap(); + if let Err(e) = hostcalls::log(LogLevel::Critical, &panic_info.to_string()) { + eprintln!("Failed to log panic info: {:?}", e); + } })); + INITIALIZED.store(true, Ordering::Relaxed); } LOGGER.set_log_level(level); + Ok(()) } + impl Logger { pub fn set_log_level(&self, level: LogLevel) { let filter = match level { @@ -64,8 +71,12 @@ impl log::Log for Logger { log::Level::Error => LogLevel::Error, }; let message = record.args().to_string(); - hostcalls::log(level, &message).unwrap(); + if let Err(e) = hostcalls::log(level, &message) { + // 如果日志记录失败,我们可以尝试打印到标准错误 + eprintln!("Failed to log message: {}. Error: {:?}", message, e); + } } + fn flush(&self) {} } diff --git a/src/traits.rs b/src/traits.rs index bd54bcbe..e00c9695 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -15,22 +15,30 @@ use crate::hostcalls; use crate::types::*; use std::time::{Duration, SystemTime}; +use log::error; pub trait Context { fn get_current_time(&self) -> SystemTime { - hostcalls::get_current_time().unwrap() + hostcalls::get_current_time().unwrap_or_else(|_| SystemTime::now()) } fn get_property(&self, path: Vec<&str>) -> Option { - hostcalls::get_property(path).unwrap() + hostcalls::get_property(path).unwrap_or_else(|_| None) } fn set_property(&self, path: Vec<&str>, value: Option<&[u8]>) { - hostcalls::set_property(path, value).unwrap() + hostcalls::set_property(path, value).unwrap_or_else(|_| ()) } fn get_shared_data(&self, key: &str) -> (Option, Option) { - hostcalls::get_shared_data(key).unwrap() + let data = hostcalls::get_shared_data(key); + match data { + Err(e) => { + error!("[get_shared_data] err is {:?}",e); + (None, None) + }, + Ok((data, status)) => (data, status), + } } fn set_shared_data( @@ -43,11 +51,11 @@ pub trait Context { } fn register_shared_queue(&self, name: &str) -> u32 { - hostcalls::register_shared_queue(name).unwrap() + hostcalls::register_shared_queue(name).unwrap_or_else(|_| 0) } fn resolve_shared_queue(&self, vm_id: &str, name: &str) -> Option { - hostcalls::resolve_shared_queue(vm_id, name).unwrap() + hostcalls::resolve_shared_queue(vm_id, name).unwrap_or_else(|_| None) } fn dequeue_shared_queue(&self, queue_id: u32) -> Result, Status> { @@ -79,39 +87,39 @@ pub trait Context { } fn get_http_call_response_headers(&self) -> Vec<(String, String)> { - hostcalls::get_map(MapType::HttpCallResponseHeaders).unwrap() + hostcalls::get_map(MapType::HttpCallResponseHeaders).unwrap_or_default() } fn get_http_call_response_headers_bytes(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::HttpCallResponseHeaders).unwrap() + hostcalls::get_map_bytes(MapType::HttpCallResponseHeaders).unwrap_or_default() } fn get_http_call_response_header(&self, name: &str) -> Option { - hostcalls::get_map_value(MapType::HttpCallResponseHeaders, name).unwrap() + hostcalls::get_map_value(MapType::HttpCallResponseHeaders, name).unwrap_or_default() } fn get_http_call_response_header_bytes(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::HttpCallResponseHeaders, name).unwrap() + hostcalls::get_map_value_bytes(MapType::HttpCallResponseHeaders, name).unwrap_or_default() } fn get_http_call_response_body(&self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::HttpCallResponseBody, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::HttpCallResponseBody, start, max_size).unwrap_or_else(|_| None) } fn get_http_call_response_trailers(&self) -> Vec<(String, String)> { - hostcalls::get_map(MapType::HttpCallResponseTrailers).unwrap() + hostcalls::get_map(MapType::HttpCallResponseTrailers).unwrap_or_default() } fn get_http_call_response_trailers_bytes(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::HttpCallResponseTrailers).unwrap() + hostcalls::get_map_bytes(MapType::HttpCallResponseTrailers).unwrap_or_default() } fn get_http_call_response_trailer(&self, name: &str) -> Option { - hostcalls::get_map_value(MapType::HttpCallResponseTrailers, name).unwrap() + hostcalls::get_map_value(MapType::HttpCallResponseTrailers, name).unwrap_or_default() } fn get_http_call_response_trailer_bytes(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::HttpCallResponseTrailers, name).unwrap() + hostcalls::get_map_value_bytes(MapType::HttpCallResponseTrailers, name).unwrap_or_default() } fn dispatch_grpc_call( @@ -136,11 +144,14 @@ pub trait Context { fn on_grpc_call_response(&mut self, _token_id: u32, _status_code: u32, _response_size: usize) {} fn get_grpc_call_response_body(&self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, start, max_size).unwrap_or_else(|e| { + error!("[get_grpc_call_response_body] err is {:?}",e); + None + }) } fn cancel_grpc_call(&self, token_id: u32) { - hostcalls::cancel_grpc_call(token_id).unwrap() + hostcalls::cancel_grpc_call(token_id).unwrap_or_else(|_| ()) } fn open_grpc_stream( @@ -156,45 +167,64 @@ pub trait Context { fn on_grpc_stream_initial_metadata(&mut self, _token_id: u32, _num_elements: u32) {} fn get_grpc_stream_initial_metadata(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::GrpcReceiveInitialMetadata).unwrap() + hostcalls::get_map_bytes(MapType::GrpcReceiveInitialMetadata).unwrap_or_default() } fn get_grpc_stream_initial_metadata_value(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::GrpcReceiveInitialMetadata, name).unwrap() + hostcalls::get_map_value_bytes(MapType::GrpcReceiveInitialMetadata, name) + .unwrap_or_else(|e| { + error!("Failed to get gRPC stream initial metadata for '{}': {:?}", name, e); + None + }) } + fn send_grpc_stream_message(&self, token_id: u32, message: Option<&[u8]>, end_stream: bool) { - hostcalls::send_grpc_stream_message(token_id, message, end_stream).unwrap() + hostcalls::send_grpc_stream_message(token_id, message, end_stream).unwrap_or_else(|e| { + error!("[send_grpc_stream_message] err is {:?}",e); }) } fn on_grpc_stream_message(&mut self, _token_id: u32, _message_size: usize) {} fn get_grpc_stream_message(&mut self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, start, max_size).unwrap_or_else(|e| { + error!("[get_grpc_stream_message] err is {:?}",e); + None + }) } fn on_grpc_stream_trailing_metadata(&mut self, _token_id: u32, _num_elements: u32) {} fn get_grpc_stream_trailing_metadata(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::GrpcReceiveTrailingMetadata).unwrap() + hostcalls::get_map_bytes(MapType::GrpcReceiveTrailingMetadata).unwrap_or_else(|e|{ + error!("[get_grpc_stream_trailing_metadata] err is {:?}",e); + Vec::new() + }) } fn get_grpc_stream_trailing_metadata_value(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::GrpcReceiveTrailingMetadata, name).unwrap() + hostcalls::get_map_value_bytes(MapType::GrpcReceiveTrailingMetadata, name).unwrap_or_else(|e| { + error!("Failed to get gRPC stream trailing metadata for '{}': {:?}", name, e); + None + }) } fn cancel_grpc_stream(&self, token_id: u32) { - hostcalls::cancel_grpc_stream(token_id).unwrap() + hostcalls::cancel_grpc_stream(token_id).unwrap_or_else(|e| { + error!("[cancel_grpc_stream] err is {:?}",e); + }) } fn close_grpc_stream(&self, token_id: u32) { - hostcalls::close_grpc_stream(token_id).unwrap() + hostcalls::close_grpc_stream(token_id).unwrap_or_else(|e| { + error!("[close_grpc_stream] err is {:?}",e); + }) } fn on_grpc_stream_close(&mut self, _token_id: u32, _status_code: u32) {} fn get_grpc_status(&self) -> (u32, Option) { - hostcalls::get_grpc_status().unwrap() + hostcalls::get_grpc_status().unwrap_or_default() } fn call_foreign_function( @@ -210,7 +240,9 @@ pub trait Context { } fn done(&self) { - hostcalls::done().unwrap() + hostcalls::done().unwrap_or_else(|e| { + error!("[on_done] err is {:?}",e); + }) } } @@ -220,7 +252,10 @@ pub trait RootContext: Context { } fn get_vm_configuration(&self) -> Option { - hostcalls::get_buffer(BufferType::VmConfiguration, 0, usize::MAX).unwrap() + hostcalls::get_buffer(BufferType::VmConfiguration, 0, usize::MAX).unwrap_or_else(|e| { + error!("[get_vm_configuration] err is {:?}",e); + None + }) } fn on_configure(&mut self, _plugin_configuration_size: usize) -> bool { @@ -228,11 +263,16 @@ pub trait RootContext: Context { } fn get_plugin_configuration(&self) -> Option { - hostcalls::get_buffer(BufferType::PluginConfiguration, 0, usize::MAX).unwrap() + hostcalls::get_buffer(BufferType::PluginConfiguration, 0, usize::MAX).unwrap_or_else(|e| { + error!("[get_plugin_configuration] err is {:?}",e); + None + }) } fn set_tick_period(&self, period: Duration) { - hostcalls::set_tick_period(period).unwrap() + hostcalls::set_tick_period(period).unwrap_or_else(|e| { + error!("[set_tick_period] err is {:?}",e); + }) } fn on_tick(&mut self) {} @@ -264,19 +304,28 @@ pub trait StreamContext: Context { } fn get_downstream_data(&self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::DownstreamData, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::DownstreamData, start, max_size).unwrap_or_else(|e| { + error!("[get_downstream_data] err is {:?}",e); + None + }) } fn set_downstream_data(&self, start: usize, size: usize, value: &[u8]) { - hostcalls::set_buffer(BufferType::DownstreamData, start, size, value).unwrap() + hostcalls::set_buffer(BufferType::DownstreamData, start, size, value).unwrap_or_else(|e| { + error!("[set_downstream_data] err is {:?}",e); + }) } fn resume_downstream(&self) { - hostcalls::resume_downstream().unwrap() + hostcalls::resume_downstream().unwrap_or_else(|e| { + error!("[resume_downstream] err is {:?}",e); + }) } fn close_downstream(&self) { - hostcalls::close_downstream().unwrap() + hostcalls::close_downstream().unwrap_or_else(|e| { + error!("[close_downstream] err is {:?}",e); + }) } fn on_downstream_close(&mut self, _peer_type: PeerType) {} @@ -286,19 +335,28 @@ pub trait StreamContext: Context { } fn get_upstream_data(&self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::UpstreamData, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::UpstreamData, start, max_size).unwrap_or_else(|e| { + error!("[get_upstream_data] err is {:?}",e); + None + }) } fn set_upstream_data(&self, start: usize, size: usize, value: &[u8]) { - hostcalls::set_buffer(BufferType::UpstreamData, start, size, value).unwrap() + hostcalls::set_buffer(BufferType::UpstreamData, start, size, value).unwrap_or_else(|e| { + error!("[set_upstream_data] err is {:?}",e); + }) } fn resume_upstream(&self) { - hostcalls::resume_upstream().unwrap() + hostcalls::resume_upstream().unwrap_or_else(|e| { + error!("[resume_upstream] err is {:?}",e); + }) } fn close_upstream(&self) { - hostcalls::close_upstream().unwrap() + hostcalls::close_upstream().unwrap_or_else(|e| { + error!("[close_upstream] err is {:?}",e); + }) } fn on_upstream_close(&mut self, _peer_type: PeerType) {} @@ -312,43 +370,67 @@ pub trait HttpContext: Context { } fn get_http_request_headers(&self) -> Vec<(String, String)> { - hostcalls::get_map(MapType::HttpRequestHeaders).unwrap() + hostcalls::get_map(MapType::HttpRequestHeaders).unwrap_or_else(|e| { + error!("get_map http_request_headers error: {:?} so return new vec", e); + Vec::new() + }) } fn get_http_request_headers_bytes(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::HttpRequestHeaders).unwrap() + hostcalls::get_map_bytes(MapType::HttpRequestHeaders).unwrap_or_else(|e| { + error!("get_map http_request_headers error: {:?} so return new vec", e); + Vec::new() + }) } fn set_http_request_headers(&self, headers: Vec<(&str, &str)>) { - hostcalls::set_map(MapType::HttpRequestHeaders, headers).unwrap() + hostcalls::set_map(MapType::HttpRequestHeaders, headers).unwrap_or_else(|e| { + error!("set_map http_request_headers error: {:?} so return new vec", e); + }) } fn set_http_request_headers_bytes(&self, headers: Vec<(&str, &[u8])>) { - hostcalls::set_map_bytes(MapType::HttpRequestHeaders, headers).unwrap() + hostcalls::set_map_bytes(MapType::HttpRequestHeaders, headers).unwrap_or_else(|e| { + error!("set_map http_request_headers error: {:?} so return new vec", e); + }) } fn get_http_request_header(&self, name: &str) -> Option { - hostcalls::get_map_value(MapType::HttpRequestHeaders, name).unwrap() + hostcalls::get_map_value(MapType::HttpRequestHeaders, name).unwrap_or_else(|e| { + error!("get_http_request_header failed for http request: {:?}", e); + None + }) } fn get_http_request_header_bytes(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::HttpRequestHeaders, name).unwrap() + hostcalls::get_map_value_bytes(MapType::HttpRequestHeaders, name).unwrap_or_else(|e| { + error!("get_http_request_header failed for http request: {:?}", e); + None + }) } fn set_http_request_header(&self, name: &str, value: Option<&str>) { - hostcalls::set_map_value(MapType::HttpRequestHeaders, name, value).unwrap() + hostcalls::set_map_value(MapType::HttpRequestHeaders, name, value).unwrap_or_else(|e| { + error!("set_http_request_header failed for http request: {:?}", e); + }) } fn set_http_request_header_bytes(&self, name: &str, value: Option<&[u8]>) { - hostcalls::set_map_value_bytes(MapType::HttpRequestHeaders, name, value).unwrap() + hostcalls::set_map_value_bytes(MapType::HttpRequestHeaders, name, value).unwrap_or_else(|e| { + error!("set_http_request_header failed for http request: {:?}", e); + }) } fn add_http_request_header(&self, name: &str, value: &str) { - hostcalls::add_map_value(MapType::HttpRequestHeaders, name, value).unwrap() + hostcalls::add_map_value(MapType::HttpRequestHeaders, name, value).unwrap_or_else(|e| { + error!("add_http_request_header failed for http request: {:?}", e); + }) } fn add_http_request_header_bytes(&self, name: &str, value: &[u8]) { - hostcalls::add_map_value_bytes(MapType::HttpRequestHeaders, name, value).unwrap() + hostcalls::add_map_value_bytes(MapType::HttpRequestHeaders, name, value).unwrap_or_else(|e| { + error!("add_http_request_header failed for http request: {:?}", e); + }) } fn on_http_request_body(&mut self, _body_size: usize, _end_of_stream: bool) -> Action { @@ -356,11 +438,16 @@ pub trait HttpContext: Context { } fn get_http_request_body(&self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::HttpRequestBody, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::HttpRequestBody, start, max_size).unwrap_or_else(|e| { + error!("get_http_request_body error: {:?} so return new vec", e); + None + }) } fn set_http_request_body(&self, start: usize, size: usize, value: &[u8]) { - hostcalls::set_buffer(BufferType::HttpRequestBody, start, size, value).unwrap() + hostcalls::set_buffer(BufferType::HttpRequestBody, start, size, value).unwrap_or_else(|e| { + error!("set_http_request_body error: {:?} so return new vec", e); + }) } fn on_http_request_trailers(&mut self, _num_trailers: usize) -> Action { @@ -368,51 +455,77 @@ pub trait HttpContext: Context { } fn get_http_request_trailers(&self) -> Vec<(String, String)> { - hostcalls::get_map(MapType::HttpRequestTrailers).unwrap() + hostcalls::get_map(MapType::HttpRequestTrailers).unwrap_or_else(|e| { + error!("get_http_request_trailers error: {:?} so return new vec", e); + Vec::new() + }) } fn get_http_request_trailers_bytes(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::HttpRequestTrailers).unwrap() + hostcalls::get_map_bytes(MapType::HttpRequestTrailers).unwrap_or_else(|e| { + error!("get_http_request_trailers error: {:?} so return new vec", e); + Vec::new() + }) } fn set_http_request_trailers(&self, trailers: Vec<(&str, &str)>) { - hostcalls::set_map(MapType::HttpRequestTrailers, trailers).unwrap() + hostcalls::set_map(MapType::HttpRequestTrailers, trailers).unwrap_or_else(|e| { + error!("set_http_request_trailers error: {:?} so return new vec", e); + }) } fn set_http_request_trailers_bytes(&self, trailers: Vec<(&str, &[u8])>) { - hostcalls::set_map_bytes(MapType::HttpRequestTrailers, trailers).unwrap() + hostcalls::set_map_bytes(MapType::HttpRequestTrailers, trailers).unwrap_or_else(|e| { + error!("set_http_request_trailers error: {:?} so return new vec", e); + }) } fn get_http_request_trailer(&self, name: &str) -> Option { - hostcalls::get_map_value(MapType::HttpRequestTrailers, name).unwrap() + hostcalls::get_map_value(MapType::HttpRequestTrailers, name).unwrap_or_else(|e| { + error!("get_http_request_trailer failed for http request: {:?}", e); + None + }) } fn get_http_request_trailer_bytes(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::HttpRequestTrailers, name).unwrap() + hostcalls::get_map_value_bytes(MapType::HttpRequestTrailers, name).unwrap_or_else(|e| { + error!("get_http_request_trailer failed for http request: {:?}", e); + None + }) } fn set_http_request_trailer(&self, name: &str, value: Option<&str>) { - hostcalls::set_map_value(MapType::HttpRequestTrailers, name, value).unwrap() + hostcalls::set_map_value(MapType::HttpRequestTrailers, name, value).unwrap_or_else(|e| { + error!("set_http_request_trailer failed for http request: {:?}", e); + }) } fn set_http_request_trailer_bytes(&self, name: &str, value: Option<&[u8]>) { - hostcalls::set_map_value_bytes(MapType::HttpRequestTrailers, name, value).unwrap() + hostcalls::set_map_value_bytes(MapType::HttpRequestTrailers, name, value).unwrap_or_else(|e| { + error!("set_http_request_trailer failed for http request: {:?}", e); + }) } fn add_http_request_trailer(&self, name: &str, value: &str) { - hostcalls::add_map_value(MapType::HttpRequestTrailers, name, value).unwrap() + hostcalls::add_map_value(MapType::HttpRequestTrailers, name, value).unwrap_or_else(|e| { + error!("add_http_request_trailer failed for http request: {:?}", e); + }) } fn add_http_request_trailer_bytes(&self, name: &str, value: &[u8]) { - hostcalls::add_map_value_bytes(MapType::HttpRequestTrailers, name, value).unwrap() + hostcalls::add_map_value_bytes(MapType::HttpRequestTrailers, name, value).unwrap_or_else(|e| { + error!("add_http_request_trailer failed for http request: {:?}", e); + }) } - fn resume_http_request(&self) { - hostcalls::resume_http_request().unwrap() + fn resume_http_request(&self) -> Result<(), Status> { + hostcalls::resume_http_request() } fn reset_http_request(&self) { - hostcalls::reset_http_request().unwrap() + hostcalls::reset_http_request().unwrap_or_else(|e| { + error!("reset_http_request error: {:?}", e); + }) } fn on_http_response_headers(&mut self, _num_headers: usize, _end_of_stream: bool) -> Action { @@ -420,43 +533,67 @@ pub trait HttpContext: Context { } fn get_http_response_headers(&self) -> Vec<(String, String)> { - hostcalls::get_map(MapType::HttpResponseHeaders).unwrap() + hostcalls::get_map(MapType::HttpResponseHeaders).unwrap_or_else(|e| { + error!("get_map http_request_headers error: {:?} so return new vec", e); + Vec::new() + }) } fn get_http_response_headers_bytes(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::HttpResponseHeaders).unwrap() + hostcalls::get_map_bytes(MapType::HttpResponseHeaders).unwrap_or_else(|e|{ + error!("get_http_response_headers error: {:?} so return new vec", e); + Vec::new() + }) } fn set_http_response_headers(&self, headers: Vec<(&str, &str)>) { - hostcalls::set_map(MapType::HttpResponseHeaders, headers).unwrap() + hostcalls::set_map(MapType::HttpResponseHeaders, headers).unwrap_or_else(|e| { + error!("set_http_response_headers error: {:?} so return new vec", e); + }) } fn set_http_response_headers_bytes(&self, headers: Vec<(&str, &[u8])>) { - hostcalls::set_map_bytes(MapType::HttpResponseHeaders, headers).unwrap() + hostcalls::set_map_bytes(MapType::HttpResponseHeaders, headers).unwrap_or_else(|e| { + error!("set_http_response_headers error: {:?} so return new vec", e); + }) } fn get_http_response_header(&self, name: &str) -> Option { - hostcalls::get_map_value(MapType::HttpResponseHeaders, name).unwrap() + hostcalls::get_map_value(MapType::HttpResponseHeaders, name).unwrap_or_else(|e| { + error!("get_http_response_headers error: {:?} so return new vec", e); + None + }) } fn get_http_response_header_bytes(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::HttpResponseHeaders, name).unwrap() + hostcalls::get_map_value_bytes(MapType::HttpResponseHeaders, name).unwrap_or_else(|e| { + error!("get_http_response_headers error: {:?} so return new vec", e); + None + }) } fn set_http_response_header(&self, name: &str, value: Option<&str>) { - hostcalls::set_map_value(MapType::HttpResponseHeaders, name, value).unwrap() + hostcalls::set_map_value(MapType::HttpResponseHeaders, name, value).unwrap_or_else(|e| { + error!("set_http_response_header failed for http request: {:?}", e); + }) } fn set_http_response_header_bytes(&self, name: &str, value: Option<&[u8]>) { - hostcalls::set_map_value_bytes(MapType::HttpResponseHeaders, name, value).unwrap() + hostcalls::set_map_value_bytes(MapType::HttpResponseHeaders, name, value).unwrap_or_else(|e| { + error!("set_http_response_header failed for http request: {:?}", e); + }) } fn add_http_response_header(&self, name: &str, value: &str) { - hostcalls::add_map_value(MapType::HttpResponseHeaders, name, value).unwrap() + hostcalls::add_map_value(MapType::HttpResponseHeaders, name, value).unwrap_or_else(|e| { + error!("add_http_response_header failed for http request: {:?}", e); + }) } fn add_http_response_header_bytes(&self, name: &str, value: &[u8]) { - hostcalls::add_map_value_bytes(MapType::HttpResponseHeaders, name, value).unwrap() + hostcalls::add_map_value_bytes(MapType::HttpResponseHeaders, name, value).unwrap_or_else(|e| { + error!("add_http_response_header_bytes failed for http request: {:?}", e); + }) } fn on_http_response_body(&mut self, _body_size: usize, _end_of_stream: bool) -> Action { @@ -464,11 +601,16 @@ pub trait HttpContext: Context { } fn get_http_response_body(&self, start: usize, max_size: usize) -> Option { - hostcalls::get_buffer(BufferType::HttpResponseBody, start, max_size).unwrap() + hostcalls::get_buffer(BufferType::HttpResponseBody, start, max_size).unwrap_or_else(|e|{ + error!("get_http_response_body error: {:?} so return new vec", e); + None + }) } fn set_http_response_body(&self, start: usize, size: usize, value: &[u8]) { - hostcalls::set_buffer(BufferType::HttpResponseBody, start, size, value).unwrap() + hostcalls::set_buffer(BufferType::HttpResponseBody, start, size, value).unwrap_or_else(|e| { + error!("set_http_response_body error: {:?} so return new vec", e); + }) } fn on_http_response_trailers(&mut self, _num_trailers: usize) -> Action { @@ -476,51 +618,79 @@ pub trait HttpContext: Context { } fn get_http_response_trailers(&self) -> Vec<(String, String)> { - hostcalls::get_map(MapType::HttpResponseTrailers).unwrap() + hostcalls::get_map(MapType::HttpResponseTrailers).unwrap_or_else(|e| { + error!("get_http_response_trailers error: {:?} so return new vec", e); + Vec::new() + }) } fn get_http_response_trailers_bytes(&self) -> Vec<(String, Bytes)> { - hostcalls::get_map_bytes(MapType::HttpResponseTrailers).unwrap() + hostcalls::get_map_bytes(MapType::HttpResponseTrailers).unwrap_or_else(|e| { + error!("get_http_response_trailers error: {:?} so return new vec", e); + Vec::new() + }) } fn set_http_response_trailers(&self, trailers: Vec<(&str, &str)>) { - hostcalls::set_map(MapType::HttpResponseTrailers, trailers).unwrap() + hostcalls::set_map(MapType::HttpResponseTrailers, trailers).unwrap_or_else(|e| { + error!("set_http_response_trailers error: {:?} so return new vec", e); + }) } fn set_http_response_trailers_bytes(&self, trailers: Vec<(&str, &[u8])>) { - hostcalls::set_map_bytes(MapType::HttpResponseTrailers, trailers).unwrap() + hostcalls::set_map_bytes(MapType::HttpResponseTrailers, trailers).unwrap_or_else(|e| { + error!("set_http_response_trailers error: {:?} so return new vec", e); + }) } fn get_http_response_trailer(&self, name: &str) -> Option { - hostcalls::get_map_value(MapType::HttpResponseTrailers, name).unwrap() + hostcalls::get_map_value(MapType::HttpResponseTrailers, name).unwrap_or_else(|e| { + error!("get_http_response_trailer failed: {:?} so return new vec", e); + None + }) } fn get_http_response_trailer_bytes(&self, name: &str) -> Option { - hostcalls::get_map_value_bytes(MapType::HttpResponseTrailers, name).unwrap() + hostcalls::get_map_value_bytes(MapType::HttpResponseTrailers, name).unwrap_or_else(|e| { + error!("get_http_response_trailer failed: {:?} so return new vec", e); + None + }) } fn set_http_response_trailer(&self, name: &str, value: Option<&str>) { - hostcalls::set_map_value(MapType::HttpResponseTrailers, name, value).unwrap() + hostcalls::set_map_value(MapType::HttpResponseTrailers, name, value).unwrap_or_else(|e| { + error!("set_http_response_trailer failed: {:?} so return new vec", e); + }) } fn set_http_response_trailer_bytes(&self, name: &str, value: Option<&[u8]>) { - hostcalls::set_map_value_bytes(MapType::HttpResponseTrailers, name, value).unwrap() + hostcalls::set_map_value_bytes(MapType::HttpResponseTrailers, name, value).unwrap_or_else(|e| { + error!("set_http_response_trailer failed: {:?} so return new vec", e); + }) } fn add_http_response_trailer(&self, name: &str, value: &str) { - hostcalls::add_map_value(MapType::HttpResponseTrailers, name, value).unwrap() + hostcalls::add_map_value(MapType::HttpResponseTrailers, name, value).unwrap_or_else(|e| { + error!("add_http_response_trailer failed: {:?} so return new vec", e); + }) } fn add_http_response_trailer_bytes(&self, name: &str, value: &[u8]) { - hostcalls::add_map_value_bytes(MapType::HttpResponseTrailers, name, value).unwrap() + hostcalls::add_map_value_bytes(MapType::HttpResponseTrailers, name, value).unwrap_or_else(|e| { + error!("add_http_response_trailer failed: {:?} so return new vec", e); + }) } fn resume_http_response(&self) { - hostcalls::resume_http_response().unwrap() + hostcalls::resume_http_response().unwrap_or_else(|e| { + error!("resume_http_response failed: {:?} so return new vec", e); + }) } fn reset_http_response(&self) { - hostcalls::reset_http_response().unwrap() + hostcalls::reset_http_response().unwrap_or_else(|e| { + error!("reset_http_response failed: {:?} so return new vec", e); + }) } fn send_http_response( @@ -529,7 +699,9 @@ pub trait HttpContext: Context { headers: Vec<(&str, &str)>, body: Option<&[u8]>, ) { - hostcalls::send_http_response(status_code, headers, body).unwrap() + hostcalls::send_http_response(status_code, headers, body).unwrap_or_else(|e| { + error!("send_http_response failed: {:?} so return new vec", e); + }) } fn send_grpc_response( @@ -538,7 +710,9 @@ pub trait HttpContext: Context { grpc_status_message: Option<&str>, custom_metadata: Vec<(&str, &[u8])>, ) { - hostcalls::send_grpc_response(grpc_status, grpc_status_message, custom_metadata).unwrap() + hostcalls::send_grpc_response(grpc_status, grpc_status_message, custom_metadata).unwrap_or_else(|e| { + error!("send_grpc_response failed: {:?} so return new vec", e); + }) } fn on_log(&mut self) {}