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
use futures::{
future::{self, BoxFuture},
Future, FutureExt,
};
use remoc::prelude::*;
use std::{
fmt,
pin::Pin,
task::{Context, Poll},
};
use tokio::sync::{mpsc, oneshot};
struct SubscribeReq<T, Codec> {
tx: rch::mpsc::Sender<T, Codec>,
err_tx: oneshot::Sender<rch::mpsc::SendError<()>>,
}
struct Subscription<T, Codec> {
pos: usize,
tx: rch::mpsc::Sender<T, Codec>,
err_tx: oneshot::Sender<rch::mpsc::SendError<()>>,
}
pub struct ReplayBuffer<T, Codec = remoc::codec::Default> {
sub_tx: mpsc::UnboundedSender<SubscribeReq<T, Codec>>,
keep_tx: Option<oneshot::Sender<()>>,
}
impl<T, Codec> fmt::Debug for ReplayBuffer<T, Codec> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ReplayBuffer").finish()
}
}
impl<T, Codec> Default for ReplayBuffer<T, Codec>
where
T: RemoteSend + Clone,
Codec: remoc::codec::Codec,
{
fn default() -> Self {
let (_tx, rx) = mpsc::channel(1);
Self::new(rx)
}
}
impl<T, Codec> ReplayBuffer<T, Codec>
where
T: RemoteSend + Clone,
Codec: remoc::codec::Codec,
{
pub fn new(rx: mpsc::Receiver<T>) -> Self {
let (sub_tx, sub_rx) = mpsc::unbounded_channel();
let (keep_tx, keep_rx) = oneshot::channel();
tokio::spawn(Self::buffer_task(rx, sub_rx, keep_rx));
Self { sub_tx, keep_tx: Some(keep_tx) }
}
pub fn new_unbounded(mut rx: mpsc::UnboundedReceiver<T>) -> Self {
let (b_tx, b_rx) = mpsc::channel(16);
tokio::spawn(async move {
while let Some(value) = rx.recv().await {
if b_tx.send(value).await.is_err() {
break;
}
}
});
Self::new(b_rx)
}
pub fn keep(&mut self) {
if let Some(keep_tx) = self.keep_tx.take() {
let _ = keep_tx.send(());
}
}
pub fn subscribe<C, B>(&self, tx: rch::mpsc::Sender<T, C, B>) -> SubscriptionHandle
where
C: remoc::codec::Codec,
B: rch::buffer::Size,
{
let tx = tx.set_codec().set_buffer();
let (err_tx, err_rx) = oneshot::channel();
if self.sub_tx.send(SubscribeReq { tx, err_tx }).is_err() {
panic!("replay buffer task was shut down");
}
SubscriptionHandle(
async move {
match err_rx.await {
Ok(err) => Err(err),
Err(_) => Ok(()),
}
}
.boxed(),
)
}
async fn buffer_task(
rx: mpsc::Receiver<T>, sub_rx: mpsc::UnboundedReceiver<SubscribeReq<T, Codec>>,
keep_rx: oneshot::Receiver<()>,
) {
let mut rx_opt = Some(rx);
let mut sub_rx_opt = Some(sub_rx);
let mut buffer: Vec<T> = Vec::new();
let mut subs: Vec<Subscription<T, Codec>> = Vec::new();
let mut keep_rx = keep_rx.fuse();
loop {
if rx_opt.is_none() {
subs.retain(|sub| sub.pos < buffer.len());
}
let mut permit_tasks = Vec::new();
for (i, sub) in subs.iter().enumerate() {
if sub.pos < buffer.len() {
permit_tasks.push(async move { (i, sub.tx.reserve().await) }.boxed());
}
}
if sub_rx_opt.is_none() && rx_opt.is_none() && permit_tasks.is_empty() {
break;
}
tokio::select! {
biased;
sub_opt = async {
match &mut sub_rx_opt {
Some(sub_rx) => sub_rx.recv().await,
None => future::pending().await,
}
} => {
match sub_opt {
Some(SubscribeReq { tx, err_tx }) => {
subs.push(Subscription { pos: 0, tx, err_tx });
}
None => sub_rx_opt = None,
}
},
value_opt = async {
match &mut rx_opt {
Some(rx) => rx.recv().await,
None => future::pending().await,
}
} => {
match value_opt {
Some(value) => buffer.push(value),
None => rx_opt = None,
}
},
res = &mut keep_rx => {
if res.is_err() {
break;
}
},
(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 pos = &mut subs[i].pos;
permit.send(buffer[*pos].clone());
*pos += 1;
}
Err(err) => {
let sub = subs.swap_remove(i);
let _ = sub.err_tx.send(err);
}
}
}
}
}
}
}
impl<T, Codec> Drop for ReplayBuffer<T, Codec> {
fn drop(&mut self) {
}
}
pub struct SubscriptionHandle(BoxFuture<'static, Result<(), rch::mpsc::SendError<()>>>);
impl Future for SubscriptionHandle {
type Output = Result<(), rch::mpsc::SendError<()>>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
self.0.poll_unpin(cx)
}
}