|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use futures_util::StreamExt; |
| 4 | +use pyo3::{Bound, Py, PyAny, Python}; |
| 5 | +use tokio::sync::Mutex; |
| 6 | + |
| 7 | +use crate::{exceptions::rust_err::NatsrpyResult, utils::natsrpy_future}; |
| 8 | + |
| 9 | +#[pyo3::pyclass] |
| 10 | +pub struct CallbackSubscription { |
| 11 | + inner: Option<Arc<Mutex<async_nats::Subscriber>>>, |
| 12 | + reading_task: tokio::task::AbortHandle, |
| 13 | +} |
| 14 | + |
| 15 | +async fn process_message(message: async_nats::message::Message, py_callback: Py<PyAny>) { |
| 16 | + let task = async || -> NatsrpyResult<()> { |
| 17 | + let message = crate::message::Message::try_from(&message)?; |
| 18 | + let awaitable = Python::attach(|gil| -> NatsrpyResult<_> { |
| 19 | + let res = py_callback.call1(gil, (message,))?; |
| 20 | + let rust_task = pyo3_async_runtimes::tokio::into_future(res.into_bound(gil))?; |
| 21 | + Ok(rust_task) |
| 22 | + })?; |
| 23 | + awaitable.await?; |
| 24 | + Ok(()) |
| 25 | + }; |
| 26 | + if let Err(err) = task().await { |
| 27 | + log::error!("Cannot process message {message:?}. Error: {err}"); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +async fn start_py_sub( |
| 32 | + sub: Arc<Mutex<async_nats::Subscriber>>, |
| 33 | + py_callback: Py<PyAny>, |
| 34 | + locals: pyo3_async_runtimes::TaskLocals, |
| 35 | +) { |
| 36 | + while let Some(message) = sub.lock().await.next().await { |
| 37 | + let py_cb = Python::attach(|py| py_callback.clone_ref(py)); |
| 38 | + tokio::spawn(pyo3_async_runtimes::tokio::scope( |
| 39 | + locals.clone(), |
| 40 | + process_message(message, py_cb), |
| 41 | + )); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl CallbackSubscription { |
| 46 | + pub fn new(sub: async_nats::Subscriber, callback: Py<PyAny>) -> NatsrpyResult<Self> { |
| 47 | + let sub = Arc::new(Mutex::new(sub)); |
| 48 | + let cb_sub = sub.clone(); |
| 49 | + let task_locals = Python::attach(pyo3_async_runtimes::tokio::get_current_locals)?; |
| 50 | + let task_handle = tokio::task::spawn(pyo3_async_runtimes::tokio::scope( |
| 51 | + task_locals.clone(), |
| 52 | + start_py_sub(cb_sub, callback, task_locals), |
| 53 | + )) |
| 54 | + .abort_handle(); |
| 55 | + Ok(Self { |
| 56 | + inner: Some(sub), |
| 57 | + reading_task: task_handle, |
| 58 | + }) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +#[pyo3::pymethods] |
| 63 | +impl CallbackSubscription { |
| 64 | + #[pyo3(signature=(limit=None))] |
| 65 | + pub fn unsubscribe<'py>( |
| 66 | + &self, |
| 67 | + py: Python<'py>, |
| 68 | + limit: Option<u64>, |
| 69 | + ) -> NatsrpyResult<Bound<'py, PyAny>> { |
| 70 | + let Some(inner) = self.inner.clone() else { |
| 71 | + unreachable!("Subscription used after del") |
| 72 | + }; |
| 73 | + natsrpy_future(py, async move { |
| 74 | + if let Some(limit) = limit { |
| 75 | + inner.lock().await.unsubscribe_after(limit).await?; |
| 76 | + } else { |
| 77 | + inner.lock().await.unsubscribe().await?; |
| 78 | + } |
| 79 | + Ok(()) |
| 80 | + }) |
| 81 | + } |
| 82 | + |
| 83 | + pub fn drain<'py>(&self, py: Python<'py>) -> NatsrpyResult<Bound<'py, PyAny>> { |
| 84 | + let Some(inner) = self.inner.clone() else { |
| 85 | + unreachable!("Subscription used after del") |
| 86 | + }; |
| 87 | + natsrpy_future(py, async move { |
| 88 | + inner.lock().await.drain().await?; |
| 89 | + Ok(()) |
| 90 | + }) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +/// This is required only because |
| 95 | +/// in nats library they run async operation on Drop. |
| 96 | +/// |
| 97 | +/// Because of that we need to execute drop in async |
| 98 | +/// runtime's context. |
| 99 | +/// |
| 100 | +/// And because we want to perform a drop, |
| 101 | +/// we need somehow drop the inner variable, |
| 102 | +/// but leave self intouch. That is exactly why we have |
| 103 | +/// Option<Arc<...>>. So we can just assign it to None |
| 104 | +/// and it will perform a drop. |
| 105 | +impl Drop for CallbackSubscription { |
| 106 | + fn drop(&mut self) { |
| 107 | + pyo3_async_runtimes::tokio::get_runtime().block_on(async move { |
| 108 | + self.inner = None; |
| 109 | + self.reading_task.abort(); |
| 110 | + }); |
| 111 | + } |
| 112 | +} |
0 commit comments