Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(comms): add or_optional trait extension for RpcStatus #4246

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions comms/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ pub mod utils;
// TODO: Test utils should be part of a `tari_comms_test` crate
// #[cfg(test)]
pub mod test_utils;
pub mod traits;

//---------------------------------- Re-exports --------------------------------------------//
// Rather than requiring dependent crates to import dependencies for use with `tari_comms` we re-export them here.
Expand Down
30 changes: 28 additions & 2 deletions comms/core/src/protocol/rpc/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ use log::*;
use thiserror::Error;

use super::RpcError;
use crate::proto;
use crate::{proto, traits::OrOptional};

const LOG_TARGET: &str = "comms::rpc::status";

#[derive(Debug, Error, Clone)]
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub struct RpcStatus {
code: RpcStatusCode,
details: String,
Expand Down Expand Up @@ -141,6 +141,10 @@ impl RpcStatus {
pub fn is_ok(&self) -> bool {
self.code.is_ok()
}

pub fn is_not_found(&self) -> bool {
self.code.is_not_found()
}
}

impl Display for RpcStatus {
Expand Down Expand Up @@ -202,6 +206,15 @@ impl<T, E: std::error::Error> RpcStatusResultExt<T> for Result<T, E> {
}
}

impl<T> OrOptional<T> for Result<T, RpcStatus> {
type Error = RpcStatus;

fn or_optional(self) -> Result<Option<T>, Self::Error> {
self.map(Some)
.or_else(|status| if status.is_not_found() { Ok(None) } else { Err(status) })
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RpcStatusCode {
/// Request succeeded
Expand Down Expand Up @@ -296,4 +309,17 @@ mod test {
assert_eq!(RpcStatusCode::from(Conflict as u32), Conflict);
assert_eq!(RpcStatusCode::from(123), InvalidRpcStatusCode);
}

#[test]
fn rpc_status_or_optional() {
assert!(Result::<(), RpcStatus>::Ok(()).or_optional().is_ok());
assert_eq!(
Result::<(), _>::Err(RpcStatus::not_found("foo")).or_optional(),
Ok(None)
);
assert_eq!(
Result::<(), _>::Err(RpcStatus::general("foo")).or_optional(),
Err(RpcStatus::general("foo"))
);
}
}
6 changes: 2 additions & 4 deletions comms/core/src/tor/control_client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,13 @@ impl TorControlPortClient {
}

/// The GETCONF command. Returns configuration keys matching the `conf_name`.
#[allow(clippy::needless_lifetimes)]
pub async fn get_conf<'a>(&mut self, conf_name: &'a str) -> Result<Vec<Cow<'a, str>>, TorClientError> {
pub async fn get_conf(&mut self, conf_name: &'static str) -> Result<Vec<Cow<'_, str>>, TorClientError> {
let command = commands::get_conf(conf_name);
self.request_response(command).await
}

/// The GETINFO command. Returns configuration keys matching the `conf_name`.
#[allow(clippy::needless_lifetimes)]
pub async fn get_info<'a>(&mut self, key_name: &'a str) -> Result<Vec<Cow<'a, str>>, TorClientError> {
pub async fn get_info(&mut self, key_name: &'static str) -> Result<Vec<Cow<'_, str>>, TorClientError> {
let command = commands::get_info(key_name);
let response = self.request_response(command).await?;
if response.is_empty() {
Expand Down
26 changes: 12 additions & 14 deletions comms/core/src/tor/control_client/commands/key_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,50 +20,48 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::{borrow::Cow, fmt, marker::PhantomData};
use std::{borrow::Cow, fmt};

use crate::tor::control_client::{commands::TorCommand, error::TorClientError, parsers, response::ResponseLine};

/// The GETCONF command.
///
/// This command is used to query the Tor proxy configuration file.
pub fn get_conf(query: &str) -> KeyValueCommand<'_, '_> {
pub fn get_conf(query: &str) -> KeyValueCommand<'_> {
KeyValueCommand::new("GETCONF", &[query])
}

/// The GETINFO command.
///
/// This command is used to retrieve Tor proxy configuration keys.
pub fn get_info(key_name: &str) -> KeyValueCommand<'_, '_> {
pub fn get_info(key_name: &str) -> KeyValueCommand<'_> {
KeyValueCommand::new("GETINFO", &[key_name])
}

/// The SETEVENTS command.
///
/// This command is used to set the events that tor will emit
pub fn set_events<'b>(event_types: &[&'b str]) -> KeyValueCommand<'static, 'b> {
pub fn set_events<'a>(event_types: &[&'a str]) -> KeyValueCommand<'a> {
KeyValueCommand::new("SETEVENTS", event_types)
}

pub struct KeyValueCommand<'a, 'b> {
command: &'a str,
args: Vec<&'b str>,
_lifetime: PhantomData<&'b ()>,
pub struct KeyValueCommand<'a> {
command: &'static str,
args: Vec<&'a str>,
}

impl<'a, 'b> KeyValueCommand<'a, 'b> {
pub fn new(command: &'a str, args: &[&'b str]) -> Self {
impl<'a> KeyValueCommand<'a> {
pub fn new(command: &'static str, args: &[&'a str]) -> Self {
Self {
command,
args: args.to_vec(),
_lifetime: PhantomData,
}
}
}

impl<'a, 'b> TorCommand for KeyValueCommand<'a, 'b> {
impl<'a> TorCommand for KeyValueCommand<'a> {
type Error = TorClientError;
type Output = Vec<Cow<'b, str>>;
type Output = Vec<Cow<'a, str>>;

fn to_command_string(&self) -> Result<String, Self::Error> {
Ok(format!("{} {}", self.command, self.args.join(" ")))
Expand Down Expand Up @@ -99,7 +97,7 @@ impl<'a, 'b> TorCommand for KeyValueCommand<'a, 'b> {
}
}

impl fmt::Display for KeyValueCommand<'_, '_> {
impl fmt::Display for KeyValueCommand<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
Expand Down
28 changes: 28 additions & 0 deletions comms/core/src/traits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2022, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/// Extension trait that typically converts Result<T, Self::Error> to Result<Option<T>, Self::Error>
/// based on some implementer logic.
pub trait OrOptional<T> {
type Error;
fn or_optional(self) -> Result<Option<T>, Self::Error>;
}