sim-cli 0.22.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, DepthGranularity, DepthRequest, DepthSelection, DepthSource,
    DepthStatusResponse, depth_dataset_prefix, modified_dataset_root,
};
use simulator_client::BacktestClient;

const MEASURE_EXAMPLES: &str = "\
Examples:
  # Measure onchain depth for every covered market, and wait for the job.
  sim depth measure --start-slot 380000000 --end-slot 380099999 \\
    --source onchain --wait

  # Sample one market at every oracle update instead of once per slot.
  sim depth measure --start-slot 380000000 --end-slot 380099999 \\
    --source onchain --granularity oracle --market SOL-USDC

  # Measure router quotes for two markets, then check on the job later.
  sim depth measure --start-slot 380000000 --end-slot 380099999 \\
    --source router --market SOL-USDC --market NVDAx-USDC
  sim depth status <job-id>";

const STATUS_EXAMPLES: &str = "\
Examples:
  sim depth status <job-id>
  sim depth status <job-id> --json";

const COVERAGE_EXAMPLES: &str = "\
Examples:
  # List the market ids `sim depth measure --market` accepts, per source.
  sim depth coverage
  sim depth coverage --json";

#[derive(Parser, Debug)]
#[command(after_help = MEASURE_EXAMPLES)]
pub struct DepthMeasureArgs {
    /// First slot to capture, inclusive. Each row is filed under the UTC date
    /// its slot falls on.
    #[arg(long)]
    pub start_slot: u64,

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

    #[command(flatten)]
    pub selection: DepthSelectionArgs,

    /// Wait until the job finishes instead of returning once it is submitted.
    /// Prints the dataset's S3 URI when the job completes, and exits with
    /// status 1 when it fails.
    #[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(clap::Args, Debug)]
pub struct DepthSelectionArgs {
    /// Where the depth numbers come from.
    #[arg(long, value_enum)]
    pub source: DepthSource,

    /// Sample once per slot, or `oracle`: after each batch that updated an account a probe reads
    /// (`onchain` only).
    #[arg(long, value_enum, default_value_t)]
    pub granularity: DepthGranularity,

    /// Measure only this market (see `sim depth coverage`); repeat for several. Unset measures all.
    #[arg(long = "market")]
    pub markets: Vec<String>,
}

#[derive(Parser, Debug)]
#[command(after_help = STATUS_EXAMPLES)]
pub struct DepthStatusArgs {
    /// The job ID `sim depth measure` returned.
    #[arg(value_name = "JOB_ID")]
    pub request_id: String,

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

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

#[derive(Parser, Debug)]
#[command(after_help = COVERAGE_EXAMPLES)]
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 server 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 {} rung(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 {
    let capture = resp
        .capture
        .map(|capture| format!(" capture {}-{}", capture.start(), capture.end()))
        .unwrap_or_default();
    let granularity = if resp.granularity.is_default() {
        String::new()
    } else {
        format!("/{}", resp.granularity)
    };
    format!(
        "{prefix}: {} ({}{granularity}, {}-{}) {}{capture}",
        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,
            selection: DepthSelection {
                source: args.selection.source,
                granularity: args.selection.granularity,
                markets: args.selection.markets,
                ..Default::default()
            },
        })
        .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)?);
    }
    super::check_job("depth job", &resp.request_id, resp.status)?;
    if matches!(resp.status, BundleBuildStatus::Completed) && !args.output.json {
        println!("dataset: {}", dataset_location(&client, &resp).await);
    }
    Ok(())
}

/// Where a job's dataset is published, relative to your datasets URI. The
/// files sit in a `v<revision>/` directory below it.
fn dataset_path(resp: &DepthStatusResponse) -> String {
    let dataset = depth_dataset_prefix(resp.source, resp.granularity);
    match &resp.modification_digest {
        Some(digest) => format!("{}/", modified_dataset_root(dataset, digest)),
        None => format!("{dataset}/"),
    }
}

/// The job's dataset as an S3 URI under your datasets URI. Without that URI it
/// names the path relative to it rather than failing a job that completed.
async fn dataset_location(client: &BacktestClient, resp: &DepthStatusResponse) -> String {
    let path = dataset_path(resp);
    match client
        .dataset_credentials()
        .await
        .map(|resp| resp.user_s3_uri)
    {
        Ok(Some(root)) => format!("{}/{path}", root.trim_end_matches('/')),
        Ok(None) | Err(_) => format!(
            "{path} under the `# your datasets:` URI that `sim datasets credentials` prints"
        ),
    }
}

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 simulator_api::SlotRange;

    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.selection.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.selection.source, source);
        }
    }

    #[test]
    fn each_market_is_its_own_flag() {
        let parsed = parse(&["--market", "NVDAx-USDC", "--market", "Mu-USDC"]).expect("parses");
        assert_eq!(parsed.selection.markets, ["NVDAx-USDC", "Mu-USDC"]);
        assert!(parse(&[]).expect("parses").selection.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());
    }

    #[rstest]
    #[case::per_slot(
        DepthSource::Onchain,
        DepthGranularity::Slot,
        None,
        "depth/onchain/slot/"
    )]
    #[case::at_oracle_updates(
        DepthSource::Onchain,
        DepthGranularity::Oracle,
        None,
        "depth/onchain/oracle/"
    )]
    #[case::router(
        DepthSource::Router,
        DepthGranularity::Slot,
        None,
        "depth/router/slot/"
    )]
    #[case::modified(
        DepthSource::Onchain,
        DepthGranularity::Slot,
        Some("ab12"),
        "modified/depth/onchain/slot/ab12/"
    )]
    fn a_dataset_path_follows_the_published_layout(
        #[case] source: DepthSource,
        #[case] granularity: DepthGranularity,
        #[case] digest: Option<&str>,
        #[case] expected: &str,
    ) {
        let resp = DepthStatusResponse {
            request_id: "r".to_string(),
            start_slot: 100,
            end_slot: 199,
            source,
            granularity,
            status: BundleBuildStatus::Completed,
            capture: None,
            modification_digest: digest.map(str::to_owned),
        };
        assert_eq!(dataset_path(&resp), expected);
    }

    #[rstest]
    #[case::not_reported(
        None,
        DepthGranularity::Slot,
        "status: r (onchain, 100-199) in_progress"
    )]
    #[case::snapped_outward(
        Some(SlotRange::new_unchecked(90, 210)),
        DepthGranularity::Slot,
        "status: r (onchain, 100-199) in_progress capture 90-210"
    )]
    #[case::at_oracle_updates(
        None,
        DepthGranularity::Oracle,
        "status: r (onchain/oracle, 100-199) in_progress"
    )]
    fn a_status_line_shows_a_granularity_and_capture_only_when_reported(
        #[case] capture: Option<SlotRange>,
        #[case] granularity: DepthGranularity,
        #[case] expected: &str,
    ) {
        let resp = DepthStatusResponse {
            request_id: "r".to_string(),
            start_slot: 100,
            end_slot: 199,
            source: DepthSource::Onchain,
            granularity,
            status: BundleBuildStatus::InProgress,
            capture,
            modification_digest: None,
        };
        assert_eq!(format_status("status", &resp), expected);
    }
}