clementine_core/task/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use std::time::Duration;
use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;
use tokio::task::JoinHandle;
use tokio::time::sleep;
use tonic::async_trait;

use crate::errors::BridgeError;

pub mod manager;
pub mod payout_checker;

/// Task trait defining the core behavior for cancelable background tasks
///
/// This trait is implemented by any struct that needs to run as a background task.
/// The run_once method contains the main logic of the task, and returns a bool
/// indicating whether it did work (true) or needs to wait (false).
#[async_trait]
pub trait Task: Send + Sync + 'static {
    type Output: Send + Sync + 'static + Sized;
    /// Run the task once, returning whether work was done
    ///
    /// Returns:
    /// - `Ok(true)` if the task did some work and is ready to run again immediately
    /// - `Ok(false)` if the task did not do work and should wait before running again
    /// - `Err(...)` if the task encountered an error
    async fn run_once(&mut self) -> Result<Self::Output, BridgeError>;
}

/// A trait for objects that can be converted into a Task
pub trait IntoTask {
    type Task: Task;

    /// Convert self into a Task
    fn into_task(self) -> Self::Task;
}

impl<T: Task> IntoTask for T {
    type Task = T;

    fn into_task(self) -> Self::Task {
        self
    }
}

/// A task that adds a certain delay after the inner task has run
/// to reduce polling frequency. When inner returns false, the delay is applied.
#[derive(Debug)]
pub struct WithDelay<T: Task>
where
    T::Output: Into<bool>,
{
    /// The task to poll
    inner: T,
    /// The interval between polls when no work is done
    poll_delay: Duration,
}

impl<T: Task> WithDelay<T>
where
    T::Output: Into<bool>,
{
    /// Create a new delayed task
    pub fn new(inner: T, poll_delay: Duration) -> Self {
        Self { inner, poll_delay }
    }
}

#[async_trait]
impl<T: Task> Task for WithDelay<T>
where
    T::Output: Into<bool>,
{
    type Output = bool;
    async fn run_once(&mut self) -> Result<bool, BridgeError> {
        // Run the inner task
        let did_work = self.inner.run_once().await?.into();

        // If the inner task did not do work, sleep for the poll delay
        if !did_work {
            sleep(self.poll_delay).await;
        }

        // Always return false since we've handled the waiting internally
        Ok(false)
    }
}

/// A task that can be canceled via a oneshot channel
#[derive(Debug)]
pub struct CancelableTask<T: Task> {
    /// The task to run
    inner: T,
    /// Receiver for cancellation signal
    cancel_rx: oneshot::Receiver<()>,
}

impl<T: Task> CancelableTask<T> {
    /// Create a new cancelable task with a cancellation channel
    pub fn new(inner: T, cancel_rx: oneshot::Receiver<()>) -> Self {
        Self { inner, cancel_rx }
    }
}

#[derive(Debug, Clone)]
pub enum CancelableResult<T> {
    Running(T),
    Cancelled,
}

#[async_trait]
impl<T: Task> Task for CancelableTask<T> {
    type Output = CancelableResult<T::Output>;

    async fn run_once(&mut self) -> Result<Self::Output, BridgeError> {
        // Check if we've been canceled
        if let Err(TryRecvError::Empty) = self.cancel_rx.try_recv() {
            // Run the inner task
            Ok(CancelableResult::Running(self.inner.run_once().await?))
        } else {
            Ok(CancelableResult::Cancelled)
        }
    }
}

#[derive(Debug)]
pub struct CancelableLoop<T: Task + Sized> {
    inner: CancelableTask<T>,
}

#[async_trait]
impl<T: Task + Sized> Task for CancelableLoop<T> {
    type Output = ();

    async fn run_once(&mut self) -> Result<Self::Output, BridgeError> {
        loop {
            match self.inner.run_once().await {
                Ok(CancelableResult::Running(_)) => {
                    tokio::task::yield_now().await;
                    continue;
                }
                Ok(CancelableResult::Cancelled) => return Ok(()),
                Err(e) => return Err(e),
            }
        }
    }
}

#[derive(Debug)]
pub struct BufferedErrors<T: Task + Sized>
where
    T::Output: Default,
{
    inner: T,
    buffer: Vec<BridgeError>,
    error_overflow_limit: usize,
}

impl<T: Task + Sized> BufferedErrors<T>
where
    T::Output: Default,
{
    pub fn new(inner: T, error_overflow_limit: usize) -> Self {
        Self {
            inner,
            buffer: Vec::new(),
            error_overflow_limit,
        }
    }
}

