diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 0232f59..0eef9dc 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -2,8 +2,9 @@ name: Build & Publish Docker Image to GHCR (Java Rules) on: push: + # main no está a propósito (SCRUM-1723 / QAS-24): PROD no se reconstruye. + # :latest sale de promote-latest.yml, que retaguea el digest de :staging. branches: - - main - release - develop tags: @@ -42,7 +43,6 @@ jobs: with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | - type=raw,value=latest,enable={{is_default_branch}} type=raw,value=staging,enable=${{ github.ref == 'refs/heads/release' }} type=raw,value=develop,enable=${{ github.ref == 'refs/heads/develop' }} type=ref,event=branch diff --git a/.github/workflows/promote-latest.yml b/.github/workflows/promote-latest.yml new file mode 100644 index 0000000..bd2318f --- /dev/null +++ b/.github/workflows/promote-latest.yml @@ -0,0 +1,89 @@ +name: Promote staging to PROD (Java Rules) + +# SCRUM-1723 / QAS-24: PROD corre exactamente la imagen que QA probó. +# Este workflow no construye nada. Lee el digest que tiene hoy :staging (o el +# que se le pase) y le pone la etiqueta :latest a ese mismo manifiesto en GHCR. +# El merge a main ya no reconstruye la imagen (ver docker-publish.yml). +# +# Uso: Actions > "Promote staging to PROD" > Run workflow (rama main). +# Rollback: ejecutarlo con el digest anterior, que queda en el resumen de cada +# ejecución. + +on: + workflow_dispatch: + inputs: + digest: + description: 'Digest a promover (sha256:...). Vacío = el que tiene :staging ahora.' + required: false + default: '' + +permissions: + contents: read + packages: write + +concurrency: + group: promote-latest + cancel-in-progress: false + +env: + REGISTRY: ghcr.io + IMAGES: mani-java + +jobs: + promote: + name: Retag staging digest as latest + runs-on: ubuntu-latest + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GitHub Container Registry (GHCR) + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote the same digest to latest + env: + OWNER: ${{ github.repository_owner }} + INPUT_DIGEST: ${{ inputs.digest }} + run: | + set -euo pipefail + owner=$(echo "$OWNER" | tr '[:upper:]' '[:lower:]') + digest_of() { + docker buildx imagetools inspect "$1" --format '{{json .Manifest}}' | jq -r '.digest' + } + + { + echo "### Promoción staging → latest" + echo + echo "| Imagen | :latest anterior | :latest promovido |" + echo "|---|---|---|" + } >> "$GITHUB_STEP_SUMMARY" + + for image in $IMAGES; do + ref="$REGISTRY/$owner/$image" + if [ -n "$INPUT_DIGEST" ]; then + digest="$INPUT_DIGEST" + else + digest=$(digest_of "$ref:staging") + fi + if ! [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]]; then + echo "::error::Digest inválido para $ref: '$digest'" + exit 1 + fi + + previous=$(digest_of "$ref:latest" 2>/dev/null || echo "ninguno") + + docker buildx imagetools create --tag "$ref:latest" "$ref@$digest" + + promoted=$(digest_of "$ref:latest") + if [ "$promoted" != "$digest" ]; then + echo "::error::$ref:latest quedó en $promoted y se esperaba $digest" + exit 1 + fi + + echo "Promovido $ref:latest -> $digest (antes: $previous)" + echo "| \`$ref\` | \`$previous\` | \`$digest\` |" >> "$GITHUB_STEP_SUMMARY" + done diff --git a/.github/workflows/quality-gate.yml b/.github/workflows/quality-gate.yml index 85dd22b..67bfd6f 100644 --- a/.github/workflows/quality-gate.yml +++ b/.github/workflows/quality-gate.yml @@ -80,6 +80,45 @@ jobs: if-no-files-found: error retention-days: 3 + # Prueba de contrato (QAS-23, SCRUM-1724): Rules contra + # docs/openapi/rules.yaml del Gateway. + # Solo hacia develop: en release y main el contrato de develop puede ir + # delante del código que se promueve, que ya pasó por aquí. + - name: Contrato y verificador (MANI-APIGateway) + if: github.event_name == 'push' || github.base_ref == 'develop' + uses: actions/checkout@v4 + with: + repository: Trama-AS/MANI-APIGateway + ref: develop + path: .mani-contrato + + - name: Configurar Node.js (verificador de contrato) + if: github.event_name == 'push' || github.base_ref == 'develop' + uses: actions/setup-node@v4 + with: + node-version: '22' + + # El secreto de prueba se genera en cada corrida: firma los JWT de las sondas. + - name: Preparar el verificador de contrato + if: github.event_name == 'push' || github.base_ref == 'develop' + run: | + npm ci --prefix .mani-contrato --ignore-scripts + echo "SUPABASE_JWT_SECRET=$(openssl rand -hex 32)" >> "$GITHUB_ENV" + + - name: Contrato de Rules + if: github.event_name == 'push' || github.base_ref == 'develop' + run: | + esperar() { + curl -sf --retry 60 --retry-delay 1 --retry-all-errors "$1" > /dev/null + } + java -jar target/mani-rules-java-*.jar > rules.log 2>&1 & + esperar http://localhost:8080/api/v1/rules/health + node .mani-contrato/scripts/verificar_contrato.js --contrato rules --url http://localhost:8080/api/v1/rules + + - name: Logs de los servicios (si algo falló) + if: failure() + run: tail -n 50 rules.log || true + sonar_quality_gate: name: Sonar Quality Gate needs: pruebas_cobertura diff --git a/README.md b/README.md index 105d8e4..0f95d32 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,22 @@ Las pruebas de contrato extremo a extremo (Gateway → Rules) viven en `MANI-API --- +## 🚢 Despliegue + +La imagen se construye una sola vez y se promueve entre ambientes; no se reconstruye para PROD (SCRUM-1723 / QAS-24). El despliegue en las VM lo hace **DevOps**. + +| Rama o acción | Workflow | Imagen en GHCR | Ambiente | +| :--- | :--- | :--- | :--- | +| Push a `develop` | `docker-publish.yml` | `ghcr.io/trama-as/mani-java:develop` | Integración | +| Push a `release` | `docker-publish.yml` | `ghcr.io/trama-as/mani-java:staging` | **QA** (VM `10.43.100.141`) | +| `promote-latest.yml` (manual, *Run workflow*) | `promote-latest.yml` | `ghcr.io/trama-as/mani-java:latest` = **el mismo digest** de `:staging` | **PROD** | +| Etiqueta `vX.Y.Z` en `main` | `docker-publish.yml` | `ghcr.io/trama-as/mani-java:X.Y.Z` | Versión publicada | + +- **Rollback:** se vuelve a ejecutar `promote-latest.yml` con el digest anterior, que queda en el resumen de cada ejecución. +- **Flujo de ramas** (rama → PR a `develop` → QA → `release` → `main`, nunca PR directo a `main`): [Ramas, flujo y protección](https://github.com/Trama-AS/MANI-docs/blob/main/wiki/03-repositorios/ramas-flujo-y-proteccion.md). **Ambientes:** [Ambientes y promoción](https://github.com/Trama-AS/MANI-docs/blob/main/wiki/04-proceso/ambientes-y-promocion.md). + +--- + ## 👥 Equipo y Gobernanza * **Organización:** [TRAMA · Ingeniería de Software](https://github.com/Trama-AS) * **Repositorio Oficial:** [MANI-Java](https://github.com/Trama-AS/MANI-Java) diff --git a/pom.xml b/pom.xml index ac2636b..0718917 100644 --- a/pom.xml +++ b/pom.xml @@ -33,6 +33,15 @@ org.springframework.boot spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-actuator + + + io.micrometer + micrometer-registry-prometheus + org.springframework.boot spring-boot-starter-test diff --git a/src/main/java/com/trama/mani/rules/config/RulesCircuitBreaker.java b/src/main/java/com/trama/mani/rules/config/RulesCircuitBreaker.java new file mode 100644 index 0000000..bf3d674 --- /dev/null +++ b/src/main/java/com/trama/mani/rules/config/RulesCircuitBreaker.java @@ -0,0 +1,116 @@ +package com.trama.mani.rules.config; + +import com.trama.mani.rules.web.ApiException; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.function.Supplier; +import org.springframework.http.HttpStatus; + +/** + * Disyuntor (Circuit Breaker, SCRUM-1663 / QAS-40) compatible con la semántica de Resilience4j + * para proteger ejecuciones y dependencias del motor de reglas ante fallas repetidas. + */ +public class RulesCircuitBreaker { + + public enum State { + CLOSED, + OPEN, + HALF_OPEN + } + + private final String name; + private final int failureThreshold; + private final Duration waitDurationInOpenState; + private final Supplier clock; + + private State state = State.CLOSED; + private int consecutiveFailures = 0; + private Instant openedAt = null; + + public RulesCircuitBreaker( + String name, + int failureThreshold, + Duration waitDurationInOpenState, + Supplier clock) { + if (failureThreshold < 1) { + throw new IllegalArgumentException("failureThreshold debe ser >= 1"); + } + this.name = Objects.requireNonNull(name, "name es requerido"); + this.failureThreshold = failureThreshold; + this.waitDurationInOpenState = Objects.requireNonNull(waitDurationInOpenState, "waitDurationInOpenState es requerido"); + this.clock = Objects.requireNonNull(clock, "clock es requerido"); + } + + public RulesCircuitBreaker(String name, int failureThreshold, Duration waitDurationInOpenState) { + this(name, failureThreshold, waitDurationInOpenState, Instant::now); + } + + public String getName() { + return name; + } + + public synchronized State getState() { + refreshState(); + return state; + } + + public synchronized int getConsecutiveFailures() { + return consecutiveFailures; + } + + public T executeSupplier(Supplier supplier) { + ensurePermitted(); + try { + T result = supplier.get(); + onSuccess(); + return result; + } catch (ApiException ex) { + if (ex.getStatus().is5xxServerError()) { + onError(); + } + throw ex; + } catch (RuntimeException ex) { + onError(); + throw ex; + } + } + + public synchronized void reset() { + state = State.CLOSED; + consecutiveFailures = 0; + openedAt = null; + } + + private synchronized void ensurePermitted() { + refreshState(); + if (state == State.OPEN) { + throw new ApiException( + HttpStatus.SERVICE_UNAVAILABLE, + "RULES_CIRCUIT_OPEN", + "Circuito abierto en Rules (" + name + "): fallas consecutivas detectadas"); + } + } + + private synchronized void onSuccess() { + consecutiveFailures = 0; + openedAt = null; + state = State.CLOSED; + } + + private synchronized void onError() { + consecutiveFailures++; + if (state == State.HALF_OPEN || consecutiveFailures >= failureThreshold) { + state = State.OPEN; + openedAt = clock.get(); + } + } + + private void refreshState() { + if (state == State.OPEN + && openedAt != null + && !Duration.between(openedAt, clock.get()).minus(waitDurationInOpenState).isNegative()) { + state = State.HALF_OPEN; + } + } +} diff --git a/src/main/java/com/trama/mani/rules/config/RulesConfiguration.java b/src/main/java/com/trama/mani/rules/config/RulesConfiguration.java index b3e5a34..5b9362c 100644 --- a/src/main/java/com/trama/mani/rules/config/RulesConfiguration.java +++ b/src/main/java/com/trama/mani/rules/config/RulesConfiguration.java @@ -1,9 +1,16 @@ package com.trama.mani.rules.config; +import java.time.Duration; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(CategoryRulesProperties.class) public class RulesConfiguration { + + @Bean + public RulesCircuitBreaker rulesCircuitBreaker() { + return new RulesCircuitBreaker("mani-rules-engine", 5, Duration.ofSeconds(10)); + } } diff --git a/src/main/java/com/trama/mani/rules/controller/TenantRulesController.java b/src/main/java/com/trama/mani/rules/controller/TenantRulesController.java index 641e1c2..4b03fac 100644 --- a/src/main/java/com/trama/mani/rules/controller/TenantRulesController.java +++ b/src/main/java/com/trama/mani/rules/controller/TenantRulesController.java @@ -20,6 +20,9 @@ * antes de guardar una versión nueva. Unas reglas incoherentes son un 200 con {@code valid=false} y la lista de * violaciones: el error es de las reglas, no de la petición. Tenant y rol llegan por encabezado, como en el resto de * Rules. + * + *

