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
use core::{
task::{Context, Poll},
time::Duration,
};
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use async_io::{Async, Timer};
use async_trait::async_trait;
use futures_util::{future, pin_mut, ready};
use ssh2::{BlockDirections, Error as Ssh2Error, Session};
use super::{AsyncSessionStream, BlockDirectionsExt as _};
use crate::{error::Error, util::ssh2_error_is_would_block};
#[async_trait]
impl<S> AsyncSessionStream for Async<S>
where
S: Send + Sync,
{
async fn x_with<R>(
&self,
mut op: impl FnMut() -> Result<R, Ssh2Error> + Send,
sess: &Session,
expected_block_directions: BlockDirections,
sleep_dur: Option<Duration>,
) -> Result<R, Error> {
loop {
match op() {
Ok(x) => return Ok(x),
Err(err) => {
if !ssh2_error_is_would_block(&err) {
return Err(err.into());
}
}
}
match sess.block_directions() {
BlockDirections::None => continue,
BlockDirections::Inbound => {
assert!(expected_block_directions.is_readable());
self.readable().await?
}
BlockDirections::Outbound => {
assert!(expected_block_directions.is_writable());
self.writable().await?
}
BlockDirections::Both => {
assert!(expected_block_directions.is_readable());
assert!(expected_block_directions.is_writable());
let (ret, _) = future::select(self.readable(), self.writable())
.await
.factor_first();
ret?
}
}
if let Some(dur) = sleep_dur {
sleep_async_fn(dur).await;
}
}
}
fn poll_x_with<R>(
&self,
cx: &mut Context,
mut op: impl FnMut() -> Result<R, IoError> + Send,
sess: &Session,
expected_block_directions: BlockDirections,
sleep_dur: Option<Duration>,
) -> Poll<Result<R, IoError>> {
match op() {
Err(err) if err.kind() == IoErrorKind::WouldBlock => {}
ret => return Poll::Ready(ret),
}
match sess.block_directions() {
BlockDirections::None => return Poll::Pending,
BlockDirections::Inbound => {
assert!(expected_block_directions.is_readable());
ready!(self.poll_readable(cx))?;
}
BlockDirections::Outbound => {
assert!(expected_block_directions.is_writable());
ready!(self.poll_writable(cx))?;
}
BlockDirections::Both => {
assert!(expected_block_directions.is_readable());
assert!(expected_block_directions.is_writable());
ready!(self.poll_writable(cx))?;
ready!(self.poll_readable(cx))?;
}
}
if let Some(dur) = sleep_dur {
let waker = cx.waker().clone();
let timer = sleep(dur);
pin_mut!(timer);
ready!(future::Future::poll(timer, cx));
waker.wake();
} else {
let waker = cx.waker().clone();
waker.wake();
}
Poll::Pending
}
}
async fn sleep_async_fn(dur: Duration) {
sleep(dur).await;
}
async fn sleep(dur: Duration) -> Timer {
Timer::after(dur)
}