Skip to main content

sapphire_framework_session/
message.rs

1//! What two replicas say to each other.
2
3use grain_id::GrainId;
4use sapphire_sync::{ContentHash, PathUpdate, ReplicaId, VersionVector};
5use serde::{Deserialize, Serialize};
6
7/// One control message.
8#[derive(Clone, Debug, Deserialize, Serialize)]
9pub enum Message {
10    /// The first message from each side.
11    Hello {
12        /// Session format this side speaks.
13        format: u32,
14        /// Which workspace this session is about.
15        workspace_id: GrainId,
16        /// The sender's replica id.
17        replica_id: ReplicaId,
18        /// Everything the sender already has.
19        vv: VersionVector,
20        /// The largest file the sender writes, in bytes. The peer sends nothing larger
21        /// unasked: content over it would be refused as a protocol error.
22        max_file_size: u64,
23        /// Whether the sender answers a [`Message::Live`] push with [`Message::Ack`], and
24        /// reads one. Absent from a peer older than acknowledgements: `false`, and no `Ack`
25        /// is ever sent to it.
26        #[serde(default)]
27        acks: bool,
28    },
29    /// A page of path states the peer's version vector does not cover.
30    Updates(Vec<PathUpdate>),
31    /// The sender has sent every `Updates` page it had.
32    Done,
33    /// The sender needs the content behind this hash.
34    Want(ContentHash),
35    /// The sender does not have the content behind this hash either.
36    Missing(ContentHash),
37    /// The sender started this content and could not finish it: the file changed under it.
38    ///
39    /// Sent in place of the content's `BLOB_END`. The receiver discards what it got and
40    /// treats the hash as [`Message::Missing`].
41    Aborted(ContentHash),
42    /// The sender will ask for nothing further, and has answered every `Want` it will get.
43    ///
44    /// Sent after the peer's `Done`, once this side's want list is empty — at which point it
45    /// cannot grow again. Without it a side that stopped reading at `Done` would drop the
46    /// `Want` the peer sends after applying a page, and every file over the inline limit
47    /// would silently never arrive.
48    Settled,
49    /// A push of path states sent after the initial exchange, while the session stays open.
50    Live(Vec<PathUpdate>),
51    /// The sender will not continue, and why.
52    Refused(String),
53    /// The sender has everything this version vector covers: the path states, and the
54    /// content behind them on disk (or answered `Missing` by whoever was asked).
55    ///
56    /// Sent in the live phase, after the `Live` batches it answers have been applied, and
57    /// only to a peer whose `Hello` said `acks`. It is what lets the pushing side know a
58    /// local edit has left the device, rather than only that it was queued.
59    Ack(VersionVector),
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    fn round_trip(msg: &Message) -> Message {
67        let json = serde_json::to_vec(msg).unwrap();
68        serde_json::from_slice(&json).unwrap()
69    }
70
71    #[test]
72    fn a_hello_round_trips() {
73        let mut vv = VersionVector::new();
74        vv.add_dot(&sapphire_sync::Dot {
75            replica: ReplicaId::new(),
76            counter: 3,
77        });
78        let msg = Message::Hello {
79            format: crate::SESSION_FORMAT_VERSION,
80            workspace_id: GrainId::random(),
81            replica_id: ReplicaId::new(),
82            vv,
83            max_file_size: 1024,
84            acks: true,
85        };
86        assert_eq!(format!("{:?}", round_trip(&msg)), format!("{msg:?}"));
87    }
88
89    #[test]
90    fn the_payload_free_messages_round_trip() {
91        assert!(matches!(round_trip(&Message::Done), Message::Done));
92        assert!(matches!(round_trip(&Message::Settled), Message::Settled));
93    }
94
95    #[test]
96    fn a_hash_carrying_message_round_trips_as_hex() {
97        let hash = ContentHash::of_bytes(b"content");
98        let json = serde_json::to_string(&Message::Want(hash)).unwrap();
99        // The hash travels as hex, not as an array of 32 numbers.
100        assert!(json.contains(&hash.to_hex()), "got {json}");
101        assert_eq!(
102            format!("{:?}", round_trip(&Message::Want(hash))),
103            format!("{:?}", Message::Want(hash))
104        );
105        assert_eq!(
106            format!("{:?}", round_trip(&Message::Missing(hash))),
107            format!("{:?}", Message::Missing(hash))
108        );
109    }
110
111    #[test]
112    fn an_abort_round_trips() {
113        let hash = ContentHash::of_bytes(b"content");
114        match round_trip(&Message::Aborted(hash)) {
115            Message::Aborted(back) => assert_eq!(back, hash),
116            other => panic!("got {other:?}"),
117        }
118    }
119
120    #[test]
121    fn a_hello_without_acks_reads_as_not_acknowledging() {
122        // What a peer from before acknowledgements sends.
123        let json = serde_json::json!({ "Hello": {
124            "format": crate::SESSION_FORMAT_VERSION,
125            "workspace_id": GrainId::random(),
126            "replica_id": ReplicaId::new(),
127            "vv": VersionVector::new(),
128            "max_file_size": 1024,
129        }});
130        match serde_json::from_value::<Message>(json).unwrap() {
131            Message::Hello { acks, .. } => assert!(!acks),
132            other => panic!("got {other:?}"),
133        }
134    }
135
136    #[test]
137    fn an_ack_round_trips() {
138        let mut vv = VersionVector::new();
139        vv.add_dot(&sapphire_sync::Dot {
140            replica: ReplicaId::new(),
141            counter: 7,
142        });
143        match round_trip(&Message::Ack(vv.clone())) {
144            Message::Ack(back) => assert!(back.covers(&vv) && vv.covers(&back)),
145            other => panic!("got {other:?}"),
146        }
147    }
148
149    #[test]
150    fn a_refusal_round_trips() {
151        let msg = Message::Refused("format 2".to_owned());
152        match round_trip(&msg) {
153            Message::Refused(why) => assert_eq!(why, "format 2"),
154            other => panic!("got {other:?}"),
155        }
156    }
157
158    #[test]
159    fn a_live_push_round_trips() {
160        let mut vv = VersionVector::new();
161        vv.add_dot(&sapphire_sync::Dot {
162            replica: ReplicaId::new(),
163            counter: 3,
164        });
165        let msg = Message::Live(vec![PathUpdate {
166            path: "notes/hello.md".to_owned(),
167            versions: vec![],
168            seen: vv,
169        }]);
170        match round_trip(&msg) {
171            Message::Live(updates) => {
172                assert_eq!(updates.len(), 1);
173                assert_eq!(updates[0].path, "notes/hello.md");
174            }
175            other => panic!("got {other:?}"),
176        }
177    }
178}