use std::time::Duration;
use clap::Parser;
use eyre::Result;
use sim_cli::{
ApiKeyArg,
args::{JsonOutputArgs, KindFilter, SlotBoundsArgs},
engine::format_slot,
};
use simulator_api::{
BundleBuildRequest, BundleBuildStatus, BundleBuildStatusResponse, BundleDeleteRequest,
BundleKind,
};
#[derive(Parser, Debug)]
pub struct BundleBuildArgs {
#[command(flatten)]
pub bounds: SlotBoundsArgs,
#[command(flatten)]
pub api_key: ApiKeyArg,
#[arg(long)]
pub latest: bool,
#[arg(long, value_parser = clap::value_parser!(u64).range(1..))]
pub bundle_size: Option<u64>,
#[arg(long)]
pub account_state: bool,
#[arg(long)]
pub idempotency_key: Option<String>,
#[arg(long)]
pub wait: bool,
#[arg(long, default_value_t = 15, value_parser = clap::value_parser!(u64).range(1..))]
pub poll_secs: u64,
#[command(flatten)]
pub output: JsonOutputArgs,
}
pub async fn build_bundle(args: BundleBuildArgs, url: String) -> Result<()> {
let client = sim_cli::client::new(&url, &args.api_key.get());
let (start_slot, end_slot) = if args.latest
&& let Some(size) = args.bundle_size
{
let start = client.get_latest_snapshot_slot().await?.snapshot_slot + 1;
(start, start + size)
} else {
args.bounds.require()?
};
println!("Requesting bundle build for: {start_slot}-{end_slot}...");
let mut resp = client
.build_bundle(&BundleBuildRequest {
start_slot,
end_slot,
bundle_size: args.bundle_size,
idempotency_key: args.idempotency_key,
kind: if args.account_state {
BundleKind::AccountState
} else {
BundleKind::Blocks
},
})
.await?;
if !args.output.json {
println!("{}", format_status("issued", &resp));
}
if args.wait {
while matches!(resp.status, BundleBuildStatus::InProgress) {
tokio::time::sleep(Duration::from_secs(args.poll_secs)).await;
resp = client.get_bundle_status(&resp.request_id).await?;
if !args.output.json {
println!("{}", format_status("status", &resp));
}
}
}
if args.output.json {
println!("{}", serde_json::to_string_pretty(&resp)?);
}
Ok(())
}
#[derive(Parser, Debug)]
pub struct BundleStatusArgs {
pub request_id: String,
#[command(flatten)]
pub api_key: ApiKeyArg,
#[command(flatten)]
pub output: JsonOutputArgs,
}
pub async fn get_status(args: BundleStatusArgs, url: String) -> Result<()> {
let client = sim_cli::client::new(&url, &args.api_key.get());
let resp = client.get_bundle_status(&args.request_id).await?;
if args.output.json {
println!("{}", serde_json::to_string_pretty(&resp)?);
} else {
println!("{}", format_status("status", &resp));
}
Ok(())
}
#[derive(Parser, Debug)]
pub struct BundleListArgs {
#[arg(long, value_parser = clap::value_parser!(u32).range(1..))]
pub limit: Option<u32>,
#[command(flatten)]
pub api_key: ApiKeyArg,
#[command(flatten)]
pub output: JsonOutputArgs,
}
pub async fn list_builds(args: BundleListArgs, url: String) -> Result<()> {
let client = sim_cli::client::new(&url, &args.api_key.get());
let resp = client.list_bundle_builds(args.limit).await?;
if args.output.json {
println!("{}", serde_json::to_string_pretty(&resp)?);
return Ok(());
}
if resp.builds.is_empty() {
println!("\nNo builds requested at this endpoint");
} else {
println!("\nBuilds requested at this endpoint");
for build in &resp.builds {
println!("{}", format_status("build", build));
}
}
match resp.bundles.as_deref() {
None => println!(
"\nBundles you own could not be listed right now; the builds section above is unaffected"
),
Some([]) => println!("\nYou own no bundles"),
Some(bundles) => {
println!("\nBundles you own");
println!(
"{:<15} {:<15} {:<15} Built (UTC)",
"Kind", "Start Slot", "End Slot"
);
println!("{}", "-".repeat(60));
for bundle in bundles {
println!(
"{:<15} {:<15} {:<15} {}",
bundle.kind,
format_slot(bundle.start_slot),
format_slot(bundle.end_slot),
bundle
.completed_at_unix_ms
.and_then(format_unix_ms)
.unwrap_or_else(|| "-".to_string()),
);
}
}
}
Ok(())
}
#[derive(Parser, Debug)]
pub struct BundleDeleteArgs {
#[command(flatten)]
pub bounds: SlotBoundsArgs,
#[arg(long, value_enum, default_value_t = KindFilter::Transactions)]
pub kind: KindFilter,
#[command(flatten)]
pub api_key: ApiKeyArg,
#[arg(long)]
pub yes: bool,
#[command(flatten)]
pub output: JsonOutputArgs,
}
pub async fn delete_bundle(args: BundleDeleteArgs, url: String) -> Result<()> {
let (start_slot, end_slot) = args.bounds.require()?;
let kind = BundleKind::from(args.kind);
let client = sim_cli::client::new(&url, &args.api_key.get());
if !args.yes {
eprintln!(
"Delete the {kind} bundle for slots {}..={}?",
format_slot(start_slot),
format_slot(end_slot)
);
eprintln!("A session currently reading it will fail.");
if !confirmed()? {
eprintln!("Left alone.");
return Ok(());
}
}
let resp = client
.delete_bundle(&BundleDeleteRequest {
start_slot,
end_slot,
kind,
})
.await?;
if args.output.json {
println!("{}", serde_json::to_string_pretty(&resp)?);
} else {
println!(
"Deleted the {} bundle for slots {}..={}.",
resp.kind,
format_slot(resp.start_slot),
format_slot(resp.end_slot)
);
}
Ok(())
}
fn confirmed() -> Result<bool> {
eprint!("Type 'yes' to confirm: ");
std::io::Write::flush(&mut std::io::stderr())?;
let mut answer = String::new();
if std::io::BufRead::read_line(&mut std::io::stdin().lock(), &mut answer)? == 0 {
return Ok(false);
}
Ok(answer.trim().eq_ignore_ascii_case("yes"))
}
fn format_unix_ms(unix_ms: i64) -> Option<String> {
chrono::DateTime::from_timestamp_millis(unix_ms)
.map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
}
fn format_status(label: &str, resp: &BundleBuildStatusResponse) -> String {
let size = resp
.bundle_size
.map_or_else(|| "default".to_string(), |s| s.to_string());
let eta = match resp.eta_secs {
Some(0) => "finishing up".to_string(),
Some(secs) => format_duration(secs),
None => "-".to_string(),
};
let kind = resp.kind;
format!(
"id={}: {label}=[{}]\nslots={}..{} size={size} kind={kind} (eta {eta})",
resp.request_id,
resp.status.as_str(),
resp.start_slot,
resp.end_slot,
)
}
fn format_duration(secs: u64) -> String {
let (hours, minutes) = (secs / 3600, (secs % 3600) / 60);
if hours > 0 {
format!("{hours}h {minutes:02}m")
} else {
format!("{minutes}m")
}
}
#[cfg(test)]
mod tests {
use simulator_api::BundleKind;
use super::*;
#[test]
fn parses_range_and_flags() {
let args = BundleBuildArgs::try_parse_from([
"bundle-build",
"--start-slot",
"100",
"--end-slot",
"200",
"--api-key",
"test-key",
"--bundle-size",
"500",
"--wait",
])
.unwrap();
assert_eq!(
(args.bounds.start_slot, args.bounds.end_slot),
(Some(100), Some(200))
);
assert_eq!(args.bundle_size, Some(500));
assert!(args.wait);
}
#[test]
fn account_state_takes_a_bundle_size() {
let args = BundleBuildArgs::try_parse_from([
"bundle-build",
"--start-slot",
"100",
"--end-slot",
"200",
"--api-key",
"test-key",
"--account-state",
"--bundle-size",
"500",
])
.expect("account-state builds accept a bundle size");
assert!(args.account_state);
assert_eq!(args.bundle_size, Some(500));
}
#[test]
fn bundle_delete_defaults_to_the_transactions_bundle() {
let args = BundleDeleteArgs::try_parse_from([
"bundle-delete",
"--start-slot",
"100",
"--end-slot",
"200",
"--api-key",
"k",
])
.unwrap();
assert_eq!(args.kind, KindFilter::Transactions);
assert!(!args.yes);
}
#[test]
fn bundle_delete_takes_a_kind_and_a_confirmation_bypass() {
let args = BundleDeleteArgs::try_parse_from([
"bundle-delete",
"--start-slot",
"100",
"--end-slot",
"200",
"--api-key",
"k",
"--kind",
"account-state",
"--yes",
])
.unwrap();
assert_eq!(
(args.bounds.start_slot, args.bounds.end_slot),
(Some(100), Some(200))
);
assert_eq!(args.kind, KindFilter::AccountState);
assert!(args.yes);
}
#[test]
fn build_times_render_as_utc_and_tolerate_a_bad_value() {
assert_eq!(
format_unix_ms(1_700_000_000_000).as_deref(),
Some("2023-11-14 22:13:20")
);
assert_eq!(format_unix_ms(i64::MAX), None);
}
#[test]
fn poll_secs_rejects_zero() {
assert!(
BundleBuildArgs::try_parse_from([
"bundle-build",
"--start-slot",
"1",
"--end-slot",
"2",
"--api-key",
"k",
"--wait",
"--poll-secs",
"0",
])
.is_err()
);
}
#[test]
fn bundle_size_rejects_zero() {
assert!(
BundleBuildArgs::try_parse_from([
"bundle-build",
"--start-slot",
"1",
"--end-slot",
"2",
"--api-key",
"k",
"--bundle-size",
"0",
])
.is_err()
);
}
fn in_progress(start: u64, end: u64, eta_secs: Option<u64>) -> BundleBuildStatusResponse {
BundleBuildStatusResponse {
request_id: "req-1".to_string(),
start_slot: start,
end_slot: end,
bundle_size: None,
status: BundleBuildStatus::InProgress,
created_at_unix_ms: 0,
kind: BundleKind::Blocks,
eta_secs,
}
}
#[test]
fn formats_status_with_default_size_and_the_servers_eta() {
let line = format_status("issued", &in_progress(1, 2, Some(3_900)));
assert!(line.contains("req-1"));
assert!(line.contains("in_progress"));
assert!(line.contains("size=default"));
assert!(line.contains("eta 1h 05m"), "{line}");
}
#[test]
fn a_status_without_a_server_eta_renders_without_one() {
let line = format_status("issued", &in_progress(1, 2, None));
assert!(line.contains("eta -"), "{line}");
let finishing = format_status("issued", &in_progress(1, 2, Some(0)));
assert!(finishing.contains("eta finishing up"), "{finishing}");
}
#[test]
fn formats_status_naming_either_kind() {
let blocks = format_status("issued", &in_progress(1, 2, None));
assert!(blocks.contains("kind=transactions"), "{blocks}");
let mut resp = in_progress(1, 2, None);
resp.kind = BundleKind::AccountState;
let account_state = format_status("issued", &resp);
assert!(
account_state.contains("kind=account_state"),
"{account_state}"
);
}
}