etherbird 0.2.2

Supervised asynchronous resources with automatic recovery
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Supervised asynchronous resources with automatic recovery.
//!
//! Implement [`Lifecycle`] and expose a typed client wrapper around [`Supervisor`].
//! Operations run once by default; retries require explicit per-operation opt-in.
//! Lifecycle futures must be cancellation-safe.

pub use async_trait::async_trait;
use std::{any::Any, fmt, future::Future, pin::Pin, sync::Arc, time::Duration};
use std::{
    collections::BTreeMap,
    sync::{
        Mutex,
        atomic::{AtomicBool, AtomicU64, Ordering},
    },
};
use tokio::sync::{mpsc, oneshot, watch};
use tokio::time::{sleep, timeout};
mod pool;
mod queue;
pub use pool::{ManagedResourceProxy, Pool, PoolConfig, QueuedOperation, ResourceLease};
mod proxy;
pub use proxy::{ManagedClientBackend, SupervisedResourceProxy};
pub use queue::{FifoQueue, OperationQueue, PriorityQueue, QueueError};

/// Protocol-specific lifecycle hooks. Resources usually contain their own interior mutability.
///
/// Hooks must yield to the executor and tolerate cancellation by future drop. Creation must
/// release partially allocated resources on cancellation. Connect/setup failures run teardown.
/// Cleanup, disconnect and destroy each get a separate timeout; failure never skips later hooks.
#[async_trait]
pub trait Lifecycle: Send + Sync + 'static {
    type Resource: Send + Sync + 'static;
    type Error: std::error::Error + Send + Sync + 'static;
    async fn create(&self) -> Result<Self::Resource, Self::Error>;
    async fn connect(&self, resource: &Self::Resource) -> Result<(), Self::Error>;
    async fn on_resource_created(&self, _resource: &Self::Resource) -> Result<(), Self::Error> {
        Ok(())
    }
    async fn setup(&self, _resource: &Self::Resource) -> Result<(), Self::Error> {
        Ok(())
    }
    async fn cleanup(&self, _resource: &Self::Resource) -> Result<(), Self::Error> {
        Ok(())
    }
    async fn disconnect(&self, resource: &Self::Resource) -> Result<(), Self::Error>;
    async fn destroy(&self, _resource: &Self::Resource) -> Result<(), Self::Error> {
        Ok(())
    }
    /// Optional connection-loss watch. No watchdog task is spawned when absent.
    fn watch_disconnect(
        &self,
        _resource: Arc<Self::Resource>,
    ) -> Option<LifecycleFuture<Self::Error>> {
        None
    }
    /// Read the transport's live connection indicator. Override alongside `wait_connected`.
    fn is_connected(&self, _resource: &Self::Resource) -> bool {
        true
    }
    /// Wait until the transport becomes connected, checking its indicator before waiting.
    async fn wait_connected(&self, _resource: &Self::Resource) {
        std::future::pending::<()>().await
    }
    /// Terminal errors skip disconnect, but still run cleanup and destroy.
    fn is_terminal(&self, _error: &Self::Error) -> bool {
        false
    }
    fn is_expected(&self, _error: &Self::Error) -> bool {
        false
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResourceState {
    Connecting,
    Connected,
    Recovering,
    Disconnected,
    Stopping,
    Stopped,
}

#[derive(Clone, Debug)]
pub struct Config {
    pub resource_name: String,
    pub create_timeout: Option<Duration>,
    pub created_timeout: Option<Duration>,
    pub connect_timeout: Duration,
    pub setup_timeout: Duration,
    pub cleanup_timeout: Duration,
    pub disconnect_timeout: Duration,
    pub destroy_timeout: Option<Duration>,
    pub retry_delay: Duration,
    pub max_retry_delay: Duration,
}
impl Default for Config {
    fn default() -> Self {
        Self {
            resource_name: "Resource".into(),
            create_timeout: None,
            created_timeout: None,
            connect_timeout: Duration::from_secs(20),
            setup_timeout: Duration::from_secs(10),
            cleanup_timeout: Duration::from_secs(10),
            disconnect_timeout: Duration::from_secs(10),
            destroy_timeout: None,
            retry_delay: Duration::from_secs(5),
            max_retry_delay: Duration::from_secs(300),
        }
    }
}

#[derive(Debug)]
pub enum Error<E> {
    Stopped,
    /// The overall deadline for an explicitly retryable operation elapsed.
    Timeout,
    Operation(E),
    Queue(QueueError),
}
impl<E: fmt::Display> fmt::Display for Error<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stopped => f.write_str("resource supervisor stopped"),
            Self::Timeout => f.write_str("operation retry deadline elapsed"),
            Self::Operation(e) => e.fmt(f),
            Self::Queue(e) => e.fmt(f),
        }
    }
}
impl<E: std::error::Error + 'static> std::error::Error for Error<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Operation(e) => Some(e),
            Self::Stopped | Self::Timeout => None,
            Self::Queue(e) => Some(e),
        }
    }
}

