use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use canvist_model::BlockId;
use canvist_model::BlockTree;
use canvist_model::Commit;
use canvist_model::Document;
use canvist_model::Schema;
use canvist_model::Step;
use yrs::Array;
use yrs::ArrayRef;
use yrs::Origin;
use yrs::ReadTxn;
use yrs::TransactionMut;
use crate::CollabError;
use crate::claims::Owners;
use crate::depth;
use crate::local::Local;
use crate::local::position_of;
use crate::registry::Registration;
use crate::registry::Registry;
use crate::remote::Remote;
use crate::remote::Repair;
use crate::remote::record;
use crate::remote::record::Record;
use crate::tree;
use crate::tree::Parent;
use crate::tree::Reader;
pub(crate) const LOCAL: &str = "canvist:local";
pub(crate) const UNTRACKED: &str = "canvist:untracked";
pub(crate) const REMOTE: &str = "canvist:remote";
pub(crate) const OBSERVER: &str = "canvist:binding";
pub(crate) struct Mirror {
schema: Arc<Schema>,
registry: Registry,
inbox: Arc<Mutex<Vec<Record>>>,
rebuild: bool,
}
impl std::fmt::Debug for Mirror {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Mirror")
.field("registry", &self.registry)
.finish_non_exhaustive()
}
}
impl Mirror {
pub(crate) fn new(schema: Arc<Schema>) -> Self {
Self {
schema,
registry: Registry::default(),
inbox: Arc::new(Mutex::new(Vec::new())),
rebuild: false,
}
}
#[cfg(feature = "scene")]
pub(crate) fn receive(&self, records: Vec<Record>) {
lock(&self.inbox).extend(records);
}
pub(crate) fn inbox(&self) -> Arc<Mutex<Vec<Record>>> {
self.inbox.clone()
}
pub(crate) fn schema(&self) -> &Arc<Schema> {
&self.schema
}
pub(crate) fn registry(&self) -> &Registry {
&self.registry
}
pub(crate) fn rejected_blocks(&self) -> u32 {
self.registry.unmirrored_total()
}
#[cfg(feature = "scene")]
pub(crate) fn has_changes(&self) -> bool {
!lock(&self.inbox).is_empty()
}
pub(crate) fn seed(
&mut self,
txn: &mut TransactionMut<'_>,
root: &ArrayRef,
doc: &Document,
) -> Result<(), CollabError> {
if root.len(txn) > 0 {
return Err(CollabError::NotEmpty);
}
let mut registration = Registration::default();
for &block in doc.children(None).iter().rev() {
let tree = doc.tree(block).ok_or(CollabError::NotShared(block))?;
tree::write(txn, &self.schema, (root, 0, None), &tree, &mut registration)?;
}
self.registry = Registry::default();
self.registry.register(registration);
Ok(())
}
pub(crate) fn document<T: ReadTxn>(
&mut self,
txn: &T,
root: &ArrayRef,
client: u32,
) -> Result<(Document, Vec<Repair>), CollabError> {
let (blocks, registration) = self.read(txn, root)?;
let mut doc = Document::empty(self.schema.clone(), client);
doc.apply_steps([Step::InsertBlocks {
parent: None,
index: 0,
blocks,
}])?;
let repairs = repairs_of(®istration);
self.reset(registration);
Ok((doc, repairs))
}
fn read<T: ReadTxn>(
&self,
txn: &T,
root: &ArrayRef,
) -> Result<(Vec<BlockTree>, Registration), CollabError> {
depth::Check::new(txn).array(root, 0)?;
let mut owners = Owners::default();
owners.scan_array(root, None, txn, &self.schema);
let mut registration = Registration::default();
let mut reader = Reader {
txn,
schema: &self.schema,
claims: &mut owners,
};
let blocks = reader.children(root, Parent::ROOT, &mut registration);
Ok((blocks, registration))
}
fn reset(&mut self, registration: Registration) {
lock(&self.inbox).clear();
self.registry = Registry::default();
self.registry.register(registration);
self.rebuild = false;
}
pub(crate) fn translate(
&mut self,
txn: &mut TransactionMut<'_>,
root: &ArrayRef,
doc: &Document,
commit: &Commit,
) -> Result<Vec<BlockId>, CollabError> {
let structural = commit
.steps
.iter()
.filter(|step| is_structural(step))
.count();
let mut local = Local {
txn,
root,
schema: &self.schema,
registry: &mut self.registry,
doc,
single_structural: structural <= 1,
settled: crate::local::settled(&commit.steps),
retyped: Vec::new(),
};
for (step, inverse) in commit.steps.iter().zip(&commit.inverses) {
local.step(step, inverse)?;
}
Ok(local.retyped)
}
pub(crate) fn reveal<T: ReadTxn>(
&mut self,
txn: &T,
root: &ArrayRef,
doc: &mut Document,
retyped: &[BlockId],
) -> Result<(Commit, Vec<Repair>), CollabError> {
let mut check = depth::Check::new(txn);
for &container in retyped {
let block = self
.registry
.block(container)
.ok_or(CollabError::NotShared(container))?;
if let Some(map) = crate::local::map_ref(txn, &block.map) {
check.subtree(&map, depth::parent_depth(&self.registry, block.parent)? + 1)?;
}
}
let remote = Remote::new(
doc.transaction(),
txn,
(root, &self.schema),
&mut self.registry,
);
remote.reveal(retyped)
}
pub(crate) fn mirror<T: ReadTxn>(
&mut self,
txn: &T,
root: &ArrayRef,
doc: &mut Document,
) -> Result<(Commit, Vec<Repair>), CollabError> {
if self.rebuild {
let (blocks, registration) = self.read(txn, root)?;
let repairs = repairs_of(®istration);
let commit = doc.apply_steps([
Step::RemoveBlocks {
parent: None,
index: 0,
count: doc.children(None).len(),
},
Step::InsertBlocks {
parent: None,
index: 0,
blocks,
},
])?;
self.reset(registration);
return Ok((commit, repairs));
}
let mut inbox = lock(&self.inbox);
if let Err(error) = depth::Check::new(txn).changes(&inbox, &self.registry, root) {
self.rebuild = true;
return Err(error);
}
let records = std::mem::take(&mut *inbox);
drop(inbox);
let remote = Remote::new(
doc.transaction(),
txn,
(root, &self.schema),
&mut self.registry,
);
remote.apply(records)
}
pub(crate) fn repair(
&mut self,
txn: &mut TransactionMut<'_>,
root: &ArrayRef,
repairs: &[Repair],
) {
for repair in repairs {
let array = match repair.parent {
None => Some(root.clone()),
Some(parent) => {
self.registry
.block(parent)
.and_then(|found| crate::local::map_ref(txn, &found.map))
.and_then(|map| tree::children_of(&map, txn))
}
};
if let Some(array) = array
&& let Some(index) = position_of(&array, txn, &repair.map)
{
array.remove(txn, index);
}
self.registry.remove_hidden(&repair.map);
}
}
}
pub(crate) fn record_events<'e>(
txn: &TransactionMut<'_>,
events: impl IntoIterator<Item = &'e yrs::types::Event>,
schema: &Schema,
root: Option<yrs::ID>,
inbox: &Mutex<Vec<Record>>,
) {
let records = events
.into_iter()
.filter_map(|event| record::record(txn, event, schema, root));
lock(inbox).extend(records);
}
pub(crate) fn is_local(txn: &TransactionMut<'_>) -> bool {
txn.origin()
.is_some_and(|origin| *origin == Origin::from(LOCAL) || *origin == Origin::from(UNTRACKED))
}
fn is_structural(step: &Step) -> bool {
matches!(
step,
Step::Split { .. }
| Step::Join { .. }
| Step::InsertBlocks { .. }
| Step::RemoveBlocks { .. }
| Step::MoveBlocks { .. }
)
}
fn repairs_of(registration: &Registration) -> Vec<Repair> {
registration
.losers
.iter()
.map(|&(map, parent)| Repair { parent, map })
.collect()
}
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}