1use std::time::Duration;
4
5use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
6use tokio::sync::mpsc;
7use tokio::time::Instant;
8
9use crate::conn::{Config, Connection, Event, Role, SendError};
10use crate::frame::Decoder;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum LinkEvent {
15 Ash(Event),
17 Closed(String),
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23pub enum LinkError {
24 #[error("ASH link task has stopped")]
26 Closed,
27 #[error(transparent)]
29 Send(#[from] SendError),
30}
31
32enum Command {
33 Send(Vec<u8>, tokio::sync::oneshot::Sender<Result<(), SendError>>),
34 Reset,
35}
36
37#[derive(Clone, Debug)]
39pub struct Link {
40 commands: mpsc::Sender<Command>,
41}
42
43impl std::fmt::Debug for Command {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 Command::Send(p, _) => write!(f, "Send({} bytes)", p.len()),
47 Command::Reset => f.write_str("Reset"),
48 }
49 }
50}
51
52impl Link {
53 pub fn spawn<T>(io: T, role: Role, config: Config) -> (Link, mpsc::Receiver<LinkEvent>)
56 where
57 T: AsyncRead + AsyncWrite + Send + 'static,
58 {
59 let (commands, command_rx) = mpsc::channel(16);
60 let (event_tx, events) = mpsc::channel(64);
61 tokio::spawn(run(io, Connection::new(role, config), command_rx, event_tx));
62 (Link { commands }, events)
63 }
64
65 pub async fn send(&self, payload: Vec<u8>) -> Result<(), LinkError> {
68 let (tx, rx) = tokio::sync::oneshot::channel();
69 self.commands
70 .send(Command::Send(payload, tx))
71 .await
72 .map_err(|_| LinkError::Closed)?;
73 rx.await
74 .map_err(|_| LinkError::Closed)?
75 .map_err(LinkError::Send)
76 }
77
78 pub async fn reset(&self) -> Result<(), LinkError> {
80 self.commands
81 .send(Command::Reset)
82 .await
83 .map_err(|_| LinkError::Closed)
84 }
85}
86
87async fn run<T>(
88 io: T,
89 mut conn: Connection,
90 mut commands: mpsc::Receiver<Command>,
91 events: mpsc::Sender<LinkEvent>,
92) where
93 T: AsyncRead + AsyncWrite + Send + 'static,
94{
95 let (mut reader, mut writer) = tokio::io::split(io);
96 let mut decoder = Decoder::new();
97 let mut buf = [0u8; 256];
98 let far = Duration::from_secs(3600);
99 loop {
100 let mut wrote = false;
101 while let Some(bytes) = conn.poll_transmit() {
102 if let Err(e) = writer.write_all(&bytes).await {
103 let _ = events
104 .send(LinkEvent::Closed(format!("write failed: {e}")))
105 .await;
106 return;
107 }
108 wrote = true;
109 }
110 if wrote {
111 if let Err(e) = writer.flush().await {
112 let _ = events
113 .send(LinkEvent::Closed(format!("flush failed: {e}")))
114 .await;
115 return;
116 }
117 }
118 while let Some(event) = conn.poll_event() {
119 if events.send(LinkEvent::Ash(event)).await.is_err() {
120 return;
121 }
122 }
123 let deadline = conn
124 .poll_timeout()
125 .map(Instant::from_std)
126 .unwrap_or_else(|| Instant::now() + far);
127 tokio::select! {
128 read = reader.read(&mut buf) => match read {
129 Ok(0) => {
130 let _ = events.send(LinkEvent::Closed("end of stream".into())).await;
131 return;
132 }
133 Ok(n) => {
134 let now = Instant::now().into_std();
135 for byte in buf.iter().take(n) {
136 match decoder.push(*byte) {
137 Some(Ok(frame)) => {
138 tracing::trace!(?frame, "ash rx");
139 conn.handle_frame(frame, now);
140 }
141 Some(Err(error)) => {
142 tracing::debug!(%error, "ash rx dropped frame");
143 conn.handle_bad_frame(error, now);
144 }
145 None => {}
146 }
147 }
148 }
149 Err(e) => {
150 let _ = events.send(LinkEvent::Closed(format!("read failed: {e}"))).await;
151 return;
152 }
153 },
154 command = commands.recv() => match command {
155 Some(Command::Send(payload, reply)) => {
156 let _ = reply.send(conn.send(payload, Instant::now().into_std()));
157 }
158 Some(Command::Reset) => {
159 decoder.reset();
160 conn.reset(Instant::now().into_std());
161 }
162 None => return,
163 },
164 _ = tokio::time::sleep_until(deadline) => {
165 conn.handle_timeout(Instant::now().into_std());
166 }
167 }
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 #[tokio::test]
176 async fn host_and_ncp_talk_over_a_duplex_stream() {
177 let (a, b) = tokio::io::duplex(1024);
178 let (host, mut host_events) = Link::spawn(a, Role::Host, Config::default());
179 let (ncp, mut ncp_events) = Link::spawn(b, Role::Ncp, Config::default());
180 host.reset().await.unwrap();
181 assert!(matches!(
182 host_events.recv().await,
183 Some(LinkEvent::Ash(Event::Connected { .. }))
184 ));
185 assert!(matches!(
186 ncp_events.recv().await,
187 Some(LinkEvent::Ash(Event::Connected { .. }))
188 ));
189 host.send(vec![1, 2, 3, 4]).await.unwrap();
190 assert_eq!(
191 ncp_events.recv().await,
192 Some(LinkEvent::Ash(Event::Data(vec![1, 2, 3, 4])))
193 );
194 ncp.send(vec![5, 6, 7]).await.unwrap();
195 assert_eq!(
196 host_events.recv().await,
197 Some(LinkEvent::Ash(Event::Data(vec![5, 6, 7])))
198 );
199 }
200}