| 1 | use std::sync::mpsc::{SyncSender, TrySendError}; |
| 2 | |
| 3 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 4 | pub enum DeliveryKind { |
| 5 | Full, |
| 6 | Disconnected, |
| 7 | } |
| 8 | |
| 9 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 10 | pub struct DeliveryFault { |
| 11 | pub kind: DeliveryKind, |
| 12 | pub first_missing_sequence: u64, |
| 13 | } |
| 14 | |
| 15 | pub struct Transport<T> { |
| 16 | sender: SyncSender<T>, |
| 17 | pub fault: Option<DeliveryFault>, |
| 18 | } |
| 19 | |
| 20 | impl<T> Transport<T> { |
| 21 | pub fn new(sender: SyncSender<T>) -> Self { |
| 22 | Self { |
| 23 | sender, |
| 24 | fault: None, |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | pub fn forward<E>( |
| 29 | &mut self, |
| 30 | sequence: u64, |
| 31 | value: T, |
| 32 | original: Result<(), E>, |
| 33 | stop: impl FnOnce() -> E, |
| 34 | ) -> Result<(), E> { |
| 35 | if self.fault.is_none() { |
| 36 | self.fault = match self.sender.try_send(value) { |
| 37 | Ok(()) => None, |
| 38 | Err(TrySendError::Full(_)) => Some(DeliveryFault { |
| 39 | kind: DeliveryKind::Full, |
| 40 | first_missing_sequence: sequence, |
| 41 | }), |
| 42 | Err(TrySendError::Disconnected(_)) => Some(DeliveryFault { |
| 43 | kind: DeliveryKind::Disconnected, |
| 44 | first_missing_sequence: sequence, |
| 45 | }), |
| 46 | }; |
| 47 | } |
| 48 | // 원래 observer 오류를 전달 오류보다 먼저 반환함. |
| 49 | original?; |
| 50 | if self.fault.is_some() { |
| 51 | Err(stop()) |
| 52 | } else { |
| 53 | Ok(()) |
| 54 | } |
| 55 | } |
| 56 | } |