underway 0.2.0

⏳ Durable step functions via Postgres
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Tasks represent a well-structured unit of work.
//!
//! A task is defined by implementing the [`execute`](crate::Task::execute)
//! method and specifying the associated type [`Input`](crate::Task::Input).
//! This provides a strongly-typed interface to execute task invocations.
//!
//! Once a task is implemented, it can be enqueued on a [`Queue`](crate::Queue)
//! for processing. A [`Worker`](crate::Worker) can then dequeue the task and
//! invoke its `execute` method, providing the input that has been deserialized
//! into the specified [`Input`](crate::Task::Input) type.
//!
//! Queues and workers operate over tasks to make them useful in the context of
//! your application.
//!
//! # Implementing `Task`
//!
//! Generally you'll want to use the higher-level [`Job`](crate::Job)
//! abstraction instead of implementing `Task` yourself. Its workflow is more
//! ergonomic and therefore preferred for virtually all cases.
//!
//! However, it's possible to implement the trait directly. This may be useful
//! for building more sophisticated behavior on top of the task concept that
//! isn't already provided by `Job`.
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use sqlx::{Postgres, Transaction};
//! use underway::{task::Result as TaskResult, Task};
//! # use sqlx::PgPool;
//! # use tokio::runtime::Runtime;
//! # fn main() {
//! # let rt = Runtime::new().unwrap();
//! # rt.block_on(async {
//!
//! // Task input representing the data needed to send a welcome email.
//! #[derive(Debug, Deserialize, Serialize)]
//! struct WelcomeEmail {
//!     user_id: i32,
//!     email: String,
//!     name: String,
//! }
//!
//! // Task that sends a welcome email to a user.
//! struct WelcomeEmailTask;
//!
//! impl Task for WelcomeEmailTask {
//!     type Input = WelcomeEmail;
//!     type Output = ();
//!
//!     /// Simulate sending a welcome email by printing a message to the console.
//!     async fn execute(
//!         &self,
//!         _tx: Transaction<'_, Postgres>,
//!         input: Self::Input,
//!     ) -> TaskResult<Self::Output> {
//!         println!(
//!             "Sending welcome email to {} <{}> (user_id: {})",
//!             input.name, input.email, input.user_id
//!         );
//!
//!         // Here you would integrate with an email service.
//!         // If email sending fails, you could return an error to trigger retries.
//!         Ok(())
//!     }
//! }
//! # let pool = PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
//! # let tx = pool.begin().await?;
//! # let task = WelcomeEmailTask;
//! # let input = WelcomeEmail {
//! #     user_id: 1,
//! #     email: "user@example.com".to_string(),
//! #     name: "Alice".to_string(),
//! # };
//! # task.execute(tx, input).await?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! # });
//! # }
//! ```
use std::{
    fmt::{self, Display},
    future::Future,
    ops::Deref,
    result::Result as StdResult,
};

use jiff::{SignedDuration, Span, ToSpan};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sqlx::{Postgres, Transaction};
use ulid::Ulid;
use uuid::Uuid;

pub(crate) use self::retry_policy::RetryCount;
pub use self::retry_policy::RetryPolicy;

mod retry_policy;

/// A type alias for task identifiers.
///
/// Task IDs are [ULID][ULID]s which are converted to UUIDv4 for storage.
///
/// [ULID]: https://github.com/ulid/spec?tab=readme-ov-file#specification
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq, PartialEq, sqlx::Type)]
#[sqlx(transparent)]
pub struct TaskId(Uuid);

impl TaskId {
    pub(crate) fn new() -> Self {
        Self(Ulid::new().into())
    }
}

