use super::FluxproDbServiceImpl;
use crate::models::id_field::IdField;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct ProcessIncident {
pub uuid: Uuid,
pub process_instance_uuid: Uuid,
pub task_uuid: Uuid,
pub task: serde_json::Value,
pub kind: String,
pub reason: String,
pub attempt: i32,
pub created_at: DateTime<Utc>,
pub resolved_at: Option<DateTime<Utc>>,
}
impl FluxproDbServiceImpl {
pub async fn get_open_incident(
&self,
token: &IdField,
) -> anyhow::Result<Option<ProcessIncident>> {
Ok(sqlx::query_as("select incident.* from fluxpro.process_incident incident join fluxpro.process_instance i on i.uuid=incident.process_instance_uuid where i.token=$1 and incident.resolved_at is null")
.bind(token.get_id()).fetch_optional(&self.db_pool).await?)
}
pub async fn resume_instance(
&self,
token: &IdField,
incident_id: Uuid,
) -> anyhow::Result<bool> {
let mut tx = self.db_pool.begin().await?;
let instance: Uuid = sqlx::query_scalar(
"select uuid from fluxpro.process_instance where token=$1 for update",
)
.bind(token.get_id())
.fetch_one(&mut *tx)
.await?;
let incident = sqlx::query("select task_uuid from fluxpro.process_incident where uuid=$1 and process_instance_uuid=$2 and resolved_at is null for update")
.bind(incident_id).bind(instance).fetch_optional(&mut *tx).await?;
let Some(incident) = incident else {
tx.rollback().await?;
return Ok(false);
};
let task: Uuid = incident.try_get("task_uuid")?;
let affected = sqlx::query("update fluxpro.queue_runner set attempts=0, lock_key='',locked_at=null,locked_by=null,run_after=clock_timestamp() where uuid=$1 and (locked_by is null or locked_by<clock_timestamp())")
.bind(task).execute(&mut *tx).await?.rows_affected();
anyhow::ensure!(affected == 1, "incident task is missing or still leased");
sqlx::query(
"update fluxpro.process_incident set resolved_at=clock_timestamp() where uuid=$1",
)
.bind(incident_id)
.execute(&mut *tx)
.await?;
sqlx::query("update fluxpro.process_instance set execution_state='running',revision=revision+1,recovery_task_uuid=$2 where uuid=$1")
.bind(instance).bind(task).execute(&mut *tx).await?;
sqlx::query("insert into fluxpro.process_instance_log(process_instance_uuid,level,event_type,source,message,queue_task_uuid,details) values ($1,'info','instance.resumed','operator','Explicitly resumed incident task',$2,jsonb_build_object('incident_id',$3::text))")
.bind(instance).bind(task).bind(incident_id.to_string()).execute(&mut *tx).await?;
tx.commit().await?;
Ok(true)
}
}