Skip to content
This repository was archived by the owner on May 11, 2023. It is now read-only.

Commit 26c433a

Browse files
committed
zb: azync::Connection implements Stream directly
instead of through MessageStream, which is dropped as part of this change. While a mutable ref is needed to operate on streams, we don't need to switch to `&mut self` in other methods since one can just clone the Connection to get a mutable ref to it. i-e All `stream()` calls can just be changed to `clone()` calls.
1 parent de2b52d commit 26c433a

File tree

4 files changed

+40
-76
lines changed

4 files changed

+40
-76
lines changed

zbus/src/azync/connection.rs

Lines changed: 29 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use async_broadcast::{broadcast, InactiveReceiver, Sender as Broadcaster};
1+
use async_broadcast::{broadcast, Receiver as BroadcastReceiver, Sender as Broadcaster};
22
use async_channel::{bounded, Receiver, Sender};
33
use async_executor::Executor;
44
#[cfg(feature = "internal-executor")]
@@ -31,8 +31,9 @@ use zvariant::ObjectPath;
3131
use futures_core::{stream, Future};
3232
use futures_sink::Sink;
3333
use futures_util::{
34+
future::{select, Either},
3435
sink::SinkExt,
35-
stream::{select as stream_select, StreamExt},
36+
stream::StreamExt,
3637
};
3738

