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
//! Observable append-only list.
//!
//! This provides a locally and remotely observable append-only list.
//! The observable list sends a change event each time a change is performed on it.
//! The [resulting event stream](ListSubscription) can either be processed event-wise
//! or used to build a [mirrored list](MirroredList).
//!
//! # Alternatives
//!
//! The [observable vector](crate::vec) provides most operations of a [vector](Vec),
//! but allocates a separate event buffer per subscriber and thus uses more memory.
//!
//! # Basic use
//!
//! Create a [ObservableList] and obtain a [subscription](ListSubscription) to it using
//! [ObservableList::subscribe].
//! Send this subscription to a remote endpoint via a [remote channel](remoc::rch) and call
//! [ListSubscription::mirror] on the remote endpoint to obtain a live mirror of the observed
//! vector or process each change event individually using [ListSubscription::recv].
//!

use futures::{future, Future, FutureExt};
use remoc::prelude::*;
use serde::{Deserialize, Serialize};
use std::{
    fmt,
    marker::PhantomData,
    ops::Deref,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
};
use tokio::sync::{mpsc, oneshot, watch, Mutex, OwnedMutexGuard, RwLock, RwLockReadGuard};

use crate::{default_on_err, RecvError, SendError};

/// A list change event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ListEvent<T> {
    /// The subscription has reached the value of the observed
    /// list at the time it was subscribed.
    #[serde(skip)]
    InitialComplete,
    /// An item was pushed at the end of the list.
    Push(T),
    /// The list has reached its final state and
    /// no further events will occur.
    Done,
}

/// Observable list task request.
enum Req<T> {
    /// Push item.
    Push(T),
    /// List is complete, i.e. no more items will be sent.
    Done,
    /// Borrow the current list.
    Borrow(oneshot::Sender<OwnedMutexGuard<Vec<T>>>),
    /// Set the error handler.
    SetErrorHandler(Box<dyn Fn(SendError) + Send + Sync + 'static>),
}

/// Oberservable list subscribing related task request.
enum DistReq<T, Codec> {
    /// Subscribe receiver.
    Subscribe(rch::mpsc::Sender<ListEvent<T>, Codec>),
    /// Notify when no subscribers are left.
    NotifyNoSubscribers(oneshot::Sender<()>),
}

/// An observable list distributor allows subscribing to an observable list.
///
/// This is clonable and can be sent to other tasks.
#[derive(Clone)]
pub struct ObservableListDistributor<T, Codec = remoc::codec::Default> {
    tx: mpsc::UnboundedSender<DistReq<T, Codec>>,
    len: Arc<AtomicUsize>,
    subscriber_count: Arc<AtomicUsize>,
}

impl<T, Codec> fmt::Debug for ObservableListDistributor<T, Codec> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ObservableListDistributor")
            .field("len", &self.len.load(Ordering::Relaxed))
            .field("subscriber_count", &self.subscriber_count.load(Ordering::Relaxed))
            .finish()
    }
}

impl<T, Codec> ObservableListDistributor<T, Codec>
where
    T: RemoteSend + Clone,
    Codec: remoc::codec::Codec,
{
    /// Sends a request to the task.
    fn req(&self, req: DistReq<T, Codec>) {
        if self.tx.send(req).is_err() {
            panic!("observable list task was terminated");
        }
    }

    /// Subscribes to the observable list with incremental sending of the current contents.
    pub fn subscribe(&self) -> ListSubscription<T, Codec> {
        let (tx, rx) = rch::mpsc::channel(1);
        let _ = self.tx.send(DistReq::Subscribe(tx));
        ListSubscription::new(self.len.load(Ordering::Relaxed), rx)
    }

    /// Current number of subscribers.
    pub fn subscriber_count(&self) -> usize {
        self.subscriber_count.load(Ordering::Relaxed)
    }

    /// Returns when all subscribers have quit.
    ///
    /// If no subscribers are currently present, this return immediately.
    /// This also returns when [done](ObservableList::done) has been called and
    /// all subscribers have received all elements of the list.
    pub fn closed(&self) -> impl Future<Output = ()> {
        let (tx, rx) = oneshot::channel();
        self.req(DistReq::NotifyNoSubscribers(tx));
        async move {
            let _ = rx.await;
        }
    }

    /// Returns `true` if there are currently no subscribers.
    pub fn is_closed(&self) -> bool {
        self.subscriber_count() == 0
    }
}

