use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use axum::body::{to_bytes, Body, HttpBody};
use axum::extract::{MatchedPath, Request};
use axum::http::{header, HeaderMap};
use axum::middleware::{from_fn, Next};
use axum::response::Response;
use axum::Router;
use base64::Engine;
use crate::base::{ambiente_atual, CredencialDeAcesso};
use super::rotas::criar_log;
use super::tipos::{LogCriar, LogEnviado};
pub const MAXIMO_DE_LOGS_POR_LOTE: usize = 500;
pub const MAXIMO_DE_LOGS_NA_FILA: usize = 20_000;
pub const SEGUNDOS_ENTRE_ENVIOS: u64 = 5;
pub const MAXIMO_DE_BYTES_LIDOS_DO_CORPO_DE_ERRO: usize = 64 * 1024;
struct FilaDeLogs {
versao: Option<String>,
logs: Vec<LogEnviado>,
tarefa_de_envio_iniciada: bool,
}
fn fila_de_logs() -> &'static Mutex<FilaDeLogs> {
static FILA: OnceLock<Mutex<FilaDeLogs>> = OnceLock::new();
FILA.get_or_init(|| Mutex::new(FilaDeLogs { versao: None, logs: Vec::new(), tarefa_de_envio_iniciada: false }))
}
pub fn registrar_logs_http<S>(router: Router<S>, versao: &str) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
if let Ok(mut fila) = fila_de_logs().lock() {
fila.versao = Some(versao.to_string()).filter(|valor| !valor.is_empty());
}
router.layer(from_fn(registrar_log_da_requisicao))
}
async fn registrar_log_da_requisicao(requisicao: Request, proximo: Next) -> Response {
let inicio = Instant::now();
let ocorrido_em = chrono::Utc::now();
let metodo = requisicao.method().to_string();
let caminho = requisicao.uri().path().to_string();
let rota = requisicao.extensions().get::<MatchedPath>().map(|rota| rota.as_str().to_string());
let cabecalhos = requisicao.headers();
let agente = valor_do_cabecalho(cabecalhos, header::USER_AGENT.as_str());
let ip = ip_de_origem(cabecalhos);
let requisicao_id = valor_do_cabecalho(cabecalhos, "x-request-id");
let (usuario_id, usuario_email) = usuario_do_token(cabecalhos);
let resposta = proximo.run(requisicao).await;
let status = resposta.status().as_u16();
let (resposta, mensagem) = if status >= 400 { ler_mensagem_de_erro(resposta).await } else { (resposta, None) };
guardar_log(LogEnviado {
agente,
caminho,
detalhes: None,
duracao_ms: Some(inicio.elapsed().as_millis() as i64),
ip,
mensagem,
metodo,
ocorrido_em: Some(ocorrido_em),
requisicao_id,
rota,
status: status as i32,
usuario_email,
usuario_id,
});
resposta
}
fn valor_do_cabecalho(cabecalhos: &HeaderMap, nome: &str) -> Option<String> {
cabecalhos
.get(nome)
.and_then(|valor| valor.to_str().ok())
.map(|valor| valor.trim().to_string())
.filter(|valor| !valor.is_empty())
}
fn ip_de_origem(cabecalhos: &HeaderMap) -> Option<String> {
valor_do_cabecalho(cabecalhos, "cf-connecting-ip")
.or_else(|| valor_do_cabecalho(cabecalhos, "x-forwarded-for").and_then(|lista| lista.split(',').next().map(|ip| ip.trim().to_string())))
.or_else(|| valor_do_cabecalho(cabecalhos, "x-real-ip"))
}
fn usuario_do_token(cabecalhos: &HeaderMap) -> (Option<String>, Option<String>) {
let Some(token) = valor_do_cabecalho(cabecalhos, header::AUTHORIZATION.as_str())
.and_then(|valor| valor.strip_prefix("Bearer ").map(|token| token.trim().to_string()))
else {
return (None, None);
};
let Some(carga) = token.split('.').nth(1) else { return (None, None) };
let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(carga.trim_end_matches('=')) else {
return (None, None);
};
let Ok(dados) = serde_json::from_slice::<serde_json::Value>(&bytes) else { return (None, None) };
let texto = |campo: &str| dados.get(campo).and_then(|valor| valor.as_str()).map(str::to_string);
(texto("sub"), texto("email"))
}
async fn ler_mensagem_de_erro(resposta: Response) -> (Response, Option<String>) {
let eh_json = resposta
.headers()
.get(header::CONTENT_TYPE)
.and_then(|valor| valor.to_str().ok())
.is_some_and(|tipo| tipo.contains("json"));
let tamanho_conhecido = resposta.body().size_hint().upper();
if !eh_json || tamanho_conhecido.is_none_or(|tamanho| tamanho > MAXIMO_DE_BYTES_LIDOS_DO_CORPO_DE_ERRO as u64) {
return (resposta, None);
}
let (partes, corpo) = resposta.into_parts();
match to_bytes(corpo, MAXIMO_DE_BYTES_LIDOS_DO_CORPO_DE_ERRO).await {
Ok(bytes) => {
let mensagem = serde_json::from_slice::<serde_json::Value>(&bytes).ok().and_then(|dados| {
["erro", "mensagem", "message", "error"]
.iter()
.find_map(|campo| dados.get(*campo).and_then(|valor| valor.as_str()).map(str::to_string))
});
(Response::from_parts(partes, Body::from(bytes)), mensagem)
}
Err(_) => (Response::from_parts(partes, Body::empty()), None),
}
}
fn guardar_log(log: LogEnviado) {
let Ok(mut fila) = fila_de_logs().lock() else { return };
if fila.logs.len() < MAXIMO_DE_LOGS_NA_FILA {
fila.logs.push(log);
}
if !fila.tarefa_de_envio_iniciada && tokio::runtime::Handle::try_current().is_ok() {
fila.tarefa_de_envio_iniciada = true;
tokio::spawn(enviar_logs_de_tempos_em_tempos());
}
}
async fn enviar_logs_de_tempos_em_tempos() {
let mut intervalo = tokio::time::interval(Duration::from_secs(SEGUNDOS_ENTRE_ENVIOS));
intervalo.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
intervalo.tick().await;
while let Some(lote) = retirar_lote_da_fila() {
enviar_lote(lote).await;
}
}
}
fn retirar_lote_da_fila() -> Option<LogCriar> {
let mut fila = fila_de_logs().lock().ok()?;
if fila.logs.is_empty() {
return None;
}
let quantidade = fila.logs.len().min(MAXIMO_DE_LOGS_POR_LOTE);
let logs: Vec<LogEnviado> = fila.logs.drain(..quantidade).collect();
Some(LogCriar { ambiente: Some(ambiente_atual().nome_do_ambiente().to_string()), logs, versao: fila.versao.clone() })
}
async fn enviar_lote(lote: LogCriar) {
let Ok(credencial_de_acesso) = CredencialDeAcesso::token_do_aplicativo().await else { return };
let _ = criar_log(&credencial_de_acesso, &lote).await;
}
#[cfg(test)]
mod testes {
use super::*;
use axum::http::StatusCode;
use axum::routing::get;
use tower::ServiceExt;
#[tokio::test]
async fn registra_rota_status_e_mensagem_sem_mudar_a_resposta() {
let router: Router = Router::new().route(
"/pedido/{id}",
get(|| async { (StatusCode::INTERNAL_SERVER_ERROR, [(header::CONTENT_TYPE, "application/json")], r#"{"erro":"Falha ao consultar o banco"}"#) }),
);
let router = registrar_logs_http(router, "1.2.3");
let requisicao = Request::builder().uri("/pedido/42?token=segredo").header("user-agent", "teste").body(Body::empty()).unwrap();
let resposta = router.oneshot(requisicao).await.unwrap();
assert_eq!(resposta.status(), StatusCode::INTERNAL_SERVER_ERROR);
let corpo = to_bytes(resposta.into_body(), 1024).await.unwrap();
assert_eq!(&corpo[..], br#"{"erro":"Falha ao consultar o banco"}"#);
let fila = fila_de_logs().lock().unwrap();
let log = fila.logs.iter().find(|log| log.caminho == "/pedido/42").expect("log guardado");
assert_eq!(log.rota.as_deref(), Some("/pedido/{id}"));
assert_eq!(log.status, 500);
assert_eq!(log.metodo, "GET");
assert_eq!(log.mensagem.as_deref(), Some("Falha ao consultar o banco"));
assert_eq!(log.agente.as_deref(), Some("teste"));
assert_eq!(fila.versao.as_deref(), Some("1.2.3"));
}
#[test]
fn le_sub_e_email_do_token() {
let carga = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"sub":"u1","email":"ana@termotubos.com.br"}"#);
let mut cabecalhos = HeaderMap::new();
cabecalhos.insert(header::AUTHORIZATION, format!("Bearer x.{carga}.y").parse().unwrap());
assert_eq!(usuario_do_token(&cabecalhos), (Some("u1".into()), Some("ana@termotubos.com.br".into())));
}
}