later 0.0.48

Distributed Background jobs manager and runner for Rust
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};

use crate::{BackgroundJobServerPublisher, JobId};

/// A serializable message that can be enqueued as a background job.
///
/// [`crate::background_job!`] implements this trait for every payload type in
/// its declaration. Manual implementations must use a stable payload type name
/// and remain able to decode bytes written by older application versions.
pub trait JobParameter
where
    Self: Serialize + DeserializeOwned,
{
    /// Encodes this payload for durable storage.
    fn to_bytes(&self) -> anyhow::Result<Vec<u8>>;
    /// Decodes a stored payload.
    ///
    /// Prefer [`Self::try_from_bytes`] when invalid data must return an error.
    fn from_bytes(payload: &[u8]) -> Self;
    /// Decodes a stored payload without requiring a panic on invalid data.
    fn try_from_bytes(payload: &[u8]) -> anyhow::Result<Self> {
        Ok(Self::from_bytes(payload))
    }
    /// Returns the stable name used to route this payload to its handler.
    fn get_ptype(&self) -> String;
}

#[async_trait]
/// Dispatches decoded jobs and exposes their application context.
///
/// The [`crate::background_job!`] macro generates this implementation. It is
/// public to support generated server types and is rarely implemented by hand.
pub trait BgJobHandler<C> {
    /// Returns the application context shared by all handlers.
    fn get_ctx(&self) -> &C;
    /// Returns the publisher used to enqueue related jobs.
    fn get_publisher(&self) -> &BackgroundJobServerPublisher;
    /// Sends encoded payload bytes to the handler registered for `ptype`.
    ///
    /// `job_id` is the id of the job currently being executed, made
    /// available to the handler through its context (see
    /// [`crate::BackgroundJobServerPublisher::enqueue_recurring_continue`]
    /// for why a handler needs its own id).
    async fn dispatch(&self, ptype: String, payload: &[u8], job_id: JobId) -> anyhow::Result<()>;
    /// Resolves a message retry policy using the application context.
    ///
    /// Generated handlers decode the payload and call
    /// [`crate::retry::JobRetryPolicy`] when the message implements it. Manual
    /// handlers may keep this default to use the server policy.
    async fn retry_policy(
        &self,
        _ptype: &str,
        _payload: &[u8],
    ) -> anyhow::Result<Option<crate::retry::RetryPolicy>> {
        Ok(None)
    }
}