Si son válidas, {@code rules} trae las reglas normalizadas, que son las que Core guarda (SCRUM-1722 / QAS-21): + * Core ya no valida por su cuenta. */ @RestController @RequestMapping({"/api/v1/rules", ""}) @@ -33,7 +36,7 @@ public TenantRulesController(TenantRulesValidator validator) { this.validator = validator; } - public record Response(boolean valid, String version, List violations, String tenantId, + public record Response(boolean valid, String version, List violations, JsonNode rules, String tenantId, String correlationId) { } @@ -53,10 +56,10 @@ public Response validate( throw new ApiException(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "rules es obligatorio"); } String tenantId = tenantHeader.trim(); - List violations = validator.violations(body.get("rules")); + TenantRulesValidator.Resultado resultado = validator.evaluar(body.get("rules")); log.info("Validación de reglas de tenant tenant={} version={} valid={} violaciones={}", tenantId, - validator.version(), violations.isEmpty(), violations.size()); - return new Response(violations.isEmpty(), validator.version(), violations, tenantId, - CorrelationIdFilter.current()); + validator.version(), resultado.valido(), resultado.violaciones().size()); + return new Response(resultado.valido(), validator.version(), resultado.violaciones(), + resultado.normalizadas(), tenantId, CorrelationIdFilter.current()); } } diff --git a/src/main/java/com/trama/mani/rules/service/TenantRulesValidator.java b/src/main/java/com/trama/mani/rules/service/TenantRulesValidator.java index 223737e..96738fd 100644 --- a/src/main/java/com/trama/mani/rules/service/TenantRulesValidator.java +++ b/src/main/java/com/trama/mani/rules/service/TenantRulesValidator.java @@ -1,8 +1,11 @@ package com.trama.mani.rules.service; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -11,13 +14,20 @@ * versionarlas pregunta aquí si son coherentes; Rules no guarda nada. Función pura: las mismas reglas con la misma * versión de política dan siempre el mismo resultado. * + *

