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
use futures::sink::SinkExt;
use mpd_protocol::{response::Frame, Command, CommandList, MpdCodec, MpdCodecError, Response};
use tokio::{
io::{self, split, AsyncRead, AsyncWrite},
stream::{Stream, StreamExt},
sync::{
mpsc::{self, UnboundedReceiver, UnboundedSender},
oneshot,
},
};
use tokio_util::codec::{FramedRead, FramedWrite};
use std::collections::VecDeque;
use std::iter;
use crate::errors::{CommandError, StateChangeError};
use crate::util::Subsystem;
static IDLE: &str = "idle";
static CANCEL_IDLE: &str = "noidle";
type CommandResponder = oneshot::Sender<Result<Response, CommandError>>;
#[derive(Clone, Debug)]
pub struct Client(UnboundedSender<(CommandList, CommandResponder)>);
impl Client {
pub async fn connect<C>(
connection: C,
) -> Result<
(
Self,
impl Stream<Item = Result<Subsystem, StateChangeError>>,
),
MpdCodecError,
>
where
C: AsyncRead + AsyncWrite + Send + 'static,
{
let (state_changes_sender, state_changes) = mpsc::unbounded_channel();
let (commands, commands_receiver) = mpsc::unbounded_channel();
let connection = connect(connection).await?;
tokio::spawn(run_loop(
connection,
commands_receiver,
state_changes_sender,
));
Ok((Self(commands), state_changes))
}
pub async fn command(&self, command: Command) -> Result<Frame, CommandError> {
self.do_send(CommandList::new(command))
.await?
.single_frame()
.map_err(Into::into)
}
pub async fn command_list(&self, commands: CommandList) -> Result<Vec<Frame>, CommandError> {
let res = self.do_send(commands).await?;
let mut frames = Vec::with_capacity(res.len());
for frame in res {
match frame {
Ok(f) => frames.push(f),
Err(error) => {
return Err(CommandError::ErrorResponse {
error,
succesful_frames: frames,
});
}
}
}
Ok(frames)
}
async fn do_send(&self, commands: CommandList) -> Result<Response, CommandError> {
let (tx, rx) = oneshot::channel();
self.0.send((commands, tx))?;
rx.await?
}
}
struct Connection<C: AsyncRead + AsyncWrite> {
read: FramedRead<io::ReadHalf<C>, MpdCodec>,
write: FramedWrite<io::WriteHalf<C>, MpdCodec>,
}
async fn connect<C: AsyncRead + AsyncWrite>(connection: C) -> Result<Connection<C>, MpdCodecError> {
let (read, write) = split(connection);
let read = FramedRead::new(read, MpdCodec::new());
let mut write = FramedWrite::new(write, MpdCodec::new());
write.send(CommandList::new(Command::new(IDLE))).await?;
Ok(Connection { read, write })
}
async fn run_loop<C>(
connection: Connection<C>,
mut commands: UnboundedReceiver<(CommandList, CommandResponder)>,
state_changes: UnboundedSender<Result<Subsystem, StateChangeError>>,
) where
C: AsyncRead + AsyncWrite,
{
let Connection {
mut read,
mut write,
} = connection;
let mut current_command_responder: Option<CommandResponder> = None;
let mut command_queue = VecDeque::new();
let mut commands_channel_open = true;
while commands_channel_open || current_command_responder.is_some() || !command_queue.is_empty()
{
tokio::select! {
command = commands.next(), if commands_channel_open => {
let command = match command {
Some(c) => c,
None => {
commands_channel_open = false;
continue;
}
};
command_queue.push_back(command);
if current_command_responder.is_none() {
if let Err(e) = write.send(CommandList::new(Command::new(CANCEL_IDLE))).await {
let (_, responder) = command_queue.pop_back().unwrap();
let _ = responder.send(Err(e.into()));
}
}
}
msg = read.next() => {
let msg = match msg {
Some(m) => m,
None => break,
};
if let Some(responder) = current_command_responder.take() {
let _ = responder.send(msg.map_err(Into::into));
} else {
let msg = msg.map_err(Into::into).and_then(response_to_subsystem);
if let Some(msg) = msg.transpose() {
let _ = state_changes.send(msg);
}
}
if let Some((command, responder)) = next_command(&mut command_queue) {
current_command_responder = Some(responder);
if let Err(e) = write.send(command).await {
let responder = current_command_responder.take().unwrap();
let _ = responder.send(Err(e.into()));
}
} else {
if let Err(e) = write.send(CommandList::new(Command::new(IDLE))).await {
let _ = state_changes.send(Err(e.into()));
}
}
}
}
}
}
fn next_command(
queue: &mut VecDeque<(CommandList, CommandResponder)>,
) -> Option<(CommandList, CommandResponder)> {
iter::from_fn(|| queue.pop_front())
.find(|(_, responder)| !responder.is_closed())
}
fn response_to_subsystem(res: Response) -> Result<Option<Subsystem>, StateChangeError> {
let values = res.single_frame()?.values;
if values.is_empty() {
Ok(None)
} else {
let raw = values
.into_iter()
.find(|(k, _)| k == "changed")
.ok_or(StateChangeError::MissingChangedKey)?
.1;
Ok(Some(Subsystem::from(raw)))
}
}