use std::sync::{Arc, Mutex};
thread_local! {
static ACTIVE_DISPATCHES: std::cell::RefCell<std::collections::HashSet<usize>> =
std::cell::RefCell::new(std::collections::HashSet::new());
static SUSPENDED_BOOKS: std::cell::RefCell<Vec<u64>> = const { std::cell::RefCell::new(Vec::new()) };
}
struct DispatchFlag {
token: usize,
}
impl DispatchFlag {
fn enter(token: usize) -> Self {
ACTIVE_DISPATCHES.with(|active| {
active.borrow_mut().insert(token);
});
Self { token }
}
}
impl Drop for DispatchFlag {
fn drop(&mut self) {
ACTIVE_DISPATCHES.with(|active| {
active.borrow_mut().remove(&self.token);
});
}
}
struct TimeSuspension {
finished: std::cell::Cell<bool>,
}
impl TimeSuspension {
fn enter() -> Self {
SUSPENDED_BOOKS.with(|books| books.borrow_mut().push(0));
Self {
finished: std::cell::Cell::new(false),
}
}
fn take(&self) -> u64 {
SUSPENDED_BOOKS.with(|books| {
let mut books = books.borrow_mut();
let elapsed = books.pop().unwrap_or_default();
if let Some(outer) = books.last_mut() {
*outer = outer.saturating_add(elapsed);
}
elapsed
})
}
fn finish(self) -> Duration {
self.finished.set(true);
Duration::from_nanos(self.take())
}
}
impl Drop for TimeSuspension {
fn drop(&mut self) {
if !self.finished.get() {
self.take();
}
}
}
use std::time::Duration;
use crate::core::metadata::{Metadata, MetadataPatch, Name};
use crate::core::object::ObjectKind;
use crate::core::object_id::ObjectId;
use crate::core::time::{Clock, VirtualClock};
use crate::core::timestamp::Timestamp;
use crate::error::Error;
use crate::events::event::{EventData, ObjectEvent};
use crate::events::event_bus::EventBus;
use crate::events::event_type::EventType;
use crate::events::subscription::SubscriptionId;
use crate::filesystem::detached_namespace::DetachedNamespace;
use crate::filesystem::path::VirtualPath;
use crate::filesystem::store::ObjectStore;
use crate::security::actor::ActorId;
use crate::security::authorization::{
AuthorizationData, AuthorizationPolicy, AuthorizationRequest, AuthorizationResult, Operation,
PermissivePolicy,
};
const COPY_SOURCE_KEY: &str = "source";
struct EventChain {
actor: Option<ActorId>,
now: Timestamp,
events: Vec<ObjectEvent>,
}
impl EventChain {
fn new(actor: Option<ActorId>, now: Timestamp) -> Self {
Self {
actor,
now,
events: Vec::new(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CreateOptions {
pub owner: Option<ActorId>,
pub authorization: AuthorizationData,
}
pub struct Engine {
store: Arc<Mutex<ObjectStore>>,
bus: Arc<Mutex<EventBus>>,
dispatch_lock: Arc<Mutex<()>>,
policy: Arc<dyn AuthorizationPolicy>,
clock: Arc<dyn Clock>,
}
impl Clone for Engine {
fn clone(&self) -> Self {
Self {
store: Arc::clone(&self.store),
bus: Arc::clone(&self.bus),
dispatch_lock: Arc::clone(&self.dispatch_lock),
policy: Arc::clone(&self.policy),
clock: Arc::clone(&self.clock),
}
}
}
impl Engine {
pub fn new(policy: Box<dyn AuthorizationPolicy>, clock: Box<dyn Clock>) -> Self {
Self {
store: Arc::new(Mutex::new(ObjectStore::new())),
bus: Arc::new(Mutex::new(EventBus::new())),
dispatch_lock: Arc::new(Mutex::new(())),
policy: Arc::from(policy),
clock: Arc::from(clock),
}
}
pub fn with_virtual_clock(policy: Box<dyn AuthorizationPolicy>) -> Self {
Self::new(policy, Box::new(VirtualClock::new()))
}
pub fn advance_time(&self, duration: Duration) {
let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
let suspended = SUSPENDED_BOOKS.with(|books| {
if let Some(top) = books.borrow_mut().last_mut() {
*top = top.saturating_add(nanos);
true
} else {
false
}
});
if !suspended {
self.clock.advance_by(duration);
}
}
pub fn set_time(&self, timestamp: Timestamp) {
self.clock.set(timestamp);
}
pub fn time(&self) -> Timestamp {
self.now()
}
pub fn suspend_time<R>(f: impl FnOnce() -> R) -> (R, Duration) {
let guard = TimeSuspension::enter();
let result = f();
let elapsed = guard.finish();
(result, elapsed)
}
pub fn subscribe(
&self,
filter: impl Into<Option<EventType>>,
callback: impl FnMut(&ObjectEvent) + Send + Sync + 'static,
) -> SubscriptionId {
self.bus
.lock()
.expect("event bus lock poisoned")
.subscribe(filter, callback)
}
pub fn unsubscribe(&self, subscription: SubscriptionId) {
self.bus
.lock()
.expect("event bus lock poisoned")
.unsubscribe(subscription);
}
pub fn listener_count(&self) -> usize {
self.bus
.lock()
.expect("event bus lock poisoned")
.listener_count()
}
pub fn root(&self) -> ObjectId {
self.store.lock().expect("store lock poisoned").root()
}
pub fn exists(&self, object: ObjectId) -> bool {
self.store
.lock()
.expect("store lock poisoned")
.get(object)
.is_some()
}
pub fn metadata(&self, actor: Option<ActorId>, object: ObjectId) -> Result<Metadata, Error> {
self.authorize(actor, Operation::Read, object)?;
let object = self.resolve_links(object)?;
let store = self.store.lock().expect("store lock poisoned");
Ok(store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.metadata
.clone())
}
pub fn parent(
&self,
actor: Option<ActorId>,
object: ObjectId,
) -> Result<Option<ObjectId>, Error> {
self.authorize(actor, Operation::Read, object)?;
let store = self.store.lock().expect("store lock poisoned");
Ok(store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.parent)
}
pub fn children(
&self,
actor: Option<ActorId>,
directory: ObjectId,
) -> Result<Vec<ObjectId>, Error> {
self.authorize(actor, Operation::Read, directory)?;
let directory = self.resolve_links(directory)?;
let store = self.store.lock().expect("store lock poisoned");
let data = store
.get(directory)
.ok_or(Error::ObjectNotFound(directory))?;
if !data.kind.is_directory() {
return Err(Error::NotADirectory(directory));
}
Ok(data.children.iter().copied().collect())
}
pub fn list(
&self,
actor: Option<ActorId>,
directory: ObjectId,
) -> Result<Vec<(Name, ObjectId)>, Error> {
self.authorize(actor, Operation::Read, directory)?;
let directory = self.resolve_links(directory)?;
let store = self.store.lock().expect("store lock poisoned");
let data = store
.get(directory)
.ok_or(Error::ObjectNotFound(directory))?;
if !data.kind.is_directory() {
return Err(Error::NotADirectory(directory));
}
let mut entries: Vec<(Name, ObjectId)> = data
.children
.iter()
.map(|child| {
let child_data = store.get(*child).expect("child of a directory exists");
(child_data.metadata.name().clone(), *child)
})
.collect();
entries.sort();
Ok(entries)
}
pub fn size(&self, actor: Option<ActorId>, object: ObjectId) -> Result<u64, Error> {
self.authorize(actor, Operation::Read, object)?;
let object = self.resolve_links(object)?;
let store = self.store.lock().expect("store lock poisoned");
Ok(store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.size())
}
pub fn check(
&self,
actor: Option<ActorId>,
operation: Operation,
object: ObjectId,
) -> Result<(), Error> {
self.authorize(actor, operation, object)
}
pub fn lookup(&self, actor: Option<ActorId>, path: &VirtualPath) -> Result<ObjectId, Error> {
let store = self.store.lock().expect("store lock poisoned");
let (object, traversed) = self.walk(&store, path)?;
drop(store);
for directory in traversed {
self.authorize(actor, Operation::Execute, directory)?;
}
self.authorize(actor, Operation::Read, object)?;
Ok(object)
}
pub fn lookup_no_follow(
&self,
actor: Option<ActorId>,
path: &VirtualPath,
) -> Result<ObjectId, Error> {
let store = self.store.lock().expect("store lock poisoned");
let mut current = store.root();
let mut traversed = Vec::new();
let segments: &[String] = path.segments();
for (index, segment) in segments.iter().enumerate() {
traversed.push(current);
let data = store.get(current).ok_or(Error::ObjectNotFound(current))?;
let next = data
.children
.iter()
.copied()
.find(|child| {
store
.get(*child)
.is_some_and(|child_data| child_data.metadata.name().as_str() == segment)
})
.ok_or_else(|| Error::PathNotFound(path.clone()))?;
let is_last = index + 1 == segments.len();
let is_link = store
.get(next)
.is_some_and(|child_data| child_data.kind.is_symlink());
if is_last && is_link {
drop(store);
for directory in traversed {
self.authorize(actor, Operation::Execute, directory)?;
}
self.authorize(actor, Operation::Read, next)?;
return Ok(next);
}
current = next;
}
drop(store);
for directory in traversed {
self.authorize(actor, Operation::Execute, directory)?;
}
self.authorize(actor, Operation::Read, current)?;
Ok(current)
}
pub fn create_symlink(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
target: String,
) -> Result<ObjectId, Error> {
self.create_symlink_with_options(actor, parent, name, target, CreateOptions::default())
}
pub fn create_symlink_with_options(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
target: String,
options: CreateOptions,
) -> Result<ObjectId, Error> {
self.create(actor, parent, name, ObjectKind::Symlink { target }, options)
}
pub fn read_link(
&self,
actor: Option<ActorId>,
object: ObjectId,
) -> Result<Option<String>, Error> {
self.authorize(actor, Operation::Read, object)?;
let store = self.store.lock().expect("store lock poisoned");
let data = store.get(object).ok_or(Error::ObjectNotFound(object))?;
match &data.kind {
ObjectKind::Symlink { target } => Ok(Some(target.clone())),
_ => Ok(None),
}
}
pub fn is_link(&self, actor: Option<ActorId>, object: ObjectId) -> Result<bool, Error> {
self.authorize(actor, Operation::Read, object)?;
let store = self.store.lock().expect("store lock poisoned");
Ok(store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.kind
.is_symlink())
}
pub fn resolve_links(&self, object: ObjectId) -> Result<ObjectId, Error> {
let store = self.store.lock().expect("store lock poisoned");
let mut current = object;
for _ in 0..=Self::MAX_SYMLINK_DEPTH {
let data = store.get(current).ok_or(Error::ObjectNotFound(current))?;
let ObjectKind::Symlink { target } = &data.kind else {
return Ok(current);
};
let target_path = if target.starts_with('/') {
target
.parse()
.map_err(|_| Error::InvalidPath(target.clone()))?
} else {
let mut base = Self::path_of(&store, current).unwrap_or(VirtualPath::root());
if let Some(parent) = base.parent() {
base = parent.clone();
}
for component in target.split('/').filter(|part| !part.is_empty()) {
base = base.join(
&Name::new(component)
.map_err(|_| Error::InvalidPath(component.to_owned()))?,
);
}
base
};
current = self.walk(&store, &target_path)?.0;
}
Err(Error::SymlinkLoop(object.get().to_string()))
}
const MAX_SYMLINK_DEPTH: usize = 40;
fn path_of(store: &ObjectStore, object: ObjectId) -> Option<VirtualPath> {
let mut names = Vec::new();
let mut current = object;
loop {
let data = store.get(current)?;
if data.parent.is_none() {
break;
}
names.push(data.metadata.name().clone());
current = data.parent?;
}
let mut path = VirtualPath::root();
for name in names.into_iter().rev() {
path = path.join(&name);
}
Some(path)
}
fn walk(
&self,
store: &ObjectStore,
path: &VirtualPath,
) -> Result<(ObjectId, Vec<ObjectId>), Error> {
self.walk_at(store, path, 0)
}
fn walk_at(
&self,
store: &ObjectStore,
path: &VirtualPath,
depth: usize,
) -> Result<(ObjectId, Vec<ObjectId>), Error> {
let mut current = store.root();
let mut traversed = Vec::new();
let mut current_path = VirtualPath::root();
for segment in path.segments() {
traversed.push(current);
let data = store.get(current).ok_or(Error::ObjectNotFound(current))?;
let next = data
.children
.iter()
.copied()
.find(|child| {
store
.get(*child)
.is_some_and(|child_data| child_data.metadata.name().as_str() == segment)
})
.ok_or_else(|| Error::PathNotFound(path.clone()))?;
current_path = current_path
.join(&Name::new(segment).map_err(|_| Error::InvalidPath(segment.to_owned()))?);
let is_link = store
.get(next)
.is_some_and(|child_data| child_data.kind.is_symlink());
if !is_link {
current = next;
continue;
}
if depth + 1 > Self::MAX_SYMLINK_DEPTH {
return Err(Error::SymlinkLoop(path.to_string()));
}
let data = store.get(next).expect("link exists");
let ObjectKind::Symlink { target } = &data.kind else {
unreachable!("checked above");
};
let target_path = if target.starts_with('/') {
target
.parse()
.map_err(|_| Error::InvalidPath(target.clone()))?
} else {
let mut base = current_path.parent().unwrap_or(VirtualPath::root()).clone();
for component in target.split('/').filter(|part| !part.is_empty()) {
base = base.join(
&Name::new(component)
.map_err(|_| Error::InvalidPath(component.to_owned()))?,
);
}
base
};
let (resolved, target_traversed) = self.walk_at(store, &target_path, depth + 1)?;
traversed.extend(target_traversed);
current = resolved;
current_path = target_path;
}
Ok((current, traversed))
}
pub fn read(&self, actor: Option<ActorId>, file: ObjectId) -> Result<Option<Vec<u8>>, Error> {
self.authorize(actor, Operation::Read, file)?;
let file = self.resolve_links(file)?;
let content = {
let store = self.store.lock().expect("store lock poisoned");
let data = store.get(file).ok_or(Error::ObjectNotFound(file))?;
match &data.kind {
ObjectKind::File { content } => content.clone(),
ObjectKind::Directory => return Err(Error::NotAFile(file)),
ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
}
};
self.dispatch(ObjectEvent::new(
EventType::ObjectRead,
file,
actor,
self.now(),
));
Ok(content)
}
pub fn create_file(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
content: Option<Vec<u8>>,
) -> Result<ObjectId, Error> {
self.create_file_with_options(actor, parent, name, content, CreateOptions::default())
}
pub fn create_directory(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
) -> Result<ObjectId, Error> {
self.create_directory_with_options(actor, parent, name, CreateOptions::default())
}
pub fn create_file_with_options(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
content: Option<Vec<u8>>,
options: CreateOptions,
) -> Result<ObjectId, Error> {
self.create(actor, parent, name, ObjectKind::File { content }, options)
}
pub fn create_directory_with_options(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
options: CreateOptions,
) -> Result<ObjectId, Error> {
self.create(actor, parent, name, ObjectKind::Directory, options)
}
pub fn create_detached_namespace(
&self,
actor: Option<ActorId>,
name: Name,
) -> Result<DetachedNamespace, Error> {
let root = self.root();
self.authorize(actor, Operation::Create, root)?;
let now = self.now();
let id = {
let mut store = self.store.lock().expect("store lock poisoned");
store.create_detached(name, now)?
};
self.dispatch(ObjectEvent::new(EventType::ObjectCreated, id, actor, now));
Ok(DetachedNamespace::new(id))
}
pub fn write(
&self,
actor: Option<ActorId>,
file: ObjectId,
content: Vec<u8>,
) -> Result<(), Error> {
let now = self.now();
let file = self.resolve_links(file)?;
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Write, file)?;
let data = store.get_mut(file).ok_or(Error::ObjectNotFound(file))?;
match &mut data.kind {
ObjectKind::File { content: target } => *target = Some(content),
ObjectKind::Directory => return Err(Error::NotAFile(file)),
ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
}
data.metadata.set_modified(now);
ObjectEvent::new(EventType::ObjectWritten, file, actor, now)
};
self.dispatch(event);
Ok(())
}
pub fn replace_file_with_options(
&self,
actor: Option<ActorId>,
file: ObjectId,
content: Vec<u8>,
options: CreateOptions,
) -> Result<(), Error> {
let now = self.now();
let file = self.resolve_links(file)?;
let mut chain = EventChain::new(actor, now);
{
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Write, file)?;
Self::authorize_in_store(&store, &*self.policy, actor, Operation::ChangeOwner, file)?;
Self::authorize_in_store(
&store,
&*self.policy,
actor,
Operation::ChangeMetadata,
file,
)?;
let data = store.get_mut(file).ok_or(Error::ObjectNotFound(file))?;
match &mut data.kind {
ObjectKind::File { content: target } => *target = Some(content),
ObjectKind::Directory => return Err(Error::NotAFile(file)),
ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
}
data.metadata.set_owner(options.owner);
data.metadata.set_authorization(options.authorization);
data.metadata.set_modified(now);
chain.events.extend([
ObjectEvent::new(EventType::ObjectWritten, file, actor, now),
ObjectEvent::new(EventType::OwnerChanged, file, actor, now),
ObjectEvent::new(EventType::AuthorizationChanged, file, actor, now),
]);
}
self.dispatch_chain(chain);
Ok(())
}
pub fn append(
&self,
actor: Option<ActorId>,
file: ObjectId,
content: Vec<u8>,
) -> Result<(), Error> {
let now = self.now();
let file = self.resolve_links(file)?;
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Write, file)?;
let data = store.get_mut(file).ok_or(Error::ObjectNotFound(file))?;
match &mut data.kind {
ObjectKind::File { content: target } => match target {
Some(existing) => existing.extend(content),
None => *target = Some(content),
},
ObjectKind::Directory => return Err(Error::NotAFile(file)),
ObjectKind::Symlink { .. } => unreachable!("links resolve above"),
}
data.metadata.set_modified(now);
ObjectEvent::new(EventType::ObjectWritten, file, actor, now)
};
self.dispatch(event);
Ok(())
}
pub fn touch(&self, actor: Option<ActorId>, object: ObjectId) -> Result<(), Error> {
let now = self.now();
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(
&store,
&*self.policy,
actor,
Operation::ChangeMetadata,
object,
)?;
let data = store.get_mut(object).ok_or(Error::ObjectNotFound(object))?;
data.metadata.set_modified(now);
data.metadata.set_accessed(now);
ObjectEvent::new(EventType::MetadataChanged, object, actor, now)
};
self.dispatch(event);
Ok(())
}
pub fn move_object(
&self,
actor: Option<ActorId>,
object: ObjectId,
destination: ObjectId,
new_name: Option<Name>,
) -> Result<(), Error> {
let now = self.now();
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Move, object)?;
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, destination)?;
if object == store.root() {
return Err(Error::RootMove);
}
let old_parent = store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.parent;
store.require_directory(destination)?;
if object == destination || store.is_ancestor_of(object, destination) {
return Err(Error::CyclicMove(object));
}
let current_name = store
.get(object)
.expect("object existence checked above")
.metadata
.name()
.clone();
if old_parent == Some(destination)
&& new_name.as_ref().is_none_or(|new| *new == current_name)
{
return Ok(());
}
let effective_name = match &new_name {
Some(name) => name.clone(),
None => current_name,
};
let conflict = store.has_child_named(destination, &effective_name)?;
if conflict {
return Err(Error::NameAlreadyExists {
name: effective_name,
directory: destination,
});
}
let old_parent = store.detach(object)?;
store.attach(object, destination)?;
if let Some(name) = new_name {
store.rename(object, name)?;
}
ObjectEvent {
event_type: EventType::ObjectMoved,
object,
source_parent: old_parent,
destination_parent: Some(destination),
actor,
timestamp: now,
data: EventData::new(),
}
};
self.dispatch(event);
Ok(())
}
pub fn detach_object(&self, actor: Option<ActorId>, object: ObjectId) -> Result<(), Error> {
let now = self.now();
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Move, object)?;
if object == store.root() {
return Err(Error::RootDetach);
}
if store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.parent
.is_none()
{
return Ok(());
}
let old_parent = store.detach(object)?;
ObjectEvent {
event_type: EventType::Detached,
object,
source_parent: old_parent,
destination_parent: None,
actor,
timestamp: now,
data: EventData::new(),
}
};
self.dispatch(event);
Ok(())
}
pub fn attach_object(
&self,
actor: Option<ActorId>,
object: ObjectId,
destination: ObjectId,
) -> Result<(), Error> {
let now = self.now();
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Move, object)?;
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, destination)?;
store.require_directory(destination)?;
let data = store.get(object).ok_or(Error::ObjectNotFound(object))?;
if data.parent.is_some() {
return Err(Error::AttachedObject(object));
}
if object == destination || store.is_ancestor_of(object, destination) {
return Err(Error::CyclicAttach(object));
}
let name = data.metadata.name().clone();
if store.has_child_named(destination, &name)? {
return Err(Error::NameAlreadyExists {
name,
directory: destination,
});
}
store.attach(object, destination)?;
ObjectEvent {
event_type: EventType::Attached,
object,
source_parent: None,
destination_parent: Some(destination),
actor,
timestamp: now,
data: EventData::new(),
}
};
self.dispatch(event);
Ok(())
}
pub fn copy_object(
&self,
actor: Option<ActorId>,
object: ObjectId,
destination: ObjectId,
name: Name,
) -> Result<ObjectId, Error> {
let mut chain = EventChain::new(actor, self.now());
let new_id = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Copy, object)?;
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, destination)?;
store.require_directory(destination)?;
if object == destination || store.is_ancestor_of(object, destination) {
return Err(Error::CyclicCopy(object));
}
self.copy_into(&mut store, object, destination, &name, &mut chain)?
};
self.dispatch_chain(chain);
Ok(new_id)
}
pub fn delete(&self, actor: Option<ActorId>, object: ObjectId) -> Result<(), Error> {
let mut chain = EventChain::new(actor, self.now());
{
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Delete, object)?;
if object == store.root() {
return Err(Error::RootDelete);
}
self.delete_recursive(&mut store, object, &mut chain)?;
}
self.dispatch_chain(chain);
Ok(())
}
pub fn set_owner(
&self,
actor: Option<ActorId>,
object: ObjectId,
owner: Option<ActorId>,
) -> Result<(), Error> {
self.set_owner_and_authorization(
actor,
object,
Some(owner),
None,
EventType::AuthorizationChanged,
)
}
pub fn set_authorization(
&self,
actor: Option<ActorId>,
object: ObjectId,
authorization: AuthorizationData,
) -> Result<(), Error> {
self.set_owner_and_authorization(
actor,
object,
None,
Some(authorization),
EventType::AuthorizationChanged,
)
}
pub fn set_permissions(
&self,
actor: Option<ActorId>,
object: ObjectId,
authorization: AuthorizationData,
) -> Result<(), Error> {
self.set_owner_and_authorization(
actor,
object,
None,
Some(authorization),
EventType::PermissionsChanged,
)
}
pub fn set_group(
&self,
actor: Option<ActorId>,
object: ObjectId,
authorization: AuthorizationData,
) -> Result<(), Error> {
self.set_owner_and_authorization(
actor,
object,
None,
Some(authorization),
EventType::GroupChanged,
)
}
pub fn set_owner_and_authorization(
&self,
actor: Option<ActorId>,
object: ObjectId,
owner: Option<Option<ActorId>>,
authorization: Option<AuthorizationData>,
authorization_event: EventType,
) -> Result<(), Error> {
let now = self.now();
let mut chain = EventChain::new(actor, now);
{
let mut store = self.store.lock().expect("store lock poisoned");
if owner.is_some() {
Self::authorize_in_store(
&store,
&*self.policy,
actor,
Operation::ChangeOwner,
object,
)?;
}
if authorization.is_some() {
Self::authorize_in_store(
&store,
&*self.policy,
actor,
Operation::ChangeMetadata,
object,
)?;
}
let data = store.get_mut(object).ok_or(Error::ObjectNotFound(object))?;
if let Some(owner) = owner {
data.metadata.set_owner(owner);
chain.events.push(ObjectEvent::new(
EventType::OwnerChanged,
object,
actor,
now,
));
}
if let Some(authorization) = authorization {
data.metadata.set_authorization(authorization);
chain
.events
.push(ObjectEvent::new(authorization_event, object, actor, now));
}
}
self.dispatch_chain(chain);
Ok(())
}
pub fn update_metadata(
&self,
actor: Option<ActorId>,
object: ObjectId,
patch: &MetadataPatch,
) -> Result<(), Error> {
if patch.is_empty() {
return Ok(());
}
let now = self.now();
let event = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(
&store,
&*self.policy,
actor,
Operation::ChangeMetadata,
object,
)?;
let data = store.get_mut(object).ok_or(Error::ObjectNotFound(object))?;
data.metadata.apply(patch)?;
ObjectEvent::new(EventType::MetadataChanged, object, actor, now)
};
self.dispatch(event);
Ok(())
}
fn now(&self) -> Timestamp {
let mut current = self.clock.now().as_nanos();
current = current.saturating_add(SUSPENDED_BOOKS.with(|books| {
books
.borrow()
.iter()
.fold(0u64, |sum, book| sum.saturating_add(*book))
}));
Timestamp::from_nanos(current)
}
fn dispatch(&self, event: ObjectEvent) {
let token = std::sync::Arc::as_ptr(&self.dispatch_lock) as usize;
let reentrant = ACTIVE_DISPATCHES.with(|active| active.borrow().contains(&token));
if reentrant {
self.dispatch_inner(event);
return;
}
let _flag = DispatchFlag::enter(token);
let _dispatching = self.dispatch_lock.lock().expect("dispatch lock poisoned");
self.dispatch_inner(event);
}
fn dispatch_inner(&self, event: ObjectEvent) {
let mut listeners = self
.bus
.lock()
.expect("event bus lock poisoned")
.detach_listeners();
crate::events::event_bus::run_listeners(&mut listeners, &event);
self.bus
.lock()
.expect("event bus lock poisoned")
.reattach_listeners(listeners);
}
fn dispatch_chain(&self, chain: EventChain) {
for event in chain.events {
self.dispatch(event);
}
}
fn authorize(
&self,
actor: Option<ActorId>,
operation: Operation,
object: ObjectId,
) -> Result<(), Error> {
let store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, operation, object)
}
fn authorize_in_store(
store: &ObjectStore,
policy: &dyn AuthorizationPolicy,
actor: Option<ActorId>,
operation: Operation,
object: ObjectId,
) -> Result<(), Error> {
let data = store.get(object).ok_or(Error::ObjectNotFound(object))?;
let parent = data
.parent
.and_then(|parent_id| store.get(parent_id))
.map(
|parent_data| crate::security::authorization::ParentReference {
object: parent_data.id,
metadata: &parent_data.metadata,
},
);
let request = AuthorizationRequest {
actor,
operation,
object,
metadata: &data.metadata,
parent,
};
match policy.authorize(&request) {
AuthorizationResult::Allowed => Ok(()),
AuthorizationResult::Denied { .. } => Err(Error::NotAuthorized {
object,
operation,
actor,
}),
}
}
fn create(
&self,
actor: Option<ActorId>,
parent: ObjectId,
name: Name,
kind: ObjectKind,
options: CreateOptions,
) -> Result<ObjectId, Error> {
let now = self.now();
let (id, event) = {
let mut store = self.store.lock().expect("store lock poisoned");
Self::authorize_in_store(&store, &*self.policy, actor, Operation::Create, parent)?;
let id = store.create(parent, name, kind, now)?;
let data = store.get_mut(id).expect("created object exists");
data.metadata.set_owner(options.owner);
data.metadata.set_authorization(options.authorization);
let event = ObjectEvent {
source_parent: Some(parent),
..ObjectEvent::new(EventType::ObjectCreated, id, actor, now)
};
(id, event)
};
self.dispatch(event);
Ok(id)
}
fn copy_into(
&self,
store: &mut ObjectStore,
source: ObjectId,
destination: ObjectId,
name: &Name,
chain: &mut EventChain,
) -> Result<ObjectId, Error> {
let new_id = store.clone_into(source, destination, name.clone())?;
let mut data = EventData::new();
data.insert(
COPY_SOURCE_KEY,
crate::core::metadata::MetadataValue::Unsigned(source.get()),
);
chain.events.push(ObjectEvent {
event_type: EventType::ObjectCopied,
object: new_id,
source_parent: Some(destination),
destination_parent: Some(destination),
actor: chain.actor,
timestamp: chain.now,
data,
});
let children: Vec<ObjectId> = store
.get(source)
.ok_or(Error::ObjectNotFound(source))?
.children
.iter()
.copied()
.collect();
for child in children {
let child_data = store.get(child).ok_or(Error::ObjectNotFound(child))?;
let child_name = child_data.metadata.name().clone();
let child_copy = store.clone_into(child, new_id, child_name)?;
chain.events.push(ObjectEvent {
event_type: EventType::ObjectCreated,
object: child_copy,
source_parent: Some(new_id),
destination_parent: Some(new_id),
actor: chain.actor,
timestamp: chain.now,
data: EventData::new(),
});
self.copy_children_into(store, child, child_copy, chain)?;
}
Ok(new_id)
}
fn copy_children_into(
&self,
store: &mut ObjectStore,
source: ObjectId,
target: ObjectId,
chain: &mut EventChain,
) -> Result<(), Error> {
let children: Vec<ObjectId> = store
.get(source)
.ok_or(Error::ObjectNotFound(source))?
.children
.iter()
.copied()
.collect();
for child in children {
let child_data = store.get(child).ok_or(Error::ObjectNotFound(child))?;
let child_name = child_data.metadata.name().clone();
let child_copy = store.clone_into(child, target, child_name)?;
chain.events.push(ObjectEvent {
event_type: EventType::ObjectCreated,
object: child_copy,
source_parent: Some(target),
destination_parent: Some(target),
actor: chain.actor,
timestamp: chain.now,
data: EventData::new(),
});
self.copy_children_into(store, child, child_copy, chain)?;
}
Ok(())
}
fn delete_recursive(
&self,
store: &mut ObjectStore,
object: ObjectId,
chain: &mut EventChain,
) -> Result<(), Error> {
let children: Vec<ObjectId> = store
.get(object)
.ok_or(Error::ObjectNotFound(object))?
.children
.iter()
.copied()
.collect();
for child in children {
self.delete_recursive(store, child, chain)?;
}
let old_parent = store.detach(object)?;
store.remove(object)?;
chain.events.push(ObjectEvent {
event_type: EventType::ObjectDeleted,
object,
source_parent: old_parent,
destination_parent: None,
actor: chain.actor,
timestamp: chain.now,
data: EventData::new(),
});
Ok(())
}
}
impl Default for Engine {
fn default() -> Self {
Self::with_virtual_clock(Box::new(PermissivePolicy))
}
}