Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
4b92904
[SCRUM-1658][SCRUM-1663] Logs JSON con correlationId y CircuitBreaker…
Alviz09 Nov 17, 2026
054f464
Merge pull request #13 from Trama-AS/feature/SCRUM-1658-1663-rules
santiagohb2830 Nov 19, 2026
348f6d9
Merge pull request #14 from Trama-AS/develop
santiagohb2830 Nov 20, 2026
1a135ff
[SCRUM-1714] Rules expone métricas Prometheus en /actuator/prometheus
Alviz09 Nov 23, 2026
ecc2bcc
[SCRUM-1722] Rules es la única validación de las reglas del tenant y …
Alviz09 Nov 23, 2026
c7a10bf
[SCRUM-1722] Pruebas: Rules rechaza valores no numéricos y criterio q…
Alviz09 Nov 23, 2026
04a2df6
[SCRUM-1722] Validador sin Optional.get() ni método sin uso; evaluar(…
Alviz09 Nov 23, 2026
3738f8c
[SCRUM-1723] Promover a :latest el digest de :staging sin reconstruir
Warriorr89 Nov 23, 2026
e873b4b
Merge pull request #16 from Trama-AS/feature/SCRUM-1722-reglas-tenant…
santiagohb2830 Nov 24, 2026
653623e
Merge pull request #15 from Trama-AS/feature/SCRUM-1714-metricas-rules
santiagohb2830 Nov 24, 2026
4787517
Merge pull request #18 from Trama-AS/chore/SCRUM-1723-promover-digest…
santiagohb2830 Nov 24, 2026
590ef72
[SCRUM-1724] Prueba de contrato de Rules contra rules.yaml en el CI (…
santiagohb2830 Nov 24, 2026
8f840b5
Merge pull request #19 from Trama-AS/feature/SCRUM-1724-contract-tests
santiagohb2830 Nov 24, 2026
ce513cb
Merge pull request #20 from Trama-AS/develop
santiagohb2830 Nov 24, 2026
f7de936
[SCRUM-1693] README: cómo se prueba y cómo se despliega
Alviz09 Nov 24, 2026
0f727f0
Merge pull request #22 from Trama-AS/docs/SCRUM-1693-readme-pruebas-d…
santiagohb2830 Nov 24, 2026
51081c4
Merge pull request #23 from Trama-AS/develop
santiagohb2830 Nov 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
89 changes: 89 additions & 0 deletions .github/workflows/promote-latest.yml
Original file line number Diff line number Diff line change
@@ -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
39 changes: 39 additions & 0 deletions .github/workflows/quality-gate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
9 changes: 9 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- SCRUM-1714: métricas HTTP y de JVM en /actuator/prometheus. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
116 changes: 116 additions & 0 deletions src/main/java/com/trama/mani/rules/config/RulesCircuitBreaker.java
Original file line number Diff line number Diff line change
@@ -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<Instant> clock;

private State state = State.CLOSED;
private int consecutiveFailures = 0;
private Instant openedAt = null;

public RulesCircuitBreaker(
String name,
int failureThreshold,
Duration waitDurationInOpenState,
Supplier<Instant> 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> T executeSupplier(Supplier<T> 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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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", ""})
Expand All @@ -33,7 +36,7 @@ public TenantRulesController(TenantRulesValidator validator) {
this.validator = validator;
}

public record Response(boolean valid, String version, List<String> violations, String tenantId,
public record Response(boolean valid, String version, List<String> violations, JsonNode rules, String tenantId,
String correlationId) {
}

Expand All @@ -53,10 +56,10 @@ public Response validate(
throw new ApiException(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "rules es obligatorio");
}
String tenantId = tenantHeader.trim();
List<String> 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());
}
}
Loading
Loading