termo_core 0.1.21

Todos os clientes da Termotubos num crate só: um módulo por serviço e cada rota da API como uma função de uma linha, com o endereço resolvido pelo ambiente atual.
Documentation
use std::error::Error;
use std::fmt;
use std::sync::OnceLock;
use std::time::Duration;

use reqwest::{header::CONTENT_TYPE, redirect::Policy, Client};
use serde::Deserialize;
use serde_json::Value;

use crate::base::{segredo_do_app_configurado, CredencialDeAcesso, VARIAVEL_DO_SEGREDO_DO_APP};
use crate::webhook::assinatura::endereco_do_termo_webhook_no_ambiente_atual;
use crate::webhook::eventos::{Envelope, Evento};

pub const CAMINHO_DE_PUBLICACAO: &str = "/eventos";

const TEMPO_LIMITE_EM_SEGUNDOS: u64 = 10;

const TAMANHO_MAXIMO_DA_MENSAGEM: usize = 500;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfiguracaoDoHub {
    pub url: String,
}

impl ConfiguracaoDoHub {
    pub fn nova(url: impl Into<String>) -> Self {
        Self {
            url: url.into().trim().trim_end_matches('/').to_string(),
        }
    }

    /// Sempre devolve o hub do ambiente atual. Enquanto o segredo do app não estiver configurado
    /// (`definir_segredo_do_app` ou `SEGREDO_DO_APP_GERADO_NO_TERMO_AUTH`), os eventos esperam na fila.
    pub fn carregar_do_ambiente_atual() -> Option<Self> {
        if !segredo_do_app_configurado() {
            eprintln!(
                "termo_webhook: segredo do app ainda não configurado ({VARIAVEL_DO_SEGREDO_DO_APP} ou definir_segredo_do_app); os eventos esperam na fila até ele ser cadastrado"
            );
        }
        Some(Self::nova(endereco_do_termo_webhook_no_ambiente_atual()))
    }

    pub fn endereco_de_publicacao(&self) -> String {
        format!("{}{CAMINHO_DE_PUBLICACAO}", self.url)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Publicado {
    pub repetido: bool,
    pub aviso: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FalhaDePublicacao {
    Rede(String),
    SemTokenDoAplicativo(String),
    Recusado {
        status: u16,
        motivo: Option<String>,
        mensagem: String,
    },
    Serializacao(String),
}

impl FalhaDePublicacao {
    pub fn vale_tentar_de_novo(&self) -> bool {
        match self {
            Self::Rede(_) | Self::SemTokenDoAplicativo(_) => true,
            Self::Serializacao(_) => false,
            Self::Recusado { status, .. } => !matches!(status, 400 | 413 | 422),
        }
    }
}

impl fmt::Display for FalhaDePublicacao {
    fn fmt(&self, formatador: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rede(mensagem) => write!(formatador, "falha de rede: {mensagem}"),
            Self::SemTokenDoAplicativo(mensagem) => write!(formatador, "sem token do aplicativo: {mensagem}"),
            Self::Serializacao(mensagem) => write!(formatador, "envelope não serializa: {mensagem}"),
            Self::Recusado {
                status,
                motivo: Some(motivo),
                mensagem,
            } => write!(formatador, "hub respondeu {status} ({motivo}): {mensagem}"),
            Self::Recusado {
                status, mensagem, ..
            } => write!(formatador, "hub respondeu {status}: {mensagem}"),
        }
    }
}

impl Error for FalhaDePublicacao {}

#[derive(Debug, Default, Deserialize)]
struct RespostaDoHub {
    situacao: Option<String>,
    aviso: Option<Value>,
    erro: Option<String>,
    motivo: Option<String>,
    erros: Option<Value>,
}

fn texto_do_valor(valor: Value) -> Option<String> {
    match valor {
        Value::Null => None,
        Value::String(texto) => Some(texto),
        outro => Some(outro.to_string()),
    }
}

fn cliente_http() -> &'static Client {
    static CLIENTE: OnceLock<Client> = OnceLock::new();
    CLIENTE.get_or_init(|| {
        Client::builder()
            .user_agent(concat!("termo_webhook/", env!("CARGO_PKG_VERSION")))
            .timeout(Duration::from_secs(TEMPO_LIMITE_EM_SEGUNDOS))
            .redirect(Policy::none())
            .build()
            .expect("falha ao montar o cliente HTTP do termo_webhook")
    })
}

fn descrever_falha_de_rede(erro: &reqwest::Error) -> String {
    if erro.is_timeout() {
        "tempo limite esgotado".to_string()
    } else if erro.is_connect() {
        "não foi possível conectar ao hub".to_string()
    } else {
        erro.to_string()
    }
}

fn resumir(texto: &str) -> String {
    texto.chars().take(TAMANHO_MAXIMO_DA_MENSAGEM).collect()
}

pub async fn publicar_evento_no_hub_agora<T: Evento>(
    configuracao: &ConfiguracaoDoHub,
    envelope: &Envelope<T>,
) -> Result<Publicado, FalhaDePublicacao> {
    let corpo =
        serde_json::to_vec(envelope).map_err(|erro| FalhaDePublicacao::Serializacao(erro.to_string()))?;
    enviar_corpo(configuracao, corpo).await
}

pub(crate) async fn enviar_corpo(
    configuracao: &ConfiguracaoDoHub,
    corpo: Vec<u8>,
) -> Result<Publicado, FalhaDePublicacao> {
    let credencial_do_aplicativo = CredencialDeAcesso::token_do_aplicativo()
        .await
        .map_err(|erro| FalhaDePublicacao::SemTokenDoAplicativo(erro.to_string()))?;

    let resposta = cliente_http()
        .post(configuracao.endereco_de_publicacao())
        .header(CONTENT_TYPE, "application/json")
        .bearer_auth(credencial_do_aplicativo.token_bearer())
        .body(corpo)
        .send()
        .await
        .map_err(|erro| FalhaDePublicacao::Rede(descrever_falha_de_rede(&erro)))?;

    let status = resposta.status();
    let texto = resposta.text().await.unwrap_or_default();
    let lida: RespostaDoHub = serde_json::from_str(&texto).unwrap_or_default();

    if status.is_success() {
        return Ok(Publicado {
            repetido: lida.situacao.as_deref() == Some("repetido"),
            aviso: lida.aviso.and_then(texto_do_valor),
        });
    }

    let mensagem = match (lida.erro, lida.erros) {
        (Some(erro), Some(erros)) => format!("{erro} {erros}"),
        (Some(erro), None) => erro,
        (None, _) if texto.trim().is_empty() => status.to_string(),
        (None, _) => texto,
    };

    Err(FalhaDePublicacao::Recusado {
        status: status.as_u16(),
        motivo: lida.motivo,
        mensagem: resumir(&mensagem),
    })
}