aide_de_camp_mongodb/
lib.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
341
342
343
344
345
346
347
pub mod job_handle;
pub mod queue;
pub mod types;

pub use queue::MongoDbQueue;

#[cfg(test)]
mod test {
    use crate::MongoDbQueue;
    use aide_de_camp::core::bincode::{Decode, Encode};
    use aide_de_camp::core::job_handle::JobHandle;
    use aide_de_camp::core::job_processor::JobProcessor;
    use aide_de_camp::core::queue::Queue;
    use aide_de_camp::core::{CancellationToken, Duration, Xid};
    use aide_de_camp::prelude::QueueError;
    use async_trait::async_trait;
    use chrono::Utc;
    use std::convert::Infallible;

    #[allow(dead_code)]
    pub fn setup_logger() {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::TRACE)
            .with_test_writer()
            .init();
    }

    #[derive(Encode, Decode, PartialEq, Clone, Debug)]
    struct TestPayload1 {
        arg1: i32,
        arg2: String,
    }

    impl Default for TestPayload1 {
        fn default() -> Self {
            Self {
                arg1: 1774,
                arg2: String::from("this is a test"),
            }
        }
    }

    struct TestJob1;

    #[async_trait]
    impl JobProcessor for TestJob1 {
        type Payload = TestPayload1;
        type Error = Infallible;

        async fn handle(
            &self,
            _jid: Xid,
            _payload: Self::Payload,
            _cancellation_token: CancellationToken,
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn name() -> &'static str
        where
            Self: Sized,
        {
            "test_job_1"
        }
    }

    #[derive(Encode, Decode, PartialEq, Clone, Debug)]
    struct TestPayload2 {
        arg1: i32,
        arg2: u64,
        arg3: String,
    }

    impl Default for TestPayload2 {
        fn default() -> Self {
            Self {
                arg1: 1774,
                arg2: 42,
                arg3: String::from("this is a test"),
            }
        }
    }

    struct TestJob2;

    #[async_trait]
    impl JobProcessor for TestJob2 {
        type Payload = TestPayload2;
        type Error = Infallible;

        async fn handle(
            &self,
            _jid: Xid,
            _payload: Self::Payload,
            _cancellation_token: CancellationToken,
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn name() -> &'static str
        where
            Self: Sized,
        {
            "test_job_2"
        }
    }

    // Job with payload2 but job_type is from TestJob1
    struct TestJob3;

    #[async_trait]
    impl JobProcessor for TestJob3 {
        type Payload = TestPayload2;
        type Error = Infallible;

        async fn handle(
            &self,
            _jid: Xid,
            _payload: Self::Payload,
            _cancellation_token: CancellationToken,
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn name() -> &'static str
        where
            Self: Sized,
        {
            "test_job_1"
        }
    }

    #[tokio::test]
    async fn queue_smoke_test() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db1", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();

        // If there are no jobs, this should return Ok(None);
        {
            let job = queue.poll_next(&[TestJob1::name()]).await.unwrap();
            assert!(job.is_none());
        }
        // Schedule a job to run now
        let jid1 = queue
            .schedule::<TestJob1>(TestPayload1::default(), 0)
            .await
            .unwrap();

        // Now poll_next should return this job to us
        let job1 = queue.poll_next(&[TestJob1::name()]).await.unwrap().unwrap();
        assert_eq!(jid1, job1.id());
        // Second time poll should not return anything
        {
            let job = queue.poll_next(&[TestJob1::name()]).await.unwrap();
            assert!(job.is_none());
        }

        // Completed jobs should not show up in queue again
        job1.complete().await.unwrap();
        {
            let job = queue.poll_next(&[TestJob1::name()]).await.unwrap();
            assert!(job.is_none());
        }
    }

    #[tokio::test]
    async fn failed_jobs() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db2", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();

        // Schedule a job to run now
        let _jid1 = queue
            .schedule::<TestJob1>(TestPayload1::default(), 0)
            .await
            .unwrap();

        // Now poll_next should return this job to us
        let job1 = queue.poll_next(&[TestJob1::name()]).await.unwrap().unwrap();
        assert_eq!(job1.retries(), 1);
        // Fail the job
        job1.fail().await.unwrap();

        // We should be able to get the same job again, but it should have increased retry count

        let job1 = queue.poll_next(&[TestJob1::name()]).await.unwrap().unwrap();
        assert_eq!(job1.retries(), 2);
    }

    #[tokio::test]
    async fn scheduling_future_jobs() {
        setup_logger();
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db3", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();

        // schedule to run job tomorrow
        // schedule a job to run now
        let tomorrow_jid = queue
            .schedule_in::<TestJob1>(TestPayload1::default(), Duration::days(1), 0)
            .await
            .unwrap();

        // Should not be polled yet
        {
            let job = queue.poll_next(&[TestJob1::name()]).await.unwrap();
            assert!(job.is_none());
        }

        let hour_ago = { Utc::now() - Duration::hours(1) };
        let hour_ago_jid = queue
            .schedule_at::<TestJob1>(TestPayload1::default(), hour_ago, 0)
            .await
            .unwrap();

        {
            let job = queue.poll_next(&[TestJob1::name()]).await.unwrap().unwrap();
            assert_eq!(hour_ago_jid, job.id());
        }

        let tomorrow = Utc::now() + Duration::days(1) + Duration::minutes(1);
        {
            let job = queue
                .poll_next_with_instant(&[TestJob1::name()], tomorrow)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(tomorrow_jid, job.id());
        }

        // Everything should be in-progress, so None
        {
            let job = queue
                .poll_next_with_instant(&[TestJob1::name()], tomorrow)
                .await
                .unwrap();
            assert!(job.is_none());
        }
    }

    #[tokio::test]
    async fn cancel_job_not_started() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db4", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();
        let jid = queue
            .schedule::<TestJob1>(TestPayload1::default(), 0)
            .await
            .unwrap();
        queue.cancel_job(jid).await.unwrap();

        // Should return None
        {
            let job = queue.poll_next(&[TestJob1::name()]).await.unwrap();
            assert!(job.is_none());
        }

        // Should fail
        let ret = queue.cancel_job(jid).await;
        assert!(matches!(ret, Err(QueueError::JobNotFound(_))));
    }

    #[tokio::test]
    async fn cancel_job_return_payload() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db5", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();
        let payload = TestPayload1::default();
        let jid = queue
            .schedule::<TestJob1>(payload.clone(), 0)
            .await
            .unwrap();

        let deleted_payload = queue.unschedule_job::<TestJob1>(jid).await.unwrap();
        assert_eq!(payload, deleted_payload);

        let ret = queue.unschedule_job::<TestJob1>(jid).await;
        assert!(matches!(ret, Err(QueueError::JobNotFound(_))));
    }

    #[tokio::test]
    async fn cancel_wrong_type() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db6", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();
        let jid = queue
            .schedule::<TestJob1>(TestPayload1::default(), 0)
            .await
            .unwrap();

        let result = queue.unschedule_job::<TestJob2>(jid).await;
        assert!(matches!(result, Err(QueueError::JobNotFound(_))));

        let result = queue.unschedule_job::<TestJob3>(jid).await;
        dbg!(&result);
        assert!(matches!(result, Err(QueueError::DecodeError { .. })));
    }

    #[tokio::test]
    async fn cancel_job_started() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db7", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();
        let payload = TestPayload1::default();
        let jid = queue
            .schedule::<TestJob1>(payload.clone(), 0)
            .await
            .unwrap();

        let _job = queue.poll_next(&[TestJob1::name()]).await.unwrap().unwrap();

        let ret = queue.cancel_job(jid).await;
        assert!(matches!(ret, Err(QueueError::JobNotFound(_))));

        let ret = queue.unschedule_job::<TestJob1>(jid).await;
        assert!(matches!(ret, Err(QueueError::JobNotFound(_))));
    }
    #[tokio::test]
    async fn priority_polling() {
        let queue = MongoDbQueue::new("mongodb://localhost:27017/test_db8", None)
            .await
            .unwrap();
        queue.delete_database().await.unwrap();

        let hour_ago = { Utc::now() - Duration::hours(1) };
        let _hour_ago_jid = queue
            .schedule_at::<TestJob1>(TestPayload1::default(), hour_ago, 0)
            .await
            .unwrap();

        let higher_priority_jid = queue
            .schedule_at::<TestJob1>(TestPayload1::default(), hour_ago, 3)
            .await
            .unwrap();

        let job = queue.poll_next(&[TestJob1::name()]).await.unwrap().unwrap();
        assert_eq!(higher_priority_jid, job.id());
    }
}