simulator-api 0.29.0

Wire-protocol types for the Solana simulator backtest WebSocket API
Documentation
use serde::{Deserialize, Serialize};

use crate::{InvertedSlotRange, SlotRange};

/// With neither field, every one of the caller's own datasets.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetListQuery {
    /// Only this dataset (e.g. `estimated-fills`), plus the shared dataset of that name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dataset: Option<String>,
    /// Only this version; requires `dataset`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<u16>,
}

/// Response of `GET /datasets`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetListResponse {
    /// One entry per dataset and scope.
    pub datasets: Vec<DatasetSummary>,
}

/// One dataset in one scope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetSummary {
    /// The dataset's name, e.g. `estimated-fills`.
    pub name: String,
    /// Whose copy of the dataset this lists.
    pub scope: DatasetScope,
    /// What the dataset holds.
    #[serde(flatten)]
    pub contents: DatasetContents,
}

/// Whose copy of a dataset a listing shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DatasetScope {
    /// Under the `user_s3_uri` of `POST /datasets/credentials`.
    Own,
    /// The dataset shared by every key.
    Shared,
}

/// What a dataset holds, by how it is laid out.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "layout", rename_all = "snake_case")]
pub enum DatasetContents {
    /// Parquet parts.
    Partitioned {
        /// The partition key below each date, as the parts' paths name it.
        partition_key: String,
        /// The versions present, each with its own coverage.
        versions: Vec<DatasetVersion>,
    },
    /// Whole files, such as a reroute run's database.
    Files {
        /// The files present.
        files: Vec<DatasetFile>,
    },
}

/// One version of a partitioned dataset.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetVersion {
    /// The dataset version.
    pub version: u16,
    /// Sorted, with touching ranges merged.
    pub coverage: Vec<SlotRange>,
    /// Slots measured but waiting for their check: not readable yet, and in neither `coverage`
    /// nor the parts.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub checking: Vec<SlotRange>,
    /// Slots measured and held by their check: not readable until the job named passes it, when
    /// submitted again.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub held: Vec<HeldSlots>,
    /// Absent while the version holds only slots waiting for their check.
    #[serde(flatten)]
    pub parts: Option<DatasetParts>,
    /// The version's parts by UTC date.
    pub dates: Vec<DatasetDate>,
}

/// A slot range held by a job's check.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeldSlots {
    /// The held slots.
    pub slots: SlotRange,
    /// The job whose check held them.
    pub job_id: String,
}

/// One UTC date.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetDate {
    /// The date, `YYYY-MM-DD`.
    pub date: String,
    /// The partitions with parts on that date.
    pub partitions: Vec<DatasetPartition>,
}

/// The parts under one value of the dataset's partition key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetPartition {
    /// The partition key's value, e.g. a market.
    pub value: String,
    /// Sorted, with touching ranges merged.
    pub coverage: Vec<SlotRange>,
    /// The partition's parts.
    #[serde(flatten)]
    pub parts: DatasetParts,
}

/// A count and extent of parquet parts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetParts {
    /// How many parts.
    pub parts: usize,
    /// Ranges with no rows; their slots still count as covered.
    pub empty_parts: usize,
    /// Their total size.
    pub bytes: u64,
    /// When the first part was written.
    pub first_written_unix_ms: u64,
    /// When the last part was written.
    pub last_written_unix_ms: u64,
    /// When the earliest part expires; absent for shared datasets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub available_until_unix_ms: Option<u64>,
}

/// One file of a files dataset.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetFile {
    /// Relative to the dataset.
    pub path: String,
    /// The session's slots, when its path names them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slots: Option<SlotRange>,
    /// The file's size.
    pub bytes: u64,
    /// When the file was written.
    pub written_unix_ms: u64,
    /// When the file expires; absent for shared datasets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub available_until_unix_ms: Option<u64>,
}

/// Query of `DELETE /datasets`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "DeleteQuery", into = "DeleteQuery")]
pub struct DatasetDeleteRequest {
    /// The dataset as `GET /datasets` names it.
    pub dataset: String,
    /// The slots to remove.
    pub slots: SlotRange,
    /// Only this version; absent takes the range out of every version.
    pub version: Option<u16>,
}

/// Flat form of the request: a query string carries no nested range.
#[derive(Serialize, Deserialize)]
struct DeleteQuery {
    dataset: String,
    start_slot: u64,
    end_slot: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    version: Option<u16>,
}

impl TryFrom<DeleteQuery> for DatasetDeleteRequest {
    type Error = InvertedSlotRange;

    fn try_from(query: DeleteQuery) -> Result<Self, Self::Error> {
        let DeleteQuery {
            dataset,
            start_slot,
            end_slot,
            version,
        } = query;
        Ok(Self {
            dataset,
            slots: SlotRange::new(start_slot, end_slot)?,
            version,
        })
    }
}

impl From<DatasetDeleteRequest> for DeleteQuery {
    fn from(request: DatasetDeleteRequest) -> Self {
        let DatasetDeleteRequest {
            dataset,
            slots,
            version,
        } = request;
        Self {
            dataset,
            start_slot: slots.start(),
            end_slot: slots.end(),
            version,
        }
    }
}

