use std::fmt::Display;
use crate::{
database::hashmap_store::HashMapStoreSnapshot,
database::hashmap_store::{read_or_recover, write_or_recover},
database::transactions::Transaction,
direct_access::repository_factory,
entities::Global,
event::{DirectAccessEntity, EntityEvent, Event, EventBuffer, Origin},
snapshot::EntityTreeSnapshot,
types::EntityId,
};
use crate::direct_access::workspace::WorkspaceRelationshipField;
use crate::error::RepositoryError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum GlobalRelationshipField {}
impl Display for GlobalRelationshipField {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
pub trait GlobalTable {
fn create(&mut self, entity: &Global) -> Result<Global, RepositoryError>;
fn create_multi(&mut self, entities: &[Global]) -> Result<Vec<Global>, RepositoryError>;
fn get(&self, id: &EntityId) -> Result<Option<Global>, RepositoryError>;
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Global>>, RepositoryError>;
fn get_all(&self) -> Result<Vec<Global>, RepositoryError>;
fn update(&mut self, entity: &Global) -> Result<Global, RepositoryError>;
fn update_multi(&mut self, entities: &[Global]) -> Result<Vec<Global>, RepositoryError>;
fn update_with_relationships(&mut self, entity: &Global) -> Result<Global, RepositoryError>;
fn update_with_relationships_multi(
&mut self,
entities: &[Global],
) -> Result<Vec<Global>, RepositoryError>;
fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError>;
fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError>;
}
pub trait GlobalTableRO {
fn get(&self, id: &EntityId) -> Result<Option<Global>, RepositoryError>;
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Global>>, RepositoryError>;
fn get_all(&self) -> Result<Vec<Global>, RepositoryError>;
}
pub struct GlobalRepository<'a> {
table: Box<dyn GlobalTable + 'a>,
transaction: &'a Transaction,
}
impl<'a> GlobalRepository<'a> {
pub fn new(table: Box<dyn GlobalTable + 'a>, transaction: &'a Transaction) -> Self {
GlobalRepository { table, transaction }
}
pub fn create_orphan(
&mut self,
event_buffer: &mut EventBuffer,
entity: &Global,
) -> Result<Global, RepositoryError> {
let new = self.table.create(entity)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Created)),
ids: vec![new.id],
data: None,
});
Ok(new)
}
pub fn create_orphan_multi(
&mut self,
event_buffer: &mut EventBuffer,
entities: &[Global],
) -> Result<Vec<Global>, RepositoryError> {
let new_entities = self.table.create_multi(entities)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Created)),
ids: new_entities.iter().map(|e| e.id).collect(),
data: None,
});
Ok(new_entities)
}
pub fn create(
&mut self,
event_buffer: &mut EventBuffer,
entity: &Global,
owner_id: EntityId,
_index: i32,
) -> Result<Global, RepositoryError> {
let new = self.table.create(entity)?;
let created_id = new.id;
let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
if relationship_ids.is_empty() {
relationship_ids = vec![created_id];
} else {
self.remove_multi(event_buffer, &relationship_ids)?;
relationship_ids = vec![created_id];
}
self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Created)),
ids: vec![created_id],
data: None,
});
Ok(new)
}
pub fn create_multi(
&mut self,
event_buffer: &mut EventBuffer,
entities: &[Global],
owner_id: EntityId,
_index: i32,
) -> Result<Vec<Global>, RepositoryError> {
let new_entities = self.table.create_multi(entities)?;
let created_ids: Vec<EntityId> = new_entities.iter().map(|e| e.id).collect();
let mut relationship_ids = self.get_relationships_from_owner(&owner_id)?;
if relationship_ids.is_empty() {
relationship_ids = created_ids.clone();
} else {
self.remove_multi(event_buffer, &relationship_ids)?;
relationship_ids = created_ids.clone();
}
self.set_relationships_in_owner(event_buffer, &owner_id, &relationship_ids)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Created)),
ids: created_ids,
data: None,
});
Ok(new_entities)
}
pub fn get(&self, id: &EntityId) -> Result<Option<Global>, RepositoryError> {
self.table.get(id)
}
pub fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Global>>, RepositoryError> {
self.table.get_multi(ids)
}
pub fn get_all(&self) -> Result<Vec<Global>, RepositoryError> {
self.table.get_all()
}
pub fn update(
&mut self,
event_buffer: &mut EventBuffer,
entity: &Global,
) -> Result<Global, RepositoryError> {
let updated = self.table.update(entity)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Updated)),
ids: vec![updated.id],
data: None,
});
Ok(updated)
}
pub fn update_multi(
&mut self,
event_buffer: &mut EventBuffer,
entities: &[Global],
) -> Result<Vec<Global>, RepositoryError> {
let updated = self.table.update_multi(entities)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Updated)),
ids: updated.iter().map(|e| e.id).collect(),
data: None,
});
Ok(updated)
}
pub fn update_with_relationships(
&mut self,
event_buffer: &mut EventBuffer,
entity: &Global,
) -> Result<Global, RepositoryError> {
let updated = self.table.update_with_relationships(entity)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Updated)),
ids: vec![updated.id],
data: None,
});
Ok(updated)
}
pub fn update_with_relationships_multi(
&mut self,
event_buffer: &mut EventBuffer,
entities: &[Global],
) -> Result<Vec<Global>, RepositoryError> {
let updated = self.table.update_with_relationships_multi(entities)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Updated)),
ids: updated.iter().map(|e| e.id).collect(),
data: None,
});
Ok(updated)
}
pub fn remove(
&mut self,
event_buffer: &mut EventBuffer,
id: &EntityId,
) -> Result<(), RepositoryError> {
let _entity = match self.table.get(id)? {
Some(e) => e,
None => return Ok(()),
};
let affected_owner_ids: Vec<EntityId> = {
let owner_repo =
repository_factory::write::create_workspace_repository(self.transaction)?;
owner_repo
.get_relationships_from_right_ids(&WorkspaceRelationshipField::Global, &[*id])?
.into_iter()
.map(|(owner_id, _)| owner_id)
.collect()
};
let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
std::collections::HashMap::new();
for owner_id in &affected_owner_ids {
owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
}
self.table.remove(id)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Removed)),
ids: vec![*id],
data: None,
});
for owner_id in &affected_owner_ids {
if let Some(rel_ids) = owner_rel_before.get(owner_id) {
let updated: Vec<EntityId> =
rel_ids.iter().copied().filter(|rid| *rid != *id).collect();
self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
}
}
Ok(())
}
pub fn remove_multi(
&mut self,
event_buffer: &mut EventBuffer,
ids: &[EntityId],
) -> Result<(), RepositoryError> {
let entities = self.table.get_multi(ids)?;
if entities.is_empty() || entities.iter().all(|e| e.is_none()) {
return Ok(());
}
let affected_owner_ids: Vec<EntityId> = {
let owner_repo =
repository_factory::write::create_workspace_repository(self.transaction)?;
owner_repo
.get_relationships_from_right_ids(&WorkspaceRelationshipField::Global, ids)?
.into_iter()
.map(|(owner_id, _)| owner_id)
.collect()
};
let mut owner_rel_before: std::collections::HashMap<EntityId, Vec<EntityId>> =
std::collections::HashMap::new();
for owner_id in &affected_owner_ids {
owner_rel_before.insert(*owner_id, self.get_relationships_from_owner(owner_id)?);
}
self.table.remove_multi(ids)?;
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Removed)),
ids: ids.into(),
data: None,
});
{
let removed_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
for owner_id in &affected_owner_ids {
if let Some(rel_ids) = owner_rel_before.get(owner_id) {
let updated: Vec<EntityId> = rel_ids
.iter()
.copied()
.filter(|rid| !removed_set.contains(rid))
.collect();
self.set_relationships_in_owner(event_buffer, owner_id, &updated)?;
}
}
}
Ok(())
}
pub fn get_relationships_from_owner(
&self,
owner_id: &EntityId,
) -> Result<Vec<EntityId>, RepositoryError> {
let repo = repository_factory::write::create_workspace_repository(self.transaction)?;
repo.get_relationship(owner_id, &WorkspaceRelationshipField::Global)
}
pub fn set_relationships_in_owner(
&mut self,
event_buffer: &mut EventBuffer,
owner_id: &EntityId,
ids: &[EntityId],
) -> Result<(), RepositoryError> {
let mut repo = repository_factory::write::create_workspace_repository(self.transaction)?;
repo.set_relationship(
event_buffer,
owner_id,
&WorkspaceRelationshipField::Global,
ids,
)
}
pub fn snapshot(&self, ids: &[EntityId]) -> Result<EntityTreeSnapshot, RepositoryError> {
let store_snap = self.transaction.snapshot_store();
Ok(EntityTreeSnapshot {
store_snapshot: Some(store_snap),
root_ids: ids.to_vec(),
})
}
pub fn restore(
&mut self,
event_buffer: &mut EventBuffer,
snap: &EntityTreeSnapshot,
) -> Result<(), RepositoryError> {
let store_snap = snap
.store_snapshot
.as_ref()
.ok_or_else(|| RepositoryError::Serialization("missing store snapshot".into()))?;
let snap_store = store_snap
.downcast_ref::<HashMapStoreSnapshot>()
.ok_or_else(|| RepositoryError::Serialization("snapshot type mismatch".into()))?;
let mut visited = std::collections::HashSet::new();
self.restore_subtree(event_buffer, snap_store, &snap.root_ids, &mut visited)?;
self.reconcile_backref_workspace_global(event_buffer, snap_store, &snap.root_ids)?;
Ok(())
}
pub(crate) fn restore_subtree(
&self,
event_buffer: &mut EventBuffer,
snap: &HashMapStoreSnapshot,
ids: &[EntityId],
visited: &mut std::collections::HashSet<(&'static str, EntityId)>,
) -> Result<(), RepositoryError> {
let ids: Vec<EntityId> = ids
.iter()
.copied()
.filter(|id| visited.insert(("global", *id)))
.collect();
if ids.is_empty() {
return Ok(());
}
let store = self.transaction.get_store();
let mut to_create: Vec<EntityId> = Vec::new(); let mut to_update: Vec<EntityId> = Vec::new(); let mut to_delete: Vec<EntityId> = Vec::new(); {
let live = read_or_recover(&store.globals);
for id in &ids {
match (snap.globals.contains_key(id), live.contains_key(id)) {
(true, false) => to_create.push(*id),
(true, true) => to_update.push(*id),
(false, true) => to_delete.push(*id),
(false, false) => {}
}
}
}
{
let mut live = write_or_recover(&store.globals);
for id in to_create.iter().chain(to_update.iter()) {
if let Some(row) = snap.globals.get(id) {
live.insert(*id, row.clone());
}
}
for id in &to_delete {
live.remove(id);
}
}
if !to_create.is_empty() {
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Created)),
ids: to_create.clone(),
data: None,
});
}
if !to_update.is_empty() {
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Updated)),
ids: to_update.clone(),
data: None,
});
}
if !to_delete.is_empty() {
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Global(EntityEvent::Removed)),
ids: to_delete.clone(),
data: None,
});
}
Ok(())
}
fn reconcile_backref_workspace_global(
&self,
event_buffer: &mut EventBuffer,
snap: &HashMapStoreSnapshot,
scope_ids: &[EntityId],
) -> Result<(), RepositoryError> {
let scope: std::collections::HashSet<EntityId> = scope_ids.iter().copied().collect();
if scope.is_empty() {
return Ok(());
}
let store = self.transaction.get_store();
let mut left_keys: std::collections::HashSet<EntityId> = std::collections::HashSet::new();
for (left, rights) in snap.jn_global_from_workspace_global.iter() {
if rights.iter().any(|rid| scope.contains(rid)) {
left_keys.insert(*left);
}
}
{
let live_jn = read_or_recover(&store.jn_global_from_workspace_global);
for (left, rights) in live_jn.iter() {
if rights.iter().any(|rid| scope.contains(rid)) {
left_keys.insert(*left);
}
}
}
for left in left_keys {
let snap_list: Vec<EntityId> = snap
.jn_global_from_workspace_global
.get(&left)
.cloned()
.unwrap_or_default();
let new_list = {
let live_jn = read_or_recover(&store.jn_global_from_workspace_global);
let live_list: Vec<EntityId> = live_jn.get(&left).cloned().unwrap_or_default();
let reconciled = crate::database::hashmap_store::reconcile_backref_list(
&live_list, &snap_list, &scope,
);
if reconciled == live_list {
None
} else {
Some(reconciled)
}
};
if let Some(reconciled) = new_list {
write_or_recover(&store.jn_global_from_workspace_global).insert(left, reconciled);
event_buffer.push(Event {
origin: Origin::DirectAccess(DirectAccessEntity::Workspace(
EntityEvent::Updated,
)),
ids: vec![left],
data: None,
});
}
}
Ok(())
}
}
pub struct GlobalRepositoryRO<'a> {
table: Box<dyn GlobalTableRO + 'a>,
}
impl<'a> GlobalRepositoryRO<'a> {
pub fn new(table: Box<dyn GlobalTableRO + 'a>) -> Self {
GlobalRepositoryRO { table }
}
pub fn get(&self, id: &EntityId) -> Result<Option<Global>, RepositoryError> {
self.table.get(id)
}
pub fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Global>>, RepositoryError> {
self.table.get_multi(ids)
}
pub fn get_all(&self) -> Result<Vec<Global>, RepositoryError> {
self.table.get_all()
}
}