use crate::object_api::hook_slot::HookSlot;
use std::sync::Arc;
#[async_trait::async_trait]
pub trait ObjectMutationHook: Send + Sync + 'static {
async fn after_object_mutation(&self, bucket: &str, object: &str);
}
static OBJECT_MUTATION_HOOK: HookSlot<dyn ObjectMutationHook> = HookSlot::new();
pub fn register_object_mutation_hook(hook: Arc<dyn ObjectMutationHook>) {
OBJECT_MUTATION_HOOK.register(
hook,
"object mutation cache hook re-registered with a different instance; \
the previous adapter's cache is now unreachable by ecstore's delete paths",
);
}
pub fn unregister_object_mutation_hook() {
OBJECT_MUTATION_HOOK.clear();
}
fn object_mutation_hook() -> Option<Arc<dyn ObjectMutationHook>> {
OBJECT_MUTATION_HOOK.get()
}
pub(crate) async fn notify_object_mutation(bucket: &str, object: &str) {
if let Some(hook) = object_mutation_hook() {
hook.after_object_mutation(bucket, object).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
struct RecordingHook {
calls: Arc<Mutex<Vec<(String, String)>>>,
}
#[async_trait::async_trait]
impl ObjectMutationHook for RecordingHook {
async fn after_object_mutation(&self, bucket: &str, object: &str) {
self.calls.lock().unwrap().push((bucket.to_string(), object.to_string()));
}
}
#[tokio::test]
#[serial_test::serial(object_mutation_hook)]
async fn notify_invokes_registered_hook_with_identity() {
unregister_object_mutation_hook();
let calls = Arc::new(Mutex::new(Vec::new()));
register_object_mutation_hook(Arc::new(RecordingHook {
calls: Arc::clone(&calls),
}));
notify_object_mutation("bucket", "photos/a.jpg").await;
assert_eq!(&*calls.lock().unwrap(), &[("bucket".to_string(), "photos/a.jpg".to_string())]);
unregister_object_mutation_hook();
}
#[tokio::test]
#[serial_test::serial(object_mutation_hook)]
async fn unregister_prevents_later_notifications() {
unregister_object_mutation_hook();
let calls = Arc::new(Mutex::new(Vec::new()));
register_object_mutation_hook(Arc::new(RecordingHook {
calls: Arc::clone(&calls),
}));
unregister_object_mutation_hook();
notify_object_mutation("bucket", "object").await;
assert!(calls.lock().unwrap().is_empty(), "an unregistered hook must receive no mutation callback");
}
#[test]
#[serial_test::serial(object_mutation_hook)]
fn unregister_releases_the_previous_hook() {
unregister_object_mutation_hook();
let calls = Arc::new(Mutex::new(Vec::new()));
let hook = Arc::new(RecordingHook { calls });
let weak = Arc::downgrade(&hook);
register_object_mutation_hook(hook);
assert!(weak.upgrade().is_some());
unregister_object_mutation_hook();
assert!(weak.upgrade().is_none());
}
}