Skip to main content

simulator_api/
subscribe_config.rs

1//! Cross-cutting subscribe options shared by the client and server.
2//!
3//! In a subscribe request's positional `[filter, config]` params, the `config`
4//! object carries per-kind fields (e.g. `commitment`) plus these options. The
5//! client builds [`SubscribeConfig`] and merges it in; the server parses it back
6//! out — one typed home for the wire field names. Absent fields default off, so
7//! peers without support interoperate.
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12/// Compression negotiated for notification frames. `lowercase` so the variant
13/// matches the on-wire token (`"zstd"`).
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16#[allow(missing_docs)]
17pub enum Compression {
18    Zstd,
19}
20
21/// Cross-cutting subscribe options the client sets in the config object.
22#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct SubscribeConfig {
24    /// Last slot the client already processed. On reconnect the server replays
25    /// from this slot (inclusive) rather than streaming the full history.
26    #[serde(
27        rename = "replayFromSlot",
28        default,
29        skip_serializing_if = "Option::is_none"
30    )]
31    pub replay_from_slot: Option<i64>,
32    /// Notification-frame compression the client opted into. `None` keeps the
33    /// uncompressed `Text` path.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub compression: Option<Compression>,
36    /// One account notification per write. Absent/false is Agave parity: one per
37    /// account per slot, carrying the slot's final state. Only `accountSubscribe`
38    /// and `programSubscribe` read it.
39    #[serde(
40        rename = "intraSlotUpdates",
41        default,
42        skip_serializing_if = "core::ops::Not::not"
43    )]
44    pub intra_slot_updates: bool,
45}
46
47impl SubscribeConfig {
48    /// Parse the cross-cutting options out of a subscribe config object. Per-kind
49    /// fields are ignored, and a missing or malformed object yields defaults
50    /// (all off), so a subscribe never fails on these optional fields.
51    pub fn from_value(config: Option<&Value>) -> Self {
52        config
53            .cloned()
54            .and_then(|v| serde_json::from_value(v).ok())
55            .unwrap_or_default()
56    }
57
58    /// Merge the set options into a subscribe request's config object (the second
59    /// positional param), leaving its per-kind fields untouched. A no-op if the
60    /// params don't have a config object.
61    pub fn apply_to(&self, params: &mut Value) {
62        let Some(config) = params.get_mut(1).and_then(Value::as_object_mut) else {
63            return;
64        };
65        if let Ok(Value::Object(fields)) = serde_json::to_value(self) {
66            config.extend(fields);
67        }
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn parses_set_options_and_ignores_per_kind_fields() {
77        let cfg = SubscribeConfig::from_value(Some(&serde_json::json!({
78            "commitment": "confirmed",
79            "replayFromSlot": 42,
80            "compression": "zstd",
81            "intraSlotUpdates": true,
82        })));
83        assert_eq!(cfg.replay_from_slot, Some(42));
84        assert_eq!(cfg.compression, Some(Compression::Zstd));
85        assert!(cfg.intra_slot_updates);
86    }
87
88    #[test]
89    fn absent_or_malformed_options_default_off() {
90        assert_eq!(
91            SubscribeConfig::from_value(None),
92            SubscribeConfig::default()
93        );
94        let cfg =
95            SubscribeConfig::from_value(Some(&serde_json::json!({ "commitment": "confirmed" })));
96        assert_eq!(cfg, SubscribeConfig::default());
97        assert!(!cfg.intra_slot_updates);
98        // An unrecognized compression token leaves compression off.
99        let cfg = SubscribeConfig::from_value(Some(&serde_json::json!({ "compression": "gzip" })));
100        assert_eq!(cfg.compression, None);
101    }
102
103    #[test]
104    fn apply_to_merges_into_config_without_clobbering() {
105        let mut params =
106            serde_json::json!([{ "mentions": ["prog"] }, { "commitment": "confirmed" }]);
107        SubscribeConfig {
108            replay_from_slot: Some(7),
109            compression: Some(Compression::Zstd),
110            intra_slot_updates: true,
111        }
112        .apply_to(&mut params);
113        assert_eq!(params[1]["commitment"], "confirmed");
114        assert_eq!(params[1]["replayFromSlot"], 7);
115        assert_eq!(params[1]["compression"], "zstd");
116        assert_eq!(params[1]["intraSlotUpdates"], true);
117    }
118
119    #[test]
120    fn apply_to_omits_unset_options() {
121        let mut params = serde_json::json!([{ "mentions": ["prog"] }, {}]);
122        SubscribeConfig::default().apply_to(&mut params);
123        assert_eq!(params[1].as_object().unwrap().len(), 0);
124    }
125}