bibby 0.1.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
//! Client and types for **Bytebury Cron** (`https://api.bytebury.com/cron/v1`).
//!
//! Create and manage scheduled UTC HTTP jobs, trigger immediate manual runs,
//! inspect 30-day run histories, and preview cron schedules.

use std::collections::BTreeMap;
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::client::Bibby;
use crate::error::Result;
use crate::pagination::{Page, PageParams};

const PRODUCT: &str = "cron";
const MANUAL_RUN_TIMEOUT: Duration = Duration::from_secs(60);

/// Client for **Bytebury Cron**.
///
/// Obtained via [`Bibby::cron`].
#[derive(Debug, Clone, Copy)]
pub struct CronClient<'a> {
    client: &'a Bibby,
}

impl<'a> CronClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Creates a new scheduled cron job.
    ///
    /// Calls `POST /cron/v1/jobs`.
    pub async fn create_job(&self, request: &CreateJobRequest) -> Result<Job> {
        self.client.post_json(PRODUCT, "jobs", request).await
    }

    /// Lists cron jobs in your account (newest first).
    ///
    /// Calls `GET /cron/v1/jobs`.
    pub async fn list_jobs(&self, params: &ListJobsParams) -> Result<Page<Job>> {
        self.client.get_json_query(PRODUCT, "jobs", params).await
    }

    /// Fetches a single cron job by ID.
    ///
    /// Calls `GET /cron/v1/jobs/{id}`.
    pub async fn get_job(&self, id: i64) -> Result<Job> {
        self.client.get_json(PRODUCT, &format!("jobs/{id}")).await
    }

    /// Updates, pauses (`enabled = false`), or resumes (`enabled = true`) a cron job.
    ///
    /// Calls `PATCH /cron/v1/jobs/{id}`.
    pub async fn update_job(&self, id: i64, changes: &UpdateJobRequest) -> Result<Job> {
        self.client
            .patch_json(PRODUCT, &format!("jobs/{id}"), changes)
            .await
    }

    /// Deletes a cron job and its run history.
    ///
    /// Calls `DELETE /cron/v1/jobs/{id}`.
    pub async fn delete_job(&self, id: i64) -> Result<Job> {
        self.client
            .delete_json(PRODUCT, &format!("jobs/{id}"))
            .await
    }

    /// Triggers a job immediately (even if paused) and waits for the run result.
    ///
    /// Calls `POST /cron/v1/jobs/{id}/run`.
    pub async fn run_now(&self, id: i64) -> Result<JobRun> {
        self.client
            .post_empty_with_timeout(PRODUCT, &format!("jobs/{id}/run"), MANUAL_RUN_TIMEOUT)
            .await
    }

    /// Lists recent runs for a job (newest first, retained for 30 days).
    ///
    /// Calls `GET /cron/v1/jobs/{id}/runs`.
    pub async fn list_runs(&self, id: i64, params: &PageParams) -> Result<Page<JobRun>> {
        self.client
            .get_json_query(PRODUCT, &format!("jobs/{id}/runs"), params)
            .await
    }

    /// Validates a cron expression or nickname and returns upcoming UTC run times.
    ///
    /// Calls `GET /cron/v1/schedules/preview`.
    pub async fn preview_schedule(
        &self,
        schedule: &str,
        count: Option<u32>,
    ) -> Result<SchedulePreview> {
        #[derive(Serialize)]
        struct Query<'a> {
            schedule: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            count: Option<u32>,
        }
        self.client
            .get_json_query(PRODUCT, "schedules/preview", &Query { schedule, count })
            .await
    }
}

/// HTTP method supported by Bytebury Cron jobs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
    /// `GET`
    Get,
    /// `POST`
    Post,
    /// `PUT`
    Put,
    /// `PATCH`
    Patch,
    /// `DELETE`
    Delete,
}