/// An append-only list that emits an event for each change.
///
/// Use [subscribe](Self::subscribe) to obtain an event stream
/// that can be used for building a mirror of this list.
///
/// The [distributor method](Self::distributor) can be used to obtain a clonable object
/// that can be used to make subscriptions from other tasks.
pub struct ObservableList<T, Codec = remoc::codec::Default> {
    tx: mpsc::UnboundedSender<Req<T>>,
    len: Arc<AtomicUsize>,
    done: bool,
    dist: ObservableListDistributor<T, Codec>,
}

impl<T, Codec> fmt::Debug for ObservableList<T, Codec> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ObservableList")
            .field("len", &self.len.load(Ordering::Relaxed))
            .field("done", &self.done)
            .field("subscriber_count", &self.dist.subscriber_count.load(Ordering::Relaxed))
            .finish()
    }
}

impl<T, Codec> Default for ObservableList<T, Codec>
where
    T: RemoteSend + Clone,
    Codec: remoc::codec::Codec,
{
    fn default() -> Self {
        Self::from(Vec::new())
    }
}

impl<T, Codec> From<Vec<T>> for ObservableList<T, Codec>
where
    T: RemoteSend + Clone,
    Codec: remoc::codec::Codec,
{
    fn from(initial: Vec<T>) -> Self {
        let (tx, rx) = mpsc::unbounded_channel();
        let (sub_tx, sub_rx) = mpsc::unbounded_channel();
        let len = Arc::new(AtomicUsize::new(initial.len()));
        let subscriber_count = Arc::new(AtomicUsize::new(0));
        tokio::spawn(Self::task(initial, rx, sub_rx, subscriber_count.clone()));
        Self {
            tx,
            len: len.clone(),
            done: false,
            dist: ObservableListDistributor { tx: sub_tx, len, subscriber_count },
        }
    }
}