#[async_trait]
impl<T: Task + Sized + std::fmt::Debug> Task for BufferedErrors<T>
where
    T::Output: Default,
{
    type Output = T::Output;

    async fn run_once(&mut self) -> Result<Self::Output, BridgeError> {
        let result = self.inner.run_once().await;

        match result {
            Ok(output) => {
                self.buffer.clear(); // clear buffer on first success
                Ok(output)
            }
            Err(e) => {
                tracing::error!("Task error, suppressing due to buffer: {e:?}");
                self.buffer.push(e);
                if self.buffer.len() >= self.error_overflow_limit {
                    let mut base_error: eyre::Report =
                        self.buffer.pop().expect("just inserted above").into();

                    for error in std::mem::take(&mut self.buffer) {
                        base_error = base_error.wrap_err(error);
                    }

                    base_error = base_error.wrap_err(format!(
                        "Exiting due to {} consecutive errors, the following chain is the list of errors.",
                        self.error_overflow_limit
                    ));

                    Err(base_error.into())
                } else {
                    Ok(Default::default())
                }
            }
        }
    }
}

#[derive(Debug)]
pub struct Map<T: Task + Sized, F: Fn(T::Output) -> T::Output + Send + Sync + 'static> {
    inner: T,
    map: F,
}

#[async_trait]
impl<T: Task + Sized, F: Fn(T::Output) -> T::Output + Send + Sync + 'static> Task for Map<T, F> {
    type Output = T::Output;

    #[track_caller]
    async fn run_once(&mut self) -> Result<Self::Output, BridgeError> {
        let result = self.inner.run_once().await;
        let output = match result {
            Ok(output) => (self.map)(output),
            Err(e) => return Err(e),
        };
        Ok(output)
    }
}

/// A task that ignores errors from the inner task and returns a default value.
#[derive(Debug)]
pub struct IgnoreError<T: Task + Sized>
where
    T::Output: Default,
{
    inner: T,
}

#[async_trait]
impl<T: Task + Sized + std::fmt::Debug> Task for IgnoreError<T>
where
    T::Output: Default,
{
    type Output = T::Output;

    async fn run_once(&mut self) -> Result<Self::Output, BridgeError> {
        Ok(self
            .inner
            .run_once()
            .await
            .inspect_err(|e| {
                tracing::error!(task=?self.inner, "Task error, suppressing due to errors ignored: {e:?}");
            })
            .ok()
            .unwrap_or_default())
    }
}

pub trait TaskExt: Task + Sized {
    /// Skips running the task after cancellation using the sender.
    fn cancelable(self) -> (CancelableTask<Self>, oneshot::Sender<()>);

    /// Runs the task in an infinite loop until cancelled using the sender.
    fn cancelable_loop(self) -> (CancelableLoop<Self>, oneshot::Sender<()>);

    /// Adds the given delay after a run of the task when the task returns false.
    fn with_delay(self, poll_delay: Duration) -> WithDelay<Self>
    where
        Self::Output: Into<bool>;

    /// Spawns a [`tokio::task`] that runs the task once in the background.
    fn into_bg(self) -> JoinHandle<Result<Self::Output, BridgeError>>;

    /// Buffers consecutive errors until the task succeeds, emits all errors when there are
    /// more than `error_overflow_limit` consecutive errors.
    fn into_buffered_errors(self, error_overflow_limit: usize) -> BufferedErrors<Self>
    where
        Self::Output: Default;

    /// Maps the task's `Ok()` output using the given function.
    fn map<F: Fn(Self::Output) -> Self::Output + Send + Sync + 'static>(
        self,
        map: F,
    ) -> Map<Self, F>;

    /// Ignores errors from the task.
    fn ignore_error(self) -> IgnoreError<Self>
    where
        Self::Output: Default;
}

impl<T: Task + Sized> TaskExt for T {
    fn cancelable(self) -> (CancelableTask<Self>, oneshot::Sender<()>) {
        let (cancel_tx, cancel_rx) = oneshot::channel();
        (CancelableTask::new(self, cancel_rx), cancel_tx)
    }

    fn cancelable_loop(self) -> (CancelableLoop<Self>, oneshot::Sender<()>) {
        let (task, cancel_tx) = self.cancelable();
        (CancelableLoop { inner: task }, cancel_tx)
    }

    fn with_delay(self, poll_delay: Duration) -> WithDelay<Self>
    where
        Self::Output: Into<bool>,
    {
        WithDelay::new(self, poll_delay)
    }

    fn into_bg(mut self) -> JoinHandle<Result<Self::Output, BridgeError>> {
        tokio::spawn(async move { self.run_once().await })
    }

    fn into_buffered_errors(self, error_overflow_limit: usize) -> BufferedErrors<Self>
    where
        Self::Output: Default,
    {
        BufferedErrors::new(self, error_overflow_limit)
    }

    fn map<F: Fn(Self::Output) -> Self::Output + Send + Sync + 'static>(
        self,
        map: F,
    ) -> Map<Self, F> {
        Map { inner: self, map }
    }

    fn ignore_error(self) -> IgnoreError<Self>
    where
        Self::Output: Default,
    {
        IgnoreError { inner: self }
    }
}

#[cfg(test)]
mod tests;