use std::time::Duration;
use chrono::{DateTime, Utc};
use serde_json::Value;
use sqlx::postgres::{PgListener, PgPool};
use sqlx::{PgExecutor, Row};
use tokio::task::JoinHandle;
use tokio::time::{sleep, timeout, Instant};
use uuid::Uuid;
use crate::webhook::eventos::{Envelope, Evento};
use crate::base::segredo_do_app_configurado;
use crate::webhook::publicar::{enviar_corpo, ConfiguracaoDoHub};
pub const TABELA_DA_FILA: &str = "termo_eventos_pendente";
pub const RETENCAO_EM_SEGUNDOS: f64 = 3600.0;
const PREFIXO_DO_CANAL: &str = "termo_eventos_";
const TAMANHO_DO_LOTE: i64 = 50;
const RESERVA_EM_SEGUNDOS: f64 = 120.0;
const INTERVALO_DE_VARREDURA: Duration = Duration::from_secs(5);
const INTERVALO_DA_LIMPEZA: Duration = Duration::from_secs(60);
const ESPERAS_ENTRE_TENTATIVAS_EM_SEGUNDOS: [f64; 5] = [5.0, 30.0, 120.0, 300.0, 600.0];
const CRIAR_TABELA: &str = r#"
SELECT pg_advisory_xact_lock(hashtext(current_schema() || '.termo_eventos_pendente'));
CREATE TABLE IF NOT EXISTS termo_eventos_pendente (
id uuid PRIMARY KEY,
tipo text NOT NULL,
versao integer NOT NULL,
entidade_id text NOT NULL,
envelope jsonb NOT NULL,
tentativas integer NOT NULL DEFAULT 0,
proxima_tentativa_em timestamptz NOT NULL DEFAULT now(),
reservado_ate timestamptz,
ultimo_erro text,
criado_em timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS termo_eventos_pendente_proxima_tentativa_em
ON termo_eventos_pendente (proxima_tentativa_em);
CREATE INDEX IF NOT EXISTS termo_eventos_pendente_criado_em
ON termo_eventos_pendente (criado_em);
"#;
struct EventoReservado {
id: Uuid,
tipo: String,
envelope: Value,
tentativas: i32,
criado_em: DateTime<Utc>,
}
pub async fn guardar_evento_para_publicar_na_mesma_transacao<'c, E, T>(executor: E, entidade_id: impl Into<String>, dados: T) -> Result<Uuid, sqlx::Error>
where
E: PgExecutor<'c>,
T: Evento,
{
guardar_envelope_para_publicar_na_mesma_transacao(executor, &Envelope::novo(entidade_id, dados)).await
}
pub async fn guardar_envelope_para_publicar_na_mesma_transacao<'c, E, T>(executor: E, envelope: &Envelope<T>) -> Result<Uuid, sqlx::Error>
where
E: PgExecutor<'c>,
T: Evento,
{
let corpo = serde_json::to_value(envelope).map_err(|erro| sqlx::Error::Encode(Box::new(erro)))?;
sqlx::query(
r#"
WITH guardado AS (
INSERT INTO termo_eventos_pendente (id, tipo, versao, entidade_id, envelope)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
)
SELECT pg_notify($6 || current_schema(), '') FROM guardado
"#,
)
.bind(envelope.id)
.bind(&envelope.tipo)
.bind(envelope.versao)
.bind(&envelope.entidade_id)
.bind(corpo)
.bind(PREFIXO_DO_CANAL)
.execute(executor)
.await?;
Ok(envelope.id)
}
pub async fn criar_tabela_da_fila_de_saida_se_nao_existir(pool: &PgPool) -> Result<(), sqlx::Error> {
sqlx::raw_sql(CRIAR_TABELA).execute(pool).await?;
Ok(())
}
pub async fn iniciar_envio_automatico_dos_eventos_guardados(pool: &PgPool, hub: Option<ConfiguracaoDoHub>) -> Result<JoinHandle<()>, sqlx::Error> {
criar_tabela_da_fila_de_saida_se_nao_existir(pool).await?;
if hub.is_none() {
eprintln!("termo_webhook: sem hub configurado, os eventos guardados serão só impressos no terminal");
}
let ouvinte = conectar_ouvinte(pool).await;
Ok(tokio::spawn(executar(pool.clone(), hub, ouvinte)))
}
async fn conectar_ouvinte(pool: &PgPool) -> Option<PgListener> {
let conexao = async {
let canal: String = sqlx::query_scalar("SELECT $1 || current_schema()")
.bind(PREFIXO_DO_CANAL)
.fetch_one(pool)
.await?;
let mut ouvinte = PgListener::connect_with(pool).await?;
ouvinte.listen(&canal).await?;
Ok::<_, sqlx::Error>(ouvinte)
};
match conexao.await {
Ok(ouvinte) => Some(ouvinte),
Err(erro) => {
eprintln!("termo_webhook: aviso imediato indisponível, a fila será varrida a cada 5 s: {erro}");
None
}
}
}
async fn executar(pool: PgPool, hub: Option<ConfiguracaoDoHub>, mut ouvinte: Option<PgListener>) {
let mut proxima_limpeza = Instant::now();
loop {
if Instant::now() >= proxima_limpeza {
if let Err(erro) = limpar_vencidos(&pool).await {
eprintln!("termo_webhook: falha ao limpar a fila de saída: {erro}");
}
proxima_limpeza = Instant::now() + INTERVALO_DA_LIMPEZA;
}
let lote_cheio = match enviar_lote(&pool, hub.as_ref()).await {
Ok(lote_cheio) => lote_cheio,
Err(erro) => {
eprintln!("termo_webhook: falha ao ler a fila de saída: {erro}");
false
}
};
if !lote_cheio {
aguardar_aviso(&pool, &mut ouvinte).await;
}
}
}
async fn aguardar_aviso(pool: &PgPool, ouvinte: &mut Option<PgListener>) {
let Some(atual) = ouvinte.as_mut() else {
sleep(INTERVALO_DE_VARREDURA).await;
*ouvinte = conectar_ouvinte(pool).await;
return;
};
if let Ok(Err(erro)) = timeout(INTERVALO_DE_VARREDURA, atual.recv()).await {
eprintln!("termo_webhook: aviso imediato caiu, reconectando: {erro}");
*ouvinte = None;
}
}
fn espera_depois_da_tentativa(tentativas: i32) -> f64 {
let posicao = usize::try_from(tentativas.saturating_sub(1)).unwrap_or(0);
ESPERAS_ENTRE_TENTATIVAS_EM_SEGUNDOS[posicao.min(ESPERAS_ENTRE_TENTATIVAS_EM_SEGUNDOS.len() - 1)]
}
async fn enviar_lote(pool: &PgPool, hub: Option<&ConfiguracaoDoHub>) -> Result<bool, sqlx::Error> {
let reservados = reservar(pool).await?;
if hub.is_some() && !segredo_do_app_configurado() {
let ids: Vec<Uuid> = reservados.iter().map(|evento| evento.id).collect();
liberar(pool, &ids).await?;
return Ok(false);
}
let lote_cheio = reservados.len() as i64 == TAMANHO_DO_LOTE;
let mut pendentes = reservados.into_iter();
while let Some(evento) = pendentes.next() {
let Some(hub) = hub else {
println!("[termo_webhook] {}", evento.envelope);
concluir(pool, evento.id).await?;
continue;
};
let corpo = serde_json::to_vec(&evento.envelope).unwrap_or_default();
match enviar_corpo(hub, corpo).await {
Ok(publicado) => {
if let Some(aviso) = publicado.aviso {
eprintln!("termo_webhook: {} {}: {aviso}", evento.tipo, evento.id);
}
concluir(pool, evento.id).await?;
}
Err(falha) if !falha.vale_tentar_de_novo() => {
eprintln!(
"termo_webhook: {} {} recusado pelo hub e descartado: {falha}",
evento.tipo, evento.id
);
concluir(pool, evento.id).await?;
}
Err(falha) => {
let tentativas = evento.tentativas + 1;
adiar(pool, evento.id, tentativas, &falha.to_string()).await?;
let restantes: Vec<Uuid> = pendentes.map(|pendente| pendente.id).collect();
liberar(pool, &restantes).await?;
return Ok(false);
}
}
}
Ok(lote_cheio)
}
async fn reservar(pool: &PgPool) -> Result<Vec<EventoReservado>, sqlx::Error> {
let linhas = sqlx::query(
r#"
UPDATE termo_eventos_pendente
SET reservado_ate = now() + make_interval(secs => $2)
WHERE id IN (
SELECT id
FROM termo_eventos_pendente
WHERE proxima_tentativa_em <= now()
AND (reservado_ate IS NULL OR reservado_ate < now())
ORDER BY criado_em
LIMIT $1
FOR UPDATE SKIP LOCKED
)
RETURNING id, tipo, envelope, tentativas, criado_em
"#,
)
.bind(TAMANHO_DO_LOTE)
.bind(RESERVA_EM_SEGUNDOS)
.fetch_all(pool)
.await?;
let mut reservados = linhas
.into_iter()
.map(|linha| {
Ok(EventoReservado {
id: linha.try_get("id")?,
tipo: linha.try_get("tipo")?,
envelope: linha.try_get("envelope")?,
tentativas: linha.try_get("tentativas")?,
criado_em: linha.try_get("criado_em")?,
})
})
.collect::<Result<Vec<_>, sqlx::Error>>()?;
reservados.sort_by_key(|evento| evento.criado_em);
Ok(reservados)
}
async fn concluir(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM termo_eventos_pendente WHERE id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(())
}
async fn adiar(pool: &PgPool, id: Uuid, tentativas: i32, erro: &str) -> Result<(), sqlx::Error> {
sqlx::query(
r#"
UPDATE termo_eventos_pendente
SET tentativas = $2,
proxima_tentativa_em = now() + make_interval(secs => $3),
reservado_ate = NULL,
ultimo_erro = $4
WHERE id = $1
"#,
)
.bind(id)
.bind(tentativas)
.bind(espera_depois_da_tentativa(tentativas))
.bind(erro)
.execute(pool)
.await?;
Ok(())
}
async fn liberar(pool: &PgPool, ids: &[Uuid]) -> Result<(), sqlx::Error> {
if ids.is_empty() {
return Ok(());
}
sqlx::query("UPDATE termo_eventos_pendente SET reservado_ate = NULL WHERE id = ANY($1)")
.bind(ids)
.execute(pool)
.await?;
Ok(())
}
async fn limpar_vencidos(pool: &PgPool) -> Result<(), sqlx::Error> {
let linhas = sqlx::query(
r#"
DELETE FROM termo_eventos_pendente
WHERE criado_em < now() - make_interval(secs => $1)
RETURNING id, tipo, tentativas, ultimo_erro
"#,
)
.bind(RETENCAO_EM_SEGUNDOS)
.fetch_all(pool)
.await?;
for linha in linhas {
let id: Uuid = linha.try_get("id")?;
let tipo: String = linha.try_get("tipo")?;
let tentativas: i32 = linha.try_get("tentativas")?;
let ultimo_erro: Option<String> = linha.try_get("ultimo_erro")?;
eprintln!(
"termo_webhook: {tipo} {id} descartado depois de 1 h sem entrega ({tentativas} tentativas): {}",
ultimo_erro.unwrap_or_else(|| "sem resposta do hub".to_string())
);
}
Ok(())
}