simulator-api 0.30.0

Wire-protocol types for the Solana simulator backtest WebSocket API
Documentation
//! Start, follow and cancel dataset jobs: `POST`, `GET` and `DELETE /dataset-jobs[/{job_id}]`.

use std::{collections::BTreeSet, fmt};

use serde::{Deserialize, Serialize};

use crate::{DepthSelection, SlotRange};

/// Request body of `POST /dataset-jobs`. Resubmitting it answers with the same job, re-running
/// it if it failed or was cancelled.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetJobRequest {
    /// Inclusive; sent as `start_slot` and `end_slot`.
    #[serde(flatten, with = "crate::slot_range::slot_bounds")]
    pub slots: SlotRange,
    /// Which dataset to build.
    #[serde(flatten)]
    pub dataset: DatasetJobSpec,
}

/// The dataset a job builds, tagged by `kind` on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DatasetJobSpec {
    /// Probes the current curated template set.
    EstimatedFills,
    /// World BTC 5-minute prediction-market tables.
    Predict {
        /// At least one table.
        tables: BTreeSet<PredictTable>,
    },
    /// What each venue's liquidity would have filled, or the router quoted, at each size across the
    /// range.
    Depth(DepthSelection),
}

impl DatasetJobSpec {
    /// The wire value of `kind`.
    pub fn kind(&self) -> &'static str {
        match self {
            Self::EstimatedFills => "estimated_fills",
            Self::Predict { .. } => "predict",
            Self::Depth(_) => "depth",
        }
    }
}

/// A predict table a dataset job produces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
pub enum PredictTable {
    /// The markets the makers quote.
    Markets,
    /// The writes to the makers' accounts.
    Writes,
    /// Maker quote ladders, per batch that changed a market account.
    Depth,
    /// An order per row, with each maker's quote.
    Orders,
}

impl PredictTable {
    /// The table's wire name.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Markets => "markets",
            Self::Writes => "writes",
            Self::Depth => "depth",
            Self::Orders => "orders",
        }
    }
}

/// A job's request, resolved range, phase and outputs, as `GET /dataset-jobs/{job_id}` answers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetJobStatusResponse {
    /// The id the job is followed and cancelled by.
    pub job_id: String,
    /// First slot requested.
    pub start_slot: u64,
    /// Last slot requested.
    pub end_slot: u64,
    /// The requested range widened to whole bundles.
    pub capture: SlotRange,
    /// The dataset the job builds.
    #[serde(flatten)]
    pub dataset: DatasetJobSpec,
    /// Where the job is.
    #[serde(flatten)]
    pub phase: DatasetJobPhase,
    /// Where the job's datasets land; filled in as they are written.
    pub outputs: Vec<DatasetLocation>,
    /// When the job was created, in Unix milliseconds.
    pub created_at_unix_ms: u64,
}

/// Where a job is, tagged by `phase` on the wire.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "phase", rename_all = "snake_case")]
pub enum DatasetJobPhase {
    /// Building the bundles the range needs.
    Building {
        /// Bundles built so far.
        bundles: Progress,
    },
    /// `sessions` is absent when they cannot be counted.
    Running {
        /// Sessions finished so far.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sessions: Option<Progress>,
        /// The job this one waits on before it measures.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        waiting_for: Option<String>,
    },
    /// Every output is written.
    Completed,
    /// The job stopped without finishing.
    Failed {
        /// Why it stopped.
        reason: String,
    },
    /// Rows already written stay.
    Cancelled,
}

impl DatasetJobPhase {
    /// The wire value of `phase`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Building { .. } => "building",
            Self::Running { .. } => "running",
            Self::Completed => "completed",
            Self::Failed { .. } => "failed",
            Self::Cancelled => "cancelled",
        }
    }

    /// Whether the job has stopped for good.
    pub fn is_terminal(&self) -> bool {
        match self {
            Self::Building { .. } | Self::Running { .. } => false,
            Self::Completed | Self::Failed { .. } | Self::Cancelled => true,
        }
    }
}

/// A count of finished units out of the total.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Progress {
    /// Units finished.
    pub done: usize,
    /// Units the job needs.
    pub total: usize,
}

/// A dataset under the `user_s3_uri` that `POST /datasets/credentials` returns, at
/// `<name>/v<version>/`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetLocation {
    /// The dataset's name.
    pub name: String,
    /// The dataset's schema version.
    pub version: u16,
}

impl fmt::Display for DatasetLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/v{}/", self.name, self.version)
    }
}

