use grain_id::GrainId;
use sapphire_sync::{ContentHash, PathUpdate, ReplicaId, VersionVector};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Message {
Hello {
format: u32,
workspace_id: GrainId,
replica_id: ReplicaId,
vv: VersionVector,
},
Updates(Vec<PathUpdate>),
Done,
Want(ContentHash),
Missing(ContentHash),
Settled,
Live(Vec<PathUpdate>),
Refused(String),
}
#[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,
};
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();
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 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:?}"),
}
}
}