Es la única copia de esta política (SCRUM-1722 / QAS-21): Core ya no valida por su cuenta y guarda las reglas + * normalizadas que devuelve {@link #evaluar}. + * *

Límites: orden de listado CALIFICACION o COBERTURA (los criterios de /rank-allies); tolerancia de la alerta de - * tarifa de 0 a 50 %; comisión de 0 a 30 %; ventana de cancelación de 0 a 72 horas y penalización de 0 a 100 %, con - * penalización mayor que 0 solo si hay ventana; tiempo para aceptar la oferta de 1 a 1440 minutos (entero). + * tarifa de 0 a 50 %; comisión de 0 a 30 % con máximo 2 decimales (la liquidación guarda 2); ventana de cancelación de + * 0 a 72 horas y penalización de 0 a 100 %, con penalización mayor que 0 solo si hay ventana; tiempo para aceptar la + * oferta de 1 a 1440 minutos (entero). */ @Service public class TenantRulesValidator { + /** Comisión máxima del tenant, en porcentaje. */ + public static final int COMISION_MAXIMA = 30; + private final String version; public TenantRulesValidator(@Value("${mani.rules.tenant.version:tenant-rules-v1}") String version) { @@ -28,41 +38,89 @@ public String version() { return version; } - /** Lista de reglas incumplidas; vacía si el conjunto es válido. */ - public List violations(JsonNode reglas) { + /** + * Resultado de evaluar unas reglas: las violaciones y, si no hay ninguna, las reglas normalizadas (criterio en + * mayúsculas y sin espacios, y solo los campos de la política). + */ + public record Resultado(List violaciones, ObjectNode normalizadas) { + public boolean valido() { + return violaciones.isEmpty(); + } + } + + public Resultado evaluar(JsonNode reglas) { List v = new ArrayList<>(); if (reglas == null || !reglas.isObject()) { v.add("rules debe ser un objeto"); - return v; + return new Resultado(v, null); } - String criterio = texto(reglas.path("ordenListado").path("criterio")); - if (criterio == null || CriterioRanking.parse(criterio).isEmpty()) { + String criterio = criterio(reglas.path("ordenListado").path("criterio")).map(Enum::name).orElse(null); + if (criterio == null) { v.add("ordenListado.criterio debe ser CALIFICACION o COBERTURA"); } - rango(v, reglas.path("alertaTarifa").path("toleranciaPorcentaje"), 0, 50, "alertaTarifa.toleranciaPorcentaje"); - rango(v, reglas.path("comision").path("porcentaje"), 0, 30, "comision.porcentaje"); - Double ventana = rango(v, reglas.path("cancelacion").path("ventanaHoras"), 0, 72, "cancelacion.ventanaHoras"); - Double penalizacion = rango(v, reglas.path("cancelacion").path("penalizacionPorcentaje"), 0, 100, + JsonNode tolerancia = rango(v, reglas.path("alertaTarifa").path("toleranciaPorcentaje"), 0, 50, + "alertaTarifa.toleranciaPorcentaje"); + JsonNode comision = comision(v, reglas.path("comision").path("porcentaje")); + JsonNode ventana = rango(v, reglas.path("cancelacion").path("ventanaHoras"), 0, 72, "cancelacion.ventanaHoras"); + JsonNode penalizacion = rango(v, reglas.path("cancelacion").path("penalizacionPorcentaje"), 0, 100, "cancelacion.penalizacionPorcentaje"); - if (ventana != null && penalizacion != null && penalizacion > 0 && ventana == 0) { + if (penalizacionSinVentana(ventana, penalizacion)) { v.add("cancelacion: una penalización mayor que 0 exige una ventana mayor que 0 horas"); } JsonNode minutos = reglas.path("oferta").path("minutosParaAceptar"); - if (!minutos.isIntegralNumber() || minutos.asLong() < 1 || minutos.asLong() > 1440) { + if (!minutosValidos(minutos)) { v.add("oferta.minutosParaAceptar debe ser un entero entre 1 y 1440"); } - return v; + if (!v.isEmpty()) { + return new Resultado(v, null); + } + return new Resultado(v, normalizadas(criterio, tolerancia, comision, ventana, penalizacion, minutos.asLong())); + } + + private static Optional criterio(JsonNode nodo) { + return nodo.isTextual() ? CriterioRanking.parse(nodo.asText()) : Optional.empty(); } - private static String texto(JsonNode nodo) { - return nodo.isTextual() ? nodo.asText() : null; + private static boolean penalizacionSinVentana(JsonNode ventana, JsonNode penalizacion) { + return ventana != null && penalizacion != null && penalizacion.asDouble() > 0 && ventana.asDouble() == 0; } - private static Double rango(List v, JsonNode nodo, double min, double max, String campo) { + private static boolean minutosValidos(JsonNode minutos) { + return minutos.isIntegralNumber() && minutos.asLong() >= 1 && minutos.asLong() <= 1440; + } + + /** Solo los campos de la política, con el criterio ya en mayúsculas: es lo que Core guarda. */ + private static ObjectNode normalizadas(String criterio, JsonNode tolerancia, JsonNode comision, JsonNode ventana, + JsonNode penalizacion, long minutos) { + ObjectNode n = JsonNodeFactory.instance.objectNode(); + n.putObject("ordenListado").put("criterio", criterio); + n.putObject("alertaTarifa").set("toleranciaPorcentaje", tolerancia); + n.putObject("comision").set("porcentaje", comision); + ObjectNode cancelacion = n.putObject("cancelacion"); + cancelacion.set("ventanaHoras", ventana); + cancelacion.set("penalizacionPorcentaje", penalizacion); + n.putObject("oferta").put("minutosParaAceptar", minutos); + return n; + } + + private static JsonNode rango(List v, JsonNode nodo, double min, double max, String campo) { if (!nodo.isNumber() || nodo.asDouble() < min || nodo.asDouble() > max) { v.add(campo + " debe ser un número entre " + (long) min + " y " + (long) max); return null; } - return nodo.asDouble(); + return nodo; + } + + /** Comisión de 0 a 30 % con máximo 2 decimales: la columna de la liquidación guarda 2. */ + private static JsonNode comision(List v, JsonNode nodo) { + boolean valida = nodo.isNumber() + && nodo.asDouble() >= 0 + && nodo.asDouble() <= COMISION_MAXIMA + && nodo.decimalValue().stripTrailingZeros().scale() <= 2; + if (!valida) { + v.add("comision.porcentaje debe ser un número entre 0 y " + COMISION_MAXIMA + ", con máximo 2 decimales"); + return null; + } + return nodo; } } diff --git a/src/main/java/com/trama/mani/rules/web/CorrelationIdFilter.java b/src/main/java/com/trama/mani/rules/web/CorrelationIdFilter.java index e9c173e..4399b2b 100644 --- a/src/main/java/com/trama/mani/rules/web/CorrelationIdFilter.java +++ b/src/main/java/com/trama/mani/rules/web/CorrelationIdFilter.java @@ -5,6 +5,8 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @@ -13,8 +15,8 @@ import org.springframework.web.filter.OncePerRequestFilter; /** - * Propaga X-Correlation-ID (lo genera el Gateway o lo reenvía Core) al MDC de los logs y a la - * respuesta. Sin encabezado se usa "none", el mismo valor que Core Node. + * Propaga X-Correlation-ID (lo genera el Gateway o lo reenvía Core/Dispatch) al MDC de los logs JSON + * y a la respuesta HTTP (SCRUM-1658 / QAS-22). Sin encabezado se usa "none". */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) @@ -22,8 +24,11 @@ public class CorrelationIdFilter extends OncePerRequestFilter { public static final String HEADER = "X-Correlation-ID"; public static final String MDC_KEY = HEADER; + public static final String MDC_CORRELATION_ID = "correlationId"; static final String MISSING = "none"; + private static final Logger log = LoggerFactory.getLogger(CorrelationIdFilter.class); + @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { @@ -31,11 +36,15 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String correlationId = StringUtils.hasText(header) ? header.trim() : MISSING; MDC.put(MDC_KEY, correlationId); + MDC.put(MDC_CORRELATION_ID, correlationId); response.setHeader(HEADER, correlationId); try { chain.doFilter(request, response); + log.info("HTTP {} {} status={} correlationId={}", + request.getMethod(), request.getRequestURI(), response.getStatus(), correlationId); } finally { MDC.remove(MDC_KEY); + MDC.remove(MDC_CORRELATION_ID); } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 7eba7ff..2075daf 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,8 +1,14 @@ server.port=8080 spring.application.name=mani-rules-java -# Formato de logging estructurado -logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - [Correlation: %X{X-Correlation-ID}] %msg%n +# SCRUM-1714: métricas en formato Prometheus en /actuator/prometheus (y salud en /actuator/health). +# El Gateway solo deja leerlas desde la red interna, con la misma regla que /metrics de Core. +management.endpoints.web.exposure.include=health,prometheus +# Histograma de latencia para poder calcular el p95 en Grafana. +management.metrics.distribution.percentiles-histogram.http.server.requests=true + +# SCRUM-1658 (T-21 / QAS-22): Formato de logging estructurado JSON con correlationId +logging.pattern.console={"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z',UTC}","level":"%level","service":"mani-rules-java","correlationId":"%X{X-Correlation-ID:-none}","correlation_id":"%X{X-Correlation-ID:-none}","logger":"%logger{36}","message":"%replace(%msg){'[\"\\\\]','_'}"}%n # Reglas de categoria de servicio (US-03.1.1-M6). Mismos valores que crear_categoria_servicio() # (migracion 003). Cambiarlas aqui (o por SPRING_APPLICATION_JSON / config montada) solo exige diff --git a/src/test/java/com/trama/mani/rules/MetricsEndpointTest.java b/src/test/java/com/trama/mani/rules/MetricsEndpointTest.java new file mode 100644 index 0000000..a632d1f --- /dev/null +++ b/src/test/java/com/trama/mani/rules/MetricsEndpointTest.java @@ -0,0 +1,48 @@ +package com.trama.mani.rules; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +/** + * SCRUM-1714: Rules expone sus métricas en formato Prometheus para que Grafana muestre + * tráfico, errores y latencia medidos dentro del servicio. + */ +// Spring Boot apaga los exportadores de métricas en pruebas; aquí se prueban justamente esos. +@AutoConfigureObservability +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class MetricsEndpointTest { + + @Autowired + private TestRestTemplate rest; + + @Test + void prometheusEndpointExposesHttpServerRequests() { + rest.getForEntity("/api/v1/rules/health", String.class); + + ResponseEntity respuesta = rest.getForEntity("/actuator/prometheus", String.class); + + assertThat(respuesta.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(respuesta.getBody()) + .contains("http_server_requests_seconds_count") + .contains("uri=\"/api/v1/rules/health\"") + // Histograma activo: permite calcular el p95 en Grafana. + .contains("http_server_requests_seconds_bucket"); + } + + @Test + void onlyHealthAndPrometheusAreExposed() { + assertThat(rest.getForEntity("/actuator/health", String.class).getStatusCode()) + .isEqualTo(HttpStatus.OK); + assertThat(rest.getForEntity("/actuator/env", String.class).getStatusCode()) + .isEqualTo(HttpStatus.NOT_FOUND); + assertThat(rest.getForEntity("/actuator/beans", String.class).getStatusCode()) + .isEqualTo(HttpStatus.NOT_FOUND); + } +} diff --git a/src/test/java/com/trama/mani/rules/config/RulesCircuitBreakerTest.java b/src/test/java/com/trama/mani/rules/config/RulesCircuitBreakerTest.java new file mode 100644 index 0000000..bf6d83d --- /dev/null +++ b/src/test/java/com/trama/mani/rules/config/RulesCircuitBreakerTest.java @@ -0,0 +1,74 @@ +package com.trama.mani.rules.config; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.trama.mani.rules.web.ApiException; +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +class RulesCircuitBreakerTest { + + @Test + void opensAfterReachingFailureThresholdAndRecoversViaHalfOpen() { + AtomicReference now = new AtomicReference<>(Instant.parse("2026-11-16T20:00:00Z")); + RulesCircuitBreaker cb = new RulesCircuitBreaker( + "rules-test", 3, Duration.ofSeconds(10), now::get); + + assertEquals("rules-test", cb.getName()); + assertEquals(RulesCircuitBreaker.State.CLOSED, cb.getState()); + + // Los errores 4xx de validación no abren el circuito + assertThrows(ApiException.class, () -> cb.executeSupplier(() -> { + throw new ApiException(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "invalido"); + })); + assertEquals(0, cb.getConsecutiveFailures()); + + // Tres fallas 5xx/runtime abren el circuito + assertThrows(ApiException.class, () -> cb.executeSupplier(() -> { + throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE, "UPSTREAM_503", "caido"); + })); + for (int i = 0; i < 2; i++) { + assertThrows(IllegalStateException.class, () -> cb.executeSupplier(() -> { + throw new IllegalStateException("fallo interno"); + })); + } + + assertEquals(RulesCircuitBreaker.State.OPEN, cb.getState()); + assertEquals(3, cb.getConsecutiveFailures()); + + // Con el circuito abierto rechaza de inmediato con 503 RULES_CIRCUIT_OPEN + ApiException openEx = assertThrows(ApiException.class, () -> cb.executeSupplier(() -> "ok")); + assertEquals(HttpStatus.SERVICE_UNAVAILABLE, openEx.getStatus()); + assertEquals("RULES_CIRCUIT_OPEN", openEx.getCode()); + + // Avanza el reloj -> HALF_OPEN; si falla vuelve a OPEN + now.set(now.get().plusSeconds(10)); + assertEquals(RulesCircuitBreaker.State.HALF_OPEN, cb.getState()); + assertThrows(RuntimeException.class, () -> cb.executeSupplier(() -> { + throw new RuntimeException("sigue caido"); + })); + assertEquals(RulesCircuitBreaker.State.OPEN, cb.getState()); + + // Avanza el reloj -> HALF_OPEN; ahora tiene éxito -> CLOSED + now.set(now.get().plusSeconds(10)); + String ok = cb.executeSupplier(() -> "recuperado"); + assertEquals("recuperado", ok); + assertEquals(RulesCircuitBreaker.State.CLOSED, cb.getState()); + assertEquals(0, cb.getConsecutiveFailures()); + + cb.reset(); + assertEquals(RulesCircuitBreaker.State.CLOSED, cb.getState()); + } + + @Test + void validatesConstructorArgumentsAndDefaultClock() { + assertThrows(IllegalArgumentException.class, + () -> new RulesCircuitBreaker("x", 0, Duration.ofSeconds(1))); + RulesCircuitBreaker cb = new RulesCircuitBreaker("default-clock", 2, Duration.ofSeconds(5)); + assertEquals("ok", cb.executeSupplier(() -> "ok")); + } +} diff --git a/src/test/java/com/trama/mani/rules/controller/TenantRulesControllerTest.java b/src/test/java/com/trama/mani/rules/controller/TenantRulesControllerTest.java index cd10319..0bb0e4c 100644 --- a/src/test/java/com/trama/mani/rules/controller/TenantRulesControllerTest.java +++ b/src/test/java/com/trama/mani/rules/controller/TenantRulesControllerTest.java @@ -61,6 +61,31 @@ void reglasCoherentesSonValidas() throws Exception { .andExpect(jsonPath("$.correlationId").value("corr-1366")); } + @Test + void devuelveLasReglasNormalizadasParaQueCoreLasGuarde() throws Exception { + String conExtras = "{\"rules\":{\"ordenListado\":{\"criterio\":\" cobertura \"}," + + "\"alertaTarifa\":{\"toleranciaPorcentaje\":15.5}," + + "\"comision\":{\"porcentaje\":10.25,\"extra\":1}," + + "\"cancelacion\":{\"ventanaHoras\":4,\"penalizacionPorcentaje\":25}," + + "\"oferta\":{\"minutosParaAceptar\":30},\"campoAjeno\":true}}"; + validar("tenant-a", "ADMIN", conExtras) + .andExpect(jsonPath("$.valid").value(true)) + .andExpect(jsonPath("$.rules.ordenListado.criterio").value("COBERTURA")) + .andExpect(jsonPath("$.rules.alertaTarifa.toleranciaPorcentaje").value(15.5)) + .andExpect(jsonPath("$.rules.comision.porcentaje").value(10.25)) + .andExpect(jsonPath("$.rules.comision.extra").doesNotExist()) + .andExpect(jsonPath("$.rules.campoAjeno").doesNotExist()) + .andExpect(jsonPath("$.rules.cancelacion.ventanaHoras").value(4)) + .andExpect(jsonPath("$.rules.oferta.minutosParaAceptar").value(30)); + } + + @Test + void reglasInvalidasNoTraenReglasNormalizadas() throws Exception { + validar("tenant-a", "ADMIN", reglas("\"PRECIO\"", "15", "10", "4", "25", "30")) + .andExpect(jsonPath("$.valid").value(false)) + .andExpect(jsonPath("$.rules").doesNotExist()); + } + @Test void losLimitesSonInclusivos() throws Exception { validar("tenant-a", "ADMIN", reglas("\"calificacion\"", "50", "30", "72", "100", "1440")) @@ -73,7 +98,11 @@ void losLimitesSonInclusivos() throws Exception { @CsvSource(delimiter = '|', value = { "\"PRECIO\"|15|10|4|25|30|ordenListado.criterio debe ser CALIFICACION o COBERTURA", "\"COBERTURA\"|51|10|4|25|30|alertaTarifa.toleranciaPorcentaje debe ser un número entre 0 y 50", - "\"COBERTURA\"|15|31|4|25|30|comision.porcentaje debe ser un número entre 0 y 30", + "\"COBERTURA\"|\"15\"|10|4|25|30|alertaTarifa.toleranciaPorcentaje debe ser un número entre 0 y 50", + "\"COBERTURA\"|null|10|4|25|30|alertaTarifa.toleranciaPorcentaje debe ser un número entre 0 y 50", + "1|15|10|4|25|30|ordenListado.criterio debe ser CALIFICACION o COBERTURA", + "\"COBERTURA\"|15|31|4|25|30|comision.porcentaje debe ser un número entre 0 y 30, con máximo 2 decimales", + "\"COBERTURA\"|15|10.555|4|25|30|comision.porcentaje debe ser un número entre 0 y 30, con máximo 2 decimales", "\"COBERTURA\"|15|10|73|25|30|cancelacion.ventanaHoras debe ser un número entre 0 y 72", "\"COBERTURA\"|15|10|4|101|30|cancelacion.penalizacionPorcentaje debe ser un número entre 0 y 100", "\"COBERTURA\"|15|10|0|25|30|cancelacion: una penalización mayor que 0 exige una ventana mayor que 0 horas",