sim-cli 0.18.0

CLI tool for running and comparing Solana simulator backtests
Documentation
use std::time::Duration;

use clap::Parser;
use eyre::Result;
use sim_cli::{ApiKeyArg, args::JsonOutputArgs};
use simulator_api::{BundleBuildStatus, DepthRequest, DepthSource, DepthStatusResponse};

#[derive(Parser, Debug)]
pub struct DepthMeasureArgs {
    /// First slot to capture, inclusive. The UTC date it falls on becomes the
    /// dataset's partition key.
    #[arg(long)]
    pub start_slot: u64,

    /// Last slot to capture, inclusive.
    #[arg(long)]
    pub end_slot: u64,

    /// Where a run's depth numbers come from.
    #[arg(long, value_enum)]
    pub source: DepthSource,

    /// Capture only this market, by id (see `sim depth coverage`).
    /// Repeat to capture multiple markets, leave unset to capture all markets.
    #[arg(long = "market")]
    pub markets: Vec<String>,

    /// Poll until the run reaches a terminal state instead of returning on submit.
    #[arg(long)]
    pub wait: bool,

    /// Seconds between status polls when `--wait` is set.
    #[arg(long, default_value_t = 30, value_parser = clap::value_parser!(u64).range(1..))]
    pub poll_secs: u64,

    #[command(flatten)]
    pub api_key: ApiKeyArg,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

#[derive(Parser, Debug)]
pub struct DepthStatusArgs {
    /// The request id `sim depth measure` returned.
    pub request_id: String,

    #[command(flatten)]
    pub api_key: ApiKeyArg,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

#[derive(Parser, Debug)]
pub struct DepthCoverageArgs {
    #[command(flatten)]
    pub api_key: ApiKeyArg,

    #[command(flatten)]
    pub output: JsonOutputArgs,
}

pub async fn coverage(args: DepthCoverageArgs, url: String) -> Result<()> {
    let client = sim_cli::client::new(&url, &args.api_key.get());
    let resp = client.get_depth_coverage().await?;

    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&resp)?);
        return Ok(());
    }
    // Every source is dropped only when the service cannot read its own configuration, so an
    // empty answer is a fault on our side rather than "nothing is sampled".
    if resp.sources.is_empty() {
        eyre::bail!(
            "unable to show coverage: the service could not describe what it samples. \
             Nothing is wrong with your request — try again in a few minutes, and report \
             this if it keeps happening."
        );
    }
    for coverage in &resp.sources {
        println!(
            "{} (revision {}): {} market(s) x {} venue(s) at {} size(s)",
            coverage.source,
            coverage.revision,
            coverage.markets.len(),
            coverage.venues.len(),
            coverage.size_rungs,
        );
        println!("  markets: {}", coverage.markets.join(", "));
        println!("  venues : {}", coverage.venues.join(", "));
        if coverage.completed_ranges.is_empty() {
            println!("  published: none yet");
        } else {
            let ranges: Vec<String> = coverage
                .completed_ranges
                .iter()
                .map(|range| format!("{}-{}", range.start(), range.end()))
                .collect();
            println!("  published: {}", ranges.join(", "));
        }
    }
    Ok(())
}

fn format_status(prefix: &str, resp: &DepthStatusResponse) -> String {
    format!(
        "{prefix}: {} ({}, {}-{}) {}",
        resp.request_id,
        resp.source,
        resp.start_slot,
        resp.end_slot,
        resp.status.as_str()
    )
}

pub async fn measure(args: DepthMeasureArgs, url: String) -> Result<()> {
    let client = sim_cli::client::new(&url, &args.api_key.get());

    let mut resp = client
        .generate_depth(&DepthRequest {
            start_slot: args.start_slot,
            end_slot: args.end_slot,
            source: args.source,
            markets: args.markets,
        })
        .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_depth_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(())
}

pub async fn status(args: DepthStatusArgs, url: String) -> Result<()> {
    let client = sim_cli::client::new(&url, &args.api_key.get());
    let resp = client.get_depth_status(&args.request_id).await?;

    if args.output.json {
        println!("{}", serde_json::to_string_pretty(&resp)?);
    } else {
        println!("{}", format_status("status", &resp));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use clap::Parser;
    use rstest::rstest;

    use super::*;

    fn parse(extra: &[&str]) -> Result<DepthMeasureArgs, clap::Error> {
        let mut argv = vec![
            "sim",
            "--start-slot",
            "100",
            "--end-slot",
            "199",
            "--source",
            "onchain",
            "--api-key",
            "k",
        ];
        argv.extend_from_slice(extra);
        DepthMeasureArgs::try_parse_from(argv)
    }

    #[test]
    fn slots_a_source_and_a_key_are_enough_to_submit() {
        let parsed = parse(&[]).expect("the happy path parses");
        assert_eq!((parsed.start_slot, parsed.end_slot), (100, 199));
        assert_eq!(parsed.source, DepthSource::Onchain);
        assert_eq!(parsed.poll_secs, 30);
    }

    /// What `--source` accepts is the wire spelling, since it is the wire enum: the CLI and the
    /// request body cannot drift apart because there is only one definition.
    #[test]
    fn a_source_parses_by_its_wire_name() {
        for source in [DepthSource::Onchain, DepthSource::Router] {
            let parsed = DepthMeasureArgs::try_parse_from([
                "sim",
                "--start-slot",
                "100",
                "--end-slot",
                "199",
                "--source",
                source.as_str(),
                "--api-key",
                "k",
            ])
            .expect("the wire name parses");
            assert_eq!(parsed.source, source);
        }
    }

    #[test]
    fn each_market_is_its_own_flag() {
        let parsed = parse(&["--market", "NVDAx-USDC", "--market", "Mu-USDC"]).expect("parses");
        assert_eq!(parsed.markets, ["NVDAx-USDC", "Mu-USDC"]);
        assert!(parse(&[]).expect("parses").markets.is_empty());
    }

    #[test]
    fn a_poll_interval_below_one_second_is_refused() {
        assert!(parse(&["--wait", "--poll-secs", "0"]).is_err());
    }

    /// Neither arm is a safe default: they publish separate datasets, so a
    /// missing `--source` has to be an error rather than a guess.
    #[rstest]
    #[case::no_start(&["sim", "--end-slot", "199", "--source", "onchain", "--api-key", "k"])]
    #[case::no_end(&["sim", "--start-slot", "100", "--source", "onchain", "--api-key", "k"])]
    #[case::no_source(&["sim", "--start-slot", "100", "--end-slot", "199", "--api-key", "k"])]
    fn both_slots_and_a_source_are_required(#[case] argv: &[&str]) {
        assert!(DepthMeasureArgs::try_parse_from(argv).is_err());
    }
}