simulator-client 0.28.0

Async WebSocket client for the Solana simulator backtest API
Documentation
use std::collections::HashSet;

use simulator_api::DirectFillTemplate;

/// The templates a JSON array names, refused if it names none or repeats a label. `source` only
/// names the input in the error.
///
/// Labels are a template's identity on every row the server writes, so it refuses a repeat;
/// caught here first to save the round trip.
pub fn parse_templates(source: &str, raw: &str) -> Result<Vec<DirectFillTemplate>, String> {
    let templates: Vec<DirectFillTemplate> =
        serde_json::from_str(raw).map_err(|error| format!("parsing {source}: {error}"))?;
    if templates.is_empty() {
        return Err(format!("{source}: names no templates"));
    }
    let mut labels = HashSet::new();
    if let Some(duplicate) = templates
        .iter()
        .map(|template| template.label.as_str())
        .find(|label| !labels.insert(*label))
    {
        return Err(format!(
            "{source}: template label {duplicate:?} appears more than once"
        ));
    }
    Ok(templates)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Recipe {
    pub name: &'static str,
    json: &'static str,
}

impl Recipe {
    pub fn templates(&self) -> Vec<DirectFillTemplate> {
        serde_json::from_str(self.json)
            .unwrap_or_else(|error| panic!("recipe {} ships invalid JSON: {error}", self.name))
    }
}

pub const VENUES: Recipe = Recipe {
    name: "venues",
    json: include_str!("../recipes/venues.json"),
};

pub const ALL: [Recipe; 1] = [VENUES];

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_recipe_parses() {
        for recipe in ALL {
            assert!(
                !recipe.templates().is_empty(),
                "{} carries no templates",
                recipe.name
            );
        }
    }

    #[test]
    fn labels_are_unique_across_every_recipe() {
        let mut seen = HashSet::new();
        for recipe in ALL {
            for template in recipe.templates() {
                assert!(
                    seen.insert(template.label.clone()),
                    "{} repeats the label {}",
                    recipe.name,
                    template.label
                );
            }
        }
    }
}