/// Request body for [`CronClient::create_job`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateJobRequest {
    /// Job display name (max 100 chars).
    pub name: String,
    /// 5-field UTC cron expression or nickname (`@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`).
    pub schedule: String,
    /// Public `http://` or `https://` target URL.
    pub url: String,
    /// HTTP method (defaults to `GET`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<HttpMethod>,
    /// Optional HTTP headers (max 20; supports [`crate::vault_ref!`] placeholders).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Optional request body (max 64 KB).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Whether the job starts enabled (default `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Whether failure notifications are enabled (default `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notify: Option<bool>,
}

impl CreateJobRequest {
    /// Creates a new cron job request with required `name`, `schedule`, and `url`.
    pub fn new(
        name: impl Into<String>,
        schedule: impl Into<String>,
        url: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            schedule: schedule.into(),
            url: url.into(),
            method: None,
            headers: None,
            body: None,
            enabled: None,
            notify: None,
        }
    }

    /// Sets the HTTP method.
    pub fn method(mut self, method: HttpMethod) -> Self {
        self.method = Some(method);
        self
    }

    /// Sets custom HTTP headers (works cleanly with [`crate::headers!`]).
    pub fn headers(mut self, headers: BTreeMap<String, String>) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Sets the request body.
    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Sets whether the job is enabled.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }

    /// Sets whether failure notifications are sent.
    pub fn notify(mut self, notify: bool) -> Self {
        self.notify = Some(notify);
        self
    }
}

/// Request body for [`CronClient::update_job`]. Omitted fields remain unchanged.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateJobRequest {
    /// Updated name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Updated cron schedule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedule: Option<String>,
    /// Updated target URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Updated HTTP method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<HttpMethod>,
    /// Replaces all custom headers (`BTreeMap::new()` clears them).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Replaces the body (`""` clears it).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Enable or pause the job.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Enable or disable failure notifications.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notify: Option<bool>,
}

/// Query parameters for [`CronClient::list_jobs`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListJobsParams {
    /// Substring match on job name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    /// Filter by enabled (`true`) or paused (`false`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`, default `25`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// A scheduled job managed by Bytebury Cron.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Job {
    /// Job ID.
    pub id: i64,
    /// Display name.
    pub name: String,
    /// Cron schedule expression or nickname.
    pub schedule: String,
    /// HTTP method.
    pub method: HttpMethod,
    /// Target URL.
    pub url: String,
    /// Custom request headers.
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    /// Optional request body.
    pub body: Option<String>,
    /// Whether the job is active.
    pub enabled: bool,
    /// Whether failure alerts are enabled.
    pub notify: bool,
    /// Next scheduled UTC run timestamp (`None` while paused).
    pub next_run_at: Option<String>,
    /// Timestamp of the most recent run, if any.
    pub last_run_at: Option<String>,
    /// Whether the most recent run returned a 2xx response.
    pub last_succeeded: Option<bool>,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
}

/// What initiated a [`JobRun`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunTrigger {
    /// Fired automatically on its cron schedule.
    Schedule,
    /// Fired manually via [`CronClient::run_now`] or the dashboard.
    Manual,
}

/// A single execution record for a Bytebury Cron job.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JobRun {
    /// Run ID.
    pub id: i64,
    /// Parent job ID.
    pub job_id: i64,
    /// Whether this run was scheduled or manual.
    pub trigger: RunTrigger,
    /// RFC 3339 start timestamp.
    pub started_at: String,
    /// Total duration in milliseconds.
    pub duration_ms: i64,
    /// HTTP status code received (`None` on connection/timeout error).
    pub status_code: Option<i32>,
    /// `true` when the target returned a 2xx status code.
    pub succeeded: bool,
    /// Error message if the run failed.
    pub error: Option<String>,
    /// First 2 KB of the target's response body, if any.
    pub response_body: Option<String>,
}

/// Result of [`CronClient::preview_schedule`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchedulePreview {
    /// Normalized schedule string.
    pub schedule: String,
    /// Human-readable English description of the schedule.
    pub description: String,
    /// Upcoming UTC run timestamps in RFC 3339 format.
    pub next_runs: Vec<String>,
}