rexecutor-sqlx 0.1.1

A robust job processing library
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! A postgres backend for Rexecutor built on [`sqlx`].
#![deny(missing_docs)]

use std::{collections::HashMap, sync::Arc};

use chrono::{DateTime, Utc};
use rexecutor::{
    backend::{BackendError, EnqueuableJob, ExecutionError, Query},
    job::{JobId, uniqueness_criteria::Resolution},
    pruner::PruneSpec,
};
use serde::Deserialize;
use sqlx::{
    PgPool, QueryBuilder, Row,
    postgres::{PgListener, PgPoolOptions},
    types::Text,
};
use tokio::sync::{RwLock, mpsc};

use crate::{query::ToQuery, unique::Unique};

mod backend;
mod query;
mod stream;
mod types;
mod unique;

type Subscriber = mpsc::UnboundedSender<DateTime<Utc>>;

/// A postgres implementation of a [`rexecutor::backend::Backend`].
#[derive(Clone, Debug)]
pub struct RexecutorPgBackend {
    pool: PgPool,
    subscribers: Arc<RwLock<HashMap<&'static str, Vec<Subscriber>>>>,
}

#[derive(Deserialize, Debug)]
struct Notification {
    executor: String,
    scheduled_at: DateTime<Utc>,
}

use types::*;

fn map_err(error: sqlx::Error) -> BackendError {
    match error {
        sqlx::Error::Io(err) => BackendError::Io(err),
        sqlx::Error::Tls(err) => BackendError::Io(std::io::Error::other(err)),
        sqlx::Error::Protocol(err) => BackendError::Io(std::io::Error::other(err)),
        sqlx::Error::AnyDriverError(err) => BackendError::Io(std::io::Error::other(err)),
        sqlx::Error::PoolTimedOut => BackendError::Io(std::io::Error::other(error)),
        sqlx::Error::PoolClosed => BackendError::Io(std::io::Error::other(error)),
        _ => BackendError::BadState,
    }
}

impl RexecutorPgBackend {
    /// Creates a new [`RexecutorPgBackend`] from a db connection string.
    pub async fn from_db_url(db_url: &str) -> Result<Self, BackendError> {
        let pool = PgPoolOptions::new()
            .connect(db_url)
            .await
            .map_err(map_err)?;
        Self::from_pool(pool).await
    }
    /// Create a new [`RexecutorPgBackend`] from an existing [`PgPool`].
    pub async fn from_pool(pool: PgPool) -> Result<Self, BackendError> {
        let this = Self {
            pool,
            subscribers: Default::default(),
        };
        let mut listener = PgListener::connect_with(&this.pool)
            .await
            .map_err(map_err)?;
        listener
            .listen("public.rexecutor_scheduled")
            .await
            .map_err(map_err)?;

        tokio::spawn({
            let subscribers = this.subscribers.clone();
            async move {
                while let Ok(notification) = listener.recv().await {
                    let notification =
                        serde_json::from_str::<Notification>(notification.payload()).unwrap();

                    match subscribers
                        .read()
                        .await
                        .get(&notification.executor.as_str())
                    {
                        Some(subscribers) => subscribers.iter().for_each(|sender| {
                            let _ = sender.send(notification.scheduled_at);
                        }),
                        None => {
                            tracing::warn!("No executors running for {}", notification.executor)
                        }
                    }
                }
            }
        });

        Ok(this)
    }

    /// This can be used to run the [`RexecutorPgBackend`]'s migrations.
    pub async fn run_migrations(&self) -> Result<(), BackendError> {
        tracing::info!("Running RexecutorPgBackend migrations");
        sqlx::migrate!()
            .run(&self.pool)
            .await
            .map_err(|err| BackendError::Io(std::io::Error::other(err)))
    }

    async fn load_job_mark_as_executing_for_executor(
        &self,
        executor: &str,
    ) -> sqlx::Result<Option<Job>> {
        sqlx::query_as!(
            Job,
            r#"UPDATE rexecutor_jobs
            SET
                status = 'executing',
                attempted_at = timezone('UTC'::text, now()),
                attempt = attempt + 1
            WHERE id IN (
                SELECT id from rexecutor_jobs
                WHERE scheduled_at - timezone('UTC'::text, now()) < '00:00:00.1'
                AND status in ('scheduled', 'retryable')
                AND executor = $1
                ORDER BY priority, scheduled_at
                LIMIT 1
                FOR UPDATE SKIP LOCKED
            )
            RETURNING
                id,
                status AS "status: JobStatus",
                executor,
                data,
                metadata,
                attempt,
                max_attempts,
                priority,
                tags,
                errors,
                inserted_at,
                scheduled_at,
                attempted_at,
                completed_at,
                cancelled_at,
                discarded_at
            "#,
            executor
        )
        .fetch_optional(&self.pool)
        .await
    }

