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
use super::*;
use std::{
    fmt::Debug,
    marker::PhantomData,
};
use tokio::sync::mpsc::UnboundedReceiver;

/// A basic worker which cannot respond or retry
#[derive(Debug, Clone)]
pub struct BasicWorker;

impl BasicWorker {
    #[allow(missing_docs)]
    pub fn new() -> Box<Self> {
        Box::new(Self)
    }
}

impl Worker for BasicWorker {
    fn handle_response(self: Box<Self>, giveload: Vec<u8>) -> anyhow::Result<()> {
        Decoder::try_from(giveload)?;
        Ok(())
    }

    fn handle_error(self: Box<Self>, error: WorkerError, _reporter: Option<&ReporterHandle>) -> anyhow::Result<()> {
        anyhow::bail!(error);
    }
}

/// A basic worker which can retry on failure
pub struct BasicRetryWorker<R> {
    /// The worker's request
    pub request: R,
    /// The number of times this worker will retry on failure
    pub retries: usize,
}

impl<R> Debug for BasicRetryWorker<R>
where
    R: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BasicRetryWorker")
            .field("request", &self.request)
            .field("retries", &self.retries)
            .finish()
    }
}

impl<R> Clone for BasicRetryWorker<R>
where
    R: Clone,
{
    fn clone(&self) -> Self {
        Self {
            request: self.request.clone(),
            retries: self.retries,
        }
    }
}

impl<R> BasicRetryWorker<R> {
    /// Create a new insert worker with a number of retries
    pub fn new(request: R) -> Box<Self> {
        Box::new(request.into())
    }
}

impl<R, H> IntoRespondingWorker<R, H> for BasicRetryWorker<R>
where
    H: 'static + Debug + Send + Sync,
    R: 'static + Send + Debug + Request + Sync + SendRequestExt,
{
    type Output = AnyWorker<H, R>;
    fn with_handle(self, handle: H) -> AnyWorker<H, R> {
        AnyWorker::<H, R>::from(self, handle)
    }
}

impl<R> From<R> for BasicRetryWorker<R> {
    fn from(request: R) -> Self {
        Self { request, retries: 0 }
    }
}

impl<R> Worker for BasicRetryWorker<R>
where
    R: 'static + Debug + Send + Request + Sync,
{
    fn handle_response(self: Box<Self>, giveload: Vec<u8>) -> anyhow::Result<()> {
        Decoder::try_from(giveload)?;
        Ok(())
    }

    fn handle_error(
        self: Box<Self>,
        mut error: WorkerError,
        reporter_opt: Option<&ReporterHandle>,
    ) -> anyhow::Result<()> {
        error!("{}", error);
        if let WorkerError::Cql(ref mut cql_error) = error {
            if let (Some(id), Some(reporter)) = (cql_error.try_unprepared_id(), reporter_opt) {
                handle_unprepared_error(self, id, reporter).map_err(|worker| {
                    error!(
                        "Error trying to reprepare query: {:?}",
                        worker.request().statement_by_id(&id)
                    );
                    anyhow::anyhow!("Error trying to reprepare query!")
                })
            } else {
                self.retry()?
                    .map_or_else(|| Ok(()), |_| anyhow::bail!("Basic worker consumed all retries"))
            }
        } else {
            self.retry()?
                .map_or_else(|| Ok(()), |_| anyhow::bail!("Basic worker consumed all retries"))
        }
    }
}

impl<R> RetryableWorker<R> for BasicRetryWorker<R>
where
    R: 'static + Debug + Send + Request + Sync,
{
    fn retries(&self) -> usize {
        self.retries
    }

    fn request(&self) -> &R {
        &self.request
    }

    fn retries_mut(&mut self) -> &mut usize {
        &mut self.retries
    }
}

/// A worker which can spawn cloneable workers and await their responses
pub struct SpawnableRespondWorker<R, I, W> {
    pub(crate) inbox: I,
    pub(crate) worker: W,
    _req: PhantomData<fn(R) -> R>,
}

