use std::sync::Arc;
use canvist_model::Commit;
use canvist_model::Document;
use canvist_model::Selection;
use yrs::StateVector;
use yrs::encoding::read::Cursor;
use yrs::encoding::read::Read;
use yrs::encoding::write::Write;
use yrs::sync::AwarenessUpdate;
use yrs::sync::Message;
use yrs::sync::MessageReader;
use yrs::sync::SyncMessage;
use yrs::updates::decoder::Decode;
use yrs::updates::decoder::DecoderV1;
use yrs::updates::encoder::Encode;
use yrs::updates::encoder::Encoder;
use yrs::updates::encoder::EncoderV1;
use crate::Binding;
use crate::CollabError;
use crate::Collaborator;
use crate::Encoding;
use crate::Presence;
use crate::User;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Framing {
YWebsocket,
Hocuspocus {
document: Arc<str>,
token: Arc<str>,
},
}
mod hocuspocus {
pub(super) const SYNC: u8 = 0;
pub(super) const AWARENESS: u8 = 1;
pub(super) const AUTH: u8 = 2;
pub(super) const QUERY_AWARENESS: u8 = 3;
pub(super) const SYNC_REPLY: u8 = 4;
pub(super) const CLOSE: u8 = 7;
pub(super) const TOKEN: u8 = 0;
pub(super) const PERMISSION_DENIED: u8 = 1;
pub(super) const AUTHENTICATED: u8 = 2;
}
#[derive(Debug)]
pub struct Received {
pub commit: Commit,
pub replies: Vec<Vec<u8>>,
}
#[derive(Debug)]
pub struct SyncSession {
binding: Binding,
presence: Presence,
framing: Framing,
synced: bool,
}
enum Incoming {
Message(Message),
Authenticated,
Ignored,
}
impl SyncSession {
pub fn new(binding: Binding, presence: Presence, framing: Framing) -> Self {
Self {
binding,
presence,
framing,
synced: false,
}
}
pub fn binding(&self) -> &Binding {
&self.binding
}
pub fn binding_mut(&mut self) -> &mut Binding {
&mut self.binding
}
pub fn presence(&self) -> &Presence {
&self.presence
}
pub fn presence_mut(&mut self) -> &mut Presence {
&mut self.presence
}
pub fn set_presence(&mut self, doc: &Document, user: &User, selection: Option<Selection>) {
self.presence
.set_local((&self.binding, doc), user, selection);
}
pub fn collaborators(&self, doc: &Document) -> Vec<Collaborator> {
self.presence.collaborators(&self.binding, doc)
}
pub fn is_synced(&self) -> bool {
self.synced
}
pub fn open(&mut self) -> Result<Vec<Vec<u8>>, CollabError> {
self.synced = false;
match &self.framing {
Framing::YWebsocket => self.greeting(),
Framing::Hocuspocus { document, token } => Ok(vec![auth_message(document, token)]),
}
}
fn greeting(&self) -> Result<Vec<Vec<u8>>, CollabError> {
let state = StateVector::decode_v1(&self.binding.state_vector())?;
let messages = [
Message::Sync(SyncMessage::SyncStep1(state)),
Message::Awareness(self.presence.update()?),
];
Ok(messages.iter().map(|message| self.frame(message)).collect())
}
pub fn receive(&mut self, doc: &mut Document, data: &[u8]) -> Result<Received, CollabError> {
let mut received = Received {
commit: doc.transaction().commit(),
replies: Vec::new(),
};
for incoming in self.decode(data)? {
self.handle(doc, incoming, &mut received)?;
}
Ok(received)
}
fn handle(
&mut self,
doc: &mut Document,
incoming: Incoming,
received: &mut Received,
) -> Result<(), CollabError> {
match incoming {
Incoming::Message(message) => self.handle_message(doc, message, received),
Incoming::Authenticated => {
received.replies.extend(self.greeting()?);
Ok(())
}
Incoming::Ignored => Ok(()),
}
}
fn handle_message(
&mut self,
doc: &mut Document,
message: Message,
received: &mut Received,
) -> Result<(), CollabError> {
match message {
Message::Sync(SyncMessage::SyncStep1(state)) => {
let update = self.binding.encode_diff_from(&state, Encoding::V1);
let reply = Message::Sync(SyncMessage::SyncStep2(update));
received.replies.push(self.frame(&reply));
}
Message::Sync(SyncMessage::SyncStep2(update)) => {
self.apply(doc, &update, received)?;
self.synced = true;
}
Message::Sync(SyncMessage::Update(update)) => self.apply(doc, &update, received)?,
Message::Awareness(update) => self.presence.apply_update(update)?,
Message::AwarenessQuery => {
let reply = Message::Awareness(self.presence.update()?);
received.replies.push(self.frame(&reply));
}
Message::Auth(Some(reason)) => return Err(CollabError::PermissionDenied(reason)),
Message::Auth(None) => {}
Message::Custom(tag, _) => return Err(CollabError::UnsupportedMessage(tag)),
}
Ok(())
}
fn apply(
&mut self,
doc: &mut Document,
update: &[u8],
received: &mut Received,
) -> Result<(), CollabError> {
let commit = self.binding.apply_update(doc, update, Encoding::V1)?;
received.commit = crate::binding::compose(
std::mem::replace(&mut received.commit, doc.transaction().commit()),
commit,
doc,
);
Ok(())
}
pub fn flush(&mut self) -> Result<Vec<Vec<u8>>, CollabError> {
let mut messages: Vec<Vec<u8>> = self
.binding
.take_updates()
.into_iter()
.map(|update| self.frame(&Message::Sync(SyncMessage::Update(update))))
.collect();
if let Some(update) = self.presence.take_local_change()? {
messages.push(self.frame(&Message::Awareness(update)));
}
Ok(messages)
}
fn frame(&self, message: &Message) -> Vec<u8> {
let mut encoder = EncoderV1::new();
if let Framing::Hocuspocus { document, .. } = &self.framing {
encoder.write_string(document);
}
message.encode(&mut encoder);
encoder.to_vec()
}
fn decode(&self, data: &[u8]) -> Result<Vec<Incoming>, CollabError> {
match &self.framing {
Framing::YWebsocket => decode_messages(data),
Framing::Hocuspocus { document, .. } => decode_hocuspocus(data, document),
}
}
}
fn decode_messages(data: &[u8]) -> Result<Vec<Incoming>, CollabError> {
let mut decoder = DecoderV1::new(Cursor::new(data));
MessageReader::new(&mut decoder)
.map(|message| Ok(Incoming::Message(message?)))
.collect()
}
fn decode_hocuspocus(data: &[u8], document: &str) -> Result<Vec<Incoming>, CollabError> {
let mut decoder = DecoderV1::new(Cursor::new(data));
if decoder.read_string()? != document {
return Ok(Vec::new());
}
let kind: u8 = decoder.read_var()?;
let incoming = match kind {
hocuspocus::SYNC | hocuspocus::SYNC_REPLY => {
Incoming::Message(Message::Sync(SyncMessage::decode(&mut decoder)?))
}
hocuspocus::AWARENESS => {
let update = AwarenessUpdate::decode_v1(decoder.read_buf()?)?;
Incoming::Message(Message::Awareness(update))
}
hocuspocus::QUERY_AWARENESS => Incoming::Message(Message::AwarenessQuery),
hocuspocus::AUTH => decode_auth(&mut decoder)?,
hocuspocus::CLOSE => {
return Err(CollabError::Closed(decoder.read_string()?.to_owned()));
}
_ => Incoming::Ignored,
};
Ok(vec![incoming])
}
fn decode_auth(decoder: &mut DecoderV1<'_>) -> Result<Incoming, CollabError> {
let kind: u8 = decoder.read_var()?;
match kind {
hocuspocus::AUTHENTICATED => Ok(Incoming::Authenticated),
hocuspocus::PERMISSION_DENIED => {
Err(CollabError::PermissionDenied(
decoder.read_string()?.to_owned(),
))
}
_ => Ok(Incoming::Ignored),
}
}
fn auth_message(document: &str, token: &str) -> Vec<u8> {
let mut encoder = EncoderV1::new();
encoder.write_string(document);
encoder.write_var(hocuspocus::AUTH);
encoder.write_var(hocuspocus::TOKEN);
encoder.write_string(token);
encoder.to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hocuspocus_messages_start_with_the_document_name() {
let message = auth_message("notes", "secret");
let mut decoder = DecoderV1::new(Cursor::new(&message));
assert_eq!(decoder.read_string().ok(), Some("notes"));
assert_eq!(decoder.read_var::<u8>().ok(), Some(hocuspocus::AUTH));
assert_eq!(decoder.read_var::<u8>().ok(), Some(hocuspocus::TOKEN));
assert_eq!(decoder.read_string().ok(), Some("secret"));
}
#[test]
fn messages_for_other_documents_are_skipped() {
let message = auth_message("other", "");
assert!(
decode_hocuspocus(&message, "notes")
.expect("decodes")
.is_empty()
);
}
}