    async fn insert_job<'a>(&self, job: EnqueuableJob<'a>) -> sqlx::Result<JobId> {
        let data = sqlx::query!(
            r#"INSERT INTO rexecutor_jobs (
                executor,
                data,
                metadata,
                max_attempts,
                scheduled_at,
                priority,
                tags
            ) VALUES ($1, $2, $3, $4, $5, $6, $7)
            RETURNING id
            "#,
            job.executor,
            job.data,
            job.metadata,
            job.max_attempts as i32,
            job.scheduled_at,
            job.priority as i32,
            &job.tags,
        )
        .fetch_one(&self.pool)
        .await?;
        Ok(data.id.into())
    }

    async fn insert_unique_job<'a>(&self, job: EnqueuableJob<'a>) -> sqlx::Result<JobId> {
        let Some(uniqueness_criteria) = job.uniqueness_criteria else {
            panic!();
        };
        let mut tx = self.pool.begin().await?;
        let unique_identifier = uniqueness_criteria.unique_identifier(job.executor.as_str());
        sqlx::query!("SELECT pg_advisory_xact_lock($1)", unique_identifier)
            .execute(&mut *tx)
            .await?;
        match uniqueness_criteria
            .query(job.executor.as_str(), job.scheduled_at)
            .build()
            .fetch_optional(&mut *tx)
            .await?
        {
            None => {
                let data = sqlx::query!(
                    r#"INSERT INTO rexecutor_jobs (
                        executor,
                        data,
                        metadata,
                        max_attempts,
                        scheduled_at,
                        priority,
                        tags,
                        uniqueness_key
                    ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
                    RETURNING id
                    "#,
                    job.executor,
                    job.data,
                    job.metadata,
                    job.max_attempts as i32,
                    job.scheduled_at,
                    job.priority as i32,
                    &job.tags,
                    unique_identifier,
                )
                .fetch_one(&mut *tx)
                .await?;
                tx.commit().await?;
                Ok(data.id.into())
            }
            Some(val) => {
                let job_id = val.get::<i32, _>(0);
                let status = val.get::<JobStatus, _>(1);
                match uniqueness_criteria.on_conflict {
                    Resolution::Replace(replace)
                        if replace
                            .for_statuses
                            .iter()
                            .map(|js| JobStatus::from(*js))
                            .any(|js| js == status) =>
                    {
                        let mut builder = QueryBuilder::new("UPDATE rexecutor_jobs SET ");
                        let mut seperated = builder.separated(", ");
                        if replace.scheduled_at {
                            seperated.push("scheduled_at = ");
                            seperated.push_bind_unseparated(job.scheduled_at);
                        }
                        if replace.data {
                            seperated.push("data = ");
                            seperated.push_bind_unseparated(job.data);
                        }
                        if replace.metadata {
                            seperated.push("metadata = ");
                            seperated.push_bind_unseparated(job.metadata);
                        }
                        if replace.priority {
                            seperated.push("priority = ");
                            seperated.push_bind_unseparated(job.priority as i32);
                        }
                        if replace.max_attempts {
                            seperated.push("max_attempts = ");
                            seperated.push_bind_unseparated(job.max_attempts as i32);
                        }
                        builder.push(" WHERE id  = ");
                        builder.push_bind(job_id);
                        builder.build().execute(&mut *tx).await?;
                        tx.commit().await?;
                    }
                    _ => {
                        tx.rollback().await?;
                    }
                }
                Ok(job_id.into())
            }
        }
    }

    async fn _mark_job_complete(&self, id: JobId) -> sqlx::Result<u64> {
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                status = 'complete',
                completed_at = timezone('UTC'::text, now())
            WHERE id = $1"#,
            i32::from(id),
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn _mark_job_retryable(
        &self,
        id: JobId,
        next_scheduled_at: DateTime<Utc>,
        error: ExecutionError,
    ) -> sqlx::Result<u64> {
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                status = 'retryable',
                scheduled_at = $4,
                errors = ARRAY_APPEND(
                    errors,
                    jsonb_build_object(
                        'attempt', attempt,
                        'error_type', $2::text,
                        'details', $3::text,
                        'recorded_at', timezone('UTC'::text, now())::timestamptz
                    )
                )
            WHERE id = $1"#,
            i32::from(id),
            Text(ErrorType::from(error.error_type)) as _,
            error.message,
            next_scheduled_at,
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn _mark_job_snoozed(
        &self,
        id: JobId,
        next_scheduled_at: DateTime<Utc>,
    ) -> sqlx::Result<u64> {
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                status = (CASE WHEN attempt = 1 THEN 'scheduled' ELSE 'retryable' END)::rexecutor_job_state,
                scheduled_at = $2,
                attempt = attempt - 1
            WHERE id = $1"#,
            i32::from(id),
            next_scheduled_at,
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn _mark_job_discarded(&self, id: JobId, error: ExecutionError) -> sqlx::Result<u64> {
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                status = 'discarded',
                discarded_at = timezone('UTC'::text, now()),
                errors = ARRAY_APPEND(
                    errors,
                    jsonb_build_object(
                        'attempt', attempt,
                        'error_type', $2::text,
                        'details', $3::text,
                        'recorded_at', timezone('UTC'::text, now())::timestamptz
                    )
                )
            WHERE id = $1"#,
            i32::from(id),
            Text(ErrorType::from(error.error_type)) as _,
            error.message,
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn _mark_job_cancelled(&self, id: JobId, error: ExecutionError) -> sqlx::Result<u64> {
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                status = 'cancelled',
                cancelled_at = timezone('UTC'::text, now()),
                errors = ARRAY_APPEND(
                    errors,
                    jsonb_build_object(
                        'attempt', attempt,
                        'error_type', $2::text,
                        'details', $3::text,
                        'recorded_at', timezone('UTC'::text, now())::timestamptz
                    )
                )
            WHERE id = $1"#,
            i32::from(id),
            Text(ErrorType::from(error.error_type)) as _,
            error.message,
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn next_available_job_scheduled_at_for_executor(
        &self,
        executor: &'static str,
    ) -> sqlx::Result<Option<DateTime<Utc>>> {
        Ok(sqlx::query!(
            r#"SELECT scheduled_at
            FROM rexecutor_jobs
            WHERE status in ('scheduled', 'retryable')
            AND executor = $1
            ORDER BY scheduled_at
            LIMIT 1
            "#,
            executor
        )
        .fetch_optional(&self.pool)
        .await?
        .map(|data| data.scheduled_at))
    }

    async fn delete_from_spec(&self, spec: &PruneSpec) -> sqlx::Result<()> {
        let result = spec.query().build().execute(&self.pool).await?;
        tracing::debug!(
            ?spec,
            "Clean up query completed {} rows removed",
            result.rows_affected()
        );
        Ok(())
    }

    async fn rerun(&self, id: JobId) -> sqlx::Result<u64> {
        // Currently this increments the max attempts and reschedules the job.
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                status = (CASE WHEN attempt = 1 THEN 'scheduled' ELSE 'retryable' END)::rexecutor_job_state,
                scheduled_at = $2,
                completed_at = null,
                cancelled_at = null,
                discarded_at = null,
                max_attempts = max_attempts + 1
            WHERE id = $1"#,
            i32::from(id),
            Utc::now(),
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn update(&self, job: rexecutor::backend::Job) -> sqlx::Result<u64> {
        Ok(sqlx::query!(
            r#"UPDATE rexecutor_jobs
            SET
                data = $2,
                metadata = $3,
                max_attempts = $4,
                scheduled_at = $5,
                priority = $6,
                tags = $7
            WHERE id = $1"#,
            job.id,
            job.data,
            job.metadata,
            job.max_attempts as i32,
            job.scheduled_at,
            job.priority as i32,
            &job.tags,
        )
        .execute(&self.pool)
        .await?
        .rows_affected())
    }

    async fn run_query<'a>(&self, query: Query<'a>) -> sqlx::Result<Vec<Job>> {
        query
            .query()
            .build_query_as::<Job>()
            .fetch_all(&self.pool)
            .await
    }
}