impl<R, I, W> SpawnableRespondWorker<R, I, W>
where
    R: Request + Debug + Send,
    W: RetryableWorker<R> + Clone,
{
    /// Create a new spawning worker with an inbox and a worker to spawn
    pub fn new(inbox: I, worker: W) -> Box<Self> {
        Box::new(Self {
            inbox,
            worker,
            _req: PhantomData,
        })
    }

    /// Send a spawned worker to a specific reporter, without waiting for a response
    pub fn send_to_reporter(self: Box<Self>, reporter: &ReporterHandle) -> Result<DecodeResult<R::Marker>, RequestError>
    where
        Self: 'static + Sized,
        W: Worker,
        R: SendRequestExt,
    {
        Box::new(self.worker.clone()).send_to_reporter(reporter)?;
        Ok(DecodeResult::new(R::Marker::new(), R::TYPE))
    }

    /// Send a spawned worker to the local datacenter, without waiting for a response
    pub fn send_local(self: Box<Self>) -> Result<DecodeResult<R::Marker>, RequestError>
    where
        Self: 'static + Sized,
        W: Worker,
        R: SendRequestExt,
    {
        Box::new(self.worker.clone()).send_local()?;
        Ok(DecodeResult::new(R::Marker::new(), R::TYPE))
    }

    /// Send a spawned worker to a global datacenter, without waiting for a response
    pub fn send_global(self: Box<Self>) -> Result<DecodeResult<R::Marker>, RequestError>
    where
        Self: 'static + Sized,
        W: Worker,
        R: SendRequestExt,
    {
        Box::new(self.worker.clone()).send_global()?;
        Ok(DecodeResult::new(R::Marker::new(), R::TYPE))
    }
}

impl<R, W> SpawnableRespondWorker<R, UnboundedReceiver<Result<Decoder, WorkerError>>, W>
where
    R: 'static + SendRequestExt + Clone + Debug + Send + Sync,
    W: 'static + RetryableWorker<R> + Clone + Worker,
{
    /// Send a spawned worker to the local datacenter and await a response asynchronously
    pub async fn get_local(&mut self) -> Result<<R::Marker as Marker>::Output, RequestError>
    where
        Self: Sized,
    {
        let marker = Box::new(self.worker.clone()).send_local()?;
        Ok(marker.try_decode(
            self.inbox
                .recv()
                .await
                .ok_or_else(|| anyhow::anyhow!("No response from worker!"))??,
        )?)
    }

    /// Send a spawned worker to the local datacenter and await a response synchronously
    pub fn get_local_blocking(&mut self) -> Result<<R::Marker as Marker>::Output, RequestError>
    where
        Self: Sized,
        W: Worker,
    {
        let marker = Box::new(self.worker.clone()).send_local()?;
        Ok(marker.try_decode(
            self.inbox
                .blocking_recv()
                .ok_or_else(|| anyhow::anyhow!("No response from worker!"))??,
        )?)
    }

    /// Send a spawned worker to a global datacenter and await a response asynchronously
    pub async fn get_global(&mut self) -> Result<<R::Marker as Marker>::Output, RequestError>
    where
        Self: Sized,
        W: Worker,
    {
        let marker = Box::new(self.worker.clone()).send_global()?;
        Ok(marker.try_decode(
            self.inbox
                .recv()
                .await
                .ok_or_else(|| anyhow::anyhow!("No response from worker!"))??,
        )?)
    }

    /// Send a spawned worker to a global datacenter and await a response synchronously
    pub fn get_global_blocking(&mut self) -> Result<<R::Marker as Marker>::Output, RequestError>
    where
        Self: Sized,
        W: Worker,
    {
        let marker = Box::new(self.worker.clone()).send_global()?;
        Ok(marker.try_decode(
            self.inbox
                .blocking_recv()
                .ok_or_else(|| anyhow::anyhow!("No response from worker!"))??,
        )?)
    }
}