use std::sync::Arc;
use std::time::Duration;
use opentelemetry_sdk::runtime::{Runtime, RuntimeChannel};
#[derive(Clone, Debug)]
pub(crate) struct SignalKitOtelRuntime {
handle: tokio::runtime::Handle,
}
#[derive(Debug)]
pub(crate) struct SignalKitOtelExportRuntime {
runtime: Option<Arc<tokio::runtime::Runtime>>,
}
impl SignalKitOtelExportRuntime {
pub(crate) fn new() -> std::io::Result<Self> {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.thread_name("signal-kit-otel")
.build()?;
Ok(Self {
runtime: Some(Arc::new(runtime)),
})
}
pub(crate) fn adapter(&self) -> SignalKitOtelRuntime {
let runtime = self
.runtime
.as_ref()
.expect("export runtime cannot be dropped before its processors");
SignalKitOtelRuntime {
handle: runtime.handle().clone(),
}
}
}
impl Drop for SignalKitOtelExportRuntime {
fn drop(&mut self) {
if let Some(runtime) = self.runtime.take() {
std::thread::Builder::new()
.name("signal-kit-otel-shutdown".to_string())
.spawn(move || drop(runtime))
.ok();
}
}
}
impl Runtime for SignalKitOtelRuntime {
fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
{
#[allow(clippy::let_underscore_future)]
let _ = self.handle.spawn(future);
}
fn delay(&self, duration: Duration) -> impl Future<Output = ()> + Send + 'static {
#[allow(clippy::manual_async_fn)]
{
async move {
tokio::time::sleep(duration).await;
}
}
}
}
impl RuntimeChannel for SignalKitOtelRuntime {
type Receiver<T: std::fmt::Debug + Send> = tokio_stream::wrappers::ReceiverStream<T>;
type Sender<T: std::fmt::Debug + Send> = tokio::sync::mpsc::Sender<T>;
fn batch_message_channel<T: std::fmt::Debug + Send>(
&self,
capacity: usize,
) -> (Self::Sender<T>, Self::Receiver<T>) {
let (sender, receiver) = tokio::sync::mpsc::channel(capacity);
(
sender,
tokio_stream::wrappers::ReceiverStream::new(receiver),
)
}
}