rustfs-targets 1.0.0

Notification target abstraction and implementations for RustFS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{
    OpenedActivation, PrepareTargetResult, PreparedActivation, ReplayEvent, ReplayWorkerManager, RuntimeActivation,
    RuntimeStatusSnapshot, RuntimeTargetHealthSnapshot, TargetActivationFailure, TargetRuntimeManager, prepare_target,
    start_replay_worker,
};
use crate::plugin::PluginEvent;
use crate::{SharedTarget, Target, TargetError};
use async_trait::async_trait;
use rayon::prelude::*;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;

type ReplayHook<E> = Arc<dyn Fn(ReplayEvent<E>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
type ReplayStartObserver = Arc<dyn Fn(&str, bool) + Send + Sync>;

const MAX_PARALLEL_STORE_OPENS: usize = 4;

static STORE_OPEN_POOL: LazyLock<Result<rayon::ThreadPool, rayon::ThreadPoolBuildError>> = LazyLock::new(|| {
    rayon::ThreadPoolBuilder::new()
        .num_threads(MAX_PARALLEL_STORE_OPENS)
        .thread_name(|index| format!("rustfs-target-store-open-{index}"))
        .build()
});

enum StoreOpenOutcome<E>
where
    E: PluginEvent,
{
    Accepted(SharedTarget<E>),
    Rejected { panicked: bool, target: SharedTarget<E> },
}

fn open_target_store<E>(target: SharedTarget<E>) -> StoreOpenOutcome<E>
where
    E: PluginEvent,
{
    match catch_unwind(AssertUnwindSafe(|| target.store().map(|store| store.open()))) {
        Ok(None | Some(Ok(()))) => StoreOpenOutcome::Accepted(target),
        Ok(Some(Err(_))) => StoreOpenOutcome::Rejected { panicked: false, target },
        Err(_) => StoreOpenOutcome::Rejected { panicked: true, target },
    }
}

/// Shared runtime contract for target plugins.
#[async_trait]
pub trait PluginRuntimeAdapter<E>: Send + Sync
where
    E: PluginEvent,
{
    async fn activate_with_replay(&self, targets: Vec<Box<dyn Target<E> + Send + Sync>>) -> RuntimeActivation<E>;

    async fn replace_runtime_targets(
        &self,
        runtime: &mut TargetRuntimeManager<E>,
        replay_workers: &mut ReplayWorkerManager,
        activation: RuntimeActivation<E>,
    ) -> Result<(), TargetError>;

    async fn stop_replay_workers(&self, replay_workers: &mut ReplayWorkerManager);

    fn snapshot_runtime_status(
        &self,
        runtime: &TargetRuntimeManager<E>,
        replay_workers: &ReplayWorkerManager,
    ) -> RuntimeStatusSnapshot;

    async fn snapshot_runtime_health(&self, runtime: &TargetRuntimeManager<E>) -> Vec<RuntimeTargetHealthSnapshot>;

    async fn shutdown(
        &self,
        runtime: &mut TargetRuntimeManager<E>,
        replay_workers: &mut ReplayWorkerManager,
    ) -> Result<(), TargetError>;
}

/// Built-in in-process runtime adapter that preserves the current replay and
/// activation behavior while presenting a stable runtime contract to callers.
#[derive(Clone)]
pub struct BuiltinPluginRuntimeAdapter<E>
where
    E: PluginEvent,
{
    replay_hook: ReplayHook<E>,
    replay_start_observer: ReplayStartObserver,
    replay_semaphore: Option<Arc<Semaphore>>,
    batch_timeout: Duration,
    idle_sleep: Duration,
    stop_log_prefix: Arc<str>,
}

impl<E> BuiltinPluginRuntimeAdapter<E>
where
    E: PluginEvent,
{
    pub fn new(
        replay_hook: ReplayHook<E>,
        replay_start_observer: ReplayStartObserver,
        replay_semaphore: Option<Arc<Semaphore>>,
        batch_timeout: Duration,
        idle_sleep: Duration,
        stop_log_prefix: impl Into<Arc<str>>,
    ) -> Self {
        Self {
            replay_hook,
            replay_start_observer,
            replay_semaphore,
            batch_timeout,
            idle_sleep,
            stop_log_prefix: stop_log_prefix.into(),
        }
    }

    pub async fn prepare_targets(&self, targets: Vec<Box<dyn Target<E> + Send + Sync>>) -> PreparedActivation<E> {
        self.prepare_targets_inner(targets, None).await
    }

    pub async fn prepare_targets_cancellable(
        &self,
        targets: Vec<Box<dyn Target<E> + Send + Sync>>,
        cancellation: &CancellationToken,
    ) -> PreparedActivation<E> {
        self.prepare_targets_inner(targets, Some(cancellation)).await
    }

    async fn prepare_targets_inner(
        &self,
        targets: Vec<Box<dyn Target<E> + Send + Sync>>,
        cancellation: Option<&CancellationToken>,
    ) -> PreparedActivation<E> {
        let mut prepared = Vec::with_capacity(targets.len());
        let mut failures = Vec::new();
        let mut rejected_targets = Vec::new();
        let mut targets = targets.into_iter();
        while let Some(target) = targets.next() {
            match prepare_target(target, cancellation).await {
                PrepareTargetResult::Ready(target) => prepared.push(target),
                PrepareTargetResult::Degraded { error, target } => {
                    drop(error);
                    tracing::warn!(
                        target_id = %target.id(),
                        reason = "initialization_failed",
                        "Target initialization failed during lifecycle preparation"
                    );
                    failures.push(TargetActivationFailure {
                        detail: format!("{}: initialization failed", target.id()),
                    });
                    prepared.push(target);
                }
                PrepareTargetResult::Failed { error, target } => {
                    drop(error);
                    let target_id = target.id().to_string();
                    tracing::warn!(
                        target_id,
                        reason = "initialization_failed",
                        "Target initialization failed during lifecycle preparation"
                    );
                    failures.push(TargetActivationFailure {
                        detail: format!("{target_id}: initialization failed"),
                    });
                    rejected_targets.push(Arc::from(target));
                }
                PrepareTargetResult::Cancelled(target) => {
                    prepared.push(Arc::from(target));
                    prepared.extend(targets.map(Arc::from));
                    break;
                }
            }
        }
        PreparedActivation {
            failures,
            rejected_targets,
            targets: prepared,
        }
    }

    /// Opens queue stores only after the previous runtime generation has been
    /// quiesced. Targets whose stores cannot be opened retain the established
    /// fault-isolation behavior and are returned for lock-free shutdown.
    pub fn open_prepared_stores(&self, prepared: PreparedActivation<E>) -> (OpenedActivation<E>, PreparedActivation<E>) {
        let mut accepted = Vec::with_capacity(prepared.targets.len());
        let mut failures = prepared.failures;
        let mut rejected = prepared.rejected_targets;
        let outcomes = if prepared.targets.len() < 2 {
            prepared.targets.into_iter().map(open_target_store).collect()
        } else {
            match STORE_OPEN_POOL.as_ref() {
                // Vec's indexed parallel iterator preserves configuration
                // order in collect, keeping failure summaries deterministic.
                Ok(pool) => pool.install(|| prepared.targets.into_par_iter().map(open_target_store).collect::<Vec<_>>()),
                Err(err) => {
                    tracing::warn!(error = %err, "Failed to create target store open pool; opening stores serially");
                    prepared.targets.into_iter().map(open_target_store).collect()
                }
            }
        };
        for outcome in outcomes {
            match outcome {
                StoreOpenOutcome::Accepted(target) => accepted.push(target),
                StoreOpenOutcome::Rejected { panicked, target } => {
                    if panicked {
                        tracing::error!(
                            target_id = %target.id(),
                            reason = "store_open_panicked",
                            "Target queue store panicked while opening during runtime handoff"
                        );
                    } else {
                        tracing::error!(
                            target_id = %target.id(),
                            reason = "store_open_failed",
                            "Failed to open target queue store during runtime handoff"
                        );
                    }
                    failures.push(TargetActivationFailure {
                        detail: format!("{}: queue store open failed", target.id()),
                    });
                    rejected.push(target);
                }
            }
        }
        (
            OpenedActivation { targets: accepted },
            PreparedActivation {
                failures,
                rejected_targets: rejected,
                targets: Vec::new(),
            },
        )
    }

    pub fn try_activate_prepared(&self, opened: OpenedActivation<E>) -> (RuntimeActivation<E>, PreparedActivation<E>) {
        let mut replay_workers = ReplayWorkerManager::new();
        let mut accepted = Vec::with_capacity(opened.targets.len());
        let mut failures = Vec::new();
        let mut rejected_targets = Vec::new();
        for target in opened.targets {
            let target_id = target.id().to_string();
            let replay = catch_unwind(AssertUnwindSafe(|| {
                target.store().filter(|_| target.is_enabled()).map(|store| {
                    start_replay_worker(
                        store.boxed_clone(),
                        Arc::clone(&target),
                        Arc::clone(&self.replay_hook),
                        self.replay_semaphore.clone(),
                        self.batch_timeout,
                        self.idle_sleep,
                    )
                })
            }));
            let replay = match replay {
                Ok(replay) => replay,
                Err(_) => {
                    tracing::error!(
                        target_id,
                        reason = "replay_activation_panicked",
                        "Target replay activation panicked during runtime handoff"
                    );
                    failures.push(TargetActivationFailure {
                        detail: format!("{target_id}: replay activation failed"),
                    });
                    rejected_targets.push(target);
                    continue;
                }
            };
            (self.replay_start_observer)(&target_id, replay.is_some());
            if let Some((cancel_tx, join)) = replay {
                replay_workers.insert_with_handle(target_id, cancel_tx, join);
            }
            accepted.push(target);
        }

        (
            RuntimeActivation {
                replay_workers,
                targets: accepted,
            },
            PreparedActivation {
                failures,
                rejected_targets,
                targets: Vec::new(),
            },
        )
    }

    #[doc(hidden)]
    pub async fn prepare_dormant_compat_activation(
        &self,
        targets: Vec<Box<dyn Target<E> + Send + Sync>>,
    ) -> RuntimeActivation<E> {
        let PreparedActivation {
            failures,
            rejected_targets,
            targets,
        } = self.prepare_targets(targets).await;
        let rejected = PreparedActivation {
            failures,
            rejected_targets,
            targets: Vec::new(),
        };
        if let Err(err) = self.close_prepared(rejected).await {
            tracing::warn!(error = %err, "Failed to close targets rejected while preparing compatibility activation");
        }
        RuntimeActivation {
            replay_workers: ReplayWorkerManager::new(),
            targets,
        }
    }

    #[doc(hidden)]
    pub fn start_dormant_compat_activation(
        &self,
        activation: RuntimeActivation<E>,
    ) -> (RuntimeActivation<E>, PreparedActivation<E>, PreparedActivation<E>) {
        let prepared = PreparedActivation {
            failures: Vec::new(),
            rejected_targets: Vec::new(),
            targets: activation.targets,
        };
        let (opened, open_rejected) = self.open_prepared_stores(prepared);
        let (activation, activation_rejected) = self.try_activate_prepared(opened);
        (activation, open_rejected, activation_rejected)
    }

    #[doc(hidden)]
    pub async fn close_compat_activation(&self, mut activation: RuntimeActivation<E>) -> Result<(), TargetError> {
        let mut runtime = TargetRuntimeManager::new();
        for target in activation.targets {
            runtime.add_arc(target);
        }
        self.shutdown(&mut runtime, &mut activation.replay_workers).await
    }

    pub async fn close_prepared(&self, prepared: PreparedActivation<E>) -> Result<(), TargetError> {
        let mut runtime = TargetRuntimeManager::new();
        for target in prepared.targets.into_iter().chain(prepared.rejected_targets) {
            runtime.add_arc(target);
        }
        let mut replay_workers = ReplayWorkerManager::new();
        self.shutdown(&mut runtime, &mut replay_workers).await
    }
}

#[async_trait]
impl<E> PluginRuntimeAdapter<E> for BuiltinPluginRuntimeAdapter<E>
where
    E: PluginEvent,
{
    async fn activate_with_replay(&self, targets: Vec<Box<dyn Target<E> + Send + Sync>>) -> RuntimeActivation<E> {
        let prepared = self.prepare_targets(targets).await;
        let (opened, rejected) = self.open_prepared_stores(prepared);
        if let Err(err) = self.close_prepared(rejected).await {
            tracing::warn!(error = %err, "Failed to close targets whose queue stores could not be opened");
        }
        let (activation, rejected) = self.try_activate_prepared(opened);
        if let Err(err) = self.close_prepared(rejected).await {
            tracing::warn!(error = %err, "Failed to close targets rejected during replay activation");
        }
        activation
    }

    async fn replace_runtime_targets(
        &self,
        runtime: &mut TargetRuntimeManager<E>,
        replay_workers: &mut ReplayWorkerManager,
        activation: RuntimeActivation<E>,
    ) -> Result<(), TargetError> {
        // Stop (and join) the old replay workers before installing the new set so
        // no two workers ever drain the same store concurrently, then close the
        // old targets. A close failure during reload is logged but does not abort
        // the reload — the new configuration must still take effect.
        self.stop_replay_workers(replay_workers).await;
        let close_errors = runtime.clear_and_close().await;
        if !close_errors.is_empty() {
            tracing::warn!(failed_targets = close_errors.len(), "Some targets failed to close during runtime reload");
        }

        for target in activation.targets {
            runtime.add_arc(target);
        }

        *replay_workers = activation.replay_workers;
        Ok(())
    }

    async fn stop_replay_workers(&self, replay_workers: &mut ReplayWorkerManager) {
        replay_workers.stop_all(&self.stop_log_prefix).await;
    }

    fn snapshot_runtime_status(
        &self,
        runtime: &TargetRuntimeManager<E>,
        replay_workers: &ReplayWorkerManager,
    ) -> RuntimeStatusSnapshot {
        runtime.status_snapshot(replay_workers)
    }

    async fn snapshot_runtime_health(&self, runtime: &TargetRuntimeManager<E>) -> Vec<RuntimeTargetHealthSnapshot> {
        runtime.health_snapshots().await
    }

    async fn shutdown(
        &self,
        runtime: &mut TargetRuntimeManager<E>,
        replay_workers: &mut ReplayWorkerManager,
    ) -> Result<(), TargetError> {
        // On explicit shutdown, propagate any close/flush failures instead of
        // swallowing them: the runtime is still fully torn down, but the caller
        // learns that a target could not be flushed/closed cleanly.
        self.stop_replay_workers(replay_workers).await;
        let close_errors = runtime.clear_and_close().await;
        if !close_errors.is_empty() {
            let detail = close_errors
                .into_iter()
                .map(|(target_id, _)| target_id)
                .collect::<Vec<_>>()
                .join("; ");
            return Err(TargetError::Storage(format!("Failed to close {detail}")));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{BuiltinPluginRuntimeAdapter, MAX_PARALLEL_STORE_OPENS, PluginRuntimeAdapter};
    use crate::store::{Key, QueueStore, Store};
    use crate::target::QueuedPayload;
    use crate::testkit::MockTarget;
    use crate::{StoreError, Target};
    use std::sync::{Arc, Condvar, Mutex};
    use std::time::Duration;
    use tempfile::tempdir;
    use tokio::sync::Notify;
    use tokio_util::sync::CancellationToken;

    type TestStore = dyn Store<QueuedPayload, Error = StoreError, Key = Key> + Send + Sync;

    type BeforeOpen = Arc<dyn Fn() + Send + Sync>;

    #[derive(Clone)]
    struct TestOpenStore {
        before_clone: BeforeOpen,
        before_open: BeforeOpen,
        store: QueueStore<QueuedPayload>,
    }

    impl Store<QueuedPayload> for TestOpenStore {
        type Error = StoreError;
        type Key = Key;

        fn open(&self) -> Result<(), Self::Error> {
            (self.before_open)();
            self.store.open()
        }

        fn put(&self, item: Arc<QueuedPayload>) -> Result<Self::Key, Self::Error> {
            self.store.put(item)
        }

        fn put_multiple(&self, items: Vec<QueuedPayload>) -> Result<Self::Key, Self::Error> {
            self.store.put_multiple(items)
        }

        fn put_raw(&self, data: &[u8]) -> Result<Self::Key, Self::Error> {
            self.store.put_raw(data)
        }

        fn get(&self, key: &Self::Key) -> Result<QueuedPayload, Self::Error> {
            self.store.get(key)
        }

        fn get_multiple(&self, key: &Self::Key) -> Result<Vec<QueuedPayload>, Self::Error> {
            self.store.get_multiple(key)
        }

        fn get_raw(&self, key: &Self::Key) -> Result<Vec<u8>, Self::Error> {
            self.store.get_raw(key)
        }

        fn del(&self, key: &Self::Key) -> Result<(), Self::Error> {
            self.store.del(key)
        }

        fn delete(&self) -> Result<(), Self::Error> {
            self.store.delete()
        }

        fn list(&self) -> Vec<Self::Key> {
            self.store.list()
        }

        fn len(&self) -> usize {
            self.store.len()
        }

        fn is_empty(&self) -> bool {
            self.store.is_empty()
        }

        fn boxed_clone(&self) -> Box<dyn Store<QueuedPayload, Error = Self::Error, Key = Self::Key> + Send + Sync> {
            (self.before_clone)();
            Box::new(self.clone())
        }
    }

    #[derive(Default)]
    struct StoreOpenGate {
        changed: Condvar,
        state: Mutex<StoreOpenGateState>,
    }

    #[derive(Default)]
    struct StoreOpenGateState {
        active: usize,
        max_active: usize,
        released: bool,
    }

    impl StoreOpenGate {
        fn enter(&self) {
            let mut state = self.state.lock().unwrap_or_else(|err| err.into_inner());
            state.active += 1;
            state.max_active = state.max_active.max(state.active);
            self.changed.notify_all();
            while !state.released {
                state = self.changed.wait(state).unwrap_or_else(|err| err.into_inner());
            }
            state.active -= 1;
        }

        fn wait_for_active(&self, expected: usize, timeout: Duration) -> bool {
            let state = self.state.lock().unwrap_or_else(|err| err.into_inner());
            let (state, _) = self
                .changed
                .wait_timeout_while(state, timeout, |state| state.max_active < expected)
                .unwrap_or_else(|err| err.into_inner());
            state.max_active >= expected
        }

        fn release(&self) {
            let mut state = self.state.lock().unwrap_or_else(|err| err.into_inner());
            state.released = true;
            self.changed.notify_all();
        }

        fn max_active(&self) -> usize {
            self.state.lock().unwrap_or_else(|err| err.into_inner()).max_active
        }
    }

    /// Builds the tempdir-backed, already-opened queue store the store-backed mock targets use.
    /// The tempdir handle is dropped here on purpose, matching the previous in-module mock: these
    /// tests never write through the store, they only need an openable handle.
    fn opened_queue_store() -> Arc<TestStore> {
        let dir = tempdir().expect("tempdir should be created for queue store tests");
        let store = QueueStore::<QueuedPayload>::new(dir.path(), 16, ".queue");
        store.open().expect("queue store should open");
        Arc::new(store)
    }

    fn builtin_adapter() -> BuiltinPluginRuntimeAdapter<String> {
        BuiltinPluginRuntimeAdapter::new(
            Arc::new(|_event| Box::pin(async {})),
            Arc::new(|_target_id, _has_replay| {}),
            None,
            Duration::from_millis(10),
            Duration::from_millis(10),
            "stopping test replay worker",
        )
    }

    #[tokio::test]
    async fn builtin_adapter_handles_empty_target_activation() {
        let adapter = builtin_adapter();
        let activation = adapter.activate_with_replay(Vec::new()).await;

        assert!(activation.targets.is_empty());
        assert!(activation.replay_workers.is_empty());
    }

    #[tokio::test]
    async fn builtin_adapter_skips_non_store_target_when_init_fails() {
        let adapter = builtin_adapter();
        let target = MockTarget::new("primary", "webhook").with_init_failures(usize::MAX);

        let activation = adapter.activate_with_replay(vec![Box::new(target)]).await;

        assert!(activation.targets.is_empty());
        assert!(activation.replay_workers.is_empty());
    }

    #[tokio::test]
    async fn builtin_adapter_keeps_store_backed_target_when_init_fails() {
        let adapter = builtin_adapter();
        let target = MockTarget::new("primary", "webhook")
            .with_init_failures(usize::MAX)
            .with_store(opened_queue_store());

        let activation = adapter.activate_with_replay(vec![Box::new(target)]).await;

        assert_eq!(activation.targets.len(), 1);
        assert_eq!(activation.replay_workers.len(), 1);
    }

    #[tokio::test]
    async fn prepared_store_target_reports_init_failure_without_dropping_queue_runtime() {
        let adapter = builtin_adapter();
        let target = MockTarget::new("primary", "webhook")
            .with_init_failures(usize::MAX)
            .with_store(opened_queue_store());

        let prepared = adapter.prepare_targets(vec![Box::new(target)]).await;
        assert_eq!(prepared.targets.len(), 1);
        assert!(
            prepared
                .failure_summary()
                .is_some_and(|summary| summary.contains("initialization failed") && !summary.contains("forced init failure"))
        );

        let (opened, rejected) = adapter.open_prepared_stores(prepared);
        assert!(rejected.failure_summary().is_some());
        let (mut activation, activation_rejected) = adapter.try_activate_prepared(opened);
        assert!(activation_rejected.failure_summary().is_none());
        assert_eq!(activation.targets.len(), 1);
        assert_eq!(activation.replay_workers.len(), 1);
        activation.replay_workers.stop_all("stop degraded target replay worker").await;
    }

    #[tokio::test]
    async fn cancellable_preparation_returns_current_and_remaining_targets_for_shutdown() {
        let adapter = builtin_adapter();
        let init_entered = Arc::new(Notify::new());
        let first = MockTarget::new("first", "webhook").with_blocking_init(init_entered.clone());
        let first_observer = first.clone();
        let second = MockTarget::new("second", "webhook");
        let second_observer = second.clone();
        let cancellation = CancellationToken::new();
        let prepare_adapter = adapter.clone();
        let prepare_cancellation = cancellation.clone();
        let prepare = tokio::spawn(async move {
            prepare_adapter
                .prepare_targets_cancellable(vec![Box::new(first), Box::new(second)], &prepare_cancellation)
                .await
        });

        init_entered.notified().await;
        cancellation.cancel();
        let prepared = tokio::time::timeout(Duration::from_secs(1), prepare)
            .await
            .expect("cancellation should interrupt target initialization")
            .expect("preparation task should finish");
        assert_eq!(prepared.targets.len(), 2);

        adapter
            .close_prepared(prepared)
            .await
            .expect("cancelled targets should close");
        assert_eq!(first_observer.close_call_count(), 1);
        assert_eq!(second_observer.close_call_count(), 1);
        assert_eq!(second_observer.init_call_count(), 0);
    }

    #[tokio::test]
    async fn prepared_activation_opens_store_before_starting_replay() {
        let adapter = builtin_adapter();
        let dir = tempdir().expect("tempdir should be created");
        let queue_path = dir.path().join("queue");
        let target = MockTarget::new("primary", "webhook").with_store(Arc::new(QueueStore::<QueuedPayload>::new(
            &queue_path,
            16,
            ".queue",
        )));

        let prepared = adapter.prepare_targets(vec![Box::new(target)]).await;
        assert!(!queue_path.exists(), "dormant preparation must not open the queue store");

        let (opened, rejected) = adapter.open_prepared_stores(prepared);
        assert!(rejected.targets.is_empty());
        assert!(queue_path.is_dir(), "handoff must open the queue store before activation");
        let (mut activation, activation_rejected) = adapter.try_activate_prepared(opened);
        assert!(activation_rejected.failure_summary().is_none());
        assert_eq!(activation.replay_workers.len(), 1);
        activation
            .replay_workers
            .stop_all("stop prepared activation test worker")
            .await;
    }

    #[tokio::test]
    async fn activation_closes_a_target_when_its_queue_store_cannot_open() {
        let adapter = builtin_adapter();
        let dir = tempdir().expect("tempdir should be created");
        let invalid_base = dir.path().join("not-a-directory");
        std::fs::write(&invalid_base, b"file").expect("invalid queue base should be created");
        let target = MockTarget::new("primary", "webhook").with_store(Arc::new(QueueStore::<QueuedPayload>::new(
            &invalid_base,
            16,
            ".queue",
        )));
        let observer = target.clone();

        let activation = adapter.activate_with_replay(vec![Box::new(target)]).await;

        assert!(activation.targets.is_empty());
        assert!(activation.replay_workers.is_empty());
        assert_eq!(observer.close_call_count(), 1);
    }

    #[tokio::test]
    async fn prepared_stores_open_with_bounded_parallelism_and_stable_order() {
        const TARGETS: usize = MAX_PARALLEL_STORE_OPENS * 2;

        let adapter = builtin_adapter();
        let dir = tempdir().expect("tempdir should be created");
        let gate = Arc::new(StoreOpenGate::default());
        let mut targets: Vec<Box<dyn Target<String> + Send + Sync>> = Vec::with_capacity(TARGETS);
        let mut expected_ids = Vec::with_capacity(TARGETS);
        for index in 0..TARGETS {
            let open_gate = gate.clone();
            let target = MockTarget::new(&format!("target-{index}"), "webhook").with_store(Arc::new(TestOpenStore {
                before_clone: Arc::new(|| {}),
                before_open: Arc::new(move || open_gate.enter()),
                store: QueueStore::new(dir.path().join(index.to_string()), 16, ".queue"),
            }));
            expected_ids.push(target.target_id().to_string());
            targets.push(Box::new(target));
        }

        let prepared = adapter.prepare_targets(targets).await;
        let open_adapter = adapter.clone();
        let opening = tokio::task::spawn_blocking(move || open_adapter.open_prepared_stores(prepared));
        let wait_gate = gate.clone();
        let reached_bound =
            tokio::task::spawn_blocking(move || wait_gate.wait_for_active(MAX_PARALLEL_STORE_OPENS, Duration::from_secs(30)))
                .await
                .expect("store-open observer should not panic");
        gate.release();
        let (opened, rejected) = opening.await.expect("bounded store opens should not panic");
        let opened_ids = opened
            .targets
            .iter()
            .map(|target| target.id().to_string())
            .collect::<Vec<_>>();

        assert!(reached_bound, "store opens did not use the configured parallelism");
        assert_eq!(gate.max_active(), MAX_PARALLEL_STORE_OPENS);
        assert_eq!(opened_ids, expected_ids, "parallel store opens must preserve configuration order");
        assert!(rejected.targets.is_empty());
        assert!(rejected.failure_summary().is_none());
    }

    #[tokio::test]
    async fn panicking_store_open_rejects_and_closes_only_that_target() {
        let adapter = builtin_adapter();
        let dir = tempdir().expect("tempdir should be created");
        let target = MockTarget::new("panicking", "webhook").with_store(Arc::new(TestOpenStore {
            before_clone: Arc::new(|| {}),
            before_open: Arc::new(|| panic!("forced store open panic: do-not-expose-payload")),
            store: QueueStore::new(dir.path(), 16, ".queue"),
        }));
        let observer = target.clone();

        let prepared = adapter.prepare_targets(vec![Box::new(target)]).await;
        let (opened, rejected) = adapter.open_prepared_stores(prepared);
        let summary = rejected
            .failure_summary()
            .expect("panicking store should report a generic activation failure");
        let (activation, activation_rejected) = adapter.try_activate_prepared(opened);

        assert!(activation.targets.is_empty(), "a target without an open store must not become visible");
        assert!(
            activation.replay_workers.is_empty(),
            "a rejected target must not publish without a replay worker"
        );
        assert!(activation_rejected.failure_summary().is_none());
        assert!(summary.contains("queue store open failed"));
        assert!(!summary.contains("do-not-expose-payload"));
        adapter
            .close_prepared(rejected)
            .await
            .expect("a target rejected after a store panic should close");
        assert_eq!(observer.close_call_count(), 1);
    }

    #[tokio::test]
    async fn panicking_store_clone_cannot_publish_target_without_replay_worker() {
        let adapter = builtin_adapter();
        let dir = tempdir().expect("tempdir should be created");
        let target = MockTarget::new("panicking-clone", "webhook").with_store(Arc::new(TestOpenStore {
            before_clone: Arc::new(|| panic!("forced store clone panic: do-not-expose-payload")),
            before_open: Arc::new(|| {}),
            store: QueueStore::new(dir.path(), 16, ".queue"),
        }));
        let observer = target.clone();

        let prepared = adapter.prepare_targets(vec![Box::new(target)]).await;
        let (opened, open_rejected) = adapter.open_prepared_stores(prepared);
        assert!(open_rejected.failure_summary().is_none());
        let (activation, rejected) = adapter.try_activate_prepared(opened);
        let summary = rejected
            .failure_summary()
            .expect("panicking store clone should report a generic activation failure");

        assert!(activation.targets.is_empty(), "a target without a replay worker must not become visible");
        assert!(activation.replay_workers.is_empty());
        assert!(summary.contains("replay activation failed"));
        assert!(!summary.contains("do-not-expose-payload"));
        adapter
            .close_prepared(rejected)
            .await
            .expect("a target rejected during replay activation should close");
        assert_eq!(observer.close_call_count(), 1);
    }

    #[tokio::test]
    async fn builtin_adapter_shutdown_clears_runtime_and_replay_workers() {
        let adapter = builtin_adapter();
        let target = MockTarget::new("primary", "webhook");
        let observer = target.clone();
        let mut runtime = crate::runtime::TargetRuntimeManager::new();
        let mut replay_workers = crate::runtime::ReplayWorkerManager::new();

        let activation = adapter.activate_with_replay(vec![Box::new(target)]).await;
        adapter
            .replace_runtime_targets(&mut runtime, &mut replay_workers, activation)
            .await
            .expect("replace_runtime_targets should succeed");

        assert_eq!(runtime.len(), 1);
        assert_eq!(replay_workers.len(), 0);

        adapter
            .shutdown(&mut runtime, &mut replay_workers)
            .await
            .expect("shutdown should succeed");

        assert!(runtime.is_empty());
        assert!(replay_workers.is_empty());
        assert_eq!(observer.close_call_count(), 1);
    }
}