Skip to content

Commit

Permalink
refactor(rust): make it easier to write commands' api req/res handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianbenavides authored and mergify[bot] committed Aug 17, 2022
1 parent 4981982 commit fdb22e2
Show file tree
Hide file tree
Showing 21 changed files with 410 additions and 324 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions implementations/rust/ockam/ockam_api/src/cloud/enroll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ use std::borrow::Cow;
use minicbor::{Decode, Encode};
use serde::{Deserialize, Serialize};

use ockam_core::{self, async_trait};

#[cfg(feature = "tag")]
use ockam_core::api::TypeTag;
use ockam_core::TypeTag;
use ockam_core::{self, async_trait};

#[derive(Encode, Decode, Serialize, Deserialize, Debug)]
#[cfg_attr(test, derive(PartialEq, Eq, Clone))]
Expand Down Expand Up @@ -222,9 +221,10 @@ pub mod auth0 {
}

pub mod enrollment_token {
use crate::auth::types::Attributes;
use serde::Serialize;

use crate::auth::types::Attributes;

use super::*;

// Main req/res types
Expand Down
9 changes: 5 additions & 4 deletions implementations/rust/ockam/ockam_api/src/cloud/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use std::str::FromStr;

use minicbor::{Decode, Encode};

#[cfg(feature = "tag")]
use ockam_core::TypeTag;
use ockam_core::{CowStr, Result, Route};
use ockam_multiaddr::MultiAddr;
use std::str::FromStr;

use crate::error::ApiError;

#[cfg(feature = "tag")]
use crate::TypeTag;

pub mod enroll;
pub mod project;
pub mod space;
Expand Down
9 changes: 5 additions & 4 deletions implementations/rust/ockam/ockam_api/src/cloud/project.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use minicbor::{Decode, Encode};
use ockam_core::CowStr;
use serde::Serialize;

use ockam_core::CowStr;
#[cfg(feature = "tag")]
use crate::TypeTag;
use ockam_core::TypeTag;

#[derive(Encode, Decode, Serialize, Debug)]
#[cfg_attr(test, derive(Clone))]
Expand Down Expand Up @@ -346,11 +346,12 @@ mod tests {
}

mod node_api {
use ockam_core::api::Status;
use ockam_core::route;

use crate::cloud::CloudRequestWrapper;
use crate::nodes::NodeManager;
use crate::route_to_multiaddr;
use ockam_core::api::Status;
use ockam_core::route;

use super::*;

Expand Down
8 changes: 4 additions & 4 deletions implementations/rust/ockam/ockam_api/src/cloud/space.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use minicbor::{Decode, Encode};
use serde::Serialize;

use ockam_core::CowStr;

#[cfg(feature = "tag")]
use crate::TypeTag;
use ockam_core::TypeTag;

#[derive(Encode, Decode, Serialize, Debug)]
#[cfg_attr(test, derive(Clone))]
Expand Down Expand Up @@ -326,11 +325,12 @@ pub mod tests {
}

mod node_api {
use ockam_core::api::Status;
use ockam_core::route;

use crate::cloud::CloudRequestWrapper;
use crate::nodes::NodeManager;
use crate::route_to_multiaddr;
use ockam_core::api::Status;
use ockam_core::route;

use super::*;

Expand Down
1 change: 1 addition & 0 deletions implementations/rust/ockam/ockam_command/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ dialoguer = "0.10"
directories = "4"
dirs = "4.0.0"
hex = "0.4"
itertools = "0.10"
minicbor = { version = "0.18.0", features = ["derive"] }
nix = "0.24"
open = "2"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ pub enum AuthenticatedSubcommand {

impl AuthenticatedCommand {
pub fn run(c: AuthenticatedCommand) {
embedded_node(run_impl, c.subcommand)
if let Err(e) = embedded_node(run_impl, c.subcommand) {
eprintln!("Ockam node failed: {:?}", e,);
}
}
}

Expand Down
4 changes: 3 additions & 1 deletion implementations/rust/ockam/ockam_command/src/enroll/email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ impl EnrollEmailCommand {
println!("\nThank you for trying Ockam. We are working towards a developer release of Ockam Orchestrator in September.
Please tell us your email and we'll let you know when we're ready to enroll new users to Ockam Orchestrator.\n");
let email = read_user_input().expect("couldn't read user input");
embedded_node(enroll, (cmd, email));
if let Err(e) = embedded_node(enroll, (cmd, email)) {
eprintln!("Ockam node failed: {:?}", e,);
}
}
}

Expand Down
32 changes: 32 additions & 0 deletions implementations/rust/ockam/ockam_command/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use crate::util::ConfigError;
use crate::{exitcode, ExitCode};
use tracing::error;

pub type Result<T> = std::result::Result<T, Error>;

pub struct Error(ExitCode);

impl Error {
pub fn new(code: ExitCode) -> Self {
assert!(code > 0, "Exit code can't be OK");
Self(code)
}

pub fn code(&self) -> ExitCode {
self.0
}
}

impl From<ConfigError> for Error {
fn from(e: ConfigError) -> Self {
error!("{e}");
Error::new(exitcode::CONFIG)
}
}

impl From<anyhow::Error> for Error {
fn from(e: anyhow::Error) -> Self {
error!("{e}");
Error::new(exitcode::SOFTWARE)
}
}
8 changes: 6 additions & 2 deletions implementations/rust/ockam/ockam_command/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use tcp::listener::TcpListenerCommand;
use tcp::outlet::TcpOutletCommand;

// to be removed
pub mod error;
mod old;

use old::cmd::identity::IdentityOpts;
Expand All @@ -43,10 +44,13 @@ use old::{add_trusted, exit_with_result, node_subcommand, print_identity, print_
use crate::enroll::GenerateEnrollmentTokenCommand;
use crate::identity::IdentityCommand;
use crate::service::ServiceCommand;
use crate::util::OckamConfig;
use crate::util::exitcode::ExitCode;
use crate::util::{exitcode, stop_node, OckamConfig};
use crate::vault::VaultCommand;
use clap::{crate_version, ArgEnum, Args, ColorChoice, Parser, Subcommand};
use util::setup_logging;
use util::{embedded_node, setup_logging};

pub use error::{Error, Result};

const HELP_TEMPLATE: &str = "\
{before-help}
Expand Down
11 changes: 5 additions & 6 deletions implementations/rust/ockam/ockam_command/src/message/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use clap::Args;
use minicbor::Decoder;
use tracing::debug;

use crate::CommandGlobalOpts;
use crate::{embedded_node, CommandGlobalOpts};
use ockam::TcpTransport;
use ockam_api::clean_multiaddr;
use ockam_api::nodes::NODEMANAGER_ADDR;
use ockam_core::api::{Response, Status};
use ockam_core::Route;
use ockam_multiaddr::MultiAddr;

use crate::util::{api, connect_to, embedded_node, exitcode, get_final_element, stop_node};
use crate::util::{api, connect_to, exitcode, stop_node};

#[derive(Clone, Debug, Args)]
pub struct SendCommand {
Expand Down Expand Up @@ -42,11 +42,10 @@ impl SendCommand {
};

if let Some(node) = &cmd.from {
let name = get_final_element(node);
let port = opts.config.get_node_port(name);
let port = opts.config.get_node_port(node);
connect_to(port, (opts, cmd), send_message_via_connection_to_a_node);
} else {
embedded_node(send_message_from_embedded_node, cmd)
} else if let Err(e) = embedded_node(send_message_from_embedded_node, cmd) {
eprintln!("Ockam node failed: {:?}", e,);
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion implementations/rust/ockam/ockam_command/src/node/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@ impl CreateCommand {
}
}

embedded_node(setup, (command, cfg.clone()));
if let Err(e) = embedded_node(setup, (command, cfg.clone())) {
eprintln!("Ockam node failed: {:?}", e,);
}
} else {
// On systems with non-obvious path setups (or during
// development) re-executing the current binary is a more
Expand Down
85 changes: 20 additions & 65 deletions implementations/rust/ockam/ockam_command/src/space/create.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
use anyhow::{anyhow, Context};
use clap::Args;
use minicbor::Decoder;
use tracing::debug;

use ockam::Context;
use ockam_api::cloud::space::Space;
use ockam_api::nodes::NODEMANAGER_ADDR;
use ockam_core::api::{Response, Status};
use ockam_core::Route;

use crate::node::NodeOpts;
use crate::util::api::CloudOpts;
use crate::util::{api, connect_to, exitcode, stop_node};
use crate::{CommandGlobalOpts, OutputFormat};
use crate::util::api::{self, CloudOpts};
use crate::util::{node_rpc, Rpc};
use crate::{stop_node, CommandGlobalOpts};

#[derive(Clone, Debug, Args)]
pub struct CreateCommand {
Expand All @@ -32,65 +27,25 @@ pub struct CreateCommand {

impl CreateCommand {
pub fn run(opts: CommandGlobalOpts, cmd: CreateCommand) {
let cfg = &opts.config;
let port = match cfg.select_node(&cmd.node_opts.api_node) {
Some(cfg) => cfg.port,
None => {
eprintln!("No such node available. Run `ockam node list` to list available nodes");
std::process::exit(exitcode::IOERR);
}
};
connect_to(port, (opts, cmd), create);
node_rpc(rpc, (opts, cmd));
}
}

async fn create(
ctx: ockam::Context,
async fn rpc(
mut ctx: Context,
(opts, cmd): (CommandGlobalOpts, CreateCommand),
mut base_route: Route,
) -> anyhow::Result<()> {
let route: Route = base_route.modify().append(NODEMANAGER_ADDR).into();
debug!(?cmd, %route, "Sending request");

let response: Vec<u8> = ctx
.send_and_receive(route, api::space::create(cmd)?)
.await
.context("Failed to process request")?;
let mut dec = Decoder::new(&response);
let header = dec
.decode::<Response>()
.context("Failed to decode Response")?;
debug!(?header, "Received response");

let res = match (header.status(), header.has_body()) {
(Some(Status::Ok), true) => {
let body = dec
.decode::<Space>()
.context("Failed to decode response body")?;
let output = match opts.global_args.output_format {
OutputFormat::Plain => body.id.to_string(),
OutputFormat::Json => serde_json::to_string(&body)
.context("Failed to serialize command output as json")?,
};
Ok(output)
}
(Some(status), true) => {
let err = dec
.decode::<String>()
.unwrap_or_else(|_| "Unknown error".to_string());
Err(anyhow!(
"An error occurred while processing the request with status code {status:?}: {err}"
))
}
_ => Err(anyhow!("Unexpected response received from node")),
};
match res {
Ok(o) => println!("{o}"),
Err(err) => {
eprintln!("{err}");
std::process::exit(exitcode::IOERR);
}
};
) -> crate::Result<()> {
let res = run_impl(&mut ctx, opts, cmd).await;
stop_node(ctx).await?;
res
}

stop_node(ctx).await
async fn run_impl(
ctx: &mut Context,
opts: CommandGlobalOpts,
cmd: CreateCommand,
) -> crate::Result<()> {
let mut rpc = Rpc::new(ctx, &opts, &cmd.node_opts.api_node)?;
rpc.request(api::space::create(&cmd)).await?;
rpc.print_response::<Space>()
}
Loading

0 comments on commit fdb22e2

Please sign in to comment.