impl<T, Codec> ObservableList<T, Codec>
where
    T: RemoteSend + Clone,
    Codec: remoc::codec::Codec,
{
    /// Creates a new, empty observable list.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sends a request to the task.
    fn req(&self, req: Req<T>) {
        if self.tx.send(req).is_err() {
            panic!("observable list task was terminated");
        }
    }

    /// Panics when `done` has been called.
    fn assert_not_done(&self) {
        if self.done {
            panic!("observable list cannot be changed after done has been called");
        }
    }

    /// Sets the error handler function that is called when sending an
    /// event fails.
    pub fn set_error_handler<E>(&mut self, on_err: E)
    where
        E: Fn(SendError) + Send + Sync + 'static,
    {
        self.req(Req::SetErrorHandler(Box::new(on_err)));
    }

    /// Returns an observable list distributor that can be used to make subscriptions
    /// to this observable list.
    ///
    /// It is clonable and can be sent to other tasks.
    pub fn distributor(&self) -> ObservableListDistributor<T, Codec> {
        self.dist.clone()
    }

    /// Subscribes to the observable list with incremental sending of the current contents.
    pub fn subscribe(&self) -> ListSubscription<T, Codec> {
        self.dist.subscribe()
    }

    /// Current number of subscribers.
    pub fn subscriber_count(&self) -> usize {
        self.dist.subscriber_count()
    }

    /// Returns when all subscribers have quit.
    ///
    /// If no subscribers are currently present, this return immediately.
    /// This also returns when [done](Self::done) has been called and
    /// all subscribers have received all elements of the list.
    pub fn closed(&self) -> impl Future<Output = ()> {
        self.dist.closed()
    }

    /// Returns `true` if there are currently no subscribers.
    pub fn is_closed(&self) -> bool {
        self.dist.is_closed()
    }

    /// Appends an element at the end.
    ///
    /// A [ListEvent::Push] change event is sent.
    ///
    /// # Panics
    /// Panics when [done](Self::done) has been called before.
    pub fn push(&mut self, value: T) {
        self.assert_not_done();
        self.req(Req::Push(value));
        self.len.fetch_add(1, Ordering::Relaxed);
    }

    /// The current number of elements in the observable list.
    pub fn len(&self) -> usize {
        self.len.load(Ordering::Relaxed)
    }

    /// Returns whether this observable list is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Prevents further changes of this list and notifies
    /// are subscribers that no further events will occur.
    ///
    /// Methods that modify the list will panic after this has been called.
    /// It is still possible to subscribe to this observable list.
    pub fn done(&mut self) {
        if !self.done {
            self.req(Req::Done);
            self.done = true;
        }
    }

    /// Returns `true` if [done](Self::done) has been called and further
    /// changes are prohibited.
    ///
    /// Methods that modify the list will panic in this case.
    pub fn is_done(&self) -> bool {
        self.done
    }

    /// Borrows the current value of the observable list.
    ///
    /// While the borrow is held sending of events to subscribers is paused.
    #[allow(clippy::needless_lifetimes)]
    pub async fn borrow<'a>(&'a self) -> ObservableListRef<'a, T> {
        let (tx, rx) = oneshot::channel();
        self.req(Req::Borrow(tx));
        ObservableListRef { buffer: rx.await.unwrap(), _phantom: PhantomData }
    }

    /// Event dispatch task.
    async fn task(
        buffer: Vec<T>, rx: mpsc::UnboundedReceiver<Req<T>>, dist_rx: mpsc::UnboundedReceiver<DistReq<T, Codec>>,
        subscriber_count: Arc<AtomicUsize>,
    ) {
        /// State of a subscription.
        struct SubState<T, Codec> {
            pos: usize,
            done: bool,
            tx: rch::mpsc::Sender<ListEvent<T>, Codec>,
        }

        let buffer_shared = Arc::new(Mutex::new(buffer));
        let mut buffer_guard_opt = None;
        let mut rx_opt = Some(rx);
        let mut dist_rx_opt = Some(dist_rx);
        let mut subs: Vec<SubState<T, Codec>> = Vec::new();
        let mut done = false;
        let mut on_err: Box<dyn Fn(SendError) + Send + Sync + 'static> = Box::new(default_on_err);
        let mut no_sub_notify: Vec<oneshot::Sender<()>> = Vec::new();

        // Event and transmit loop.
        loop {
            // Obtain buffer mutex.
            let buffer = match &mut buffer_guard_opt {
                Some(br) => br,
                None => {
                    buffer_guard_opt = Some(buffer_shared.clone().lock_owned().await);
                    buffer_guard_opt.as_mut().unwrap()
                }
            };

            // If no more items can arrive, keep only subscription that have
            // not yet received all items.
            if rx_opt.is_none() {
                if done {
                    subs.retain(|sub| !sub.done);
                } else {
                    subs.retain(|sub| sub.pos < buffer.len());
                }
            }

            // Update subscriber counts.
            subscriber_count.store(subs.len(), Ordering::Relaxed);
            if subs.is_empty() {
                for tx in no_sub_notify.drain(..) {
                    let _ = tx.send(());
                }
            }

            // Create tasks that obtain send permits.
            let mut permit_tasks = Vec::new();
            for (i, sub) in subs.iter().enumerate() {
                if sub.pos < buffer.len() || (done && !sub.done) {
                    permit_tasks.push(async move { (i, sub.tx.reserve().await) }.boxed());
                }
            }

            // Check for termination.
            if rx_opt.is_none() && dist_rx_opt.is_none() && permit_tasks.is_empty() {
                break;
            }

            tokio::select! {
                biased;

                // Process request.
                req = async {
                    match &mut rx_opt {
                        Some(rx) => rx.recv().await,
                        None => future::pending().await,
                    }
                } => match req {
                    Some(Req::Push(v)) => buffer.push(v),
                    Some(Req::Done) => done = true,
                    Some(Req::Borrow(tx)) => {
                        let _ = tx.send(buffer_guard_opt.take().unwrap());
                    }
                    Some(Req::SetErrorHandler(handler)) => on_err = handler,
                    None => rx_opt = None,
                },

                // Process distribution request.
                req = async {
                    match &mut dist_rx_opt {
                        Some(rx) => rx.recv().await,
                        None => future::pending().await,
                    }
                } => match req {
                    Some(DistReq::Subscribe(tx)) => subs.push(SubState { pos: 0, done: false, tx }),
                    Some(DistReq::NotifyNoSubscribers(tx)) => no_sub_notify.push(tx),
                    None => dist_rx_opt = None,
                },

                // Process send permit ready.
                (i, res) = async move {
                    if permit_tasks.is_empty() {
                        future::pending().await
                    } else {
                        future::select_all(permit_tasks).await.0
                    }
                } => match res {
                    Ok(permit) => {
                        let sub = &mut subs[i];
                        if sub.pos < buffer.len() {
                            permit.send(ListEvent::Push(buffer[sub.pos].clone()));
                            sub.pos += 1;
                        } else if done && !sub.done {
                            permit.send(ListEvent::Done);
                            sub.done = true;
                        } else {
                            unreachable!()
                        }
                    }
                    Err(err) => {
                        subs.swap_remove(i);
                        if let Ok(err) = SendError::try_from(err) {
                            on_err(err);
                        }
                    }
                },
            }
        }
    }
}

impl<T, Codec> Drop for ObservableList<T, Codec> {
    fn drop(&mut self) {
        // empty
    }
}