/// The caller's jobs, as `GET /dataset-jobs` answers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DatasetJobListResponse {
    /// Newest first.
    pub jobs: Vec<DatasetJobStatusResponse>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DepthGranularity, DepthSource};

    #[test]
    fn a_status_carries_its_kind_and_phase_beside_its_fields() {
        let status = DatasetJobStatusResponse {
            job_id: "j".to_owned(),
            start_slot: 100,
            end_slot: 199,
            capture: SlotRange::new_unchecked(90, 210),
            dataset: DatasetJobSpec::EstimatedFills,
            phase: DatasetJobPhase::Running {
                sessions: Some(Progress { done: 1, total: 3 }),
                waiting_for: None,
            },
            outputs: vec![DatasetLocation {
                name: "estimated-fills".to_owned(),
                version: 2,
            }],
            created_at_unix_ms: 7,
        };
        let wire = serde_json::json!({
            "job_id": "j",
            "start_slot": 100,
            "end_slot": 199,
            "capture": {"start": 90, "end": 210},
            "kind": "estimated_fills",
            "phase": "running",
            "sessions": {"done": 1, "total": 3},
            "outputs": [{"name": "estimated-fills", "version": 2}],
            "created_at_unix_ms": 7,
        });
        assert_eq!(serde_json::to_value(&status).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobStatusResponse>(wire).unwrap(),
            status
        );
    }

    #[test]
    fn a_running_phase_without_a_count_leaves_sessions_out() {
        let wire = serde_json::json!({"phase": "running"});
        let phase = DatasetJobPhase::Running {
            sessions: None,
            waiting_for: None,
        };
        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
            phase
        );
    }

    #[test]
    fn a_waiting_job_names_the_job_it_waits_for() {
        let phase = DatasetJobPhase::Running {
            sessions: None,
            waiting_for: Some("j2".to_owned()),
        };
        let wire = serde_json::json!({"phase": "running", "waiting_for": "j2"});
        assert_eq!(serde_json::to_value(&phase).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobPhase>(wire).unwrap(),
            phase
        );
    }

    /// The Prefect `dispatch-dataset-jobs` flow reads this file and must send exactly it.
    #[test]
    fn the_prefect_dispatch_bodies_round_trip() {
        let golden: serde_json::Value =
            serde_json::from_str(include_str!("../tests/data/dataset_job_requests.json")).unwrap();
        let requests: Vec<DatasetJobRequest> = serde_json::from_value(golden.clone()).unwrap();
        assert_eq!(serde_json::to_value(requests).unwrap(), golden);
    }

    #[test]
    fn a_request_names_its_kind_and_range() {
        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "estimated_fills",
        }))
        .unwrap();
        assert_eq!(request.dataset, DatasetJobSpec::EstimatedFills);
        assert_eq!(request.slots, SlotRange::new_unchecked(1, 2));
    }

    #[test]
    fn a_request_with_an_inverted_range_is_refused_as_it_is_read() {
        let request = serde_json::from_value::<DatasetJobRequest>(serde_json::json!({
            "start_slot": 2,
            "end_slot": 1,
            "kind": "estimated_fills",
        }));

        assert!(request.is_err());
    }

    #[test]
    fn a_request_writes_its_range_as_start_and_end_slots() {
        let request = DatasetJobRequest {
            slots: SlotRange::new_unchecked(5, 9),
            dataset: DatasetJobSpec::EstimatedFills,
        };

        assert_eq!(
            serde_json::to_value(&request).unwrap(),
            serde_json::json!({"start_slot": 5, "end_slot": 9, "kind": "estimated_fills"})
        );
    }

    #[test]
    fn a_predict_request_names_its_tables() {
        let request = DatasetJobRequest {
            slots: SlotRange::new_unchecked(1, 2),
            dataset: DatasetJobSpec::Predict {
                tables: BTreeSet::from([
                    PredictTable::Orders,
                    PredictTable::Depth,
                    PredictTable::Markets,
                ]),
            },
        };
        let wire = serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "predict",
            "tables": ["markets", "depth", "orders"],
        });
        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
            request
        );
    }

    #[test]
    fn a_depth_request_spells_its_options_beside_its_slots() {
        let request = DatasetJobRequest {
            slots: SlotRange::new_unchecked(1, 2),
            dataset: DatasetJobSpec::Depth(DepthSelection {
                source: DepthSource::Onchain,
                granularity: DepthGranularity::Oracle,
                markets: vec!["SOL-USDC".to_owned()],
                ..DepthSelection::default()
            }),
        };
        let wire = serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "depth",
            "source": "onchain",
            "granularity": "oracle",
            "markets": ["SOL-USDC"],
        });
        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DatasetJobRequest>(wire).unwrap(),
            request
        );
    }

    #[test]
    fn a_depth_request_naming_only_its_kind_measures_every_onchain_market_by_slot() {
        let request: DatasetJobRequest = serde_json::from_value(serde_json::json!({
            "start_slot": 1,
            "end_slot": 2,
            "kind": "depth",
        }))
        .unwrap();
        assert_eq!(
            request.dataset,
            DatasetJobSpec::Depth(DepthSelection::default())
        );
    }
}