/// Bounds for an explicitly retryable operation. The caller must ensure replay is safe.
///
/// The attempt count includes the initial call. The deadline covers acquisition,
/// every operation attempt, and recovery/teardown between attempts. Connection
/// failures while acquiring a ready resource do not consume operation attempts.
#[derive(Clone, Copy, Debug)]
pub struct RetryPolicy {
    pub max_attempts: std::num::NonZeroUsize,
    pub timeout: Duration,
}

/// A specific resource generation. Old handles do not silently become new resources.
pub struct ResourceHandle<R> {
    resource: Arc<R>,
    generation: u64,
}
impl<R> Clone for ResourceHandle<R> {
    fn clone(&self) -> Self {
        Self {
            resource: self.resource.clone(),
            generation: self.generation,
        }
    }
}
impl<R> ResourceHandle<R> {
    pub fn resource(&self) -> &Arc<R> {
        &self.resource
    }
    pub fn generation(&self) -> u64 {
        self.generation
    }
}
pub struct ResourceStatus<R> {
    pub state: ResourceState,
    pub handle: Option<ResourceHandle<R>>,
}
type Snapshot<R> = ResourceStatus<R>;
impl<R> Clone for Snapshot<R> {
    fn clone(&self) -> Self {
        Self {
            state: self.state,
            handle: self.handle.clone(),
        }
    }
}
struct Owner {
    stop: watch::Sender<bool>,
    started: AtomicBool,
}
impl Drop for Owner {
    fn drop(&mut self) {
        self.stop.send_replace(true);
    }
}
struct Recovery {
    generation: u64,
    terminal: bool,
    completed: Option<oneshot::Sender<()>>,
}
pub type LifecycleFuture<E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send>>;
pub type CreatedHook<R, E> = Arc<dyn Fn(Arc<R>) -> LifecycleFuture<E> + Send + Sync>;
pub type AttributeSetter<R> = Arc<dyn Fn(&R) + Send + Sync>;
struct Attributes<R, E> {
    setters: BTreeMap<String, AttributeSetter<R>>,
    last: Option<Arc<R>>,
    values: BTreeMap<String, Arc<dyn Any + Send + Sync>>,
    on_created: Option<CreatedHook<R, E>>,
    after_created: Option<CreatedHook<R, E>>,
}