impl Deref for TaskId {
    type Target = Uuid;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Display for TaskId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A type alias for task execution results.
pub type Result<T> = StdResult<T, Error>;

/// Task errors.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Error returned by the `sqlx` crate during database operations.
    #[error(transparent)]
    Database(#[from] sqlx::Error),

    /// Indicates the task timed out during execution.
    #[error("Task timed out after {0} during execution")]
    TimedOut(SignedDuration),

    /// Error indicating that the task has encountered an unrecoverable error
    /// state.
    ///
    /// **Note:** Returning this error from an execute future will override any
    /// remaining retries and set the task to [`State::Failed`].
    #[error("{0}")]
    Fatal(String),

    /// Error indicating that the task has encountered a recoverable error
    /// state.
    #[error("{0}")]
    Retryable(String),
}

/// Convenience trait for converting results into task results.
///
/// This makes it easier to convert execution errors to either
/// [`Retryable`](Error::Retryable) or [`Fatal`](Error::Fatal). These are
/// recoverable and unrecoverable, respectively.
///
/// # Examples
///
/// Sometimes errors are retryable:
///
///```rust
/// use tokio::net;
/// use underway::{Job, To, ToTaskResult};
///
/// Job::<(), ()>::builder().step(|_, _| async {
///     // If we can't resolve DNS the issue may be transient and recoverable.
///     net::lookup_host("example.com:80").await.retryable()?;
///
///     To::done()
/// });
/// ```
///
/// And other times they're fatal:
///
/// ```rust
/// use std::env;
///
/// use underway::{Job, To, ToTaskResult};
///
/// Job::<(), ()>::builder().step(|_, _| async {
///     // If the API_KEY environment variable isn't set we can't recover.
///     let api_key = env::var("API_KEY").fatal()?;
///
///     To::done()
/// });
/// ```
pub trait ToTaskResult<T> {
    /// Converts the error into a [`Retryable`](Error::Retryable) task error.
    fn retryable(self) -> StdResult<T, Error>;

    /// Converts the error into a [`Fatal`](Error::Fatal) task error.
    fn fatal(self) -> StdResult<T, Error>;
}

impl<T, E: std::fmt::Display> ToTaskResult<T> for StdResult<T, E> {
    fn retryable(self) -> StdResult<T, Error> {
        self.map_err(|err| Error::Retryable(err.to_string()))
    }

    fn fatal(self) -> StdResult<T, Error> {
        self.map_err(|err| Error::Fatal(err.to_string()))
    }
}

/// Trait for defining tasks.
///
/// Queues and workers operate over types that implement this trait.
pub trait Task: Send + 'static {
    /// The input type that the execute method will take.
    ///
    /// This type must be serialized to and deserialized from the database.
    type Input: DeserializeOwned + Serialize + Send + 'static;

    /// The output type that the execute method will return upon success.
    type Output: Serialize + Send + 'static;

    /// Executes the task with the provided input.
    ///
    /// The core of a task, this method is called when the task is picked up by
    /// a worker.
    ///
    /// Typically this method will do something with the provided input. If no
    /// input is needed, then the unit type, `()`, can be used instead and the
    /// input ignored.
    ///
    /// # Example
    ///
    /// ```
    /// use serde::{Deserialize, Serialize};
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// // Task input representing the data needed to send a welcome email.
    /// #[derive(Debug, Deserialize, Serialize)]
    /// struct WelcomeEmail {
    ///     user_id: i32,
    ///     email: String,
    ///     name: String,
    /// }
    ///
    /// // Task that sends a welcome email to a user.
    /// struct WelcomeEmailTask;
    ///
    /// impl Task for WelcomeEmailTask {
    ///     type Input = WelcomeEmail;
    ///     type Output = ();
    ///
    ///     /// Simulate sending a welcome email by printing a message to the console.
    ///     async fn execute(
    ///         &self,
    ///         tx: Transaction<'_, Postgres>,
    ///         input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         println!(
    ///             "Sending welcome email to {} <{}> (user_id: {})",
    ///             input.name, input.email, input.user_id
    ///         );
    ///
    ///         // Here you would integrate with an email service.
    ///         // If email sending fails, you could return an error to trigger retries.
    ///         Ok(())
    ///     }
    /// }
    /// ```
    fn execute(
        &self,
        tx: Transaction<'_, Postgres>,
        input: Self::Input,
    ) -> impl Future<Output = Result<Self::Output>> + Send;