/// Anything reaching past either end of the range stays.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetDeleteResponse {
    /// How many parquet parts were removed.
    pub parts: usize,
    /// How many of them held no rows.
    pub empty_parts: usize,
    /// How many whole files were removed.
    pub files: usize,
    /// Their total size.
    pub bytes: u64,
}

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

    fn round_trips<T>(value: &T, wire: serde_json::Value)
    where
        T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug,
    {
        assert_eq!(serde_json::to_value(value).unwrap(), wire);
        assert_eq!(&serde_json::from_value::<T>(wire).unwrap(), value);
    }

    fn parts(available_until_unix_ms: Option<u64>) -> DatasetParts {
        DatasetParts {
            parts: 2,
            empty_parts: 1,
            bytes: 300,
            first_written_unix_ms: 10,
            last_written_unix_ms: 20,
            available_until_unix_ms,
        }
    }

    #[test]
    fn a_partitioned_dataset_carries_its_layout_and_part_counts_beside_its_fields() {
        let coverage = vec![SlotRange::new_unchecked(100, 199)];
        let summary = DatasetSummary {
            name: "estimated-fills".to_owned(),
            scope: DatasetScope::Own,
            contents: DatasetContents::Partitioned {
                partition_key: "market".to_owned(),
                versions: vec![DatasetVersion {
                    version: 2,
                    coverage: coverage.clone(),
                    checking: vec![SlotRange::new_unchecked(200, 299)],
                    held: Vec::new(),
                    parts: Some(parts(Some(30))),
                    dates: vec![DatasetDate {
                        date: "2026-10-19".to_owned(),
                        partitions: vec![DatasetPartition {
                            value: "SOL-USDC".to_owned(),
                            coverage,
                            parts: parts(Some(30)),
                        }],
                    }],
                }],
            },
        };
        round_trips(
            &summary,
            serde_json::json!({
                "name": "estimated-fills",
                "scope": "own",
                "layout": "partitioned",
                "partition_key": "market",
                "versions": [{
                    "version": 2,
                    "coverage": [{"start": 100, "end": 199}],
                    "checking": [{"start": 200, "end": 299}],
                    "parts": 2,
                    "empty_parts": 1,
                    "bytes": 300,
                    "first_written_unix_ms": 10,
                    "last_written_unix_ms": 20,
                    "available_until_unix_ms": 30,
                    "dates": [{
                        "date": "2026-10-19",
                        "partitions": [{
                            "value": "SOL-USDC",
                            "coverage": [{"start": 100, "end": 199}],
                            "parts": 2,
                            "empty_parts": 1,
                            "bytes": 300,
                            "first_written_unix_ms": 10,
                            "last_written_unix_ms": 20,
                            "available_until_unix_ms": 30,
                        }],
                    }],
                }],
            }),
        );
    }

    #[test]
    fn a_version_only_waiting_for_its_check_has_no_parts() {
        round_trips(
            &DatasetVersion {
                version: 2,
                coverage: Vec::new(),
                checking: vec![SlotRange::new_unchecked(200, 299)],
                held: vec![HeldSlots {
                    slots: SlotRange::new_unchecked(300, 399),
                    job_id: "j".to_owned(),
                }],
                parts: None,
                dates: Vec::new(),
            },
            serde_json::json!({
                "version": 2,
                "coverage": [],
                "checking": [{"start": 200, "end": 299}],
                "held": [{"slots": {"start": 300, "end": 399}, "job_id": "j"}],
                "dates": [],
            }),
        );
    }

    #[test]
    fn a_shared_file_dataset_has_no_end_to_its_availability() {
        let summary = DatasetSummary {
            name: "reroute".to_owned(),
            scope: DatasetScope::Shared,
            contents: DatasetContents::Files {
                files: vec![DatasetFile {
                    path: "my-run.sqlite".to_owned(),
                    slots: None,
                    bytes: 5,
                    written_unix_ms: 7,
                    available_until_unix_ms: None,
                }],
            },
        };
        round_trips(
            &summary,
            serde_json::json!({
                "name": "reroute",
                "scope": "shared",
                "layout": "files",
                "files": [{"path": "my-run.sqlite", "bytes": 5, "written_unix_ms": 7}],
            }),
        );
    }

    #[test]
    fn an_empty_query_lists_everything_of_ones_own() {
        let query: DatasetListQuery = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(query, DatasetListQuery::default());
        round_trips(
            &DatasetListQuery {
                dataset: Some("estimated-fills".to_owned()),
                version: Some(2),
            },
            serde_json::json!({"dataset": "estimated-fills", "version": 2}),
        );
    }

    #[test]
    fn a_delete_names_its_dataset_range_and_any_version() {
        round_trips(
            &DatasetDeleteRequest {
                dataset: "reroute".to_owned(),
                slots: SlotRange::new_unchecked(1, 22),
                version: None,
            },
            serde_json::json!({"dataset": "reroute", "start_slot": 1, "end_slot": 22}),
        );
        round_trips(
            &DatasetDeleteResponse {
                parts: 3,
                empty_parts: 1,
                files: 0,
                bytes: 220,
            },
            serde_json::json!({"parts": 3, "empty_parts": 1, "files": 0, "bytes": 220}),
        );
    }

    #[test]
    fn a_delete_of_an_inverted_range_is_refused_as_it_is_read() {
        let request = serde_json::from_value::<DatasetDeleteRequest>(
            serde_json::json!({"dataset": "reroute", "start_slot": 22, "end_slot": 1}),
        );

        assert!(request.is_err());
    }
}