/// Cloneable client-facing handle. Start inside a Tokio runtime.
/// Dropping the last supervisor requests shutdown; `stop().await` waits for teardown.
pub struct Supervisor<L: Lifecycle> {
    lifecycle: Arc<L>,
    owner: Arc<Owner>,
    snapshot: watch::Receiver<Snapshot<L::Resource>>,
    recovery: mpsc::UnboundedSender<Recovery>,
    attributes: Arc<Mutex<Attributes<L::Resource, L::Error>>>,
    config: Config,
    sender: watch::Sender<Snapshot<L::Resource>>,
    driver: Arc<tokio::sync::Mutex<Option<mpsc::UnboundedReceiver<Recovery>>>>,
    generations: Arc<AtomicU64>,
}
impl<L: Lifecycle> Clone for Supervisor<L> {
    fn clone(&self) -> Self {
        Self {
            lifecycle: self.lifecycle.clone(),
            owner: self.owner.clone(),
            snapshot: self.snapshot.clone(),
            recovery: self.recovery.clone(),
            attributes: self.attributes.clone(),
            config: self.config.clone(),
            sender: self.sender.clone(),
            driver: self.driver.clone(),
            generations: self.generations.clone(),
        }
    }
}
impl<L: Lifecycle> Supervisor<L> {
    pub fn start(lifecycle: L, config: Config) -> Self {
        let supervisor = Self::new(lifecycle, config);
        supervisor.begin();
        supervisor
    }
    /// Construct without spawning tasks, so hooks and setters can be configured first.
    pub fn new(lifecycle: L, config: Config) -> Self {
        let lifecycle = Arc::new(lifecycle);
        let (stop, stopping) = watch::channel(false);
        let (sender, snapshot) = watch::channel(Snapshot {
            state: ResourceState::Disconnected,
            handle: None,
        });
        let (recovery, requests) = mpsc::unbounded_channel();
        let attributes = Arc::new(Mutex::new(Attributes {
            setters: BTreeMap::new(),
            last: None,
            values: BTreeMap::new(),
            on_created: None,
            after_created: None,
        }));
        drop(stopping);
        Self {
            lifecycle,
            owner: Arc::new(Owner {
                stop,
                started: AtomicBool::new(false),
            }),
            snapshot,
            recovery,
            attributes,
            config,
            sender,
            driver: Arc::new(tokio::sync::Mutex::new(Some(requests))),
            generations: Arc::new(AtomicU64::new(0)),
        }
    }
    /// Start supervision once. Acquisition starts an unstarted supervisor automatically.
    pub fn begin(&self) {
        if self.sender.send_if_modified(|status| {
            if status.state == ResourceState::Stopped {
                status.state = ResourceState::Connecting;
                true
            } else {
                false
            }
        }) {
            self.owner.stop.send_replace(false);
            self.owner.started.store(true, Ordering::Release);
            self.launch();
            return;
        }
        if !*self.owner.stop.borrow() && !self.owner.started.swap(true, Ordering::AcqRel) {
            publish(&self.sender, ResourceState::Connecting, None);
            self.launch();
        }
    }
    fn launch(&self) {
        let driver = self.driver.clone();
        let lifecycle = self.lifecycle.clone();
        let config = self.config.clone();
        let stopping = self.owner.stop.subscribe();
        let sender = self.sender.clone();
        let attributes = self.attributes.clone();
        let generations = self.generations.clone();
        tokio::spawn(async move {
            let mut guard = driver.lock().await;
            let requests = guard.take().expect("only one lifecycle worker");
            *guard = Some(
                maintain(
                    lifecycle,
                    config,
                    stopping,
                    sender,
                    requests,
                    attributes,
                    generations,
                )
                .await,
            );
        });
    }
    /// Restart a fully stopped supervisor, preserving setters and public handles.
    /// Returns false if it is already running. Pools remain permanently stopped.
    pub async fn restart(&self) -> bool {
        if self.state() != ResourceState::Stopped {
            return false;
        }
        let guard = self.driver.lock().await;
        if self.state() != ResourceState::Stopped {
            return false;
        }
        self.owner.stop.send_replace(false);
        self.owner.started.store(true, Ordering::Release);
        publish(&self.sender, ResourceState::Connecting, None);
        drop(guard);
        self.launch();
        true
    }
    pub fn subscribe(&self) -> watch::Receiver<ResourceStatus<L::Resource>> {
        self.snapshot.clone()
    }
    pub fn current(&self) -> Option<ResourceHandle<L::Resource>> {
        self.snapshot.borrow().handle.clone()
    }
    /// Read an owned attribute from the latest created resource, even during recovery.
    pub fn with_latest<T>(&self, read: impl FnOnce(&L::Resource) -> T) -> Option<T> {
        self.attributes.lock().unwrap().last.as_deref().map(read)
    }
    /// Replay a synchronous attribute setter on the latest resource and all replacements.
    /// Setters must be short, nonblocking, and must not reenter this supervisor.
    pub fn set_attribute(&self, name: impl Into<String>, setter: AttributeSetter<L::Resource>) {
        let mut attributes = self.attributes.lock().unwrap();
        if let Some(resource) = &attributes.last {
            setter(resource);
        }
        attributes.setters.insert(name.into(), setter);
    }
    /// Store a typed value that is readable before creation and replay it on replacement.
    pub fn set_value<T: Clone + Send + Sync + 'static>(
        &self,
        name: impl Into<String>,
        value: T,
        apply: impl Fn(&L::Resource, &T) + Send + Sync + 'static,
    ) {
        let name = name.into();
        let value = Arc::new(value);
        let stored = value.clone();
        let setter: AttributeSetter<L::Resource> =
            Arc::new(move |resource| apply(resource, &value));
        let mut attributes = self.attributes.lock().unwrap();
        attributes.values.insert(name.clone(), stored);
        if let Some(resource) = &attributes.last {
            setter(resource);
        }
        attributes.setters.insert(name, setter);
    }
    pub fn value<T: Clone + Send + Sync + 'static>(&self, name: &str) -> Option<T> {
        self.attributes
            .lock()
            .unwrap()
            .values
            .get(name)?
            .downcast_ref::<T>()
            .cloned()
    }
    pub fn set_on_resource_created(&self, hook: CreatedHook<L::Resource, L::Error>) {
        self.attributes.lock().unwrap().on_created = Some(hook);
    }
    pub fn is_connected(&self) -> bool {
        self.current()
            .is_some_and(|handle| self.lifecycle.is_connected(&handle.resource))
    }
    pub fn stopped(&self) -> watch::Receiver<bool> {
        self.owner.stop.subscribe()
    }
    pub fn state(&self) -> ResourceState {
        self.snapshot.borrow().state
    }
    pub async fn acquire(&self) -> Result<ResourceHandle<L::Resource>, Error<L::Error>> {
        self.begin();
        self.acquire_running().await
    }
    pub(crate) async fn acquire_running(
        &self,
    ) -> Result<ResourceHandle<L::Resource>, Error<L::Error>> {
        let mut snapshot = self.snapshot.clone();
        loop {
            if *self.owner.stop.borrow() || snapshot.has_changed().is_err() {
                return Err(Error::Stopped);
            }
            if let Some(handle) = snapshot.borrow_and_update().handle.clone() {
                return Ok(handle);
            }
            snapshot.changed().await.map_err(|_| Error::Stopped)?;
        }
    }
    /// Request recovery without waiting for teardown.
    pub fn request_recovery(&self, handle: &ResourceHandle<L::Resource>, terminal: bool) {
        let _ = self.submit_recovery(handle, terminal, None);
    }
    /// Wait for bounded teardown. Does not wait for reconnection.
    pub async fn recover(
        &self,
        handle: &ResourceHandle<L::Resource>,
        terminal: bool,
    ) -> Result<(), Error<L::Error>> {
        let (sender, receiver) = oneshot::channel();
        if self.submit_recovery(handle, terminal, Some(sender)) {
            receiver.await.map_err(|_| Error::Stopped)?;
        }
        Ok(())
    }
    pub async fn recover_current(&self, terminal: bool) -> Result<(), Error<L::Error>> {
        if let Some(handle) = self.current() {
            self.recover(&handle, terminal).await?;
        }
        Ok(())
    }
    fn submit_recovery(
        &self,
        handle: &ResourceHandle<L::Resource>,
        terminal: bool,
        completed: Option<oneshot::Sender<()>>,
    ) -> bool {
        // Pointer identity also rejects handles from a different supervisor.
        let mut matched = self.sender.send_if_modified(|snapshot| {
            if snapshot
                .handle
                .as_ref()
                .is_some_and(|current| Arc::ptr_eq(&current.resource, &handle.resource))
            {
                snapshot.handle = None;
                snapshot.state = ResourceState::Recovering;
                true
            } else {
                false
            }
        });
        if !matched && self.state() == ResourceState::Recovering {
            matched = self
                .attributes
                .lock()
                .unwrap()
                .last
                .as_ref()
                .is_some_and(|resource| Arc::ptr_eq(resource, &handle.resource));
        }
        if matched {
            let _ = self.recovery.send(Recovery {
                generation: handle.generation,
                terminal,
                completed,
            });
        }
        matched
    }
    /// Run once. Failures request recovery and return the original error without replay.
    /// Dropping this future cancels the operation; protocol-specific cancellation safety
    /// remains the client's responsibility. Shutdown cancels operations driven by this method.
    pub async fn execute<F, Fut, T>(&self, operation: F) -> Result<T, Error<L::Error>>
    where
        F: FnOnce(Arc<L::Resource>) -> Fut,
        Fut: Future<Output = Result<T, L::Error>>,
    {
        self.begin();
        self.execute_running(operation).await
    }
    pub(crate) async fn execute_running<F, Fut, T>(
        &self,
        operation: F,
    ) -> Result<T, Error<L::Error>>
    where
        F: FnOnce(Arc<L::Resource>) -> Fut,
        Fut: Future<Output = Result<T, L::Error>>,
    {
        let handle = self.acquire_running().await?;
        let mut stopping = self.owner.stop.subscribe();
        let result = tokio::select! {
            biased;
            _ = shutdown(&mut stopping) => return Err(Error::Stopped),
            result = operation(handle.resource.clone()) => result,
        };
        match result {
            Ok(value) => Ok(value),
            Err(error) => {
                let _ = self
                    .recover(&handle, self.lifecycle.is_terminal(&error))
                    .await;
                Err(Error::Operation(error))
            }
        }
    }
    /// Retry an operation only when `retry_if` accepts its error and attempts remain.
    /// Each invocation of `operation` must create a fresh future and safely repeat
    /// the remote action. The next attempt waits for replacement setup to complete.
    /// Exhaustion returns the last operation error; the overall deadline returns
    /// [`Error::Timeout`]. Shutdown returns [`Error::Stopped`]; cancellation drops
    /// the active attempt without starting another. As with [`Self::execute`],
    /// resource-specific cancellation safety is the adapter's responsibility.
    /// Terminal classification controls teardown, not whether replay is allowed.
    pub async fn execute_with_retry<F, Fut, T, P>(
        &self,
        policy: RetryPolicy,
        operation: F,
        retry_if: P,
    ) -> Result<T, Error<L::Error>>
    where
        F: FnMut(Arc<L::Resource>) -> Fut,
        Fut: Future<Output = Result<T, L::Error>>,
        P: FnMut(&L::Error) -> bool,
    {
        if policy.timeout.is_zero() {
            return Err(Error::Timeout);
        }
        self.begin();
        self.execute_with_retry_running(policy, operation, retry_if)
            .await
    }
    pub(crate) async fn execute_with_retry_running<F, Fut, T, P>(
        &self,
        policy: RetryPolicy,
        mut operation: F,
        mut retry_if: P,
    ) -> Result<T, Error<L::Error>>
    where
        F: FnMut(Arc<L::Resource>) -> Fut,
        Fut: Future<Output = Result<T, L::Error>>,
        P: FnMut(&L::Error) -> bool,
    {
        if policy.timeout.is_zero() {
            return Err(Error::Timeout);
        }
        let mut stopping = self.owner.stop.subscribe();
        let retry_stopping = stopping.clone();
        let attempts = async {
            for attempt in 1..=policy.max_attempts.get() {
                // Do not implicitly restart a stopped supervisor between attempts.
                if *retry_stopping.borrow() {
                    return Err(Error::Stopped);
                }
                match self.execute_running(&mut operation).await {
                    Err(Error::Operation(error))
                        if attempt < policy.max_attempts.get() && retry_if(&error) => {}
                    result => return result,
                }
            }
            unreachable!("a nonzero final attempt always returns")
        };
        tokio::select! {
            biased;
            _ = shutdown(&mut stopping) => Err(Error::Stopped),
            result = timeout(policy.timeout, attempts) => result.unwrap_or(Err(Error::Timeout)),
        }
    }
    /// Idempotent, cancellation-safe shutdown. The background task owns cleanup.
    pub async fn stop(&self) {
        self.request_stop();
        let mut snapshot = self.snapshot.clone();
        loop {
            if snapshot.borrow_and_update().state == ResourceState::Stopped {
                // Wait for the worker to return its receiver and release lifecycle state.
                drop(self.driver.lock().await);
                return;
            }
            if snapshot.changed().await.is_err() {
                return;
            }
        }
    }
    pub(crate) fn request_stop(&self) {
        self.owner.stop.send_replace(true);
        if !self.owner.started.load(Ordering::Acquire) {
            publish(&self.sender, ResourceState::Stopped, None);
        } else {
            self.sender.send_if_modified(|status| {
                if status.state == ResourceState::Stopped {
                    false
                } else {
                    status.state = ResourceState::Stopping;
                    status.handle = None;
                    true
                }
            });
        }
    }
}
async fn shutdown(receiver: &mut watch::Receiver<bool>) {
    loop {
        if *receiver.borrow_and_update() {
            return;
        }
        if receiver.changed().await.is_err() {
            return;
        }
    }
}
fn publish<R>(
    sender: &watch::Sender<Snapshot<R>>,
    state: ResourceState,
    handle: Option<ResourceHandle<R>>,
) {
    sender.send_replace(Snapshot { state, handle });
}
fn log_failure<L: Lifecycle>(lifecycle: &L, config: &Config, name: &str, error: &L::Error) {
    if lifecycle.is_expected(error) {
        tracing::warn!(resource = config.resource_name, hook = name, %error);
        tracing::debug!(resource = config.resource_name, hook = name, ?error);
    } else {
        tracing::error!(resource = config.resource_name, hook = name, %error);
    }
}
fn log_late_failure<L: Lifecycle>(lifecycle: &L, config: &Config, name: &str, error: &L::Error) {
    if lifecycle.is_expected(error) {
        tracing::debug!(
            resource = config.resource_name,
            hook = name,
            ?error,
            "abandoned hook failed"
        );
    } else {
        log_failure(lifecycle, config, name, error);
    }
}
async fn bounded<L: Lifecycle>(
    lifecycle: Arc<L>,
    config: Config,
    name: &'static str,
    duration: Option<Duration>,
    future: impl Future<Output = Result<(), L::Error>> + Send + 'static,
) -> Result<(), bool> {
    let mut task = tokio::spawn(future);
    match deadline(duration, &mut task).await {
        Ok(Ok(Ok(()))) => Ok(()),
        Ok(Ok(Err(error))) => {
            log_failure(lifecycle.as_ref(), &config, name, &error);
            Err(lifecycle.is_terminal(&error))
        }
        Ok(Err(error)) => {
            tracing::error!(hook = name, %error, "hook task failed");
            Err(false)
        }
        Err(_) => {
            tracing::warn!(
                resource = config.resource_name,
                hook = name,
                "hook abandoned after timeout"
            );
            tokio::spawn(async move {
                match task.await {
                    Ok(Err(error)) => log_late_failure(lifecycle.as_ref(), &config, name, &error),
                    Ok(Ok(())) => tracing::warn!(
                        resource = config.resource_name,
                        hook = name,
                        "abandoned hook completed after timeout"
                    ),
                    Err(error) => {
                        tracing::error!(hook = name, %error, "abandoned hook task failed")
                    }
                }
            });
            Err(false)
        }
    }
}
async fn deadline<T>(
    duration: Option<Duration>,
    future: impl Future<Output = T>,
) -> Result<T, tokio::time::error::Elapsed> {
    match duration {
        Some(duration) => timeout(duration, future).await,
        None => Ok(future.await),
    }
}
async fn destroy<L: Lifecycle>(lifecycle: Arc<L>, config: Config, resource: Arc<L::Resource>) {
    let manager = lifecycle.clone();
    let _ = bounded(
        lifecycle,
        config.clone(),
        "destroy",
        config.destroy_timeout,
        async move { manager.destroy(&resource).await },
    )
    .await;
}
async fn close<L: Lifecycle>(
    lifecycle: Arc<L>,
    config: Config,
    resource: Arc<L::Resource>,
    terminal: bool,
) {
    let manager = lifecycle.clone();
    let value = resource.clone();
    let _ = bounded(
        lifecycle.clone(),
        config.clone(),
        "cleanup",
        Some(config.cleanup_timeout),
        async move { manager.cleanup(&value).await },
    )
    .await;
    if !terminal {
        let manager = lifecycle.clone();
        let value = resource.clone();
        let mut task = tokio::spawn(async move { manager.disconnect(&value).await });
        match timeout(config.disconnect_timeout, &mut task).await {
            Ok(Ok(Err(error))) => log_failure(lifecycle.as_ref(), &config, "disconnect", &error),
            Ok(Err(error)) => tracing::error!(%error, "disconnect task failed"),
            Ok(Ok(Ok(()))) => {}
            Err(_) => {
                tracing::warn!(
                    resource = config.resource_name,
                    "disconnect abandoned after timeout"
                );
                tokio::spawn(async move {
                    if let Ok(Err(error)) = task.await {
                        log_late_failure(lifecycle.as_ref(), &config, "disconnect", &error);
                    }
                    destroy(lifecycle, config, resource).await;
                });
                return;
            }
        }
    }
    destroy(lifecycle, config, resource).await;
}
async fn connect<L: Lifecycle>(
    lifecycle: Arc<L>,
    config: Config,
    resource: Arc<L::Resource>,
    stopping: &mut watch::Receiver<bool>,
) -> Result<(), bool> {
    let manager = lifecycle.clone();
    let value = resource.clone();
    let mut task = tokio::spawn(async move { manager.connect(&value).await });
    tokio::select! {
        biased;
        _ = shutdown(stopping) => { task.abort(); let _ = task.await; Err(false) }
        result = timeout(config.connect_timeout, &mut task) => match result {
            Ok(Ok(Ok(()))) => Ok(()),
            Ok(Ok(Err(error))) => {
                log_failure(lifecycle.as_ref(), &config, "connect", &error);
                Err(lifecycle.is_terminal(&error))
            }
            Ok(Err(error)) => { tracing::error!(%error, "connect task failed"); Err(false) }
            Err(_) => {
                tracing::warn!(resource = config.resource_name, "connect abandoned after timeout");
                tokio::spawn(async move {
                    match task.await {
                        Ok(Ok(())) => close(lifecycle, config, resource, false).await,
                        Ok(Err(error)) => log_late_failure(lifecycle.as_ref(), &config, "late connect", &error),
                        Err(error) => tracing::error!(%error, "late connect task failed"),
                    }
                });
                Err(false)
            }
        }
    }
}
async fn maintain<L: Lifecycle>(
    lifecycle: Arc<L>,
    config: Config,
    mut stopping: watch::Receiver<bool>,
    sender: watch::Sender<Snapshot<L::Resource>>,
    mut requests: mpsc::UnboundedReceiver<Recovery>,
    attributes: Arc<Mutex<Attributes<L::Resource, L::Error>>>,
    generations: Arc<AtomicU64>,
) -> mpsc::UnboundedReceiver<Recovery> {
    let mut delay = config.retry_delay;
    loop {
        while let Ok(request) = requests.try_recv() {
            if let Some(completed) = request.completed {
                let _ = completed.send(());
            }
        }
        if *stopping.borrow() {
            break;
        }
        publish(&sender, ResourceState::Connecting, None);
        let manager = lifecycle.clone();
        let mut creating = tokio::spawn(async move { manager.create().await });
        let created = tokio::select! {
            biased;
            _ = shutdown(&mut stopping) => { creating.abort(); let _ = creating.await; break },
            result = deadline(config.create_timeout, &mut creating) => result,
        };
        match created {
            Ok(Ok(Ok(resource))) => {
                let resource = Arc::new(resource);
                let (on_created, after_created) = {
                    let mut attributes = attributes.lock().unwrap();
                    attributes.last = Some(resource.clone());
                    (
                        attributes.on_created.clone(),
                        attributes.after_created.clone(),
                    )
                };
                let manager = lifecycle.clone();
                let value = resource.clone();
                let settings = attributes.clone();
                let created = bounded(
                    lifecycle.clone(),
                    config.clone(),
                    "on_resource_created",
                    config.created_timeout,
                    async move {
                        manager.on_resource_created(&value).await?;
                        if let Some(hook) = on_created {
                            hook(value.clone()).await?;
                        }
                        {
                            let settings = settings.lock().unwrap();
                            for setter in settings.setters.values() {
                                setter(&value);
                            }
                        }
                        if let Some(hook) = after_created {
                            hook(value).await?;
                        }
                        Ok(())
                    },
                );
                let created = tokio::select! { biased; _ = shutdown(&mut stopping) => Err(false), result = created => result };
                let connected = if created.is_ok() {
                    connect(
                        lifecycle.clone(),
                        config.clone(),
                        resource.clone(),
                        &mut stopping,
                    )
                    .await
                } else {
                    created
                };
                let manager = lifecycle.clone();
                let value = resource.clone();
                let setup = if connected.is_ok() {
                    tokio::select! {
                        biased;
                        _ = shutdown(&mut stopping) => Err(false),
                        ready = bounded(lifecycle.clone(), config.clone(), "setup", Some(config.setup_timeout),
                            async move { manager.setup(&value).await }) => ready,
                    }
                } else {
                    connected
                };
                let terminal = setup.err().unwrap_or(false);
                if setup.is_ok() {
                    let generation = generations.fetch_add(1, Ordering::AcqRel) + 1;
                    delay = config.retry_delay;
                    tracing::info!(resource = config.resource_name, "connected");
                    publish(
                        &sender,
                        ResourceState::Connected,
                        Some(ResourceHandle {
                            resource: resource.clone(),
                            generation,
                        }),
                    );
                    let mut watchdog = lifecycle
                        .watch_disconnect(resource.clone())
                        .map(tokio::spawn);
                    let mut watchdog_done = false;
                    let mut completed = None;
                    let terminal = loop {
                        tokio::select! {
                            biased;
                            _ = shutdown(&mut stopping) => break false,
                            request = requests.recv() => {
                                match request {
                                    Some(request) if request.generation == generation => { completed = request.completed; break request.terminal },
                                    Some(request) => { if let Some(completed) = request.completed { let _ = completed.send(()); } continue },
                                    None => break false,
                                }
                            }
                            result = async { match watchdog.as_mut() { Some(task) => task.await, None => std::future::pending().await } } => {
                                watchdog_done = true;
                                break match result { Ok(Err(error)) => { log_failure(lifecycle.as_ref(), &config, "watch_disconnect", &error); lifecycle.is_terminal(&error) }, _ => false };
                            }
                        }
                    };
                    if !watchdog_done && let Some(watchdog) = watchdog {
                        watchdog.abort();
                        let _ = watchdog.await;
                    }
                    let state = if *stopping.borrow() {
                        ResourceState::Stopping
                    } else {
                        ResourceState::Recovering
                    };
                    publish(&sender, state, None);
                    close(lifecycle.clone(), config.clone(), resource, terminal).await;
                    if let Some(completed) = completed {
                        let _ = completed.send(());
                    }
                    continue;
                }
                publish(&sender, ResourceState::Disconnected, None);
                close(lifecycle.clone(), config.clone(), resource, terminal).await;
            }
            Ok(Ok(Err(error))) => log_failure(lifecycle.as_ref(), &config, "create", &error),
            Ok(Err(error)) => tracing::error!(%error, "creation task failed"),
            Err(_) => {
                tracing::warn!("resource creation timed out");
                let manager = lifecycle.clone();
                let settings = config.clone();
                tokio::spawn(async move {
                    if let Ok(Ok(resource)) = creating.await {
                        close(manager, settings, Arc::new(resource), false).await;
                    }
                });
            }
        }
        publish(&sender, ResourceState::Disconnected, None);
        tracing::info!(resource = config.resource_name, retry_delay = ?delay, "retrying connection");
        tokio::select! { biased; _ = shutdown(&mut stopping) => break, _ = sleep(delay) => {} }
        delay = delay.saturating_mul(2).min(config.max_retry_delay);
    }
    while let Ok(request) = requests.try_recv() {
        if let Some(completed) = request.completed {
            let _ = completed.send(());
        }
    }
    publish(&sender, ResourceState::Stopped, None);
    requests
}