Skip to main content

diagprint_async/
lib.rs

1//! Bounded asynchronous diagnostic delivery for diagprint.
2//!
3//! Queues are always bounded and overload behavior is always explicit.
4//! The synchronous `diagprint` crate remains independent of any async runtime.
5
6use diagprint::{Diagnostic, DiagnosticReport, DiagnosticSink, Severity, SinkError, SinkResult};
7use std::{
8    error::Error,
9    fmt,
10    sync::{Arc, Mutex},
11};
12use tokio::{
13    sync::{mpsc, oneshot},
14    task::JoinHandle,
15};
16
17/// Behavior when the bounded delivery queue reaches capacity.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19pub enum BackpressurePolicy {
20    /// Wait asynchronously until queue capacity becomes available.
21    #[default]
22    Block,
23
24    /// Reject the new diagnostic immediately when the queue is full.
25    Reject,
26
27    /// Drop the newest diagnostic only when its severity is less than or equal
28    /// to `up_to`.
29    ///
30    /// Diagnostics above the configured threshold are rejected instead of
31    /// silently discarded. Setting `up_to` to `Fatal` explicitly permits all
32    /// severities to be dropped under overload.
33    DropNewest { up_to: Severity },
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum SubmitOutcome {
38    Enqueued,
39    Dropped,
40}
41
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub struct SubmissionSummary {
44    pub enqueued: usize,
45    pub dropped: usize,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum AsyncSinkError {
50    NoRuntime,
51
52    InvalidCapacity,
53
54    QueueFull { severity: Severity },
55
56    Closed,
57
58    Worker { error: SinkError },
59
60    Join { message: String },
61}
62
63impl fmt::Display for AsyncSinkError {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            Self::NoRuntime => {
67                formatter.write_str("diagprint-async requires an active Tokio runtime")
68            }
69
70            Self::InvalidCapacity => {
71                formatter.write_str("async diagnostic queue capacity must be greater than zero")
72            }
73
74            Self::QueueFull { severity } => {
75                write!(
76                    formatter,
77                    "async diagnostic queue is full; {severity} diagnostic was not accepted"
78                )
79            }
80
81            Self::Closed => formatter.write_str("async diagnostic worker is closed"),
82
83            Self::Worker { error } => {
84                write!(formatter, "async diagnostic worker failed: {error}")
85            }
86
87            Self::Join { message } => {
88                write!(formatter, "async diagnostic worker join failed: {message}")
89            }
90        }
91    }
92}
93
94impl Error for AsyncSinkError {
95    fn source(&self) -> Option<&(dyn Error + 'static)> {
96        match self {
97            Self::Worker { error } => Some(error),
98
99            _ => None,
100        }
101    }
102}
103
104#[derive(Debug)]
105pub struct ReportSubmitError {
106    pub error: AsyncSinkError,
107    pub submitted: SubmissionSummary,
108}
109
110impl fmt::Display for ReportSubmitError {
111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(
113            formatter,
114            "{} after {} enqueued and {} dropped diagnostics",
115            self.error, self.submitted.enqueued, self.submitted.dropped,
116        )
117    }
118}
119
120impl Error for ReportSubmitError {
121    fn source(&self) -> Option<&(dyn Error + 'static)> {
122        Some(&self.error)
123    }
124}
125
126enum Command {
127    Diagnostic(Box<Diagnostic>),
128
129    Flush(oneshot::Sender<SinkResult<()>>),
130
131    Shutdown(oneshot::Sender<SinkResult<()>>),
132}
133
134#[derive(Clone, Default)]
135struct WorkerState {
136    failure: Arc<Mutex<Option<SinkError>>>,
137}
138
139impl WorkerState {
140    fn failure(&self) -> Option<SinkError> {
141        self.failure
142            .lock()
143            .unwrap_or_else(|poisoned| poisoned.into_inner())
144            .clone()
145    }
146
147    fn fail(&self, error: SinkError) {
148        let mut failure = self
149            .failure
150            .lock()
151            .unwrap_or_else(|poisoned| poisoned.into_inner());
152
153        if failure.is_none() {
154            *failure = Some(error);
155        }
156    }
157}
158
159/// Bounded asynchronous front-end for a synchronous [`DiagnosticSink`].
160///
161/// Diagnostics are moved to a blocking worker thread. The queue never grows
162/// beyond its configured capacity.
163pub struct AsyncDiagnosticSink {
164    sender: mpsc::Sender<Command>,
165
166    worker: JoinHandle<SinkResult<()>>,
167
168    state: WorkerState,
169
170    backpressure: BackpressurePolicy,
171}
172
173impl AsyncDiagnosticSink {
174    pub fn spawn<S>(
175        sink: S,
176        capacity: usize,
177        backpressure: BackpressurePolicy,
178    ) -> Result<Self, AsyncSinkError>
179    where
180        S: DiagnosticSink + 'static,
181    {
182        if capacity == 0 {
183            return Err(AsyncSinkError::InvalidCapacity);
184        }
185
186        let runtime =
187            tokio::runtime::Handle::try_current().map_err(|_| AsyncSinkError::NoRuntime)?;
188
189        let (sender, receiver) = mpsc::channel(capacity);
190
191        let state = WorkerState::default();
192
193        let worker_state = state.clone();
194
195        let sink: Box<dyn DiagnosticSink> = Box::new(sink);
196
197        let worker = runtime.spawn_blocking(move || worker_loop(receiver, sink, worker_state));
198
199        Ok(Self {
200            sender,
201            worker,
202            state,
203            backpressure,
204        })
205    }
206
207    pub const fn backpressure(&self) -> BackpressurePolicy {
208        self.backpressure
209    }
210
211    pub fn capacity(&self) -> usize {
212        self.sender.capacity()
213    }
214
215    pub fn max_capacity(&self) -> usize {
216        self.sender.max_capacity()
217    }
218
219    pub async fn emit(&self, diagnostic: Diagnostic) -> Result<SubmitOutcome, AsyncSinkError> {
220        if let Some(error) = self.state.failure() {
221            return Err(AsyncSinkError::Worker { error });
222        }
223
224        let severity = diagnostic.severity;
225
226        let command = Command::Diagnostic(Box::new(diagnostic));
227
228        match self.backpressure {
229            BackpressurePolicy::Block => {
230                self.sender
231                    .send(command)
232                    .await
233                    .map_err(|_| self.closed_error())?;
234
235                Ok(SubmitOutcome::Enqueued)
236            }
237
238            BackpressurePolicy::Reject => match self.sender.try_send(command) {
239                Ok(()) => Ok(SubmitOutcome::Enqueued),
240
241                Err(mpsc::error::TrySendError::Full(_)) => {
242                    Err(AsyncSinkError::QueueFull { severity })
243                }
244
245                Err(mpsc::error::TrySendError::Closed(_)) => Err(self.closed_error()),
246            },
247
248            BackpressurePolicy::DropNewest { up_to } => match self.sender.try_send(command) {
249                Ok(()) => Ok(SubmitOutcome::Enqueued),
250
251                Err(mpsc::error::TrySendError::Full(_)) if severity <= up_to => {
252                    Ok(SubmitOutcome::Dropped)
253                }
254
255                Err(mpsc::error::TrySendError::Full(_)) => {
256                    Err(AsyncSinkError::QueueFull { severity })
257                }
258
259                Err(mpsc::error::TrySendError::Closed(_)) => Err(self.closed_error()),
260            },
261        }
262    }
263
264    pub async fn emit_ref(&self, diagnostic: &Diagnostic) -> Result<SubmitOutcome, AsyncSinkError> {
265        self.emit(diagnostic.clone()).await
266    }
267
268    pub async fn emit_report(
269        &self,
270        report: &DiagnosticReport,
271    ) -> Result<SubmissionSummary, ReportSubmitError> {
272        let mut submitted = SubmissionSummary::default();
273
274        for diagnostic in report {
275            match self.emit_ref(diagnostic).await {
276                Ok(SubmitOutcome::Enqueued) => {
277                    submitted.enqueued += 1;
278                }
279
280                Ok(SubmitOutcome::Dropped) => {
281                    submitted.dropped += 1;
282                }
283
284                Err(error) => {
285                    return Err(ReportSubmitError { error, submitted });
286                }
287            }
288        }
289
290        Ok(submitted)
291    }
292
293    /// Waits until all previously submitted diagnostics have been delivered
294    /// and the underlying sink has flushed.
295    pub async fn flush(&self) -> Result<(), AsyncSinkError> {
296        if let Some(error) = self.state.failure() {
297            return Err(AsyncSinkError::Worker { error });
298        }
299
300        let (response_tx, response_rx) = oneshot::channel();
301
302        self.sender
303            .send(Command::Flush(response_tx))
304            .await
305            .map_err(|_| self.closed_error())?;
306
307        let result = response_rx.await.map_err(|_| self.closed_error())?;
308
309        result.map_err(|error| AsyncSinkError::Worker { error })
310    }
311
312    /// Flushes all queued diagnostics and shuts the worker down.
313    pub async fn shutdown(self) -> Result<(), AsyncSinkError> {
314        let state = self.state.clone();
315
316        let (response_tx, response_rx) = oneshot::channel();
317
318        let send_result = self.sender.send(Command::Shutdown(response_tx)).await;
319
320        let response_result = if send_result.is_ok() {
321            match response_rx.await {
322                Ok(result) => result.map_err(|error| AsyncSinkError::Worker { error }),
323
324                Err(_) => Err(state_error_or_closed(&state)),
325            }
326        } else {
327            Err(state_error_or_closed(&state))
328        };
329
330        drop(self.sender);
331
332        let worker_result = self
333            .worker
334            .await
335            .map_err(|error| AsyncSinkError::Join {
336                message: error.to_string(),
337            })?
338            .map_err(|error| AsyncSinkError::Worker { error });
339
340        response_result?;
341        worker_result
342    }
343
344    fn closed_error(&self) -> AsyncSinkError {
345        state_error_or_closed(&self.state)
346    }
347}
348
349fn state_error_or_closed(state: &WorkerState) -> AsyncSinkError {
350    match state.failure() {
351        Some(error) => AsyncSinkError::Worker { error },
352
353        None => AsyncSinkError::Closed,
354    }
355}
356
357fn worker_loop(
358    mut receiver: mpsc::Receiver<Command>,
359    sink: Box<dyn DiagnosticSink>,
360    state: WorkerState,
361) -> SinkResult<()> {
362    while let Some(command) = receiver.blocking_recv() {
363        match command {
364            Command::Diagnostic(diagnostic) => {
365                if let Err(error) = sink.emit(&diagnostic) {
366                    state.fail(error.clone());
367
368                    receiver.close();
369
370                    return Err(error);
371                }
372            }
373
374            Command::Flush(response) => {
375                let result = sink.flush();
376
377                if let Err(error) = &result {
378                    state.fail(error.clone());
379
380                    receiver.close();
381                }
382
383                let failed = result.is_err();
384
385                let _ = response.send(result.clone());
386
387                if failed {
388                    return result;
389                }
390            }
391
392            Command::Shutdown(response) => {
393                receiver.close();
394
395                let result = sink.flush();
396
397                if let Err(error) = &result {
398                    state.fail(error.clone());
399                }
400
401                let _ = response.send(result.clone());
402
403                return result;
404            }
405        }
406    }
407
408    let result = sink.flush();
409
410    if let Err(error) = &result {
411        state.fail(error.clone());
412    }
413
414    result
415}