|
| 1 | +use core::pin::pin; |
| 2 | + |
| 3 | +use std::path::PathBuf; |
| 4 | +use std::sync::Arc; |
| 5 | + |
| 6 | +use anyhow::Context as _; |
| 7 | +use clap::Parser; |
| 8 | +use futures::stream::select_all; |
| 9 | +use futures::StreamExt as _; |
| 10 | +use tokio::task::JoinSet; |
| 11 | +use tokio::{fs, select, signal}; |
| 12 | +use tracing::{debug, error, info, warn}; |
| 13 | + |
| 14 | +mod bindings { |
| 15 | + wit_bindgen_wrpc::generate!({ |
| 16 | + with: { |
| 17 | + "wrpc-examples:hello/handler": generate, |
| 18 | + } |
| 19 | + }); |
| 20 | +} |
| 21 | + |
| 22 | +#[derive(Parser, Debug)] |
| 23 | +#[command(author, version, about, long_about = None)] |
| 24 | +struct Args { |
| 25 | + /// Path to serve `wrpc-examples:hello/handler.hello` on |
| 26 | + #[arg(default_value = "/tmp/wrpc/hello.sock")] |
| 27 | + path: PathBuf, |
| 28 | +} |
| 29 | + |
| 30 | +#[derive(Clone, Copy)] |
| 31 | +struct Server; |
| 32 | + |
| 33 | +impl bindings::exports::wrpc_examples::hello::handler::Handler<tokio::net::unix::SocketAddr> |
| 34 | + for Server |
| 35 | +{ |
| 36 | + async fn hello(&self, _: tokio::net::unix::SocketAddr) -> anyhow::Result<String> { |
| 37 | + Ok("hello from Rust".to_string()) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +#[tokio::main] |
| 42 | +async fn main() -> anyhow::Result<()> { |
| 43 | + tracing_subscriber::fmt().init(); |
| 44 | + |
| 45 | + let Args { path } = Args::parse(); |
| 46 | + |
| 47 | + if let Some(dir) = path.parent() { |
| 48 | + if !dir.exists() { |
| 49 | + fs::create_dir_all(dir) |
| 50 | + .await |
| 51 | + .with_context(|| format!("failed to create `{}`", dir.display()))? |
| 52 | + } |
| 53 | + } |
| 54 | + let lis = tokio::net::UnixListener::bind(&path) |
| 55 | + .with_context(|| format!("failed to bind Unix listener on `{}`", path.display()))?; |
| 56 | + let srv = Arc::new(wrpc_transport::Server::default()); |
| 57 | + let accept = tokio::spawn({ |
| 58 | + let srv = Arc::clone(&srv); |
| 59 | + async move { |
| 60 | + loop { |
| 61 | + if let Err(err) = srv.accept(&lis).await { |
| 62 | + error!(?err, "failed to accept Unix connection"); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + }); |
| 67 | + |
| 68 | + let invocations = bindings::serve(srv.as_ref(), Server) |
| 69 | + .await |
| 70 | + .context("failed to serve `wrpc-examples.hello/handler.hello`")?; |
| 71 | + // NOTE: This will conflate all invocation streams into a single stream via `futures::stream::SelectAll`, |
| 72 | + // to customize this, iterate over the returned `invocations` and set up custom handling per export |
| 73 | + let mut invocations = select_all( |
| 74 | + invocations |
| 75 | + .into_iter() |
| 76 | + .map(|(instance, name, invocations)| invocations.map(move |res| (instance, name, res))), |
| 77 | + ); |
| 78 | + let shutdown = signal::ctrl_c(); |
| 79 | + let mut shutdown = pin!(shutdown); |
| 80 | + let mut tasks = JoinSet::new(); |
| 81 | + loop { |
| 82 | + select! { |
| 83 | + Some((instance, name, res)) = invocations.next() => { |
| 84 | + match res { |
| 85 | + Ok(fut) => { |
| 86 | + debug!(instance, name, "invocation accepted"); |
| 87 | + tasks.spawn(async move { |
| 88 | + if let Err(err) = fut.await { |
| 89 | + warn!(?err, "failed to handle invocation"); |
| 90 | + } else { |
| 91 | + info!(instance, name, "invocation successfully handled"); |
| 92 | + } |
| 93 | + }); |
| 94 | + } |
| 95 | + Err(err) => { |
| 96 | + warn!(?err, instance, name, "failed to accept invocation"); |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + Some(res) = tasks.join_next() => { |
| 101 | + if let Err(err) = res { |
| 102 | + error!(?err, "failed to join task"); |
| 103 | + } |
| 104 | + } |
| 105 | + res = &mut shutdown => { |
| 106 | + accept.abort(); |
| 107 | + // wait for all invocations to complete |
| 108 | + while let Some(res) = tasks.join_next().await { |
| 109 | + if let Err(err) = res { |
| 110 | + error!(?err, "failed to join task"); |
| 111 | + } |
| 112 | + } |
| 113 | + return res.context("failed to listen for ^C") |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | +} |
0 commit comments