Skip to content

Commit

Permalink
Remove unwraps
Browse files Browse the repository at this point in the history
  • Loading branch information
Philipp Reiter committed Sep 28, 2024
1 parent 49efefb commit 6a05aac
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 22 deletions.
2 changes: 1 addition & 1 deletion wireman-core/examples/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() -> Result<()> {
}

pub fn do_request(req: &RequestMessage) -> Result<ResponseMessage> {
let tls_config = TlsConfig::native()?;
let tls_config = TlsConfig::native();
let resp = call_unary_blocking(req, Some(tls_config))?;
Ok(resp)
}
5 changes: 1 addition & 4 deletions wireman-core/examples/reflection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,11 @@ async fn main() -> Result<()> {
let mut req = desc.get_request(&method);
req.set_address("http://localhost:50051");

// let resp = do_request(&req).await?;
// println!("\nResponse:\n{:}", resp.message.to_json()?);

Ok(())
}

pub async fn do_request(req: &RequestMessage) -> Result<ResponseMessage> {
let tls_config = TlsConfig::native()?;
let tls_config = TlsConfig::native();
let resp = call_unary_async(req, Some(tls_config)).await?;
Ok(resp)
}
4 changes: 4 additions & 0 deletions wireman-core/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ pub struct GrpcClient {
impl GrpcClient {
/// Returns a new Grpc Client. if no tls is given, the standard tonic
/// client is used.
///
/// # Errors
///
/// Errors if tls config cannot be build.
pub fn new<T: Into<Uri>>(uri: T, tls_config: Option<TlsConfig>) -> Result<Self> {
let builder = Channel::builder(uri.into());

Expand Down
37 changes: 31 additions & 6 deletions wireman-core/src/client/reflection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ use tonic_reflection::pb::v1::{

use crate::error::Error;

/// # Errors
///
/// Fails if server reflection fails.
pub async fn make_file_by_symbol_reflection_request(
host: &str,
containing_symbol: &str,
Expand All @@ -20,6 +23,9 @@ pub async fn make_file_by_symbol_reflection_request(
make_file_reflection_request(host, request).await
}

/// # Errors
///
/// Fails if server reflection fails.
pub async fn make_file_by_filename_reflection_request(
host: &str,
filename: &str,
Expand All @@ -28,6 +34,9 @@ pub async fn make_file_by_filename_reflection_request(
make_file_reflection_request(host, request).await
}

/// # Errors
///
/// Fails if server reflection fails.
pub async fn make_file_reflection_request(
host: &str,
request: MessageRequest,
Expand All @@ -38,7 +47,8 @@ pub async fn make_file_reflection_request(
};
let request = Request::new(tokio_stream::once(request));

let uri = Uri::from_str(host).unwrap();
let uri = Uri::from_str(host)
.map_err(|_| Error::Internal(format!("Could not create uri from string {host}")))?;
let builder = Channel::builder(uri);
let channel = builder.connect_lazy();

Expand All @@ -52,21 +62,31 @@ pub async fn make_file_reflection_request(
.message_response
.ok_or(Error::Internal("No message response".to_string()))?;

assert!(inbound.next().await.is_none());
debug_assert!(inbound.next().await.is_none());

let MessageResponse::FileDescriptorResponse(descriptor) = response else {
let internal =
Error::Internal("File descriptor reflection response is of incorrect type".to_string());
return Err(internal);
};

let buf = descriptor.file_descriptor_proto.first().unwrap().as_ref();
let buf = descriptor
.file_descriptor_proto
.first()
.ok_or(Error::Internal(
"No file descriptor proto found".to_string(),
))?
.as_ref();

let file_descriptor = FileDescriptorProto::decode(buf).expect("Failed to decode");
let file_descriptor = FileDescriptorProto::decode(buf)
.map_err(|_| Error::Internal("Failed to decode".to_string()))?;

Ok(file_descriptor)
}

/// # Errors
///
/// Fails if server reflection fails.
pub async fn make_list_service_reflection_request(host: &str) -> Result<Vec<String>, Error> {
let message_request = MessageRequest::ListServices(String::new());
let request = ServerReflectionRequest {
Expand All @@ -75,7 +95,8 @@ pub async fn make_list_service_reflection_request(host: &str) -> Result<Vec<Stri
};
let request = Request::new(tokio_stream::once(request));

let uri = Uri::from_str(host).unwrap();
let uri = Uri::from_str(host)
.map_err(|_| Error::Internal(format!("Could not create uri from string {host}")))?;
let builder = Channel::builder(uri);
let channel = builder.connect_lazy();

Expand All @@ -89,7 +110,7 @@ pub async fn make_list_service_reflection_request(host: &str) -> Result<Vec<Stri
.message_response
.ok_or(Error::Internal("No message response".to_string()))?;

assert!(inbound.next().await.is_none());
debug_assert!(inbound.next().await.is_none());

let MessageResponse::ListServicesResponse(response) = response else {
let internal =
Expand All @@ -100,6 +121,10 @@ pub async fn make_list_service_reflection_request(host: &str) -> Result<Vec<Stri
Ok(response.service.into_iter().map(|s| s.name).collect())
}

/// # Errors
///
/// Fails if server reflection fails.
#[allow(clippy::implicit_hasher)]
pub async fn handle_reflection_dependencies(
host: &str,
file_descriptor: &FileDescriptorProto,
Expand Down
9 changes: 7 additions & 2 deletions wireman-core/src/client/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ pub struct TlsConfig(pub(super) ClientTlsConfig);

impl TlsConfig {
/// Create a new `TlsConfig` with native certificate.
pub fn native() -> Result<Self> {
Ok(Self(ClientTlsConfig::new().with_enabled_roots()))
#[must_use]
pub fn native() -> Self {
Self(ClientTlsConfig::new().with_enabled_roots())
}

/// Create a new `TlsConfig` with a custom certificate.
///
/// # Errors
///
/// Errors if root certificates cannot be read from path.
pub fn custom(cert_path: String) -> Result<Self> {
let pem = std::fs::read_to_string(cert_path).map_err(Error::LoadTLSCertificateError)?;
let ca = Certificate::from_pem(pem);
Expand Down
7 changes: 5 additions & 2 deletions wireman-core/src/descriptor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,14 @@ impl ProtoDescriptor {

/// Instantiates a `DescriptorPool` from a grpc server that supports
/// reflection.
///
/// # Errors
/// Errors if server reflection or dependency resolving fails.
pub async fn reflect(host: &str) -> Result<Self> {
let services = make_list_service_reflection_request(host).await?;

let mut file_descriptors: HashMap<String, FileDescriptorProto> = HashMap::new();
for service in services.iter() {
for service in &services {
if service.contains("ServerReflection") {
continue;
}
Expand All @@ -63,7 +66,7 @@ impl ProtoDescriptor {
};

let pool = DescriptorPool::from_file_descriptor_set(file_descriptor_set)
.map_err(|e| Error::Internal(format!("err {:?}", e)))?;
.map_err(|e| Error::Internal(format!("err {e}")))?;

Ok(Self { pool })
}
Expand Down
2 changes: 1 addition & 1 deletion wireman-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub enum Error {
#[error("internal error {0}")]
Internal(String),

/// Failed to deserialize DynamicMessage from json
/// Failed to deserialize `DynamicMessage` from json
#[error("error deserializing message from json")]
DeserializeMessage(#[source] serde_json::Error),

Expand Down
6 changes: 3 additions & 3 deletions wireman/src/events/selection/reflection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,18 @@ impl EventHandler for ReflectionDialogEventHandler {
match event {
ReflectionDialogEvents::Headers(event) => HeadersEventHandler::handle_event(event, ctx),
ReflectionDialogEvents::Selection(event) => {
ServicesSelectionEventsHandler::handle_event(event, ctx)
ServicesSelectionEventsHandler::handle_event(event, ctx);
}
ReflectionDialogEvents::Reflection(events) => match events {
ReflectionEvents::ReflectServer => {
ctx.reflection.borrow_mut().dispatch_reflection()
ctx.reflection.borrow_mut().dispatch_reflection();
}
ReflectionEvents::CloseDialog => {
ctx.reflection
.borrow()
.selection
.borrow_mut()
.selection_mode = SelectionMode::File
.selection_mode = SelectionMode::File;
}
},
}
Expand Down
4 changes: 2 additions & 2 deletions wireman/src/model/core_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ impl CoreClient {
match (tls_config.use_native, tls_config.custom_cert) {
(Some(use_native), _) => {
if use_native {
return Some(TlsConfig::native().unwrap());
return Some(TlsConfig::native());
}
None
}
(None, Some(custom)) => Some(TlsConfig::custom(custom).unwrap()),
_ => TlsConfig::native().ok(),
_ => Some(TlsConfig::native()),
}
}

Expand Down
2 changes: 1 addition & 1 deletion wireman/src/model/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl SelectionModel {
SelectionMode::Reflection => {
let _ = self.core_client.borrow_mut().reset();
self.load_core_services_and_methods_from_files();
self.selection_mode = SelectionMode::File
self.selection_mode = SelectionMode::File;
}
}
}
Expand Down

0 comments on commit 6a05aac

Please sign in to comment.