-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
experiments.rs
482 lines (412 loc) · 14.8 KB
/
experiments.rs
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
pub mod deep_experiments {
use crate::{
types::{OneshotSender, TypeFactory},
RsbtResult,
};
use async_trait::async_trait;
use futures::{
future::{join, BoxFuture},
stream::BoxStream,
AsyncRead, AsyncWrite, FutureExt, Sink, SinkExt, Stream, StreamExt,
};
use std::{
any::Any,
fmt::{Debug, Formatter},
future::Future,
net::{IpAddr, Ipv4Addr, SocketAddr},
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tokio::net::{TcpListener, TcpStream};
use tokio_util::compat::{Compat, Tokio02AsyncReadCompatExt};
macro_rules! request {
($sender:ident, |$x:ident: &mut $xt:ty| $expression:expr) => {
$sender
.request(move |$x: &mut $xt| $expression.boxed())
.await
};
}
pub struct App<T: AppTypeFactory> {
sender: <T as TypeFactory<Command<T, Self>>>::MpscSender,
receiver: <T as TypeFactory<Command<T, Self>>>::MpscReceiver,
properties: T::AppProperties,
data: Vec<u8>,
}
impl<T: AppTypeFactory> App<T> {
pub fn new(properties: T::AppProperties) -> Self {
let (sender, receiver) = <T as TypeFactory<Command<T, Self>>>::mpsc_channel(10);
Self {
sender,
receiver,
properties,
data: vec![],
}
}
async fn run(mut self) {
let mut sender = self.sender.clone();
let data = vec![5];
let incoming_connections_loop = async move {
let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
match T::SocketListener::bind(socket).await {
Ok(mut listener) => {
eprintln!("listen on {}", socket);
while let Some(socket) = listener.next().await {}
}
Err(e) => {
eprintln!("{}", e);
}
}
let result = request!(sender, |x: &mut Self| x.say_hello(data));
eprintln!("{:?}", result);
};
let handler: Handler<T> = Handler::new(self.sender.clone());
T::AppRuntime::spawn(async move {
handler.run().await;
});
let command_loop = async move {
while let Some(cmd) = self.receiver.next().await {
cmd.execute(&mut self).await;
}
};
join(incoming_connections_loop, command_loop).await;
}
async fn say_hello(&mut self, data: Vec<u8>) -> String {
eprintln!("hello new beautiful world! {}", data.len());
self.data = data;
"check me".into()
}
}
pub struct Handler<T: AppTypeFactory> {
app_sender: <T as TypeFactory<Command<T, App<T>>>>::MpscSender,
sender: <T as TypeFactory<Command<T, Self>>>::MpscSender,
receiver: <T as TypeFactory<Command<T, Self>>>::MpscReceiver,
data: Vec<u8>,
}
impl<A: AppTypeFactory> Debug for Handler<A> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Handler")
}
}
impl<T: AppTypeFactory> Handler<T> {
pub fn new(app_sender: <T as TypeFactory<Command<T, App<T>>>>::MpscSender) -> Self {
let (sender, receiver) = <T as TypeFactory<Command<T, Self>>>::mpsc_channel(10);
Self {
app_sender,
sender,
receiver,
data: vec![],
}
}
async fn run(mut self) {
let mut sender = self.sender.clone();
let mut app_sender = self.app_sender.clone();
let data = vec![5];
let incoming_connections_loop = async move {
let result = request!(sender, |x: &mut Self| x.say_hello(data));
eprintln!("handler: {:?}", result);
let data = result.unwrap().clone().as_bytes().to_vec();
let result = request!(app_sender, |x: &mut App<T>| x.say_hello(data));
eprintln!("app: {:?}", result);
};
let command_loop = async move {
while let Some(cmd) = self.receiver.next().await {
cmd.execute(&mut self).await;
}
};
join(incoming_connections_loop, command_loop).await;
}
async fn say_hello(&mut self, data: Vec<u8>) -> String {
eprintln!("hello new beautiful world from handle!");
self.data = data;
"check me too from handle".into()
}
}
pub trait AppTypeFactory:
Sized
+ TypeFactory<String>
+ TypeFactory<AnyResult>
+ TypeFactory<Command<Self, App<Self>>>
+ TypeFactory<Command<Self, Handler<Self>>>
+ Sync
+ Send
+ 'static
{
type AppRuntime: AppRuntime;
type SocketStream: Unpin + Send + AsyncRead + AsyncWrite;
type SocketListener: SocketListener + Stream<Item = RsbtResult<Self::SocketStream>> + Unpin;
type SocketConnect: SocketConnect<Self::SocketStream> + Unpin;
type AppProperties: AppProperties;
}
pub trait AppProperties: Send + Sync + Debug {
fn listen_addr(&self) -> &SocketAddr;
}
#[derive(Debug)]
pub struct RsbtAppProperties {
listen_addr: SocketAddr,
}
impl Default for RsbtAppProperties {
fn default() -> Self {
Self {
listen_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6881),
}
}
}
impl AppProperties for RsbtAppProperties {
fn listen_addr(&self) -> &SocketAddr {
&self.listen_addr
}
}
pub struct TokioTypeFactory;
impl AppTypeFactory for TokioTypeFactory {
type AppRuntime = TokioAppRuntime;
type SocketStream = Compat<TcpStream>;
type SocketListener = BoxStream<'static, RsbtResult<Self::SocketStream>>;
type SocketConnect = TokioSocketConnect;
type AppProperties = RsbtAppProperties;
}
pub struct TokioMpscSender<M>(tokio::sync::mpsc::Sender<M>);
impl<M> Clone for TokioMpscSender<M> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<M> Debug for TokioMpscSender<M> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "TokioMpscSender({:?})", self.0)
}
}
impl<M> Sink<M> for TokioMpscSender<M>
where
M: Debug + Send + Sync,
{
type Error = anyhow::Error;
fn poll_ready(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(cx).map_err(anyhow::Error::from)
}
fn start_send(mut self: Pin<&mut Self>, item: M) -> Result<(), Self::Error> {
self.0.try_send(item).map_err(|e| anyhow::anyhow!("{}", e))
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
match self.0.poll_ready(cx) {
Poll::Ready(Err(_)) => Poll::Ready(Ok(())),
x => x.map_err(anyhow::Error::from),
}
}
fn poll_close(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
pub struct TokioOneshotSender<M>(tokio::sync::oneshot::Sender<M>);
impl<M> Debug for TokioOneshotSender<M>
where
M: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "TokioOneshotSender({:?})", self.0)
}
}
impl<M> OneshotSender<M> for TokioOneshotSender<M> {
fn send(self, message: M) -> Result<(), M> {
self.0.send(message)
}
}
pub struct TokioOneshotReceiver<M>(tokio::sync::oneshot::Receiver<M>);
impl<M: Debug> Debug for TokioOneshotReceiver<M> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "TokioOneshotReceiver({:?})", self.0)
}
}
impl<M> Future for TokioOneshotReceiver<M> {
type Output = RsbtResult<M>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.0).poll(cx).map_err(anyhow::Error::from)
}
}
impl<M> TypeFactory<M> for TokioTypeFactory
where
M: Debug + Send + Sync,
{
type MpscSender = TokioMpscSender<M>;
type MpscReceiver = tokio::sync::mpsc::Receiver<M>;
type OneshotSender = TokioOneshotSender<M>;
type OneshotReceiver = TokioOneshotReceiver<M>;
fn mpsc_channel(buffer: usize) -> (Self::MpscSender, Self::MpscReceiver) {
let (sender, receiver) = tokio::sync::mpsc::channel(buffer);
(TokioMpscSender(sender), receiver)
}
fn oneshot_channel() -> (Self::OneshotSender, Self::OneshotReceiver) {
let (sender, receiver) = tokio::sync::oneshot::channel();
(TokioOneshotSender(sender), TokioOneshotReceiver(receiver))
}
}
pub trait AppRuntime {
fn spawn<'a, F>(f: F) -> BoxFuture<'a, RsbtResult<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static;
fn delay_for<'a>(duration: Duration) -> BoxFuture<'a, ()>;
fn timeout<'a, T>(duration: Duration, future: T) -> BoxFuture<'a, RsbtResult<T::Output>>
where
T: Future + Send + 'a;
}
pub struct TokioAppRuntime;
impl AppRuntime for TokioAppRuntime {
fn spawn<'a, F>(f: F) -> BoxFuture<'a, RsbtResult<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::spawn(f)
.map(|x| x.map_err(anyhow::Error::from))
.boxed()
}
fn delay_for<'a>(duration: Duration) -> BoxFuture<'a, ()> {
tokio::time::delay_for(duration).boxed()
}
fn timeout<'a, T>(duration: Duration, future: T) -> BoxFuture<'a, RsbtResult<T::Output>>
where
T: Future + Send + 'a,
{
tokio::time::timeout(duration, future)
.map(|x| x.map_err(anyhow::Error::from))
.boxed()
}
}
pub async fn main() -> RsbtResult<()> {
let app: App<TokioTypeFactory> = App::new(Default::default());
let _ = app.run().await;
/* let (mut sender, mut receiver) = app.mpsc_channel(10);
let sender_loop = async move {
eprintln!("sending message...");
if let Err(err) = sender.send("hello, world!".into()).await {
eprintln!("{}", err);
}
eprintln!("wait 10 seconds...");
tokio::time::delay_for(Duration::from_secs(10)).await;
eprintln!("done sender");
};
let receiver_loop = async move {
while let Some(message) = receiver.next().await {
eprintln!("{}", message);
}
eprintln!("done receiver");
};
join(sender_loop, receiver_loop).await;*/
Ok(())
}
pub enum Command<A: AppTypeFactory, B> {
Request(
<A as TypeFactory<AnyResult>>::OneshotSender,
Box<dyn AnyRequest<B> + Send + Sync>,
),
}
impl<A: AppTypeFactory, B> Debug for Command<A, B> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Command")
}
}
impl<A: AppTypeFactory, B> Command<A, B> {
async fn execute(self, target: &mut B) {
match self {
Command::Request(sender, mut any_request) => {
let any_result = any_request.any_request(target).await;
sender.send(any_result).ok();
}
}
}
}
pub(crate) type AnyResult = Box<dyn Any + Send + Sync>;
#[async_trait]
pub trait AnyRequest<A> {
async fn any_request(&mut self, o: &mut A) -> AnyResult;
}
struct AnyCommand<A, R: 'static>(
Option<Box<dyn FnOnce(&mut A) -> BoxFuture<'_, R> + Send + Sync>>,
);
#[async_trait]
impl<A, R> AnyRequest<A> for AnyCommand<A, R>
where
A: Send,
R: Send + Sync + 'static,
{
async fn any_request(&mut self, o: &mut A) -> AnyResult {
if let Some(command) = self.0.take() {
let result: AnyResult = Box::new(command(o).await);
result
} else {
panic!();
}
}
}
#[async_trait]
trait CommandSender<A, B>:
Sink<Command<A, B>, Error = anyhow::Error> + Clone + Debug + Unpin + Send + Sync
where
A: AppTypeFactory,
B: Sync + Send + 'static,
{
async fn request<F, R>(&mut self, f: F) -> RsbtResult<R>
where
F: FnOnce(&mut B) -> BoxFuture<'_, R> + Send + Sync + 'static,
R: Send + Sync + 'static,
{
let (sender, receiver) = <A as TypeFactory<AnyResult>>::oneshot_channel();
self.send(Command::Request(
sender,
Box::new(AnyCommand(Some(Box::new(f)))),
))
.await?;
let result = receiver.await?;
if let Ok(any) = <Box<dyn Any + Send>>::downcast::<R>(result) {
Ok(*any)
} else {
Err(anyhow::anyhow!(
"cannot downcast from request, caller and cally types do not match"
))
}
}
}
impl<T, A: AppTypeFactory, B> CommandSender<A, B> for T
where
B: Sync + Send + 'static,
T: Sink<Command<A, B>, Error = anyhow::Error> + Clone + Debug + Unpin + Send + Sync,
{
}
#[async_trait]
pub trait SocketListener: Sized {
async fn bind(addr: SocketAddr) -> RsbtResult<Self>;
}
#[async_trait]
impl SocketListener for BoxStream<'static, RsbtResult<Compat<TcpStream>>> {
async fn bind(addr: SocketAddr) -> RsbtResult<Self> {
Ok(TcpListener::bind(addr)
.await?
.map(|x| x.map(|x| x.compat()).map_err(anyhow::Error::from))
.boxed())
}
}
#[async_trait]
pub trait SocketConnect<SS> {
async fn connect(addr: SocketAddr) -> RsbtResult<SS>;
}
pub struct TokioSocketConnect;
#[async_trait]
impl SocketConnect<Compat<TcpStream>> for TokioSocketConnect {
async fn connect(addr: SocketAddr) -> RsbtResult<Compat<TcpStream>> {
TcpStream::connect(addr)
.await
.map(|x| x.compat())
.map_err(anyhow::Error::from)
}
}
}