    /// Defines the retry policy of the task.
    ///
    /// The retry policy determines how many times the task should be retried in
    /// the event of failure, and the interval between retries. This is useful
    /// for handling transient failures like network issues or external API
    /// errors.
    ///
    /// # Example
    ///
    /// ```rust
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{
    ///     task::{Result as TaskResult, RetryPolicy},
    ///     Task,
    /// };
    ///
    /// struct MyCustomRetryTask;
    ///
    /// impl Task for MyCustomRetryTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Specify our own retry policy for the task.
    ///     fn retry_policy(&self) -> RetryPolicy {
    ///         RetryPolicy::builder()
    ///             .max_attempts(20)
    ///             .initial_interval_ms(2_500)
    ///             .backoff_coefficient(1.5)
    ///             .build()
    ///     }
    /// }
    /// ```
    fn retry_policy(&self) -> RetryPolicy {
        RetryPolicy::default()
    }

    /// Provides the task execution timeout.
    ///
    /// Override this if your tasks need to have shorter or longer timeouts.
    ///
    /// Defaults to 15 minutes.
    ///
    /// # Example
    ///
    /// ```rust
    /// use jiff::{Span, ToSpan};
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// struct MyImpatientTask;
    ///
    /// impl Task for MyImpatientTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Only give the task a short time to complete execution.
    ///     fn timeout(&self) -> Span {
    ///         1.second()
    ///     }
    /// }
    /// ```
    fn timeout(&self) -> Span {
        15.minutes()
    }

    /// Provides task time-to-live (TTL) duration in queue.
    ///
    /// After the duration has elapsed, a task may be removed from the queue,
    /// e.g. via [`run_deletion`](crate::queue::run_deletion).
    ///
    /// **Note:** Tasks are not removed from the queue unless the `run_deletion`
    /// routine is active.
    ///
    /// Defaults to 14 days.
    ///
    /// # Example
    ///
    /// ```rust
    /// use jiff::{Span, ToSpan};
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// struct MyLongLivedTask;
    ///
    /// impl Task for MyLongLivedTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Keep the task around in the queue for a very long time.
    ///     fn ttl(&self) -> Span {
    ///         10.years()
    ///     }
    /// }
    /// ```
    fn ttl(&self) -> Span {
        14.days()
    }

    /// Provides a delay before which the task won't be dequeued.
    ///
    /// Delays are used to prevent a task from running immediately after being
    /// enqueued.
    ///
    /// Defaults to no delay.
    ///
    /// # Example
    ///
    /// ```rust
    /// use jiff::{Span, ToSpan};
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// struct MyDelayedTask;
    ///
    /// impl Task for MyDelayedTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Delay dequeuing the task for one hour.
    ///     fn delay(&self) -> Span {
    ///         1.hour()
    ///     }
    /// }
    /// ```
    fn delay(&self) -> Span {
        Span::new()
    }

    /// Specifies interval on which the task's heartbeat timestamp should be
    /// updated.
    ///
    /// This is used by workers to update the task row with the current
    /// timestamp. Doing so makes it possible to detect tasks that may have
    /// become stuck, for example because a worker crashed or otherwise
    /// didn't exit cleanly.
    ///
    /// The default is 30 seconds.
    ///
    /// # Example
    ///
    /// ```rust
    /// use jiff::{Span, ToSpan};
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// struct MyLivelyTask;
    ///
    /// impl Task for MyLivelyTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Set the heartbeat interval to 1 second.
    ///     fn heartbeat(&self) -> Span {
    ///         1.second()
    ///     }
    /// }
    /// ```
    fn heartbeat(&self) -> Span {
        30.seconds()
    }

    /// Provides an optional concurrency key for the task.
    ///
    /// Concurrency keys are used to limit how many tasks of a specific type are
    /// allowed to run concurrently. By providing a unique key, tasks with
    /// the same key can be processed sequentially rather than concurrently.
    ///
    /// This can be useful when working with shared resources or for preventing
    /// race conditions. If no concurrency key is provided, tasks will be
    /// executed concurrently.
    ///
    /// # Example
    ///
    /// If you're processing files, you might want to use the file path as the
    /// concurrency key to prevent two workers from processing the same file
    /// simultaneously.
    ///
    /// ```rust
    /// use std::path::PathBuf;
    ///
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// struct MyUniqueTask(PathBuf);
    ///
    /// impl Task for MyUniqueTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Use the path buf as our concurrency key.
    ///     fn concurrency_key(&self) -> Option<String> {
    ///         Some(self.0.display().to_string())
    ///     }
    /// }
    /// ```
    fn concurrency_key(&self) -> Option<String> {
        None
    }

    /// Specifies the priority of the task.
    ///
    /// Higher-priority tasks will be processed before lower-priority ones. This
    /// can be useful in systems where certain jobs are time-sensitive and
    /// need to be handled before others.
    ///
    /// The default priority is `0`, and higher numbers represent higher
    /// priority.
    ///
    /// # Example
    ///
    /// ```rust
    /// use sqlx::{Postgres, Transaction};
    /// use underway::{task::Result as TaskResult, Task};
    ///
    /// struct MyHighPriorityTask;
    ///
    /// impl Task for MyHighPriorityTask {
    ///     type Input = ();
    ///     type Output = ();
    ///
    ///     async fn execute(
    ///         &self,
    ///         _tx: Transaction<'_, Postgres>,
    ///         _input: Self::Input,
    ///     ) -> TaskResult<Self::Output> {
    ///         Ok(())
    ///     }
    ///
    ///     // Set the priority to 10.
    ///     fn priority(&self) -> i32 {
    ///         10
    ///     }
    /// }
    /// ```
    fn priority(&self) -> i32 {
        0
    }
}

/// Represents the possible states a task can be in.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, sqlx::Type)]
#[sqlx(type_name = "underway.task_state", rename_all = "snake_case")]
pub enum State {
    /// Awaiting execution.
    Pending,