3839
use crate::{
@@ -128,12 +129,6 @@ struct ConnectionInner<S> {
128129
// Message receiver task
129130
msg_receiver_task: sync::Mutex<Option<Task<()>>>,
130131

131-
// We're using sync Mutex here as we don't intend to keep it locked while awaiting.
132-
msg_receiver: sync::RwLock<InactiveReceiver<Arc<Message>>>,
133-
134-
// Receiver side of the error channel
135-
error_receiver: Receiver<Error>,
136-
137132
signal_subscriptions: Mutex<HashMap<u64, SignalSubscription>>,
138133
}
139134

@@ -223,8 +218,7 @@ impl MessageReceiverTask<Box<dyn Socket>> {
223218
///
224219
/// Unlike [`zbus::Connection`], there is no direct async equivalent of
225220
/// [`zbus::Connection::receive_message`] method provided. This is because the `futures` crate
226-
/// already provides a nice rich API that makes use of the [`stream::Stream`] implementation that is
227-
/// returned by [`Connection::stream`] method.
221+
/// already provides a nice rich API that makes use of the [`stream::Stream`] implementation.
228222
///
229223
/// # Caveats
230224
///
@@ -283,7 +277,7 @@ impl MessageReceiverTask<Box<dyn Socket>> {
283277
/// )
284278
/// .await?;
285279
///
286-
/// while let Some(msg) = connection.stream().await.try_next().await? {
280+
/// while let Some(msg) = connection.try_next().await? {
287281
/// println!("Got message: {}", msg);
288282
/// }
289283
///
@@ -307,6 +301,11 @@ impl MessageReceiverTask<Box<dyn Socket>> {
307301
#[derive(Clone, Debug)]
308302
pub struct Connection {
309303
inner: Arc<ConnectionInner<Box<dyn Socket>>>,
304+
305+
msg_receiver: BroadcastReceiver<Arc<Message>>,
306+
307+
// Receiver side of the error channel
308+
error_receiver: Receiver<Error>,
310309
}
311310

312311
assert_impl_all!(Connection: Send, Sync, Unpin);
@@ -366,22 +365,6 @@ impl Connection {
366365
Self::new(auth, false).await
367366
}
368367

369-
/// Get a stream to receive incoming messages.
370-
pub async fn stream(&self) -> MessageStream {
371-
let msg_receiver = self
372-
.inner
373-
.msg_receiver
374-
.read()
375-
// SAFETY: Not much we can do about a poisoned mutex.
376-
.expect("poisoned lock")
377-
.activate_cloned()
378-
.map(Ok);
379-
let error_stream = self.inner.error_receiver.clone().map(Err);
380-
let stream = stream_select(error_stream, msg_receiver).boxed();
381-
382-
MessageStream { stream }
383-
}
384-
385368
/// Send `msg` to the peer.
386369
///
387370
/// Unlike our [`Sink`] implementation, this method sets a unique (to this connection) serial
@@ -415,7 +398,7 @@ impl Connection {
415398
B: serde::ser::Serialize + zvariant::Type,
416399
E: Into<MessageError>,
417400
{
418-
let stream = self.stream().await;
401+
let stream = self.clone();
419402
let m = Message::method(
420403
self.unique_name(),
421404
destination,
@@ -544,11 +527,7 @@ impl Connection {
544527

545528
/// Max number of messages to queue.
546529
pub fn max_queued(&self) -> usize {
547-
self.inner
548-
.msg_receiver
549-
.read()
550-
.expect("poisoned lock")
551-
.capacity()
530+
self.msg_receiver.capacity()
552531
}
553532

554533
/// Set the max number of messages to queue.
@@ -576,12 +555,8 @@ impl Connection {
576555
/// // Do something useful with `conn`..
577556
///# Ok::<_, Box<dyn Error + Send + Sync>>(())
578557
/// ```
579-
pub fn set_max_queued(self, max: usize) -> Self {
580-
self.inner
581-
.msg_receiver
582-
.write()
583-
.expect("poisoned lock")
584-
.set_capacity(max);
558+
pub fn set_max_queued(mut self, max: usize) -> Self {
559+
self.msg_receiver.set_capacity(max);
585560

586561
self
587562
}
@@ -742,8 +717,6 @@ impl Connection {
742717
// ourselves in parallel to making the method call.
743718
#[cfg(not(feature = "internal-executor"))]
744719
let name = {
745-
use futures_util::future::{select, Either};
746-
747720
let executor = self.inner.executor.clone();
748721
let ticking_future = async move {
749722
// Keep running as long as this task/future is not cancelled.
@@ -785,7 +758,6 @@ impl Connection {
785758

786759
let (mut msg_sender, msg_receiver) = broadcast(DEFAULT_MAX_QUEUED);
787760
msg_sender.set_overflow(true);
788-
let msg_receiver = msg_receiver.deactivate();
789761
let (error_sender, error_receiver) = bounded(1);
790762
let executor = Arc::new(Executor::new());
791763
let raw_in_conn = Arc::new(Mutex::new(auth.conn));
@@ -796,17 +768,17 @@ impl Connection {
796768
.spawn(&executor);
797769

798770
let connection = Self {
771+
error_receiver,
772+
msg_receiver,
799773
inner: Arc::new(ConnectionInner {
800774
raw_in_conn,
801775
sink,
802-
error_receiver,
803776
server_guid: auth.server_guid,
804777
cap_unix_fd,
805778
bus_conn: bus_connection,
806779
serial: AtomicU32::new(1),
807780
unique_name: OnceCell::new(),
808781
signal_subscriptions: Mutex::new(HashMap::new()),
809-
msg_receiver: sync::RwLock::new(msg_receiver),
810782
executor: executor.clone(),
811783
msg_receiver_task: sync::Mutex::new(Some(msg_receiver_task)),
812784
}),
@@ -942,20 +914,19 @@ impl Sink<Message> for Connection {
942914
}
943915
}
944916

945-
/// A [`stream::Stream`] implementation that yields [`Message`] items.
946-
///
947-
/// Use [`Connection::stream`] to create an instance of this type.
948-
pub struct MessageStream {
949-
stream: stream::BoxStream<'static, Result<Arc<Message>>>,
950-
}
951-
952-
assert_impl_all!(MessageStream: Send, Unpin);
953-
954-
impl stream::Stream for MessageStream {
917+
impl stream::Stream for Connection {
955918
type Item = Result<Arc<Message>>;
956919

957920
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
958-
stream::Stream::poll_next(self.get_mut().stream.as_mut(), cx)
921+
let stream = self.get_mut();
922+
let msg_fut = stream.msg_receiver.next();
923+
let err_fut = stream.error_receiver.next();
924+
let mut select_fut = select(msg_fut, err_fut);
925+
926+
match futures_core::ready!(Pin::new(&mut select_fut).poll(cx)) {
927+
Either::Left((msg, _)) => Poll::Ready(msg.map(Ok)),
928+
Either::Right((error, _)) => Poll::Ready(error.map(Err)),
929+
}
959930
}
960931
}
961932

@@ -1016,13 +987,11 @@ mod tests {
1016987
let server = Connection::new_unix_server(p0, &guid);
1017988
let client = Connection::new_unix_client(p1, false);
1018989

1019-
let (client_conn, server_conn) = futures_util::try_join!(client, server)?;
1020-
let mut client_stream = client_conn.stream().await;
1021-
let mut server_stream = server_conn.stream().await;
990+
let (mut client_conn, mut server_conn) = futures_util::try_join!(client, server)?;
1022991

1023992
let server_future = async {
1024993
let mut method: Option<Arc<Message>> = None;
1025-
while let Some(m) = server_stream.try_next().await? {
994+
while let Some(m) = server_conn.try_next().await? {
1026995
if m.to_string() == "Method call Test" {
1027996
method.replace(m);
1028997

@@ -1044,7 +1013,7 @@ mod tests {
10441013
.await?;
10451014
assert_eq!(reply.to_string(), "Method return");
10461015
// Check we didn't miss the signal that was sent during the call.
1047-
let m = client_stream.try_next().await?.unwrap();
1016+
let m = client_conn.try_next().await?.unwrap();
10481017
assert_eq!(m.to_string(), "Signal ASignalForYou");
10491018
reply.body::<String>().map_err(|e| e.into())
10501019
};

zbus/src/azync/proxy.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use std::{
2121
use zvariant::{ObjectPath, OwnedValue, Value};
2222

2323
use crate::{
24-
azync::{Connection, MessageStream},
24+
azync::Connection,
2525
fdo::{self, AsyncIntrospectableProxy, AsyncPropertiesProxy},
2626
Error, Message, MessageHeader, MessageType, Result,
2727
};
@@ -145,7 +145,7 @@ pub(crate) struct ProxyInner<'a> {
145145
#[derivative(Debug = "ignore")]
146146
sig_handlers: Mutex<SlotMap<SignalHandlerId, SignalHandlerInfo>>,
147147
#[derivative(Debug = "ignore")]
148-
signal_msg_stream: OnceCell<Mutex<MessageStream>>,
148+
signal_msg_stream: OnceCell<Mutex<Connection>>,
149149
}
150150

151151
pub struct PropertyStream<'a, T> {
@@ -575,8 +575,7 @@ impl<'a> Proxy<'a> {
575575
let stream = self
576576
.inner
577577
.conn
578-
.stream()
579-
.await
578+
.clone()
580579
.filter(move |m| {
581580
ready(
582581
m.as_ref()
@@ -772,11 +771,11 @@ impl<'a> Proxy<'a> {
772771
Ok(self.inner.dest_unique_name.get().unwrap())
773772
}
774773

775-
async fn msg_stream(&self) -> &Mutex<MessageStream> {
774+
async fn msg_stream(&self) -> &Mutex<Connection> {
776775
match self.inner.signal_msg_stream.get() {
777776
Some(stream) => stream,
778777
None => {
779-
let stream = self.inner.conn.stream().await;
778+
let stream = self.inner.conn.clone();
780779
self.inner
781780
.signal_msg_stream
782781
.set(Mutex::new(stream))

zbus/src/connection.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,7 @@ use zvariant::ObjectPath;
1313

1414
use async_io::block_on;
1515

16-
use crate::{
17-
azync::{self, MessageStream},
18-
Error, Guid, Message, MessageError, Result,
19-
};
16+
use crate::{azync, Error, Guid, Message, MessageError, Result};
2017

2118
/// A D-Bus connection.
2219
///
@@ -58,7 +55,7 @@ use crate::{
5855
pub struct Connection {
5956
inner: azync::Connection,
6057
#[derivative(Debug = "ignore")]
61-
stream: Arc<Mutex<MessageStream>>,
58+
stream: Arc<Mutex<azync::Connection>>,
6259
}
6360

6461
assert_impl_all!(Connection: Send, Sync, Unpin);
@@ -260,7 +257,7 @@ impl Connection {
260257

261258
impl From<azync::Connection> for Connection {
262259
fn from(conn: azync::Connection) -> Self {
263-
let stream = Arc::new(Mutex::new(block_on(conn.stream())));
260+
let stream = Arc::new(Mutex::new(conn.clone()));
264261

265262
Self {
266263
inner: conn,

zbus/src/object_server.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@ use static_assertions::assert_impl_all;
1616
use zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Value};
1717

1818
use crate::{
19-
azync::MessageStream,
20-
fdo,
19+
azync, fdo,
2120
fdo::{Introspectable, Peer, Properties},
2221
Connection, Error, Message, MessageHeader, MessageType, Result,
2322
};
@@ -268,7 +267,7 @@ pub struct ObjectServer {
268267
conn: Connection,
269268
root: Node,
270269
#[derivative(Debug = "ignore")]
271-
msg_stream: MessageStream,
270+
msg_stream: azync::Connection,
272271
}
273272

274273
assert_impl_all!(ObjectServer: Unpin);
@@ -278,7 +277,7 @@ impl ObjectServer {
278277
pub fn new(connection: &Connection) -> Self {
279278
Self {
280279
conn: connection.clone(),
281-
msg_stream: block_on(connection.inner().stream()),
280+
msg_stream: connection.inner().clone(),
282281
root: Node::new("/".try_into().expect("zvariant bug")),
283282
}
284283
}

0 commit comments

Comments
 (0)