mirror of
https://github.com/rustfs/rustfs.git
synced 2026-08-29 16:37:07 +00:00
test(targets,notify,audit): share a builder MockTarget testkit (#6717)
* test(targets): ship a builder MockTarget testkit and retire the in-crate Target mocks Adds crates/targets/src/testkit.rs with a builder-style MockTarget implementing Target<E> for every E: PluginEvent, with orthogonal off-by-default knobs: disabled/active override, health delay plus health-started signal plus a drop-guard counter proving a cancelled probe future was dropped, an init failure budget (usize::MAX = always fail) plus blocking init plus an init counter, a close counter/signal/semaphore gate with a runtime block toggle, a save counter plus save failure budget, caller-supplied store and failed-store handles, and a shared final-failure counter. Clones and clone_dyn share all counters, so an observer clone keeps watching a target after it is boxed into a runtime. The module is gated as #[cfg(any(test, feature = "test-support"))]: in-crate unit tests get it via cfg(test), and downstream test suites opt in through the new off-by-default test-support cargo feature (test-support = [], activating no dependencies). Migrates the five in-crate duplicate mocks onto it: the plugin.rs registry-factory TestTarget, the runtime/adapter.rs lifecycle TestTarget (init/close/store knobs), the runtime/mod.rs TestTarget plus HealthDropGuard (close gating and health-probe tests), the target/mod.rs MoveTestTarget (folded into the test_support helper constructors used by the NATS JetStream failed-store tests), and the target/mod.rs StoreBackedTarget (the default send_from_store purge test; the mock deliberately does not override send_from_store or handle_terminal_failure). The forced init failure now uses TargetError::Initialization instead of the old adapter mock's Configuration; the adapter derives its redacted failure summary from the target id alone, so the migrated assertions are unchanged. Leak guard: testkit unit tests assert the crate manifest still declares default = [] and that test-support = [] stays a pure cfg gate, complementing the compile-level cfg gate that keeps the mock out of production builds. Part of rustfs/backlog#1846 (cluster 3, step 1). * test(notify,audit): migrate the Target mocks onto the shared testkit Retires the hand-written Target mocks in crates/notify and crates/audit in favor of rustfs_targets::testkit::MockTarget: notify's notifier.rs TestTarget/DeferredTestTarget/ClosableTestTarget, lifecycle.rs BlockingInitTarget/RetryInitTarget (rebuilt as observed MockTarget templates cloned by their plugin-descriptor factories, sharing the init signal, close counter, and single-failure init budget across generations), runtime_view.rs TestTarget, runtime_facade.rs TestTarget, and audit's pipeline.rs MockTarget, system.rs TestTarget, registry.rs CloseTestTarget, plus TestTarget and FailingTarget in audit/tests/pipeline_layer_test.rs. Removing the two integration-test mocks also removes their respelled PluginEvent bound (E: Send + Sync + 'static + Clone + Serialize + DeserializeOwned), which the plugin-contract rules require to be spelled only via PluginEvent. lifecycle.rs ReplayTarget stays bespoke on purpose: its generation tags, mpsc observation channels, gated send_raw delivery, and ObservedQueueStore model the replay pipeline itself and would contort a general-purpose mock. The other bespoke mocks named out of scope in PR-3a (ProgrammedTarget, ClassifyingTarget, the ReloadableTargetTls fakes) are likewise untouched. New testkit knobs, each defaulted off and unit-tested: with_id (rename a clone while keeping the shared counters, for factory templates), with_first_save_gate (the first save notifies entered and waits on release; several mocks may share one pair), with_health_gate (is_active waits on a release handle after notifying health_started), with_delivery_snapshot (fixed snapshot overriding the store-derived default), with_close_failures (close-failure budget, default TargetError::Storage) with with_close_failure_error to shape the variant (audit's registry test pins TargetError::Unknown), and an always-on is_enabled call counter exposed as enabled_call_count (notifier's generation tests count dispatcher selections through it). Both crates enable the testkit through a dev-dependency on rustfs-targets with the test-support feature; the feature stays out of default and activates no dependencies, so production builds are unchanged. Part of rustfs/backlog#1846 (cluster 3, step 2).
This commit is contained in:
@@ -91,6 +91,7 @@ metrics = { workspace = true }
|
||||
quick-xml = { workspace = true, features = ["serialize", "serde-types", "encoding"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rustfs-targets = { workspace = true, features = ["test-support"] }
|
||||
tokio = { workspace = true, features = ["test-util", "fs", "rt-multi-thread"] }
|
||||
tracing-subscriber = { workspace = true, features = ["env-filter", "time"] }
|
||||
axum = { workspace = true }
|
||||
|
||||
+23
-127
@@ -476,6 +476,7 @@ mod tests {
|
||||
use rustfs_targets::arn::TargetID;
|
||||
use rustfs_targets::store::{Key, QueueStore, Store};
|
||||
use rustfs_targets::target::{EntityTarget, QueuedPayload, QueuedPayloadMeta};
|
||||
use rustfs_targets::testkit::MockTarget;
|
||||
use rustfs_targets::{
|
||||
EventName, ReplayWorkerManager, StoreError, Target, TargetError, TargetPluginDescriptor, TargetPluginRegistry,
|
||||
};
|
||||
@@ -488,108 +489,6 @@ mod tests {
|
||||
const RETRY_INIT_TARGET_TYPE: &str = "lifecycle_retry_init";
|
||||
const REPLAY_TARGET_TYPE: &str = "lifecycle_replay";
|
||||
|
||||
struct BlockingInitState {
|
||||
close_calls: AtomicUsize,
|
||||
init_entered: Notify,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct BlockingInitTarget {
|
||||
id: TargetID,
|
||||
state: Arc<BlockingInitState>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Target<Event> for BlockingInitTarget {
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<Event>>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
self.state.close_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
None
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<Event> + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
self.state.init_entered.notify_one();
|
||||
std::future::pending::<()>().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RetryInitTarget {
|
||||
fail_once: Arc<AtomicBool>,
|
||||
id: TargetID,
|
||||
should_fail: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Target<Event> for RetryInitTarget {
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<Event>>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
None
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<Event> + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
if self.should_fail && self.fail_once.swap(false, Ordering::AcqRel) {
|
||||
return Err(TargetError::Initialization("forced transient init failure".to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
struct ReplayState {
|
||||
active_workers: AtomicUsize,
|
||||
completed_deliveries: AtomicUsize,
|
||||
@@ -929,28 +828,24 @@ mod tests {
|
||||
}
|
||||
|
||||
fn blocking_init_runtime() -> (
|
||||
Arc<BlockingInitState>,
|
||||
Arc<Notify>,
|
||||
MockTarget,
|
||||
NotifyLifecycleCoordinator,
|
||||
NotifyRuntimeView,
|
||||
Arc<AtomicUsize>,
|
||||
Config,
|
||||
) {
|
||||
let state = Arc::new(BlockingInitState {
|
||||
close_calls: AtomicUsize::new(0),
|
||||
init_entered: Notify::new(),
|
||||
});
|
||||
// One observed template feeds every factory-constructed instance, so the returned
|
||||
// observer sees the shared init signal and close counter across generations.
|
||||
let init_entered = Arc::new(Notify::new());
|
||||
let template = MockTarget::new("primary", BLOCKING_INIT_TARGET_TYPE).with_blocking_init(init_entered.clone());
|
||||
let observer = template.clone();
|
||||
let mut plugins = TargetPluginRegistry::<Event>::new();
|
||||
let factory_state = state.clone();
|
||||
plugins.register(TargetPluginDescriptor::new(
|
||||
BLOCKING_INIT_TARGET_TYPE,
|
||||
&[ENABLE_KEY],
|
||||
|_config| Ok(()),
|
||||
move |id, _config| {
|
||||
Ok(Box::new(BlockingInitTarget {
|
||||
id: TargetID::new(id, BLOCKING_INIT_TARGET_TYPE.to_string()),
|
||||
state: factory_state.clone(),
|
||||
}))
|
||||
},
|
||||
move |id, _config| Ok(Box::new(template.clone().with_id(&id, BLOCKING_INIT_TARGET_TYPE))),
|
||||
));
|
||||
let config = config_with_enabled_test_target(BLOCKING_INIT_TARGET_TYPE, "primary");
|
||||
let handoff_count = Arc::new(AtomicUsize::new(0));
|
||||
@@ -962,7 +857,7 @@ mod tests {
|
||||
observer_count.fetch_add(1, Ordering::SeqCst);
|
||||
})),
|
||||
);
|
||||
(state, coordinator, runtime_view, handoff_count, config)
|
||||
(init_entered, observer, coordinator, runtime_view, handoff_count, config)
|
||||
}
|
||||
|
||||
async fn recv_until_generation(receiver: &mut mpsc::UnboundedReceiver<usize>, expected: usize, context: &str) {
|
||||
@@ -1001,10 +896,10 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn real_runtime_disable_supersedes_target_init_and_leaves_no_runtime_state() {
|
||||
let (state, coordinator, runtime_view, handoff_count, config) = blocking_init_runtime();
|
||||
let (init_entered, observer, coordinator, runtime_view, handoff_count, config) = blocking_init_runtime();
|
||||
|
||||
let enable = coordinator.set_mode(true, Some(config));
|
||||
state.init_entered.notified().await;
|
||||
init_entered.notified().await;
|
||||
let disable = coordinator.set_mode(false, None);
|
||||
|
||||
enable.wait().await.expect("superseded real enable should finish");
|
||||
@@ -1013,7 +908,7 @@ mod tests {
|
||||
let status = runtime_view.runtime_status_snapshot().await;
|
||||
assert_eq!(status.target_count, 0);
|
||||
assert_eq!(status.replay_worker_count, 0);
|
||||
assert_eq!(state.close_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(observer.close_call_count(), 1);
|
||||
assert_eq!(handoff_count.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(coordinator.state(), NotificationRuntimeState::LiveOnly);
|
||||
}
|
||||
@@ -1057,10 +952,10 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn real_runtime_terminate_cancels_target_init_and_is_final() {
|
||||
let (state, coordinator, runtime_view, handoff_count, config) = blocking_init_runtime();
|
||||
let (init_entered, observer, coordinator, runtime_view, handoff_count, config) = blocking_init_runtime();
|
||||
|
||||
let enable = coordinator.set_mode(true, Some(config));
|
||||
state.init_entered.notified().await;
|
||||
init_entered.notified().await;
|
||||
let terminate = coordinator.terminate();
|
||||
|
||||
enable.wait().await.expect("superseded real enable should finish");
|
||||
@@ -1069,7 +964,7 @@ mod tests {
|
||||
let status = runtime_view.runtime_status_snapshot().await;
|
||||
assert_eq!(status.target_count, 0);
|
||||
assert_eq!(status.replay_worker_count, 0);
|
||||
assert_eq!(state.close_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(observer.close_call_count(), 1);
|
||||
assert_eq!(handoff_count.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(coordinator.state(), NotificationRuntimeState::Terminated);
|
||||
let err = coordinator
|
||||
@@ -1085,18 +980,19 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_activation_reports_error_and_same_config_can_retry() {
|
||||
let fail_once = Arc::new(AtomicBool::new(true));
|
||||
// The template's single-failure init budget is shared by every clone the factory hands
|
||||
// out, so the "bad" instance fails once in the first generation and recovers on retry.
|
||||
let bad_template = MockTarget::new("bad", RETRY_INIT_TARGET_TYPE).with_init_failures(1);
|
||||
let mut plugins = TargetPluginRegistry::<Event>::new();
|
||||
let factory_fail_once = fail_once.clone();
|
||||
plugins.register(TargetPluginDescriptor::new(
|
||||
RETRY_INIT_TARGET_TYPE,
|
||||
&[ENABLE_KEY],
|
||||
|_config| Ok(()),
|
||||
move |id, _config| {
|
||||
Ok(Box::new(RetryInitTarget {
|
||||
should_fail: id == "bad",
|
||||
id: TargetID::new(id, RETRY_INIT_TARGET_TYPE.to_string()),
|
||||
fail_once: factory_fail_once.clone(),
|
||||
Ok(Box::new(if id == "bad" {
|
||||
bad_template.clone()
|
||||
} else {
|
||||
MockTarget::new(&id, RETRY_INIT_TARGET_TYPE)
|
||||
}))
|
||||
},
|
||||
));
|
||||
|
||||
+67
-304
@@ -610,18 +610,10 @@ impl TargetList {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{rule_engine::NotifyRuleEngine, rules::RulesMap};
|
||||
use async_trait::async_trait;
|
||||
use rustfs_s3_types::EventName;
|
||||
use rustfs_targets::StoreError;
|
||||
use rustfs_targets::{
|
||||
ReplayWorkerManager, TargetError,
|
||||
store::{Key, QueueStore, Store},
|
||||
target::{EntityTarget, QueuedPayload, QueuedPayloadMeta},
|
||||
};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use rustfs_targets::testkit::MockTarget;
|
||||
use rustfs_targets::{ReplayWorkerManager, store::QueueStore};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -680,105 +672,6 @@ mod tests {
|
||||
assert!(suffix_targets.is_empty());
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestTarget {
|
||||
block_first_save: Option<(Arc<Notify>, Arc<Notify>)>,
|
||||
close_calls: Arc<AtomicUsize>,
|
||||
close_entered: Option<Arc<Notify>>,
|
||||
id: TargetID,
|
||||
enabled: bool,
|
||||
save_calls: Arc<AtomicUsize>,
|
||||
selected_calls: Arc<AtomicUsize>,
|
||||
store: Option<QueueStore<QueuedPayload>>,
|
||||
}
|
||||
|
||||
impl TestTarget {
|
||||
fn new(id: &str, name: &str, enabled: bool) -> Self {
|
||||
Self {
|
||||
block_first_save: None,
|
||||
close_calls: Arc::new(AtomicUsize::new(0)),
|
||||
close_entered: None,
|
||||
id: TargetID::new(id.to_string(), name.to_string()),
|
||||
enabled,
|
||||
save_calls: Arc::new(AtomicUsize::new(0)),
|
||||
selected_calls: Arc::new(AtomicUsize::new(0)),
|
||||
store: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_blocked_first_save(mut self, entered: Arc<Notify>, release: Arc<Notify>) -> Self {
|
||||
self.block_first_save = Some((entered, release));
|
||||
self
|
||||
}
|
||||
|
||||
fn with_store(mut self, store: QueueStore<QueuedPayload>) -> Self {
|
||||
self.store = Some(store);
|
||||
self
|
||||
}
|
||||
|
||||
fn with_close_observer(mut self, close_entered: Arc<Notify>) -> Self {
|
||||
self.close_entered = Some(close_entered);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<E> Target<E> for TestTarget
|
||||
where
|
||||
E: rustfs_targets::PluginEvent,
|
||||
{
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
Ok(self.enabled)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<E>>) -> Result<(), TargetError> {
|
||||
let call = self.save_calls.fetch_add(1, Ordering::SeqCst);
|
||||
if call == 0
|
||||
&& let Some((entered, release)) = &self.block_first_save
|
||||
{
|
||||
entered.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
self.close_calls.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(close_entered) = &self.close_entered {
|
||||
close_entered.notify_one();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
self.store
|
||||
.as_ref()
|
||||
.map(|store| store as &(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync))
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<E> + Send + Sync> {
|
||||
let cloned = self.clone();
|
||||
Box::new(cloned)
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
self.selected_calls.fetch_add(1, Ordering::SeqCst);
|
||||
self.enabled
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_pause_drains_entered_deferred_dispatch_and_blocks_new_dispatch() {
|
||||
let metrics = Arc::new(NotificationMetrics::new());
|
||||
@@ -787,12 +680,12 @@ mod tests {
|
||||
let save_entered = Arc::new(Notify::new());
|
||||
let save_release = Arc::new(Notify::new());
|
||||
let queue_dir = tempfile::tempdir().expect("queue tempdir should be created");
|
||||
let target = TestTarget::new("gated-target", "webhook", true)
|
||||
.with_blocked_first_save(save_entered.clone(), save_release.clone())
|
||||
.with_store(QueueStore::new(queue_dir.path(), 16, ".event"));
|
||||
let target = MockTarget::new("gated-target", "webhook")
|
||||
.with_first_save_gate(save_entered.clone(), save_release.clone())
|
||||
.with_store(Arc::new(QueueStore::new(queue_dir.path(), 16, ".event")));
|
||||
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.target_id());
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier
|
||||
.target_list()
|
||||
@@ -817,7 +710,7 @@ mod tests {
|
||||
}
|
||||
});
|
||||
save_entered.notified().await;
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.save_call_count(), 1);
|
||||
|
||||
let mut pause = Box::pin(facade.pause_dispatch());
|
||||
tokio::select! {
|
||||
@@ -830,7 +723,7 @@ mod tests {
|
||||
first_dispatch.await.expect("first dispatch task should finish");
|
||||
let pause_guard = pause.await;
|
||||
|
||||
let replacement = TestTarget::new("gated-target", "webhook", true);
|
||||
let replacement = MockTarget::new("gated-target", "webhook");
|
||||
{
|
||||
let target_list = notifier.target_list();
|
||||
let mut target_list = target_list.write().await;
|
||||
@@ -848,19 +741,19 @@ mod tests {
|
||||
_ = std::future::ready(()) => {}
|
||||
}
|
||||
assert_eq!(
|
||||
replacement.selected_calls.load(Ordering::SeqCst),
|
||||
replacement.enabled_call_count(),
|
||||
0,
|
||||
"a paused dispatch must not select a target from the replacement generation early"
|
||||
);
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(replacement.save_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(target.save_call_count(), 1);
|
||||
assert_eq!(replacement.save_call_count(), 0);
|
||||
|
||||
drop(pause_guard);
|
||||
second_dispatch.await;
|
||||
assert_eq!(target.selected_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(replacement.selected_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(replacement.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.enabled_call_count(), 1);
|
||||
assert_eq!(target.save_call_count(), 1);
|
||||
assert_eq!(replacement.enabled_call_count(), 1);
|
||||
assert_eq!(replacement.save_call_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -870,11 +763,10 @@ mod tests {
|
||||
let notifier = Arc::new(EventNotifier::new(metrics.clone(), rule_engine.clone()));
|
||||
let save_entered = Arc::new(Notify::new());
|
||||
let save_release = Arc::new(Notify::new());
|
||||
let target =
|
||||
TestTarget::new("direct-target", "webhook", true).with_blocked_first_save(save_entered.clone(), save_release.clone());
|
||||
let target = MockTarget::new("direct-target", "webhook").with_first_save_gate(save_entered.clone(), save_release.clone());
|
||||
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.target_id());
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier
|
||||
.target_list()
|
||||
@@ -921,13 +813,11 @@ mod tests {
|
||||
});
|
||||
let first_entered = Arc::new(Notify::new());
|
||||
let first_release = Arc::new(Notify::new());
|
||||
let close_entered = Arc::new(Notify::new());
|
||||
let target = TestTarget::new("direct-target", "webhook", true)
|
||||
.with_blocked_first_save(first_entered.clone(), first_release.clone())
|
||||
.with_close_observer(close_entered);
|
||||
let target =
|
||||
MockTarget::new("direct-target", "webhook").with_first_save_gate(first_entered.clone(), first_release.clone());
|
||||
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.target_id());
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier
|
||||
.target_list()
|
||||
@@ -964,7 +854,7 @@ mod tests {
|
||||
}
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
while target.selected_calls.load(Ordering::SeqCst) != 2 {
|
||||
while target.enabled_call_count() != 2 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
@@ -978,14 +868,14 @@ mod tests {
|
||||
result = &mut replace => panic!("replacement closed a generation with selected direct sends: {result:?}"),
|
||||
_ = std::future::ready(()) => {}
|
||||
}
|
||||
assert_eq!(target.close_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(target.close_call_count(), 0);
|
||||
|
||||
first_release.notify_one();
|
||||
first.await.expect("first direct dispatch should finish");
|
||||
second.await.expect("permit-waiting direct dispatch should be cancelled");
|
||||
replace.await.expect("replacement should close after direct leases drain");
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.close_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.save_call_count(), 1);
|
||||
assert_eq!(target.close_call_count(), 1);
|
||||
assert_eq!(metrics.processing_count(), 0);
|
||||
assert_eq!(metrics.processed_count(), 1);
|
||||
assert_eq!(metrics.skipped_count(), 1);
|
||||
@@ -999,12 +889,12 @@ mod tests {
|
||||
let save_entered = Arc::new(Notify::new());
|
||||
let save_release = Arc::new(Notify::new());
|
||||
let queue_dir = tempfile::tempdir().expect("queue tempdir should be created");
|
||||
let target = TestTarget::new("deferred", "webhook", true)
|
||||
.with_blocked_first_save(save_entered.clone(), save_release.clone())
|
||||
.with_store(QueueStore::new(queue_dir.path(), 16, ".event"));
|
||||
let target = MockTarget::new("deferred", "webhook")
|
||||
.with_first_save_gate(save_entered.clone(), save_release.clone())
|
||||
.with_store(Arc::new(QueueStore::new(queue_dir.path(), 16, ".event")));
|
||||
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.target_id());
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier
|
||||
.target_list()
|
||||
@@ -1060,10 +950,10 @@ mod tests {
|
||||
let mut targets = Vec::new();
|
||||
let mut rules_map = RulesMap::new();
|
||||
for index in 0..TARGETS {
|
||||
let target = TestTarget::new(&format!("deferred-{index}"), "webhook", true)
|
||||
.with_blocked_first_save(entered.clone(), release.clone())
|
||||
.with_store(QueueStore::new(queue_dir.path().join(index.to_string()), 16, ".event"));
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.id.clone());
|
||||
let target = MockTarget::new(&format!("deferred-{index}"), "webhook")
|
||||
.with_first_save_gate(entered.clone(), release.clone())
|
||||
.with_store(Arc::new(QueueStore::new(queue_dir.path().join(index.to_string()), 16, ".event")));
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.target_id());
|
||||
notifier
|
||||
.target_list()
|
||||
.write()
|
||||
@@ -1082,12 +972,7 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
});
|
||||
let total_calls = || {
|
||||
targets
|
||||
.iter()
|
||||
.map(|target| target.save_calls.load(Ordering::SeqCst))
|
||||
.sum::<usize>()
|
||||
};
|
||||
let total_calls = || targets.iter().map(|target| target.save_call_count()).sum::<usize>();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
while total_calls() != LIMIT {
|
||||
tokio::task::yield_now().await;
|
||||
@@ -1122,20 +1007,19 @@ mod tests {
|
||||
});
|
||||
let direct_entered = Arc::new(Notify::new());
|
||||
let direct_release = Arc::new(Notify::new());
|
||||
let direct =
|
||||
TestTarget::new("direct", "webhook", true).with_blocked_first_save(direct_entered.clone(), direct_release.clone());
|
||||
let direct = MockTarget::new("direct", "webhook").with_first_save_gate(direct_entered.clone(), direct_release.clone());
|
||||
let deferred_entered = Arc::new(Notify::new());
|
||||
let deferred_release = Arc::new(Notify::new());
|
||||
let queue_dir = tempfile::tempdir().expect("queue tempdir should be created");
|
||||
let deferred = TestTarget::new("deferred", "webhook", true)
|
||||
.with_blocked_first_save(deferred_entered.clone(), deferred_release.clone())
|
||||
.with_store(QueueStore::new(queue_dir.path(), 16, ".event"));
|
||||
let deferred = MockTarget::new("deferred", "webhook")
|
||||
.with_first_save_gate(deferred_entered.clone(), deferred_release.clone())
|
||||
.with_store(Arc::new(QueueStore::new(queue_dir.path(), 16, ".event")));
|
||||
|
||||
let mut direct_rules = RulesMap::new();
|
||||
direct_rules.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), direct.id.clone());
|
||||
direct_rules.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), direct.target_id());
|
||||
rule_engine.set_bucket_rules("direct-bucket", direct_rules).await;
|
||||
let mut deferred_rules = RulesMap::new();
|
||||
deferred_rules.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), deferred.id.clone());
|
||||
deferred_rules.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), deferred.target_id());
|
||||
rule_engine.set_bucket_rules("deferred-bucket", deferred_rules).await;
|
||||
{
|
||||
let target_list = notifier.target_list();
|
||||
@@ -1198,12 +1082,12 @@ mod tests {
|
||||
let rule_engine = NotifyRuleEngine::new();
|
||||
let notifier = EventNotifier::new(Arc::new(NotificationMetrics::new()), rule_engine.clone());
|
||||
|
||||
let enabled_target = TestTarget::new("enabled-target", "webhook", true);
|
||||
let disabled_target = TestTarget::new("disabled-target", "webhook", false);
|
||||
let enabled_target = MockTarget::new("enabled-target", "webhook");
|
||||
let disabled_target = MockTarget::new("disabled-target", "webhook").disabled();
|
||||
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), enabled_target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), disabled_target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), enabled_target.target_id());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), disabled_target.target_id());
|
||||
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier
|
||||
@@ -1222,17 +1106,17 @@ mod tests {
|
||||
let event = Arc::new(Event::new_test_event("bucket", "object", EventName::ObjectCreatedPut));
|
||||
notifier.send(event).await;
|
||||
|
||||
assert_eq!(enabled_target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(disabled_target.save_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(enabled_target.save_call_count(), 1);
|
||||
assert_eq!(disabled_target.save_call_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_event_respects_prefix_suffix_filters() {
|
||||
let rule_engine = NotifyRuleEngine::new();
|
||||
let notifier = EventNotifier::new(Arc::new(NotificationMetrics::new()), rule_engine.clone());
|
||||
let target = TestTarget::new("filtered-target", "webhook", true);
|
||||
let target = MockTarget::new("filtered-target", "webhook");
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "uploads/*.csv".to_string(), target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "uploads/*.csv".to_string(), target.target_id());
|
||||
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier.target_list().write().await.add(Arc::new(target.clone())).unwrap();
|
||||
@@ -1248,7 +1132,7 @@ mod tests {
|
||||
)))
|
||||
.await;
|
||||
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(target.save_call_count(), 0);
|
||||
|
||||
notifier
|
||||
.send(Arc::new(Event::new_test_event(
|
||||
@@ -1258,72 +1142,18 @@ mod tests {
|
||||
)))
|
||||
.await;
|
||||
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.save_call_count(), 1);
|
||||
}
|
||||
|
||||
/// A store-backed (deferred) target. `save` only enqueues to the store, so
|
||||
/// the actual delivery happens later in the replay worker.
|
||||
#[derive(Clone)]
|
||||
struct DeferredTestTarget {
|
||||
id: TargetID,
|
||||
save_calls: Arc<AtomicUsize>,
|
||||
store: QueueStore<QueuedPayload>,
|
||||
}
|
||||
|
||||
impl DeferredTestTarget {
|
||||
fn new(id: &str, name: &str) -> Self {
|
||||
Self {
|
||||
id: TargetID::new(id.to_string(), name.to_string()),
|
||||
save_calls: Arc::new(AtomicUsize::new(0)),
|
||||
// The store is never actually written to here: `save` below only bumps a
|
||||
// counter. It just has to exist so the notifier treats this target as
|
||||
// store-backed (deferred delivery), exercising the deferred counting path.
|
||||
store: QueueStore::new(std::env::temp_dir().join("rustfs-notify-979-noop-store"), 0, ""),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<E> Target<E> for DeferredTestTarget
|
||||
where
|
||||
E: rustfs_targets::PluginEvent,
|
||||
{
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<E>>) -> Result<(), TargetError> {
|
||||
self.save_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
Some(&self.store)
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<E> + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
true
|
||||
}
|
||||
/// Builds a store-backed (deferred) mock target. `save` only bumps the mock's counter, so the
|
||||
/// attached store is never written to: it just has to exist so the notifier treats the target
|
||||
/// as store-backed (deferred delivery), exercising the deferred counting path.
|
||||
fn deferred_test_target(id: &str, name: &str) -> MockTarget {
|
||||
MockTarget::new(id, name).with_store(Arc::new(QueueStore::new(
|
||||
std::env::temp_dir().join("rustfs-notify-979-noop-store"),
|
||||
0,
|
||||
"",
|
||||
)))
|
||||
}
|
||||
|
||||
/// Regression test for backlog#979 (a): dispatching to a store-backed
|
||||
@@ -1338,9 +1168,9 @@ mod tests {
|
||||
let rule_engine = NotifyRuleEngine::new();
|
||||
let notifier = EventNotifier::new(metrics.clone(), rule_engine.clone());
|
||||
|
||||
let target = DeferredTestTarget::new("deferred-target", "webhook");
|
||||
let target = deferred_test_target("deferred-target", "webhook");
|
||||
let mut rules_map = RulesMap::new();
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.id.clone());
|
||||
rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target.target_id());
|
||||
rule_engine.set_bucket_rules("bucket", rules_map).await;
|
||||
notifier.target_list().write().await.add(Arc::new(target.clone())).unwrap();
|
||||
|
||||
@@ -1349,7 +1179,7 @@ mod tests {
|
||||
.send(Arc::new(Event::new_test_event("bucket", "object", EventName::ObjectCreatedPut)))
|
||||
.await;
|
||||
|
||||
assert_eq!(target.save_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(target.save_call_count(), 1);
|
||||
assert_eq!(
|
||||
metrics.processing_count(),
|
||||
1,
|
||||
@@ -1394,87 +1224,20 @@ mod tests {
|
||||
let rule_engine = NotifyRuleEngine::new();
|
||||
let notifier = EventNotifier::new(Arc::new(NotificationMetrics::new()), rule_engine);
|
||||
|
||||
let old_target = ClosableTestTarget::new("old", "webhook");
|
||||
let old_target = MockTarget::new("old", "webhook");
|
||||
notifier
|
||||
.init_bucket_targets_shared(vec![Arc::new(old_target.clone()) as SharedTarget<Event>])
|
||||
.await
|
||||
.expect("initial install should succeed");
|
||||
assert_eq!(old_target.close_calls.load(Ordering::SeqCst), 0, "target must not close on first install");
|
||||
assert_eq!(old_target.close_call_count(), 0, "target must not close on first install");
|
||||
|
||||
let new_target = ClosableTestTarget::new("new", "webhook");
|
||||
let new_target = MockTarget::new("new", "webhook");
|
||||
notifier
|
||||
.init_bucket_targets_shared(vec![Arc::new(new_target.clone()) as SharedTarget<Event>])
|
||||
.await
|
||||
.expect("replacement install should succeed");
|
||||
|
||||
assert_eq!(
|
||||
old_target.close_calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"the replaced target must be closed exactly once"
|
||||
);
|
||||
assert_eq!(
|
||||
new_target.close_calls.load(Ordering::SeqCst),
|
||||
0,
|
||||
"the freshly installed target must stay open"
|
||||
);
|
||||
}
|
||||
|
||||
/// A target that records `close()` invocations, for lifecycle assertions.
|
||||
#[derive(Clone)]
|
||||
struct ClosableTestTarget {
|
||||
id: TargetID,
|
||||
close_calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl ClosableTestTarget {
|
||||
fn new(id: &str, name: &str) -> Self {
|
||||
Self {
|
||||
id: TargetID::new(id.to_string(), name.to_string()),
|
||||
close_calls: Arc::new(AtomicUsize::new(0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<E> Target<E> for ClosableTestTarget
|
||||
where
|
||||
E: rustfs_targets::PluginEvent,
|
||||
{
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<E>>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
self.close_calls.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
None
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<E> + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
true
|
||||
}
|
||||
assert_eq!(old_target.close_call_count(), 1, "the replaced target must be closed exactly once");
|
||||
assert_eq!(new_target.close_call_count(), 0, "the freshly installed target must stay open");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -409,108 +409,14 @@ mod tests {
|
||||
Event, integration::NotificationMetrics, notifier::EventNotifier, rule_engine::NotifyRuleEngine,
|
||||
runtime_view::NotifyRuntimeView,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use rustfs_targets::arn::TargetID;
|
||||
use rustfs_targets::store::{Key, QueueStore, Store};
|
||||
use rustfs_targets::target::{EntityTarget, QueuedPayload, QueuedPayloadMeta};
|
||||
use rustfs_targets::{ReplayWorkerManager, SharedTarget, StoreError, Target, TargetError};
|
||||
use rustfs_targets::store::QueueStore;
|
||||
use rustfs_targets::target::QueuedPayload;
|
||||
use rustfs_targets::testkit::MockTarget;
|
||||
use rustfs_targets::{ReplayWorkerManager, SharedTarget, TargetError};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio::sync::{Notify, RwLock, Semaphore};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestTarget {
|
||||
close_entered: Option<Arc<Notify>>,
|
||||
close_error: bool,
|
||||
close_release: Option<Arc<Notify>>,
|
||||
close_calls: Arc<AtomicUsize>,
|
||||
id: TargetID,
|
||||
store: Option<QueueStore<QueuedPayload>>,
|
||||
}
|
||||
|
||||
impl TestTarget {
|
||||
fn new(id: &str, name: &str) -> Self {
|
||||
Self {
|
||||
close_entered: None,
|
||||
close_error: false,
|
||||
close_release: None,
|
||||
close_calls: Arc::new(AtomicUsize::new(0)),
|
||||
id: TargetID::new(id.to_string(), name.to_string()),
|
||||
store: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_blocking_close(mut self, entered: Arc<Notify>, release: Arc<Notify>) -> Self {
|
||||
self.close_entered = Some(entered);
|
||||
self.close_release = Some(release);
|
||||
self
|
||||
}
|
||||
|
||||
fn with_close_error(mut self) -> Self {
|
||||
self.close_error = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_store(mut self, store: QueueStore<QueuedPayload>) -> Self {
|
||||
self.store = Some(store);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<E> Target<E> for TestTarget
|
||||
where
|
||||
E: rustfs_targets::PluginEvent,
|
||||
{
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<E>>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
self.close_calls.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(entered) = &self.close_entered {
|
||||
entered.notify_one();
|
||||
}
|
||||
if let Some(release) = &self.close_release {
|
||||
release.notified().await;
|
||||
}
|
||||
if self.close_error {
|
||||
return Err(TargetError::Storage("forced close failure".to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
self.store
|
||||
.as_ref()
|
||||
.map(|store| store as &(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync))
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<E> + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn build_facade() -> (NotifyRuntimeFacade, Arc<EventNotifier>, Arc<RwLock<ReplayWorkerManager>>) {
|
||||
let metrics = Arc::new(NotificationMetrics::new());
|
||||
let notifier = Arc::new(EventNotifier::new(metrics.clone(), NotifyRuleEngine::new()));
|
||||
@@ -555,8 +461,8 @@ mod tests {
|
||||
async fn compatibility_activation_stays_dormant_until_ordered_replace() {
|
||||
let (facade, _, replay_workers) = build_facade();
|
||||
let queue_root = tempfile::tempdir().expect("queue root");
|
||||
let store = QueueStore::new_with_compression(queue_root.path(), 16, ".event", false);
|
||||
let target = TestTarget::new("primary", "webhook").with_store(store);
|
||||
let store = QueueStore::<QueuedPayload>::new_with_compression(queue_root.path(), 16, ".event", false);
|
||||
let target = MockTarget::new("primary", "webhook").with_store(Arc::new(store));
|
||||
|
||||
let activation = facade.activate_targets_with_replay(vec![Box::new(target)]).await;
|
||||
assert_eq!(activation.targets.len(), 1);
|
||||
@@ -574,7 +480,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn runtime_facade_replace_targets_commits_runtime_state() {
|
||||
let (facade, notifier, replay_workers) = build_facade();
|
||||
let target = TestTarget::new("primary", "webhook");
|
||||
let target = MockTarget::new("primary", "webhook");
|
||||
let activation = rustfs_targets::RuntimeActivation {
|
||||
replay_workers: ReplayWorkerManager::new(),
|
||||
targets: vec![Arc::new(target) as SharedTarget<Event>],
|
||||
@@ -594,9 +500,9 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn runtime_queries_do_not_wait_for_target_close() {
|
||||
let (facade, notifier, replay_workers) = build_facade();
|
||||
let close_entered = Arc::new(Notify::new());
|
||||
let close_release = Arc::new(Notify::new());
|
||||
let target = TestTarget::new("primary", "webhook").with_blocking_close(close_entered.clone(), close_release.clone());
|
||||
let target = MockTarget::new("primary", "webhook");
|
||||
target.set_block_on_close(true);
|
||||
let observer = target.clone();
|
||||
facade
|
||||
.replace_targets(rustfs_targets::RuntimeActivation {
|
||||
replay_workers: ReplayWorkerManager::new(),
|
||||
@@ -609,12 +515,12 @@ mod tests {
|
||||
let facade = facade.clone();
|
||||
async move { facade.shutdown_checked().await }
|
||||
});
|
||||
close_entered.notified().await;
|
||||
observer.close_started().notified().await;
|
||||
|
||||
let target_list = notifier.target_list();
|
||||
assert!(target_list.try_read().is_ok(), "target list lock must not be held during close");
|
||||
assert!(replay_workers.try_read().is_ok(), "replay manager lock must not be held during close");
|
||||
close_release.notify_one();
|
||||
observer.close_gate().add_permits(1);
|
||||
shutdown
|
||||
.await
|
||||
.expect("shutdown task should not panic")
|
||||
@@ -664,7 +570,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn shutdown_returns_close_error_after_detaching_runtime() {
|
||||
let (facade, notifier, replay_workers) = build_facade();
|
||||
let target = TestTarget::new("primary", "webhook").with_close_error();
|
||||
let target = MockTarget::new("primary", "webhook").with_close_failures(usize::MAX);
|
||||
facade
|
||||
.replace_targets(rustfs_targets::RuntimeActivation {
|
||||
replay_workers: ReplayWorkerManager::new(),
|
||||
@@ -686,9 +592,10 @@ mod tests {
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn shutdown_bounds_a_target_that_never_closes() {
|
||||
let (facade, notifier, replay_workers) = build_facade();
|
||||
let close_entered = Arc::new(Notify::new());
|
||||
let never_release = Arc::new(Notify::new());
|
||||
let target = TestTarget::new("primary", "webhook").with_blocking_close(close_entered.clone(), never_release);
|
||||
// The close gate never receives a permit, so this target's close blocks forever.
|
||||
let target = MockTarget::new("primary", "webhook");
|
||||
target.set_block_on_close(true);
|
||||
let observer = target.clone();
|
||||
facade
|
||||
.replace_targets(rustfs_targets::RuntimeActivation {
|
||||
replay_workers: ReplayWorkerManager::new(),
|
||||
@@ -701,7 +608,7 @@ mod tests {
|
||||
let facade = facade.clone();
|
||||
async move { facade.shutdown_checked().await }
|
||||
});
|
||||
close_entered.notified().await;
|
||||
observer.close_started().notified().await;
|
||||
tokio::time::advance(super::TARGET_CLOSE_TIMEOUT).await;
|
||||
|
||||
let err = shutdown
|
||||
|
||||
@@ -76,128 +76,13 @@ impl NotifyRuntimeView {
|
||||
mod tests {
|
||||
use super::NotifyRuntimeView;
|
||||
use crate::{Event, notifier::TargetList};
|
||||
use async_trait::async_trait;
|
||||
use rustfs_targets::arn::TargetID;
|
||||
use rustfs_targets::store::{Key, Store};
|
||||
use rustfs_targets::target::{EntityTarget, QueuedPayload, QueuedPayloadMeta, TargetDeliverySnapshot};
|
||||
use rustfs_targets::{ReplayWorkerManager, StoreError, Target, TargetError};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
use rustfs_targets::target::TargetDeliverySnapshot;
|
||||
use rustfs_targets::testkit::MockTarget;
|
||||
use rustfs_targets::{ReplayWorkerManager, Target};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Notify, RwLock};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestTarget {
|
||||
active: bool,
|
||||
enabled: bool,
|
||||
failed_messages: Arc<AtomicU64>,
|
||||
failed_store_length: u64,
|
||||
id: TargetID,
|
||||
health_started: Option<Arc<Notify>>,
|
||||
health_release: Option<Arc<Notify>>,
|
||||
total_messages: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl TestTarget {
|
||||
fn new(id: &str, name: &str) -> Self {
|
||||
Self {
|
||||
active: true,
|
||||
enabled: true,
|
||||
failed_messages: Arc::new(AtomicU64::new(0)),
|
||||
failed_store_length: 0,
|
||||
id: TargetID::new(id.to_string(), name.to_string()),
|
||||
health_started: None,
|
||||
health_release: None,
|
||||
total_messages: Arc::new(AtomicU64::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_active(mut self, active: bool) -> Self {
|
||||
self.active = active;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_failed_store_length(mut self, failed_store_length: u64) -> Self {
|
||||
self.failed_store_length = failed_store_length;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_health_gate(mut self, started: Arc<Notify>, release: Arc<Notify>) -> Self {
|
||||
self.health_started = Some(started);
|
||||
self.health_release = Some(release);
|
||||
self
|
||||
}
|
||||
|
||||
fn record_successes(&self, count: u64) {
|
||||
self.total_messages.store(count, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn record_failures(&self, count: u64) {
|
||||
self.failed_messages.store(count, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<E> Target<E> for TestTarget
|
||||
where
|
||||
E: rustfs_targets::PluginEvent,
|
||||
{
|
||||
fn id(&self) -> TargetID {
|
||||
self.id.clone()
|
||||
}
|
||||
|
||||
async fn is_active(&self) -> Result<bool, TargetError> {
|
||||
if let (Some(started), Some(release)) = (&self.health_started, &self.health_release) {
|
||||
started.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
Ok(self.active)
|
||||
}
|
||||
|
||||
async fn save(&self, _event: Arc<EntityTarget<E>>) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_raw_from_store(&self, _key: Key, _body: Vec<u8>, _meta: QueuedPayloadMeta) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self) -> Option<&(dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync)> {
|
||||
None
|
||||
}
|
||||
|
||||
fn clone_dyn(&self) -> Box<dyn Target<E> + Send + Sync> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
async fn init(&self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_enabled(&self) -> bool {
|
||||
self.enabled
|
||||
}
|
||||
|
||||
fn delivery_snapshot(&self) -> TargetDeliverySnapshot {
|
||||
TargetDeliverySnapshot {
|
||||
failed_messages: self.failed_messages.load(Ordering::Relaxed),
|
||||
failed_store_length: self.failed_store_length,
|
||||
queue_length: 0,
|
||||
total_messages: self.total_messages.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_view_reports_empty_runtime_queries() {
|
||||
let runtime_view = NotifyRuntimeView::new(
|
||||
@@ -230,12 +115,22 @@ mod tests {
|
||||
let target_list = Arc::new(RwLock::new(TargetList::new()));
|
||||
let replay_workers = Arc::new(RwLock::new(ReplayWorkerManager::new()));
|
||||
|
||||
let online = Arc::new(TestTarget::new("primary", "webhook").with_failed_store_length(7));
|
||||
online.record_successes(3);
|
||||
online.record_failures(1);
|
||||
let online = Arc::new(MockTarget::new("primary", "webhook").with_delivery_snapshot(TargetDeliverySnapshot {
|
||||
failed_messages: 1,
|
||||
failed_store_length: 7,
|
||||
queue_length: 0,
|
||||
total_messages: 3,
|
||||
}));
|
||||
|
||||
let disabled = Arc::new(TestTarget::new("backup", "mqtt").with_enabled(false).with_active(false));
|
||||
disabled.record_successes(2);
|
||||
let disabled = Arc::new(
|
||||
MockTarget::new("backup", "mqtt")
|
||||
.disabled()
|
||||
.with_active(false)
|
||||
.with_delivery_snapshot(TargetDeliverySnapshot {
|
||||
total_messages: 2,
|
||||
..TargetDeliverySnapshot::default()
|
||||
}),
|
||||
);
|
||||
|
||||
{
|
||||
let mut targets = target_list.write().await;
|
||||
@@ -287,13 +182,13 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn health_probe_does_not_hold_the_target_list_read_lock() {
|
||||
let target_list = Arc::new(RwLock::new(TargetList::new()));
|
||||
let started = Arc::new(Notify::new());
|
||||
let release = Arc::new(Notify::new());
|
||||
let target = Arc::new(TestTarget::new("blocked", "webhook").with_health_gate(started.clone(), release.clone()));
|
||||
let target = MockTarget::new("blocked", "webhook").with_health_gate(release.clone());
|
||||
let started = target.health_started();
|
||||
target_list
|
||||
.write()
|
||||
.await
|
||||
.add(target as Arc<dyn Target<Event> + Send + Sync>)
|
||||
.add(Arc::new(target) as Arc<dyn Target<Event> + Send + Sync>)
|
||||
.expect("test target should be added");
|
||||
let runtime_view = NotifyRuntimeView::new(target_list.clone(), Arc::new(RwLock::new(ReplayWorkerManager::new())));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user