Skip to content

Commit

Permalink
refactor(rust): identity show command to use rpc abstraction and to s…
Browse files Browse the repository at this point in the history
…top mapping errors manually
  • Loading branch information
divyank-aggarwal authored and mergify[bot] committed Oct 17, 2022
1 parent 5b8ffc4 commit 5485a38
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 76 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use minicbor::{Decode, Encode};
use ockam_core::compat::borrow::Cow;
use serde::Serialize;

use ockam_core::CowBytes;

Expand All @@ -26,11 +27,12 @@ impl<'a> CreateIdentityResponse<'a> {
}
}

#[derive(Debug, Clone, Decode, Encode)]
#[derive(Debug, Clone, Decode, Encode, Serialize)]
#[rustfmt::skip]
#[cbor(map)]
pub struct LongIdentityResponse<'a> {
#[cfg(feature = "tag")]
#[serde(skip)]
#[n(0)] tag: TypeTag<7961643>,
#[b(1)] pub identity: CowBytes<'a>,
}
Expand All @@ -45,11 +47,12 @@ impl<'a> LongIdentityResponse<'a> {
}
}

#[derive(Debug, Clone, Decode, Encode)]
#[derive(Debug, Clone, Decode, Encode, Serialize)]
#[rustfmt::skip]
#[cbor(map)]
pub struct ShortIdentityResponse<'a> {
#[cfg(feature = "tag")]
#[serde(skip)]
#[n(0)] tag: TypeTag<5773131>,
#[b(1)] pub identity_id: Cow<'a, str>,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl IdentityCommand {
pub fn run(self, options: CommandGlobalOpts) {
match self.subcommand {
IdentitySubcommand::Create(c) => c.run(options),
IdentitySubcommand::Show(c) => c.run(options).unwrap(),
IdentitySubcommand::Show(c) => c.run(options),
}
}
}
92 changes: 37 additions & 55 deletions implementations/rust/ockam/ockam_command/src/identity/show.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::util::{connect_to, exitcode, extract_address_value};
use crate::node::util::delete_embedded_node;
use crate::node::NodeOpts;
use crate::util::output::Output;
use crate::util::{extract_address_value, node_rpc, Rpc};
use crate::CommandGlobalOpts;
use crate::{node::NodeOpts, util::api};
use clap::Args;
use ockam::{Context, Route};
use ockam_api::nodes::NODEMANAGER_ADDR;
use ockam_core::api::Status;
use core::fmt::Write;
use ockam::Context;
use ockam_api::nodes::models::identity::{LongIdentityResponse, ShortIdentityResponse};
use ockam_core::api::Request;

#[derive(Clone, Debug, Args)]
pub struct ShowCommand {
Expand All @@ -15,63 +18,42 @@ pub struct ShowCommand {
}

impl ShowCommand {
pub fn run(self, options: CommandGlobalOpts) -> anyhow::Result<()> {
let cfg = options.config;
let node = extract_address_value(&self.node_opts.api_node)?;
let port = cfg.get_node_port(&node).unwrap();

connect_to(port, self, show_identity);

Ok(())
pub fn run(self, options: CommandGlobalOpts) {
node_rpc(run_impl, (options, self))
}
}

pub async fn show_identity(
async fn run_impl(
ctx: Context,
cmd: ShowCommand,
mut base_route: Route,
) -> anyhow::Result<()> {
(opts, cmd): (CommandGlobalOpts, ShowCommand),
) -> crate::Result<()> {
let node_name = extract_address_value(&cmd.node_opts.api_node)?;
let mut rpc = Rpc::background(&ctx, &opts, &node_name)?;
if cmd.full {
let resp: Vec<u8> = ctx
.send_and_receive(
base_route.modify().append(NODEMANAGER_ADDR),
api::long_identity()?,
)
.await?;

let (response, result) = api::parse_long_identity_response(&resp)?;

match response.status() {
Some(Status::Ok) => {
println!("{}", hex::encode(result.identity.0.as_ref()))
}
_ => {
eprintln!("An error occurred while exporting Identity",);
std::process::exit(exitcode::IOERR);
}
}

Ok(())
let req = Request::post("/node/identity/actions/show/long");
rpc.request(req).await?;
rpc.parse_and_print_response::<LongIdentityResponse>()?;
} else {
let resp: Vec<u8> = ctx
.send_and_receive(
base_route.modify().append(NODEMANAGER_ADDR),
api::short_identity().to_vec()?,
)
.await?;

let (response, result) = api::parse_short_identity_response(&resp)?;
let req = Request::post("/node/identity/actions/show/short");
rpc.request(req).await?;
rpc.parse_and_print_response::<ShortIdentityResponse>()?;
}
delete_embedded_node(&opts.config, &node_name).await;
Ok(())
}

match response.status() {
Some(Status::Ok) => {
println!("{}", result.identity_id)
}
_ => {
eprintln!("An error occurred while getting Identity",);
std::process::exit(exitcode::IOERR);
}
}
impl Output for LongIdentityResponse<'_> {
fn output(&self) -> anyhow::Result<String> {
let mut w = String::new();
write!(w, "{}", hex::encode(self.identity.0.as_ref()))?;
Ok(w)
}
}

Ok(())
impl Output for ShortIdentityResponse<'_> {
fn output(&self) -> anyhow::Result<String> {
let mut w = String::new();
write!(w, "{}", self.identity_id)?;
Ok(w)
}
}
18 changes: 0 additions & 18 deletions implementations/rust/ockam/ockam_command/src/util/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,6 @@ pub(crate) fn delete_tcp_connection(
Ok(buf)
}

/// Construct a request to export Identity
pub(crate) fn long_identity() -> Result<Vec<u8>> {
let mut buf = vec![];
Request::post("/node/identity/actions/show/long").encode(&mut buf)?;
Ok(buf)
}

/// Construct a request to print Identity Id
pub(crate) fn short_identity() -> RequestBuilder<'static, ()> {
Request::post("/node/identity/actions/show/short")
Expand Down Expand Up @@ -394,17 +387,6 @@ pub(crate) fn parse_transport_status(
))
}

pub(crate) fn parse_long_identity_response(
resp: &[u8],
) -> Result<(Response, models::identity::LongIdentityResponse<'_>)> {
let mut dec = Decoder::new(resp);
let response = dec.decode::<Response>()?;
Ok((
response,
dec.decode::<models::identity::LongIdentityResponse>()?,
))
}

pub(crate) fn parse_short_identity_response(
resp: &[u8],
) -> Result<(Response, models::identity::ShortIdentityResponse<'_>)> {
Expand Down
9 changes: 9 additions & 0 deletions implementations/rust/ockam/ockam_command/tests/commands.bats
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,15 @@ teardown() {
assert_success
}

@test "create a node and show its identity" {
run $OCKAM node create n1
assert_success

run $OCKAM identity show --node n1
assert_success
assert_output --regexp '^P'
}

@test "create a node with a name and do show on it" {
run $OCKAM node create n1
assert_success
Expand Down

0 comments on commit 5485a38

Please sign in to comment.