Skip to content

Commit

Permalink
pcli: 💿 crate can be used as a library
Browse files Browse the repository at this point in the history
currently, types and interfaces defined in the workspace's `pcli` crate
are only available within the `pcli` binary itself. this means that the
client functionality provided by this crate cannot be depended on as a
library, or otherwise used in unit tests.

this state of affairs is a significant part of why our tests for pcli
are contained in the `crates/bin/pcli/tests/network_integration.rs` test
suite, which rely on shelling out via a `std::process::Command` wrapper
and invoking the compiled `pcli` binary.

to facilitate future unit testing, this commit introduces a `lib.rs`
file to the `pcli` crate. the `App` structure is moved there as part of
this change, but is not changed in this commit.
  • Loading branch information
cratelyn committed Jun 14, 2024
1 parent a0d38e6 commit d09f4ad
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 74 deletions.
80 changes: 80 additions & 0 deletions crates/bin/pcli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#![deny(clippy::unwrap_used)]
#![allow(clippy::clone_on_copy)]

use {
crate::{command::*, config::PcliConfig},
anyhow::Result,
futures::StreamExt,
penumbra_proto::{
box_grpc_svc::BoxGrpcService, custody::v1::custody_service_client::CustodyServiceClient,
view::v1::view_service_client::ViewServiceClient,
},
penumbra_view::ViewClient,
};

pub mod command;
pub mod config;
pub mod opt;
pub mod warning;

mod dex_utils;
mod network;
mod terminal;
mod transaction_view_ext;

const CONFIG_FILE_NAME: &str = "config.toml";
const VIEW_FILE_NAME: &str = "pcli-view.sqlite";

#[derive(Debug)]
pub struct App {
/// view will be `None` when a command indicates that it can be run offline via
/// `.offline()` and Some(_) otherwise. Assuming `.offline()` has been implemenented
/// correctly, this can be unwrapped safely.
pub view: Option<ViewServiceClient<BoxGrpcService>>,
pub custody: CustodyServiceClient<BoxGrpcService>,
pub governance_custody: CustodyServiceClient<BoxGrpcService>,
pub config: PcliConfig,
}

impl App {
pub fn view(&mut self) -> &mut impl ViewClient {
self.view.as_mut().expect("view service initialized")
}

pub async fn sync(&mut self) -> Result<()> {
let mut status_stream =
ViewClient::status_stream(self.view.as_mut().expect("view service initialized"))
.await?;

// Pull out the first message from the stream, which has the current state, and use
// it to set up a progress bar.
let initial_status = status_stream
.next()
.await
.transpose()?
.ok_or_else(|| anyhow::anyhow!("view service did not report sync status"))?;

eprintln!(
"Scanning blocks from last sync height {} to latest height {}",
initial_status.full_sync_height, initial_status.latest_known_block_height,
);

use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
let progress_bar = ProgressBar::with_draw_target(
initial_status.latest_known_block_height - initial_status.full_sync_height,
ProgressDrawTarget::stdout(),
)
.with_style(
ProgressStyle::default_bar()
.template("[{elapsed}] {bar:50.cyan/blue} {pos:>7}/{len:7} {per_sec} ETA: {eta}"),
);
progress_bar.set_position(0);

while let Some(status) = status_stream.next().await.transpose()? {
progress_bar.set_position(status.full_sync_height - initial_status.full_sync_height);
}
progress_bar.finish();

Ok(())
}
}
76 changes: 2 additions & 74 deletions crates/bin/pcli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,86 +5,14 @@ use std::fs;

use anyhow::{Context, Result};
use clap::Parser;
use futures::StreamExt;
use penumbra_proto::{
box_grpc_svc::BoxGrpcService, custody::v1::custody_service_client::CustodyServiceClient,
view::v1::view_service_client::ViewServiceClient,
};
use penumbra_view::ViewClient;

use crate::{command::*, config::PcliConfig, opt::Opt};

mod command;
mod config;
mod dex_utils;
mod network;
mod opt;
mod terminal;
mod transaction_view_ext;
mod warning;

const CONFIG_FILE_NAME: &str = "config.toml";
const VIEW_FILE_NAME: &str = "pcli-view.sqlite";

#[derive(Debug)]
pub struct App {
/// view will be `None` when a command indicates that it can be run offline via
/// `.offline()` and Some(_) otherwise. Assuming `.offline()` has been implemenented
/// correctly, this can be unwrapped safely.
pub view: Option<ViewServiceClient<BoxGrpcService>>,
pub custody: CustodyServiceClient<BoxGrpcService>,
pub governance_custody: CustodyServiceClient<BoxGrpcService>,
pub config: PcliConfig,
}

impl App {
pub fn view(&mut self) -> &mut impl ViewClient {
self.view.as_mut().expect("view service initialized")
}

async fn sync(&mut self) -> Result<()> {
let mut status_stream =
ViewClient::status_stream(self.view.as_mut().expect("view service initialized"))
.await?;

// Pull out the first message from the stream, which has the current state, and use
// it to set up a progress bar.
let initial_status = status_stream
.next()
.await
.transpose()?
.ok_or_else(|| anyhow::anyhow!("view service did not report sync status"))?;

eprintln!(
"Scanning blocks from last sync height {} to latest height {}",
initial_status.full_sync_height, initial_status.latest_known_block_height,
);

use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
let progress_bar = ProgressBar::with_draw_target(
initial_status.latest_known_block_height - initial_status.full_sync_height,
ProgressDrawTarget::stdout(),
)
.with_style(
ProgressStyle::default_bar()
.template("[{elapsed}] {bar:50.cyan/blue} {pos:>7}/{len:7} {per_sec} ETA: {eta}"),
);
progress_bar.set_position(0);

while let Some(status) = status_stream.next().await.transpose()? {
progress_bar.set_position(status.full_sync_height - initial_status.full_sync_height);
}
progress_bar.finish();

Ok(())
}
}
use pcli::{command::*, opt::Opt};

#[tokio::main]
async fn main() -> Result<()> {
// Display a warning message to the user so they don't get upset when all their tokens are lost.
if std::env::var("PCLI_UNLEASH_DANGER").is_err() {
warning::display();
pcli::warning::display();
}

let mut opt = Opt::parse();
Expand Down

0 comments on commit d09f4ad

Please sign in to comment.