use std::collections::HashMap;
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::Notify;
use yrs::types::ToJson;
use yrs::updates::decoder::Decode;
use yrs::{
Any, Array, ArrayRef, Doc, GetString, Map, MapPrelim, MapRef, OffsetKind, Options, Origin, Out,
ReadTxn, Subscription, Text, Transact, Update,
};
use crate::drive::{self, DriveAuthorization};
use crate::error::{Error, Result};
use crate::parrot::share::Attachment;
use crate::shared::server::{
Authorization, Hooks as ServerHooks, Presence, Room, connect as connect_server,
};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
Text,
Table,
Image,
#[default]
View,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
#[default]
Read,
Write,
}
pub const EDIT_MAX_BYTES: u64 = 1024 * 1024;
const TEXT_TYPES: [&str; 7] = [
"application/json",
"application/xml",
"application/javascript",
"application/x-sh",
"application/x-yaml",
"application/toml",
"application/x-ndjson",
];
const TEXT_EXTENSIONS: [&str; 48] = [
"txt", "md", "markdown", "json", "jsonl", "xml", "html", "htm", "css", "js", "mjs", "cjs",
"jsx", "ts", "tsx", "py", "rb", "go", "rs", "java", "kt", "c", "h", "cc", "cpp", "hpp", "cs",
"php", "sh", "bash", "zsh", "sql", "yaml", "yml", "toml", "ini", "cfg", "conf", "log", "env",
"r", "swift", "lua", "pl", "scala", "vue", "svelte", "tsv",
];
fn extension(name: &str) -> Option<String> {
let (_, extension) = name.rsplit_once('.')?;
Some(extension.to_ascii_lowercase())
}
pub fn is_text(content_type: &str, name: &str) -> bool {
content_type.starts_with("text/")
|| TEXT_TYPES.contains(&content_type)
|| extension(name).is_some_and(|extension| TEXT_EXTENSIONS.contains(&extension.as_str()))
}
pub fn kind_of(content_type: &str, name: &str, size: u64) -> Kind {
if content_type.starts_with("image/") {
return Kind::Image;
}
if size > EDIT_MAX_BYTES {
return Kind::View;
}
if content_type == "text/csv" || extension(name).as_deref() == Some("csv") {
return Kind::Table;
}
if is_text(content_type, name) {
return Kind::Text;
}
Kind::View
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MarkKind {
Pen,
Box,
Arrow,
Note,
Pin,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mark {
pub id: String,
pub kind: MarkKind,
pub points: Vec<[f64; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
pub author: String,
pub color: String,
pub at: f64,
}
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
let mut rows = Vec::new();
let mut row = Vec::new();
let mut cell = String::new();
let mut quoted = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if quoted {
if c == '"' && chars.peek() == Some(&'"') {
cell.push('"');
chars.next();
} else if c == '"' {
quoted = false;
} else {
cell.push(c);
}
} else if c == '"' && cell.is_empty() {
quoted = true;
} else if c == ',' {
row.push(std::mem::take(&mut cell));
} else if c == '\n' || c == '\r' {
if c == '\r' && chars.peek() == Some(&'\n') {
chars.next();
}
row.push(std::mem::take(&mut cell));
rows.push(std::mem::take(&mut row));
} else {
cell.push(c);
}
}
if !cell.is_empty() || !row.is_empty() {
row.push(cell);
rows.push(row);
}
rows
}
pub fn format_csv(rows: &[Vec<String>]) -> String {
let quote = |cell: &String| {
let needs = cell.contains(['"', ',', '\r', '\n'])
|| cell.starts_with(char::is_whitespace)
|| cell.ends_with(char::is_whitespace);
if needs {
format!("\"{}\"", cell.replace('"', "\"\""))
} else {
cell.clone()
}
};
let mut text = rows
.iter()
.map(|row| row.iter().map(quote).collect::<Vec<_>>().join(","))
.collect::<Vec<_>>()
.join("\n");
if !rows.is_empty() {
text.push('\n');
}
text
}
fn radix36(mut value: u128) -> String {
const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
let mut out = Vec::new();
loop {
out.push(DIGITS[(value % 36) as usize]);
value /= 36;
if value == 0 {
break;
}
}
out.reverse();
String::from_utf8(out).unwrap_or_default()
}
fn id() -> String {
let random = radix36(uuid::Uuid::new_v4().as_u128());
let now = radix36(chrono::Utc::now().timestamp_millis().max(0) as u128);
format!("{}{}", &random[..8], &now[now.len().saturating_sub(4)..])
}
fn new_doc() -> Doc {
Doc::with_options(Options {
offset_kind: OffsetKind::Utf16,
..Options::default()
})
}
fn out_text<T: ReadTxn>(out: Out, txn: &T) -> String {
match out {
Out::Any(Any::String(text)) => text.to_string(),
out => out.to_string(txn),
}
}
fn strings<T: ReadTxn>(array: &ArrayRef, txn: &T) -> Vec<String> {
array.iter(txn).map(|out| out_text(out, txn)).collect()
}
fn position(array: &[String], item: &str) -> Option<u32> {
array
.iter()
.position(|other| other == item)
.map(|index| index as u32)
}
pub fn table_rows(doc: &Doc) -> Vec<Vec<String>> {
let columns = doc.get_or_insert_array("columns");
let rows = doc.get_or_insert_array("rows");
let cells = doc.get_or_insert_map("cells");
let txn = doc.transact();
let columns = strings(&columns, &txn);
strings(&rows, &txn)
.iter()
.map(|row| {
let map: Option<MapRef> = match cells.get(&txn, row) {
Some(Out::YMap(map)) => Some(map),
_ => None,
};
columns
.iter()
.map(|column| {
map.as_ref()
.and_then(|map| map.get(&txn, column))
.map(|out| out_text(out, &txn))
.unwrap_or_default()
})
.collect()
})
.collect()
}
pub fn fill_table(doc: &Doc, rows: &[Vec<String>]) {
let width = rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
let columns: Vec<String> = (0..width).map(|_| id()).collect();
let row_ids: Vec<String> = rows.iter().map(|_| id()).collect();
let columns_ref = doc.get_or_insert_array("columns");
let rows_ref = doc.get_or_insert_array("rows");
let cells = doc.get_or_insert_map("cells");
let mut txn = doc.transact_mut();
let length = columns_ref.len(&txn);
columns_ref.insert_range(&mut txn, length, columns.clone());
let length = rows_ref.len(&txn);
rows_ref.insert_range(&mut txn, length, row_ids.clone());
for (r, row) in rows.iter().enumerate() {
let map: MapPrelim = columns
.iter()
.zip(row)
.filter(|(_, cell)| !cell.is_empty())
.map(|(column, cell)| (column.clone(), cell.clone()))
.collect();
cells.insert(&mut txn, row_ids[r].clone(), map);
}
}
pub fn add_row(doc: &Doc, after: Option<&str>) -> String {
let rows = doc.get_or_insert_array("rows");
let cells = doc.get_or_insert_map("cells");
let row = id();
let mut txn = doc.transact_mut();
let length = rows.len(&txn);
let index = match after {
Some(after) => position(&strings(&rows, &txn), after).map_or(0, |index| index + 1),
None => length,
};
rows.insert(&mut txn, index.min(length), row.clone());
cells.insert(&mut txn, row.clone(), MapPrelim::default());
row
}
pub fn add_column(doc: &Doc, after: Option<&str>) -> String {
let columns = doc.get_or_insert_array("columns");
let column = id();
let mut txn = doc.transact_mut();
let length = columns.len(&txn);
let index = match after {
Some(after) => position(&strings(&columns, &txn), after).map_or(0, |index| index + 1),
None => length,
};
columns.insert(&mut txn, index.min(length), column.clone());
column
}
pub fn remove_row(doc: &Doc, row: &str) {
let rows = doc.get_or_insert_array("rows");
let cells = doc.get_or_insert_map("cells");
let mut txn = doc.transact_mut();
if let Some(index) = position(&strings(&rows, &txn), row) {
rows.remove(&mut txn, index);
}
cells.remove(&mut txn, row);
}
pub fn remove_column(doc: &Doc, column: &str) {
let columns = doc.get_or_insert_array("columns");
let mut txn = doc.transact_mut();
if let Some(index) = position(&strings(&columns, &txn), column) {
columns.remove(&mut txn, index);
}
}
fn decode(content: Option<&[u8]>) -> String {
let text = String::from_utf8_lossy(content.unwrap_or_default());
text.strip_prefix('\u{feff}').unwrap_or(&text).to_string()
}
fn any_from_json(value: &Value) -> Any {
match value {
Value::Null => Any::Null,
Value::Bool(value) => Any::Bool(*value),
Value::Number(number) => Any::Number(number.as_f64().unwrap_or_default()),
Value::String(value) => Any::String(value.as_str().into()),
Value::Array(values) => Any::Array(values.iter().map(any_from_json).collect()),
Value::Object(fields) => Any::Map(Arc::new(
fields
.iter()
.map(|(key, value)| (key.clone(), any_from_json(value)))
.collect::<HashMap<_, _>>(),
)),
}
}
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
const MARK_FIELDS: [&str; 7] = ["id", "kind", "points", "text", "author", "color", "at"];
fn write_json(any: &Any, out: &mut String) {
match any {
Any::Null | Any::Undefined => out.push_str("null"),
Any::Bool(value) => out.push_str(if *value { "true" } else { "false" }),
Any::Number(number) if number.trunc() == *number && number.abs() <= MAX_SAFE_INTEGER => {
out.push_str(&(*number as i64).to_string())
}
Any::Number(number) => out.push_str(&Value::from(*number).to_string()),
Any::BigInt(int) => out.push_str(&int.to_string()),
Any::String(value) => out.push_str(&Value::from(value.as_ref()).to_string()),
Any::Buffer(bytes) => out.push_str(&Value::from(bytes.to_vec()).to_string()),
Any::Array(values) => {
out.push('[');
for (index, value) in values.iter().enumerate() {
if index > 0 {
out.push(',');
}
write_json(value, out);
}
out.push(']');
}
Any::Map(fields) => {
let mut keys: Vec<&String> = fields
.iter()
.filter(|(_, value)| !matches!(value, Any::Undefined))
.map(|(key, _)| key)
.collect();
keys.sort_by_key(|key| {
(
MARK_FIELDS
.iter()
.position(|field| field == key)
.unwrap_or(MARK_FIELDS.len()),
key.as_str(),
)
});
out.push('{');
for (index, key) in keys.into_iter().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str(&Value::from(key.as_str()).to_string());
out.push(':');
write_json(&fields[key.as_str()], out);
}
out.push('}');
}
}
}
pub fn doc_from(kind: Kind, content: Option<&[u8]>) -> Doc {
let doc = new_doc();
let text = decode(content);
match kind {
Kind::Text => {
let shared = doc.get_or_insert_text("text");
shared.insert(&mut doc.transact_mut(), 0, &text);
}
Kind::Table => fill_table(&doc, &parse_csv(&text)),
Kind::Image => {
let marks = if text.is_empty() {
Vec::new()
} else {
match serde_json::from_str::<Value>(&text) {
Ok(Value::Array(marks)) => marks,
_ => Vec::new(),
}
};
let shared = doc.get_or_insert_array("marks");
shared.insert_range(&mut doc.transact_mut(), 0, marks.iter().map(any_from_json));
}
Kind::View => {}
}
doc
}
pub fn content_of(kind: Kind, doc: &Doc) -> Vec<u8> {
match kind {
Kind::Text => {
let text = doc.get_or_insert_text("text");
text.get_string(&doc.transact()).into_bytes()
}
Kind::Table => format_csv(&table_rows(doc)).into_bytes(),
Kind::Image => {
let marks = doc.get_or_insert_array("marks");
let mut json = String::new();
write_json(&marks.to_json(&doc.transact()), &mut json);
json.into_bytes()
}
Kind::View => Vec::new(),
}
}
pub fn to_base64(bytes: &[u8]) -> String {
STANDARD.encode(bytes)
}
pub fn from_base64(text: &str) -> Result<Vec<u8>> {
STANDARD.decode(text).map_err(|_| {
Error::Message("The string to be decoded is not correctly encoded.".to_string())
})
}
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Target {
File(drive::File),
Attachment(Attachment),
}
pub trait Hooks: Send + Sync {
fn on_people(&self, _room: &ViewRoom) {}
fn on_reload(&self, _room: &ViewRoom) {}
fn on_saved(&self, _room: &ViewRoom) {}
fn on_closed(&self, _room: &ViewRoom) {}
}
impl Hooks for () {}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ViewFile {
pub name: String,
pub content_type: String,
pub content_length: u64,
}
const BATCH: Duration = Duration::from_millis(50);
const REMOTE: &str = "remote";
#[derive(Default)]
struct View {
kind: Kind,
role: Role,
owner: bool,
file: ViewFile,
ended: bool,
saved: u64,
}
struct ViewState {
target: Target,
hooks: Mutex<Arc<dyn Hooks>>,
view: Mutex<View>,
doc: Mutex<Doc>,
subscription: Mutex<Option<Subscription>>,
outgoing: Mutex<Vec<Vec<u8>>>,
armed: AtomicBool,
notify: Notify,
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Clone)]
pub struct ViewRoom {
room: Room,
inner: Arc<ViewState>,
}
impl Deref for ViewRoom {
type Target = Room;
fn deref(&self) -> &Room {
&self.room
}
}
impl ViewRoom {
fn view(&self) -> MutexGuard<'_, View> {
lock(&self.inner.view)
}
fn hooks(&self) -> Arc<dyn Hooks> {
lock(&self.inner.hooks).clone()
}
pub fn target(&self) -> &Target {
&self.inner.target
}
pub fn kind(&self) -> Kind {
self.view().kind
}
pub fn role(&self) -> Role {
self.view().role
}
pub fn owner(&self) -> bool {
self.view().owner
}
pub fn file(&self) -> ViewFile {
self.view().file.clone()
}
pub fn doc(&self) -> Doc {
lock(&self.inner.doc).clone()
}
pub fn set_hooks(&self, hooks: Arc<dyn Hooks>) {
*lock(&self.inner.hooks) = hooks;
}
pub fn people(&self, me: Option<&Presence>) -> Vec<Presence> {
self.get_presences()
.into_iter()
.filter(|presence| me.is_none_or(|me| presence.id() != me.id()))
.collect()
}
pub fn people_changed(&self) {
self.hooks().on_people(self);
}
pub fn hydrate(&self, state: &Value) {
{
let mut view = self.view();
view.kind = serde_json::from_value(state["kind"].clone()).unwrap_or_default();
view.role = if state["role"] == "write" {
Role::Write
} else {
Role::Read
};
view.owner = state["owner"] == true;
let file = &state["file"];
view.file = ViewFile {
name: match &file["name"] {
Value::Null => String::new(),
Value::String(name) => name.clone(),
name => name.to_string(),
},
content_type: match &file["contentType"] {
Value::Null => String::new(),
Value::String(content_type) => content_type.clone(),
content_type => content_type.to_string(),
},
content_length: file["contentLength"].as_f64().unwrap_or_default() as u64,
};
view.saved = state["saved"].as_f64().unwrap_or_default() as u64;
}
self.replace(state["doc"].as_str());
}
pub fn handle_event(&self, packet: &Value) -> bool {
let data = &packet["data"];
match packet["event"].as_str() {
Some("doc-update") if data["update"].is_string() => {
if let Ok(update) = from_base64(data["update"].as_str().unwrap_or_default()) {
apply_remote(&self.doc(), &update);
}
true
}
Some("doc-reload") => {
if let Some(snapshot) = data["doc"].as_str() {
self.replace(Some(snapshot));
}
self.hooks().on_reload(self);
true
}
Some("doc-saved") => {
let saved = data["saved"].as_f64().unwrap_or_default() as u64;
let newer = {
let mut view = self.view();
let newer = saved > view.saved;
if newer {
view.saved = saved;
}
newer
};
if newer {
self.hooks().on_saved(self);
}
true
}
_ => false,
}
}
fn replace(&self, snapshot: Option<&str>) {
let doc = new_doc();
if let Some(update) = snapshot.and_then(|snapshot| from_base64(snapshot).ok()) {
apply_remote(&doc, &update);
}
let state = Arc::downgrade(&self.inner);
let subscription = doc.observe_update_v1(move |txn, event| {
if txn.origin() == Some(&Origin::from(REMOTE)) {
return;
}
let Some(state) = state.upgrade() else {
return;
};
{
let view = lock(&state.view);
if view.role != Role::Write || view.ended {
return;
}
}
lock(&state.outgoing).push(event.update.clone());
if !state.armed.swap(true, Ordering::SeqCst) {
state.notify.notify_one();
}
});
*lock(&self.inner.subscription) = subscription.ok();
*lock(&self.inner.doc) = doc;
}
pub fn flush(&self) {
self.inner.armed.store(false, Ordering::SeqCst);
let outgoing = std::mem::take(&mut *lock(&self.inner.outgoing));
if outgoing.is_empty() {
return;
}
let updates = if outgoing.len() == 1 {
outgoing
} else {
match yrs::merge_updates_v1(&outgoing) {
Ok(update) => vec![update],
Err(_) => outgoing,
}
};
for update in updates {
self.post(&json!({ "event": "doc-update", "data": { "update": to_base64(&update) } }));
}
}
pub fn closed(&self) {
{
let mut view = self.view();
if view.ended {
return;
}
view.ended = true;
}
self.inner.notify.notify_one();
self.hooks().on_closed(self);
}
pub fn disconnect(&self) {
self.flush();
self.view().ended = true;
self.inner.notify.notify_one();
self.room.disconnect();
}
}
fn apply_remote(doc: &Doc, update: &[u8]) {
if let Ok(update) = Update::decode_v1(update) {
let _ = doc.transact_mut_with(REMOTE).apply_update(update);
}
}
struct ViewHooks {
inner: Arc<ViewState>,
}
impl ViewHooks {
fn room(&self, room: &Room) -> ViewRoom {
ViewRoom {
room: room.clone(),
inner: self.inner.clone(),
}
}
}
impl ServerHooks for ViewHooks {
fn on_connection(&self, room: &Room, state: &Value) {
self.room(room).hydrate(state);
}
fn on_event(&self, room: &Room, packet: &Value) -> bool {
self.room(room).handle_event(packet)
}
fn on_presence(&self, room: &Room) {
self.room(room).people_changed();
}
fn on_closed(&self, room: &Room, _reason: Option<&str>) {
self.room(room).closed();
}
}
fn authorization_for(target: &Target) -> Result<Authorization> {
let file = match target {
Target::Attachment(attachment) => {
if !attachment.chat.is_empty() && !attachment.r#ref.is_empty() {
let authorization = match &attachment.file.authorization {
DriveAuthorization::Path { authorization, .. }
| DriveAuthorization::AccessCode { authorization, .. }
| DriveAuthorization::Repository { authorization, .. } => authorization.clone(),
};
return Ok(Authorization::Server {
authorization,
server: format!("fauna:file:chat:{}/{}", attachment.chat, attachment.r#ref),
group: None,
});
}
&attachment.file
}
Target::File(file) => file,
};
Ok(match &file.authorization {
DriveAuthorization::AccessCode {
authorization,
access_code,
} => Authorization::AccessCode {
authorization: authorization.clone(),
access_code: access_code.clone(),
},
DriveAuthorization::Repository {
authorization,
repository,
path,
group,
} => Authorization::Server {
authorization: authorization.clone(),
server: format!(
"fauna:file:repository:{repository}/{}",
path.trim_start_matches('/')
),
group: group.clone(),
},
DriveAuthorization::Path {
authorization,
path,
group,
} => Authorization::Server {
authorization: authorization.clone(),
server: format!("fauna:file:{path}"),
group: group.clone(),
},
})
}
pub async fn connect(
target: Target,
hooks: Option<Arc<dyn Hooks>>,
) -> Result<(ViewRoom, Presence)> {
let authorization = authorization_for(&target)?;
let inner = Arc::new(ViewState {
target,
hooks: Mutex::new(hooks.unwrap_or_else(|| Arc::new(()))),
view: Mutex::new(View::default()),
doc: Mutex::new(new_doc()),
subscription: Mutex::new(None),
outgoing: Mutex::new(Vec::new()),
armed: AtomicBool::new(false),
notify: Notify::new(),
});
let me = connect_server(
authorization,
&format!("{}/drive/live", crate::get_url()),
Arc::new(ViewHooks {
inner: inner.clone(),
}),
)
.await?;
let room = ViewRoom {
room: me.room().clone(),
inner,
};
let batching = room.clone();
tokio::spawn(async move {
loop {
batching.inner.notify.notified().await;
if batching.view().ended {
break;
}
tokio::time::sleep(BATCH).await;
if batching.view().ended {
break;
}
batching.flush();
}
});
let mut socket_closed = room.socket_closed();
let closing = room.clone();
tokio::spawn(async move {
let _ = socket_closed.wait_for(|closed| *closed).await;
closing.closed();
});
Ok((room, me))
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use yrs::{GetString, ReadTxn, StateVector, Text, Transact};
use super::*;
use crate::authentification::{ApiKey, CredentialsOrApiKey};
use crate::drive::{FileMeta, from_access_code};
#[derive(Default)]
struct Recorder {
events: Mutex<Vec<&'static str>>,
}
impl Hooks for Recorder {
fn on_reload(&self, _room: &ViewRoom) {
self.events.lock().unwrap().push("reload");
}
fn on_saved(&self, _room: &ViewRoom) {
self.events.lock().unwrap().push("saved");
}
fn on_closed(&self, _room: &ViewRoom) {
self.events.lock().unwrap().push("closed");
}
}
fn view_room(recorder: Arc<Recorder>) -> (ViewRoom, mpsc::UnboundedReceiver<Message>) {
let (ws, outbox) = mpsc::unbounded_channel();
let authorization = CredentialsOrApiKey::ApiKey(ApiKey {
id: "key".to_string(),
..ApiKey::default()
});
let file = from_access_code(authorization.clone(), "code", FileMeta::default());
let room = Room::new(
"http://localhost/drive/live".to_string(),
ws,
Authorization::AccessCode {
authorization,
access_code: "code".to_string(),
},
"room".to_string(),
);
let inner = Arc::new(ViewState {
target: Target::File(file),
hooks: Mutex::new(recorder),
view: Mutex::new(View::default()),
doc: Mutex::new(new_doc()),
subscription: Mutex::new(None),
outgoing: Mutex::new(Vec::new()),
armed: AtomicBool::new(false),
notify: Notify::new(),
});
(ViewRoom { room, inner }, outbox)
}
fn snapshot(text: &str) -> String {
let doc = doc_from(Kind::Text, Some(text.as_bytes()));
to_base64(
&doc.transact()
.encode_state_as_update_v1(&StateVector::default()),
)
}
fn text_of(doc: &Doc) -> String {
doc.get_or_insert_text("text").get_string(&doc.transact())
}
fn sent(outbox: &mut mpsc::UnboundedReceiver<Message>) -> Vec<Value> {
let mut frames = Vec::new();
while let Ok(Message::Text(frame)) = outbox.try_recv() {
frames.push(serde_json::from_str(frame.as_str()).unwrap());
}
frames
}
#[test]
fn writers_send_their_edits_and_never_echo_remote_ones() {
let recorder = Arc::new(Recorder::default());
let (room, mut outbox) = view_room(recorder.clone());
room.hydrate(&json!({
"kind": "text",
"role": "write",
"owner": true,
"file": { "name": "plan.md", "contentType": "text/markdown", "contentLength": 5 },
"saved": 2,
"doc": snapshot("hello"),
}));
assert_eq!(room.kind(), Kind::Text);
assert_eq!(room.role(), Role::Write);
assert!(room.owner());
assert_eq!(room.file().name, "plan.md");
assert_eq!(text_of(&room.doc()), "hello");
let peer = Doc::new();
apply_remote(
&peer,
&room
.doc()
.transact()
.encode_state_as_update_v1(&StateVector::default()),
);
let text = room.doc().get_or_insert_text("text");
text.insert(&mut room.doc().transact_mut(), 5, " there");
text.insert(&mut room.doc().transact_mut(), 0, ">");
room.flush();
let frames = sent(&mut outbox);
assert_eq!(frames.len(), 1);
assert_eq!(frames[0]["event"], "doc-update");
apply_remote(
&peer,
&from_base64(frames[0]["data"]["update"].as_str().unwrap()).unwrap(),
);
assert_eq!(text_of(&peer), ">hello there");
let peer_text = peer.get_or_insert_text("text");
let update = {
let before = room.doc().transact().state_vector();
peer_text.insert(&mut peer.transact_mut(), 0, "!");
peer.transact().encode_state_as_update_v1(&before)
};
assert!(room.handle_event(
&json!({ "event": "doc-update", "data": { "update": to_base64(&update) } })
));
assert_eq!(text_of(&room.doc()), "!>hello there");
room.flush();
assert!(sent(&mut outbox).is_empty());
room.handle_event(&json!({ "event": "doc-saved", "data": { "saved": 3 } }));
room.handle_event(&json!({ "event": "doc-saved", "data": { "saved": 1 } }));
room.handle_event(&json!({ "event": "doc-reload", "data": { "doc": snapshot("fresh") } }));
assert_eq!(text_of(&room.doc()), "fresh");
room.closed();
room.closed();
assert_eq!(
*recorder.events.lock().unwrap(),
vec!["saved", "reload", "closed"]
);
let text = room.doc().get_or_insert_text("text");
text.insert(&mut room.doc().transact_mut(), 0, "late ");
room.flush();
assert!(sent(&mut outbox).is_empty());
}
#[test]
fn readers_keep_their_edits_local() {
let (room, mut outbox) = view_room(Arc::new(Recorder::default()));
room.hydrate(&json!({ "kind": "text", "role": "read", "doc": snapshot("hi") }));
let text = room.doc().get_or_insert_text("text");
text.insert(&mut room.doc().transact_mut(), 2, "!");
room.flush();
assert!(sent(&mut outbox).is_empty());
assert!(!room.handle_event(&json!({ "event": "something-else" })));
}
#[test]
fn repository_files_open_in_their_room() {
let authorization = CredentialsOrApiKey::ApiKey(ApiKey {
id: "key".to_string(),
..ApiKey::default()
});
let file = drive::File::from_json(
&json!({ "name": "a.ts", "contentType": "text/typescript", "contentLength": 3 }),
DriveAuthorization::Repository {
authorization,
repository: 41,
path: "/repository/src/a.ts".to_string(),
group: Some("7".to_string()),
},
);
match authorization_for(&Target::File(file)).unwrap() {
Authorization::Server { server, group, .. } => {
assert_eq!(server, "fauna:file:repository:41/repository/src/a.ts");
assert_eq!(group.as_deref(), Some("7"));
}
_ => panic!("a repository file opens by its server reference"),
}
}
}