//! `notificar_{{ name }}`: deja la notificación `{{ name }}` en la bandeja de `{{ to }}` tras {% for a in arms %}`{{ a.event_type }}`{% if not loop.last %}, {% endif %}{% endfor %}.
//! Lo escribe una vez `puerto generar notificacion`; desde entonces es tuyo: cambia el mensaje, el
//! enlace o a quién va.
//!
//! La entrega es al menos una vez: `procesar_una_vez` la deja una sola vez por evento
//! (`eventos_procesados`); solo se repetiría si el worker cae justo entre la notificación y su
//! marca. Quien tenga la app abierta la ve llegar en vivo.
use std::sync::Arc;
use async_trait::async_trait;
{%- for import in imports %}
use {{ import }};
{%- endfor %}
use puerto_eventos::procesar_una_vez;
use puerto_nucleo::eventos::{EventosProcesados, SobreEvento, ManejadorEvento, ResultadoManejo, MOTIVO_PAYLOAD_INVALIDO};
use puerto_nucleo::notificaciones::{NotificacionNueva, Notificaciones};
use puerto_sqlx::eventos::EventosProcesadosPostgres;
use puerto_sqlx::notificaciones::NotificacionesPostgres;
use sqlx::PgPool;
/// El `tipo` de la notificación en la bandeja.
const TIPO: &str = "{{ name }}";
pub struct Notificar{{ pascal }} {
pub notificaciones: Arc<dyn Notificaciones>,
/// Los eventos que ya procesó (`eventos_procesados`): una reentrega no repite la notificación.
pub procesados: Arc<dyn EventosProcesados>,
}
impl Notificar{{ pascal }} {
/// Lo llama `generado/registro.rs` al arrancar el worker, con su pool.
pub fn construir(pool: &PgPool) -> Self {
Self {
notificaciones: Arc::new(NotificacionesPostgres::new(pool.clone())),
procesados: Arc::new(EventosProcesadosPostgres::new(pool.clone())),
}
}
}
#[async_trait]
impl ManejadorEvento for Notificar{{ pascal }} {
async fn manejar(&self, evento: &SobreEvento) -> ResultadoManejo {
let notificacion = match evento.tipo_evento.as_str() {
{%- for a in arms %}
{{ a.constant }} => match evento.decodificar::<Snapshot{{ a.entity_pascal }}>() {
Ok({{ a.entity_snake }}) => NotificacionNueva::new({{ a.entity_snake }}.{{ to }}, TIPO, "{{ message }}"){% if a.plural %}
.con_enlace(format!("/{{ a.plural }}/{}", {{ a.entity_snake }}.id)){% endif %},
Err(err) => return ResultadoManejo::descartar(MOTIVO_PAYLOAD_INVALIDO, err.detalle),
},
{%- endfor %}
// No es uno de sus eventos (puerto.toml `[[consumidor]] eventos`): nada que notificar.
_ => return ResultadoManejo::Ack,
};
procesar_una_vez(&*self.procesados, "notificar_{{ name }}", evento.id, async {
match self.notificaciones.notificar(notificacion).await {
Ok(_) => ResultadoManejo::Ack,
Err(error) => {
tracing::warn!(
id_evento = %evento.id,
%error,
"notificar_{{ name }}: la bandeja no está disponible, se reintenta"
);
ResultadoManejo::Reintentar
}
}
})
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
use dominio_{{ first.entity_snake }}::eventos::Evento{{ first.entity_pascal }};
use dominio_{{ first.entity_snake }}::pruebas::madres::Madre{{ first.entity_pascal }};
use puerto_nucleo::ErrorRepositorio;
use puerto_nucleo::eventos::procesados::dobles::EventosProcesadosEnMemoria;
use puerto_nucleo::notificaciones::dobles::MockNotificaciones;
fn {{ first.const_lower }}() -> (Snapshot{{ first.entity_pascal }}, SobreEvento) {
let snapshot = Snapshot{{ first.entity_pascal }}::from_entidad(&Madre{{ first.entity_pascal }}::aleatorio());
let evento = SobreEvento::new(&Evento{{ first.entity_pascal }}::{{ first.variant }}(snapshot.clone()));
(snapshot, evento)
}
/// Una bandeja que espera `times` notificaciones, y a cada una responde `resultado`.
fn bandeja(times: usize, resultado: Result<(), ErrorRepositorio>) -> MockNotificaciones {
let mut bandeja = MockNotificaciones::new();
bandeja
.expect_notificar()
.times(times)
.returning(move |_| resultado.map(|()| Default::default()));
bandeja
}
fn consumidor(bandeja: MockNotificaciones) -> Notificar{{ pascal }} {
Notificar{{ pascal }} {
notificaciones: Arc::new(bandeja),
procesados: Arc::new(EventosProcesadosEnMemoria::new()),
}
}
#[tokio::test]
async fn deberia_notificar_a_{{ to }}_cuando_llega_un_evento_{{ first.event_type }}() {
// Preparar
let (snapshot, evento) = {{ first.const_lower }}();
let mut doble = MockNotificaciones::new();
doble
.expect_notificar()
.withf(move |nueva| nueva.usuario_id == snapshot.{{ to }} && nueva.tipo == TIPO)
.times(1)
.returning(|_| Ok(Default::default()));
// Actuar
let resultado = consumidor(doble).manejar(&evento).await;
// Comprobar
assert_eq!(resultado, ResultadoManejo::Ack);
}
#[tokio::test]
async fn deberia_notificar_una_vez_cuando_el_mismo_evento_llega_dos_veces() {
// Preparar
let (_, evento) = {{ first.const_lower }}();
let consumidor = consumidor(bandeja(1, Ok(())));
// Actuar
let primero = consumidor.manejar(&evento).await;
let segundo = consumidor.manejar(&evento).await;
// Comprobar
assert_eq!((primero, segundo), (ResultadoManejo::Ack, ResultadoManejo::Ack));
}
#[tokio::test]
async fn deberia_descartar_sin_notificar_cuando_el_payload_esta_mal_formado() {
// Preparar
let (_, mut evento) = {{ first.const_lower }}();
evento.payload = serde_json::json!({ "unexpected": true });
// Actuar
let resultado = consumidor(bandeja(0, Ok(()))).manejar(&evento).await;
// Comprobar
assert!(
matches!(
resultado,
ResultadoManejo::Descartar {
motivo: MOTIVO_PAYLOAD_INVALIDO,
..
}
),
"{resultado:?}"
);
}
#[tokio::test]
async fn deberia_reintentar_cuando_la_bandeja_no_esta_disponible() {
// Preparar
let (_, evento) = {{ first.const_lower }}();
// Actuar
let resultado = consumidor(bandeja(1, Err(ErrorRepositorio::NoDisponible)))
.manejar(&evento)
.await;
// Comprobar
assert_eq!(resultado, ResultadoManejo::Reintentar);
}
}