Skip to content

Commit

Permalink
fix(rs-nats): create a Tokio runtime if one does not exist
Browse files Browse the repository at this point in the history
Signed-off-by: Roman Volosatovs <[email protected]>
  • Loading branch information
rvolosatovs committed Sep 25, 2024
1 parent 424edd4 commit 34f3603
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
15 changes: 12 additions & 3 deletions crates/transport-nats/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use futures::{Stream, StreamExt};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::sync::oneshot;
use tokio::try_join;
use tracing::{debug, instrument, trace, warn};
use tracing::{debug, error, instrument, trace, warn};
use wrpc_transport::Index as _;

pub const PROTOCOL: &str = "wrpc.0.0.1";
Expand Down Expand Up @@ -472,12 +472,21 @@ impl Drop for SubjectWriter {
if !self.shutdown {
let nats = self.nats.clone();
let subject = mem::replace(&mut self.tx, Subject::from_static(""));
tokio::spawn(async move {
let fut = async move {
trace!("writing stream shutdown message");
if let Err(err) = nats.publish(subject, Bytes::default()).await {
warn!(?err, "failed to publish stream shutdown message")
}
});
};
match tokio::runtime::Handle::try_current() {
Ok(rt) => {
rt.spawn(fut);
}
Err(_) => match tokio::runtime::Runtime::new() {
Ok(rt) => rt.block_on(fut),
Err(err) => error!(?err, "failed to create a new Tokio runtime"),
},
}
}
}
}
Expand Down
19 changes: 18 additions & 1 deletion tests/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use core::str;
use core::time::Duration;

use std::sync::Arc;
use std::thread;

use anyhow::Context;
use bytes::Bytes;
Expand Down Expand Up @@ -576,7 +577,7 @@ where
#[instrument(skip_all, ret)]
async fn assert_dynamic<C, I, S>(clt: Arc<I>, srv: Arc<S>) -> anyhow::Result<()>
where
C: Send + Sync + Default,
C: Send + Sync + Default + 'static,
I: wrpc::Invoke<Context = C>,
S: wrpc::Serve<Context = C>,
{
Expand Down Expand Up @@ -625,6 +626,12 @@ where
.await
.expect("failed to accept invocation")
.expect("unexpected end of stream");
let inv = reset_inv
.try_next()
.await
.expect("failed to accept invocation")
.expect("unexpected end of stream");
thread::spawn(|| inv);
anyhow::Ok(())
}
.instrument(info_span!("server")),
Expand All @@ -649,6 +656,16 @@ where
)
.await
.expect_err("`test.reset` should have failed");
info!("invoking `test.reset`");
clt.invoke_values_blocking::<_, _, (String,)>(
C::default(),
"test",
"reset",
("arg",),
&[[]; 0],
)
.await
.expect_err("`test.reset` should have failed");
}
.instrument(info_span!("client")),
);
Expand Down

0 comments on commit 34f3603

Please sign in to comment.