    /// Currently being processed.
    InProgress,

    /// Execute completed successfully.
    Succeeded,

    /// Execute cancelled.
    Cancelled,

    /// Execute completed unsuccessfully.
    Failed,
}

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};
    use sqlx::PgPool;

    use super::*;

    #[derive(Debug, Deserialize, Serialize)]
    struct TestTaskInput {
        message: String,
    }

    struct TestTask;

    impl Task for TestTask {
        type Input = TestTaskInput;
        type Output = ();

        async fn execute(
            &self,
            _tx: Transaction<'_, Postgres>,
            input: Self::Input,
        ) -> Result<Self::Output> {
            println!("Executing task with message: {}", input.message);
            if input.message == "fail" {
                return Err(Error::Retryable("Task failed".to_string()));
            }
            Ok(())
        }
    }

    #[sqlx::test]
    async fn task_execution_success(pool: PgPool) {
        let task = TestTask;
        let input = TestTaskInput {
            message: "Hello, World!".to_string(),
        };

        let tx = pool.begin().await.unwrap();
        let result = task.execute(tx, input).await;
        assert!(result.is_ok())
    }

    #[sqlx::test]
    async fn task_execution_failure(pool: PgPool) {
        let task = TestTask;
        let input = TestTaskInput {
            message: "fail".to_string(),
        };

        let tx = pool.begin().await.unwrap();
        let result = task.execute(tx, input).await;
        assert!(result.is_err())
    }

    #[test]
    fn retry_policy_defaults() {
        let default_policy = RetryPolicy::default();
        assert_eq!(default_policy.max_attempts, 5);
        assert_eq!(default_policy.initial_interval_ms, 1_000);
        assert_eq!(default_policy.max_interval_ms, 60_000);
        assert_eq!(default_policy.backoff_coefficient, 2.0);
    }

    #[test]
    fn retry_policy_custom() {
        let retry_policy = RetryPolicy::builder()
            .max_attempts(3)
            .initial_interval_ms(500)
            .max_interval_ms(5_000)
            .backoff_coefficient(1.5)
            .build();

        assert_eq!(retry_policy.max_attempts, 3);
        assert_eq!(retry_policy.initial_interval_ms, 500);
        assert_eq!(retry_policy.max_interval_ms, 5_000);
        assert_eq!(retry_policy.backoff_coefficient, 1.5);
    }
}