impl<T, Codec> Extend<T> for ObservableList<T, Codec>
where
    T: RemoteSend + Clone,
    Codec: remoc::codec::Codec,
{
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for value in iter {
            self.push(value);
        }
    }
}

/// A reference to an observable list.
///
/// While this is held sending of events to subscribers is paused.
pub struct ObservableListRef<'a, T> {
    buffer: OwnedMutexGuard<Vec<T>>,
    _phantom: PhantomData<&'a ()>,
}

impl<'a, T> fmt::Debug for ObservableListRef<'a, T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.buffer.fmt(f)
    }
}

impl<'a, T> Deref for ObservableListRef<'a, T> {
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &*self.buffer
    }
}

struct MirroredListInner<T> {
    v: Vec<T>,
    complete: bool,
    done: bool,
    error: Option<RecvError>,
    max_size: usize,
}

impl<T> MirroredListInner<T> {
    fn handle_event(&mut self, event: ListEvent<T>) -> Result<(), RecvError> {
        match event {
            ListEvent::InitialComplete => {
                self.complete = true;
            }
            ListEvent::Push(v) => {
                self.v.push(v);
                if self.v.len() > self.max_size {
                    return Err(RecvError::MaxSizeExceeded(self.max_size));
                }
            }
            ListEvent::Done => {
                self.done = true;
            }
        }
        Ok(())
    }
}

/// Observable list subscription.
///
/// This can be sent to a remote endpoint via a [remote channel](remoc::rch).
/// Then, on the remote endpoint, [mirror](Self::mirror) can be used to build
/// and keep up-to-date a mirror of the observed list.
///
/// The event stream can also be processed event-wise using [recv](Self::recv).
#[derive(Debug, Serialize, Deserialize)]
#[serde(bound(serialize = "T: RemoteSend, Codec: remoc::codec::Codec"))]
#[serde(bound(deserialize = "T: RemoteSend, Codec: remoc::codec::Codec"))]
pub struct ListSubscription<T, Codec = remoc::codec::Default> {
    /// Length of list at time of subscription.
    initial_len: usize,
    /// Initial value received completely.
    #[serde(skip, default)]
    complete: bool,
    /// Change events receiver.
    events: Option<rch::mpsc::Receiver<ListEvent<T>, Codec>>,
    /// Number of elements received so far.
    len: usize,
}

impl<T, Codec> ListSubscription<T, Codec>
where
    T: RemoteSend + Clone,
    Codec: remoc::codec::Codec,
{
    fn new(initial_len: usize, events: rch::mpsc::Receiver<ListEvent<T>, Codec>) -> Self {
        Self { initial_len, complete: false, events: Some(events), len: 0 }
    }

    /// Returns whether the initial value event or
    /// stream of events that build up the initial value
    /// has completed.
    pub fn is_complete(&self) -> bool {
        self.complete
    }

    /// Returns whether the observed list has indicated that no further
    /// change events will occur.
    pub fn is_done(&self) -> bool {
        self.events.is_none()
    }

    /// Receives the next change event.
    pub async fn recv(&mut self) -> Result<Option<ListEvent<T>>, RecvError> {
        // Provide initial value complete event.
        if self.len == self.initial_len && !self.complete {
            self.complete = true;
            return Ok(Some(ListEvent::InitialComplete));
        }

        // Provide change event.
        match &mut self.events {
            Some(rx) => match rx.recv().await? {
                Some(ListEvent::InitialComplete) => unreachable!(),
                Some(evt @ ListEvent::Push(_)) => {
                    self.len += 1;
                    Ok(Some(evt))
                }
                Some(ListEvent::Done) => {
                    self.events = None;
                    Ok(Some(ListEvent::Done))
                }
                None => Err(RecvError::Closed),
            },
            None => Ok(None),
        }
    }
}

