sapphire-framework-session 0.29.0

The replication session two sapphire-framework replicas run over a byte stream
Documentation
//! What two replicas say to each other.

use grain_id::GrainId;
use sapphire_sync::{ContentHash, PathUpdate, ReplicaId, VersionVector};
use serde::{Deserialize, Serialize};

/// One control message.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Message {
    /// The first message from each side.
    Hello {
        /// Session format this side speaks.
        format: u32,
        /// Which workspace this session is about.
        workspace_id: GrainId,
        /// The sender's replica id.
        replica_id: ReplicaId,
        /// Everything the sender already has.
        vv: VersionVector,
        /// The largest file the sender writes, in bytes. The peer sends nothing larger
        /// unasked: content over it would be refused as a protocol error.
        max_file_size: u64,
        /// Whether the sender answers a [`Message::Live`] push with [`Message::Ack`], and
        /// reads one. Absent from a peer older than acknowledgements: `false`, and no `Ack`
        /// is ever sent to it.
        #[serde(default)]
        acks: bool,
    },
    /// A page of path states the peer's version vector does not cover.
    Updates(Vec<PathUpdate>),
    /// The sender has sent every `Updates` page it had.
    Done,
    /// The sender needs the content behind this hash.
    Want(ContentHash),
    /// The sender does not have the content behind this hash either.
    Missing(ContentHash),
    /// The sender started this content and could not finish it: the file changed under it.
    ///
    /// Sent in place of the content's `BLOB_END`. The receiver discards what it got and
    /// treats the hash as [`Message::Missing`].
    Aborted(ContentHash),
    /// The sender will ask for nothing further, and has answered every `Want` it will get.
    ///
    /// Sent after the peer's `Done`, once this side's want list is empty — at which point it
    /// cannot grow again. Without it a side that stopped reading at `Done` would drop the
    /// `Want` the peer sends after applying a page, and every file over the inline limit
    /// would silently never arrive.
    Settled,
    /// A push of path states sent after the initial exchange, while the session stays open.
    Live(Vec<PathUpdate>),
    /// The sender will not continue, and why.
    Refused(String),
    /// The sender has everything this version vector covers: the path states, and the
    /// content behind them on disk (or answered `Missing` by whoever was asked).
    ///
    /// Sent in the live phase, after the `Live` batches it answers have been applied, and
    /// only to a peer whose `Hello` said `acks`. It is what lets the pushing side know a
    /// local edit has left the device, rather than only that it was queued.
    Ack(VersionVector),
}

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

    fn round_trip(msg: &Message) -> Message {
        let json = serde_json::to_vec(msg).unwrap();
        serde_json::from_slice(&json).unwrap()
    }

    #[test]
    fn a_hello_round_trips() {
        let mut vv = VersionVector::new();
        vv.add_dot(&sapphire_sync::Dot {
            replica: ReplicaId::new(),
            counter: 3,
        });
        let msg = Message::Hello {
            format: crate::SESSION_FORMAT_VERSION,
            workspace_id: GrainId::random(),
            replica_id: ReplicaId::new(),
            vv,
            max_file_size: 1024,
            acks: true,
        };
        assert_eq!(format!("{:?}", round_trip(&msg)), format!("{msg:?}"));
    }

    #[test]
    fn the_payload_free_messages_round_trip() {
        assert!(matches!(round_trip(&Message::Done), Message::Done));
        assert!(matches!(round_trip(&Message::Settled), Message::Settled));
    }

    #[test]
    fn a_hash_carrying_message_round_trips_as_hex() {
        let hash = ContentHash::of_bytes(b"content");
        let json = serde_json::to_string(&Message::Want(hash)).unwrap();
        // The hash travels as hex, not as an array of 32 numbers.
        assert!(json.contains(&hash.to_hex()), "got {json}");
        assert_eq!(
            format!("{:?}", round_trip(&Message::Want(hash))),
            format!("{:?}", Message::Want(hash))
        );
        assert_eq!(
            format!("{:?}", round_trip(&Message::Missing(hash))),
            format!("{:?}", Message::Missing(hash))
        );
    }

    #[test]
    fn an_abort_round_trips() {
        let hash = ContentHash::of_bytes(b"content");
        match round_trip(&Message::Aborted(hash)) {
            Message::Aborted(back) => assert_eq!(back, hash),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn a_hello_without_acks_reads_as_not_acknowledging() {
        // What a peer from before acknowledgements sends.
        let json = serde_json::json!({ "Hello": {
            "format": crate::SESSION_FORMAT_VERSION,
            "workspace_id": GrainId::random(),
            "replica_id": ReplicaId::new(),
            "vv": VersionVector::new(),
            "max_file_size": 1024,
        }});
        match serde_json::from_value::<Message>(json).unwrap() {
            Message::Hello { acks, .. } => assert!(!acks),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn an_ack_round_trips() {
        let mut vv = VersionVector::new();
        vv.add_dot(&sapphire_sync::Dot {
            replica: ReplicaId::new(),
            counter: 7,
        });
        match round_trip(&Message::Ack(vv.clone())) {
            Message::Ack(back) => assert!(back.covers(&vv) && vv.covers(&back)),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn a_refusal_round_trips() {
        let msg = Message::Refused("format 2".to_owned());
        match round_trip(&msg) {
            Message::Refused(why) => assert_eq!(why, "format 2"),
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn a_live_push_round_trips() {
        let mut vv = VersionVector::new();
        vv.add_dot(&sapphire_sync::Dot {
            replica: ReplicaId::new(),
            counter: 3,
        });
        let msg = Message::Live(vec![PathUpdate {
            path: "notes/hello.md".to_owned(),
            versions: vec![],
            seen: vv,
        }]);
        match round_trip(&msg) {
            Message::Live(updates) => {
                assert_eq!(updates.len(), 1);
                assert_eq!(updates[0].path, "notes/hello.md");
            }
            other => panic!("got {other:?}"),
        }
    }
}