use crate::engine::{self, DockerClient, networks};
use crate::features::jobs::JobsContext;
use crate::platform::event_bus::EventBus;
use crate::platform::secrets::SecretsManager;
use crate::store;
use anyhow::Result;
use chrono::Utc;
use shared::{Event, Job, JobRun};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::{error, info, warn};
use crate::features::deploy::queue::{QueueTaskFn, QueueTaskInfo};
use shared::QueueItemKind;
pub struct JobRunner {
pub db: Arc<store::Db>,
pub docker: Arc<DockerClient>,
pub bus: Arc<EventBus>,
pub secrets: Arc<SecretsManager>,
pub db_path: PathBuf,
pub registry_internal_token: Option<Arc<str>>,
}
pub async fn spawn(state: &JobsContext, job: Job) -> Result<JobRun> {
let run = store::job_run::create(&state.db, &job.id).await?;
let runner = Arc::new(JobRunner {
db: state.db.clone(),
docker: state.docker.clone(),
bus: state.bus.clone(),
secrets: state.secrets.clone(),
db_path: state.db_path.clone(),
registry_internal_token: state.registry_internal_token.clone(),
});
let run_id = run.id.clone();
let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);
if let Ok(mut map) = state.active_jobs.lock() {
map.insert(run_id.clone(), cancel_tx);
}
let active_jobs = state.active_jobs.clone();
runner.reschedule(&job).await;
let queue = state.deploy_queue.clone();
if !queue.is_idle() {
runner
.linha(
&job.id,
&run_id,
"==> Aguardando a vez: há um deploy ou outro job em execução (ou a fila está pausada)",
)
.await;
}
let info = QueueTaskInfo {
kind: QueueItemKind::Job,
job_id: job.id.clone(),
};
let run_task: QueueTaskFn = {
let (runner, job, run_id, active_jobs) = (
runner.clone(),
job.clone(),
run_id.clone(),
active_jobs.clone(),
);
Box::new(move || {
Box::pin(async move {
runner
.linha(&job.id, &run_id, "==> Sua vez: iniciando")
.await;
runner.run(&job, run_id.clone(), Some(cancel_rx)).await;
if let Ok(mut map) = active_jobs.lock() {
map.remove(&run_id);
}
})
})
};
let on_cancel: QueueTaskFn = {
let (runner, job, run_id) = (runner.clone(), job.clone(), run_id.clone());
Box::new(move || {
Box::pin(async move {
runner.cancelar_antes_de_comecar(&job, &run_id).await;
if let Ok(mut map) = active_jobs.lock() {
map.remove(&run_id);
}
})
})
};
queue.enqueue_task(run_id, info, run_task, on_cancel);
state.bus.publish(Event::DeployQueueChanged);
Ok(run)
}
impl JobRunner {
pub async fn run(
&self,
job: &Job,
run_id: String,
cancel_rx: Option<tokio::sync::watch::Receiver<bool>>,
) {
info!(job_id = %job.id, run_id = %run_id, "job_runner: iniciando execução");
self.bus.publish(Event::JobRunStateChanged {
job_id: job.id.clone(),
job_run_id: run_id.clone(),
running: true,
success: None,
});
let result = self.run_inner_mirrored(job, &run_id, None, cancel_rx).await;
let success = match &result {
Ok(exit_code) => *exit_code == 0,
Err(e) => {
error!(job_id = %job.id, run_id = %run_id, error = %e, "job_runner: falha ao executar job");
let _ = store::job_run::finish(&self.db, &run_id, -1).await;
false
}
};
self.bus.publish(Event::JobRunStateChanged {
job_id: job.id.clone(),
job_run_id: run_id.clone(),
running: false,
success: Some(success),
});
self.reschedule(job).await;
}
pub(crate) async fn run_inner_mirrored(
&self,
job: &Job,
run_id: &str,
mirror_deployment: Option<(String, String)>,
cancel_rx: Option<tokio::sync::watch::Receiver<bool>>,
) -> Result<i32> {
let project_net = crate::store::projects::network_name(&self.db, &job.project_id).await?;
let network_name =
networks::ensure_project_network(&self.docker.inner, &project_net).await?;
let env_vars =
crate::features::deploy::env_resolve::resolve_job(&self.db, &self.secrets, job).await?;
let project_name = run_id.to_lowercase();
let build_dir = self.db_path.join("jobs").join(run_id);
let build_source = match &job.git_source {
Some(git) => {
let bus = self.bus.clone();
let db_handle = self.db.clone();
let jid = job.id.clone();
let rid = run_id.to_string();
super::source::clone_git_source(
&self.db,
&self.secrets,
job,
git,
&build_dir,
move |p| {
let ts = Utc::now();
bus.publish(Event::JobLogLine {
job_run_id: rid.clone(),
job_id: jid.clone(),
line: p.description.clone(),
timestamp: ts,
stream: shared::protocol::LogStream::Stdout,
});
let db_handle = db_handle.clone();
let rid = rid.clone();
let line = p.description;
tokio::spawn(async move {
let _ = store::job_log::append(
&db_handle,
&rid,
&shared::protocol::LogStream::Stdout,
&line,
ts,
)
.await;
});
},
)
.await?;
engine::compose::JobBuildSource::Git {
compose_rel_path: &git.compose_path,
}
}
None => engine::compose::JobBuildSource::Compose(&job.compose),
};
let already_cancelled = cancel_rx.as_ref().map(|rx| *rx.borrow()).unwrap_or(false);
let (exit_code, images) = if already_cancelled {
(engine::compose::CANCELLED_EXIT_CODE, None)
} else {
engine::compose::run_once(
build_source,
&project_name,
&network_name,
&job.main_service,
&job.id,
run_id,
&self.bus,
&self.db,
&env_vars,
&build_dir,
self.registry_internal_token.clone(),
mirror_deployment,
cancel_rx,
)
.await?
};
store::job_run::finish(&self.db, run_id, exit_code).await?;
if let Some(images) = images {
super::warm::record(&self.db, job, &images).await;
}
if let Err(e) = tokio::fs::remove_dir_all(&build_dir).await {
warn!(run_id = %run_id, error = %e, "job_runner: falha ao limpar build_dir (best-effort)");
}
Ok(exit_code)
}
async fn linha(&self, job_id: &str, run_id: &str, texto: &str) {
let ts = Utc::now();
self.bus.publish(Event::JobLogLine {
job_run_id: run_id.to_string(),
job_id: job_id.to_string(),
line: texto.to_string(),
timestamp: ts,
stream: shared::protocol::LogStream::Stdout,
});
let _ = store::job_log::append(
&self.db,
run_id,
&shared::protocol::LogStream::Stdout,
texto,
ts,
)
.await;
}
async fn cancelar_antes_de_comecar(&self, job: &Job, run_id: &str) {
self.linha(&job.id, run_id, "==> Cancelado antes de começar a executar")
.await;
let _ =
store::job_run::finish(&self.db, run_id, engine::compose::CANCELLED_EXIT_CODE).await;
self.bus.publish(Event::JobRunStateChanged {
job_id: job.id.clone(),
job_run_id: run_id.to_string(),
running: false,
success: Some(false),
});
}
async fn reschedule(&self, job: &Job) {
let now = Utc::now();
let next_run_at = job.recurrence.map(|r| r.next_after(now));
if let Err(e) = store::job::mark_fired(&self.db, &job.id, now, next_run_at).await {
error!(job_id = %job.id, error = %e, "job_runner: falha ao reagendar");
}
}
}