impl<T, Codec> ListSubscription<T, Codec>
where
    T: RemoteSend + Clone + Sync,
    Codec: remoc::codec::Codec,
{
    /// Mirror the list that this subscription is observing.
    ///
    /// `max_size` specifies the maximum allowed size of the mirrored collection.
    /// If this size is reached, processing of events is stopped and
    /// [RecvError::MaxSizeExceeded] is returned.
    pub fn mirror(mut self, max_size: usize) -> MirroredList<T> {
        let (changed_tx, changed_rx) = watch::channel(());
        let (dropped_tx, mut dropped_rx) = oneshot::channel();

        // Build initial state.
        let inner = Arc::new(RwLock::new(Some(MirroredListInner {
            v: Vec::new(),
            complete: false,
            done: false,
            error: None,
            max_size,
        })));
        let inner_task = inner.clone();

        // Process change events.
        tokio::spawn(async move {
            loop {
                let event = tokio::select! {
                    event = self.recv() => event,
                    _ = &mut dropped_rx => return,
                };

                let mut inner = inner_task.write().await;
                let mut inner = match inner.as_mut() {
                    Some(inner) => inner,
                    None => return,
                };

                changed_tx.send_replace(());

                match event {
                    Ok(Some(event)) => {
                        if let Err(err) = inner.handle_event(event) {
                            inner.error = Some(err);
                            return;
                        }

                        if inner.done {
                            break;
                        }
                    }
                    Ok(None) => break,
                    Err(err) => {
                        inner.error = Some(err);
                        return;
                    }
                }
            }
        });

        MirroredList { inner, changed_rx, _dropped_tx: dropped_tx }
    }
}

/// An append-only list that is mirroring an observable append-only list.
pub struct MirroredList<T> {
    inner: Arc<RwLock<Option<MirroredListInner<T>>>>,
    changed_rx: watch::Receiver<()>,
    _dropped_tx: oneshot::Sender<()>,
}

impl<T> fmt::Debug for MirroredList<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("MirroredList").finish()
    }
}

impl<T> MirroredList<T>
where
    T: RemoteSend,
{
    /// Returns a reference to the current value of the list.
    ///
    /// Updates are paused while the read lock is held.
    ///
    /// This method returns an error if the observed list has been dropped
    /// or the connection to it failed before it was marked as done by calling
    /// [ObservableList::done].
    /// In this case the mirrored contents at the point of loss of connection
    /// can be obtained using [detach](Self::detach).
    pub async fn borrow(&self) -> Result<MirroredListRef<'_, T>, RecvError> {
        let inner = self.inner.read().await;
        let inner = RwLockReadGuard::map(inner, |inner| inner.as_ref().unwrap());
        match &inner.error {
            None => Ok(MirroredListRef(inner)),
            Some(err) => Err(err.clone()),
        }
    }

    /// Returns a reference to the current value of the list and marks it as seen.
    ///
    /// Thus [changed](Self::changed) will not return immediately until the value changes
    /// after this method returns.
    ///
    /// Updates are paused while the read lock is held.
    ///
    /// This method returns an error if the observed list has been dropped
    /// or the connection to it failed before it was marked as done by calling
    /// [ObservableList::done].
    /// In this case the mirrored contents at the point of loss of connection
    /// can be obtained using [detach](Self::detach).
    pub async fn borrow_and_update(&mut self) -> Result<MirroredListRef<'_, T>, RecvError> {
        let inner = self.inner.read().await;
        self.changed_rx.borrow_and_update();
        let inner = RwLockReadGuard::map(inner, |inner| inner.as_ref().unwrap());
        match &inner.error {
            None => Ok(MirroredListRef(inner)),
            Some(err) => Err(err.clone()),
        }
    }

    /// Stops updating the list and returns its current contents.
    pub async fn detach(self) -> Vec<T> {
        let mut inner = self.inner.write().await;
        inner.take().unwrap().v
    }

    /// Waits for a change (append of one or more elements) and marks the newest value as seen.
    ///
    /// This also returns when connection to the observed list has been lost
    /// or the list has been marked as done.
    pub async fn changed(&mut self) {
        let _ = self.changed_rx.changed().await;
    }
}

impl<T> Drop for MirroredList<T> {
    fn drop(&mut self) {
        // empty
    }
}

/// A snapshot view of an observable append-only list.
pub struct MirroredListRef<'a, T>(RwLockReadGuard<'a, MirroredListInner<T>>);

impl<'a, T> MirroredListRef<'a, T> {
    /// Returns `true` if the mirror list has reached the length of the observed
    /// list at the time of subscription.
    pub fn is_complete(&self) -> bool {
        self.0.complete
    }

    /// Returns `true` if the observed list has been marked as done by calling
    /// [ObservableList::done] and thus no further changes can occur.
    pub fn is_done(&self) -> bool {
        self.0.done
    }
}

impl<'a, T> fmt::Debug for MirroredListRef<'a, T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.v.fmt(f)
    }
}

impl<'a, T> Deref for MirroredListRef<'a, T> {
    type Target = Vec<T>;

    fn deref(&self) -> &Self::Target {
        &self.0.v
    }
}

impl<'a, T> Drop for MirroredListRef<'a, T> {
    fn drop(&mut self) {
        // required for drop order
    }
}