use chrono::{DateTime, Datelike, Utc};
use serde::{Deserialize, Serialize};
use crate::domain::*;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Job {
pub id: String,
pub project_id: String,
pub trigger_service_id: Option<String>,
pub name: String,
pub compose: String,
#[serde(default)]
pub git_source: Option<JobGitSource>,
pub main_service: String,
#[serde(default)]
pub env_vars: Vec<EnvVar>,
#[serde(default)]
pub env_comments: Vec<EnvComment>,
pub enabled: bool,
pub recurrence: Option<Recurrence>,
pub last_run_at: Option<DateTime<Utc>>,
pub next_run_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JobGitSource {
#[serde(default)]
pub provider_id: Option<String>,
pub url: String,
pub branch: String,
#[serde(default)]
pub username: Option<String>,
#[serde(default)]
pub credentials: Option<String>,
pub compose_path: String,
}
impl Default for JobGitSource {
fn default() -> Self {
Self {
provider_id: None,
url: String::new(),
branch: "main".into(),
username: None,
credentials: None,
compose_path: "docker-compose.yml".into(),
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub enum Recurrence {
IntervalHours(u32),
Daily {
hour: u8,
minute: u8,
},
Weekly {
weekday: u8,
hour: u8,
minute: u8,
},
}
impl Recurrence {
pub fn next_after(&self, from: DateTime<Utc>) -> DateTime<Utc> {
match self {
Recurrence::IntervalHours(hours) => {
from + chrono::Duration::hours((*hours).max(1) as i64)
}
Recurrence::Daily { hour, minute } => {
let mut candidate = Self::at_time(from, *hour, *minute);
if candidate <= from {
candidate += chrono::Duration::days(1);
}
candidate
}
Recurrence::Weekly {
weekday,
hour,
minute,
} => {
let mut candidate = Self::at_time(from, *hour, *minute);
let target = (*weekday % 7) as i64;
let current = from.weekday().num_days_from_monday() as i64;
let mut delta_days = target - current;
if delta_days < 0 {
delta_days += 7;
}
candidate += chrono::Duration::days(delta_days);
if candidate <= from {
candidate += chrono::Duration::days(7);
}
candidate
}
}
}
fn at_time(from: DateTime<Utc>, hour: u8, minute: u8) -> DateTime<Utc> {
from.date_naive()
.and_hms_opt(hour.min(23) as u32, minute.min(59) as u32, 0)
.unwrap_or_else(|| from.date_naive().and_hms_opt(0, 0, 0).unwrap())
.and_utc()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JobRun {
pub id: String,
pub job_id: String,
pub started_at: DateTime<Utc>,
pub finished_at: Option<DateTime<Utc>>,
pub exit_code: Option<i32>,
pub success: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobSummary {
pub job: Job,
pub project_name: String,
pub trigger_service_name: Option<String>,
pub last_run: Option<JobRun>,
#[serde(default)]
pub warm: JobWarmStatus,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct JobWarmStatus {
pub job_id: String,
pub warm: bool,
pub warming: bool,
pub reason: Option<String>,
pub warmed_at: Option<DateTime<Utc>>,
}
#[cfg(test)]
mod job_tests {
use super::*;
#[test]
fn docker_cleanup_config_saved_before_warm_after_cleanup_warms_by_default() {
let mut json = serde_json::to_value(DockerCleanupConfig::default()).unwrap();
json.as_object_mut().unwrap().remove("warm_after_cleanup");
let loaded: DockerCleanupConfig = serde_json::from_value(json).unwrap();
assert!(loaded.warm_after_cleanup);
}
#[test]
fn docker_cleanup_config_saved_before_retention_fields_keeps_its_values() {
let config = DockerCleanupConfig {
enabled: true,
build_cache: true,
..DockerCleanupConfig::default()
};
let mut json = serde_json::to_value(&config).unwrap();
let object = json.as_object_mut().unwrap();
object.remove("build_cache_older_than_hours");
object.remove("images_older_than_hours");
let loaded: DockerCleanupConfig = serde_json::from_value(json).unwrap();
assert!(
loaded.enabled && loaded.build_cache,
"config antiga não pode resetar"
);
assert_eq!(
loaded.build_cache_older_than_hours,
DEFAULT_CLEANUP_RETENTION_HOURS
);
assert_eq!(
loaded.images_older_than_hours,
DEFAULT_CLEANUP_RETENTION_HOURS
);
}
#[test]
fn job_summary_from_older_daemon_has_cold_default_warm_status() {
let status: JobWarmStatus = serde_json::from_str(
r#"{"job_id":"j","warm":false,"warming":false,"reason":null,"warmed_at":null}"#,
)
.unwrap();
assert_eq!(
status,
JobWarmStatus {
job_id: "j".into(),
..JobWarmStatus::default()
}
);
}
#[test]
fn interval_advances_by_hours() {
let from = "2026-01-01T10:00:00Z".parse::<DateTime<Utc>>().unwrap();
let next = Recurrence::IntervalHours(6).next_after(from);
assert_eq!(next, from + chrono::Duration::hours(6));
}
#[test]
fn daily_before_time_today_fires_today() {
let from = "2026-01-01T02:00:00Z".parse::<DateTime<Utc>>().unwrap();
let next = Recurrence::Daily { hour: 3, minute: 0 }.next_after(from);
assert_eq!(
next,
"2026-01-01T03:00:00Z".parse::<DateTime<Utc>>().unwrap()
);
}
#[test]
fn daily_after_time_today_fires_tomorrow() {
let from = "2026-01-01T04:00:00Z".parse::<DateTime<Utc>>().unwrap();
let next = Recurrence::Daily { hour: 3, minute: 0 }.next_after(from);
assert_eq!(
next,
"2026-01-02T03:00:00Z".parse::<DateTime<Utc>>().unwrap()
);
}
#[test]
fn weekly_picks_next_matching_weekday() {
let from = "2026-01-01T10:00:00Z".parse::<DateTime<Utc>>().unwrap();
assert_eq!(from.weekday().num_days_from_monday(), 3);
let next = Recurrence::Weekly {
weekday: 0,
hour: 3,
minute: 0,
}
.next_after(from);
assert_eq!(
next,
"2026-01-05T03:00:00Z".parse::<DateTime<Utc>>().unwrap()
);
}
#[test]
fn weekly_same_weekday_but_time_passed_rolls_to_next_week() {
let from = "2026-01-01T10:00:00Z".parse::<DateTime<Utc>>().unwrap();
let next = Recurrence::Weekly {
weekday: 3,
hour: 3,
minute: 0,
}
.next_after(from);
assert_eq!(
next,
"2026-01-08T03:00:00Z".parse::<DateTime<Utc>>().unwrap()
);
}
#[test]
fn recurrence_json_round_trip() {
for r in [
Recurrence::IntervalHours(6),
Recurrence::Daily {
hour: 3,
minute: 30,
},
Recurrence::Weekly {
weekday: 6,
hour: 0,
minute: 0,
},
] {
let json = serde_json::to_string(&r).unwrap();
let back: Recurrence = serde_json::from_str(&json).unwrap();
assert_eq!(r, back);
}
}
}