14
Fallas, operación y evolución

Diseñar para las fallas: resiliencia y observabilidad

Fallas, operación y evolución

Semana 14 — Diseñar para las fallas: resiliencia y observabilidad

Objetivos

  • Explicar cómo una dependencia lenta produce una falla en cascada, y por qué una respuesta lenta es peor que un error.
  • Aplicar los patrones de estabilidad (timeout, retry con backoff y jitter, circuit breaker, bulkhead, load shedding) y decir qué problema evita cada uno y qué riesgo trae.
  • Instrumentar un servicio con logs estructurados, métricas y trazas, y explicar qué pregunta responde cada señal.
  • Definir SLIs y SLOs para un servicio, calcular su error budget y comprobar el diseño inyectando fallas.

Sesión A — Resiliencia: timeouts, retries, circuit breaker, bulkhead y load shedding

Lecturas:

Lecturas complementarias:

Temas:

  • En un sistema con varias partes, alguna está fallando casi siempre. La resiliencia no es evitar las faltas, sino que el sistema siga dando lo esencial mientras ocurren y se recupere solo. Se diseña: cada llamada que sale del proceso es un punto de integración, y cada punto de integración puede fallar de varias maneras.
  • Lento es peor que caído. Un servicio que rechaza la conexión libera a quien lo llama en milisegundos; uno que acepta y no responde lo retiene. Cada petición en espera ocupa una conexión, memoria y, a veces, una transacción abierta. Cuando el pool se agota, quien llama también deja de responder, y quien lo llama a él, igual: una falla en cascada, que sube desde la dependencia más lenta hasta el usuario.
  • En Tinkuy: la pasarela tarda cinco segundos en vez de ochenta milisegundos. Cada compra retiene una conexión a la base de datos, con su transacción, durante cinco segundos; las conexiones se agotan, y entonces también falla listar los eventos, que no tiene nada que ver con los pagos. Cómo falla depende del diseño: con un pool, las peticiones esperan una conexión y el sistema parece colgado; sin pool, como en el Tinkuy inicial, PostgreSQL rechaza las conexiones nuevas y el catálogo responde con errores.
  • Timeout: toda llamada remota tiene un tiempo máximo. Sin él, la capacidad del sistema la decide su dependencia más lenta. Cómo se elige: a partir del percentil alto de la latencia normal de la dependencia y de lo que el usuario está dispuesto a esperar. Deadline propagado: si al usuario le quedan 300 ms, no tiene sentido una llamada interna con un timeout de 2 s.
  • Retry: recupera de una falta transitoria. Solo sobre operaciones idempotentes (semana 12), con un número máximo de intentos, con backoff exponencial para dar tiempo, y con jitter para que mil clientes que fallaron juntos no reintenten juntos. Riesgo: una tormenta de reintentos. Tres capas que reintentan tres veces cada una multiplican la carga por veintisiete justo cuando el servicio de abajo está saturado. Por eso: reintentar en una sola capa y con un presupuesto de reintentos.
  • Circuit breaker: envuelve las llamadas a una dependencia y cuenta sus fallas. Cerrado: las llamadas pasan. Si las fallas superan un umbral, se abre: las llamadas fallan de inmediato, sin tocar la dependencia. Pasado un tiempo, semiabierto: deja pasar una llamada de prueba; si sale bien, se cierra, y si no, vuelve a abrirse. Protege a quien llama (falla rápido) y a la dependencia (le da aire para recuperarse). Qué se responde con el circuito abierto es una decisión de negocio: un error claro, un valor por defecto, o encolar para después.
  • Bulkhead: separar los recursos por dependencia o por tipo de trabajo, como los compartimentos de un barco, para que agotar uno no hunda a los demás. Un pool de conexiones para las compras y otro para el catálogo; un límite de llamadas concurrentes a la pasarela.
  • Load shedding: cuando llega más de lo que se puede atender, rechazar pronto una parte (un 503 rápido) para atender bien al resto. La alternativa es encolar todo y atender mal a todos. Rate limiting: el tope por cliente. Backpressure: avisarle a quien produce que baje el ritmo. Una cola sin límite no es ninguna de las tres.
  • Degradar: decidir por adelantado qué se apaga primero. En Tinkuy, sin reportes se puede vender; sin el correo, también; sin pagos, se puede seguir mostrando el catálogo.
  • Comprobar que funciona: una defensa que nunca se ejerció no es una defensa. Se inyectan fallas a propósito (latencia, cortes, errores) y se mide el escenario. En el curso, con Toxiproxy entre Tinkuy y la pasarela.
  • Error común: un timeout más largo “para que no falle”. Se cambia un error rápido por uno lento, que es peor.
  • Error común: reintentar una operación que no es idempotente. El resultado es un cobro doble.

Sesión B — Observabilidad: logs, métricas, trazas y SLOs

Lecturas:

Lecturas complementarias:

  • The Site Reliability Workbook, cap. 2, Implementing SLOs.
  • Software Architecture in Practice, cap. 5 Deployability y cap. 12 Testability.

Temas:

  • Monitorear es vigilar las preguntas que ya se conocen; un sistema es observable si se puede entender qué le pasa, incluso algo que nadie previó, mirando lo que emite. En un sistema distribuido es un atributo de calidad con consecuencias de arquitectura: hay que diseñarlo, no se agrega al final.
  • Tres señales. Logs: registros de eventos discretos; responden qué pasó en este caso. Deben ser estructurados (JSON con campos, no frases) y llevar un identificador de la petición. Métricas: números agregados en el tiempo (contadores, medidores, histogramas); responden cuánto y con qué tendencia, y son baratas de guardar. Trazas: el recorrido de una petición por todos los servicios, como un árbol de spans con sus tiempos; responden dónde se fue el tiempo.
  • Propagar el contexto: el identificador de la traza viaja en cada llamada y en cada mensaje (la cabecera traceparent). Si un servicio no lo propaga, la traza se corta ahí. Con mensajería, el identificador va en el mensaje.
  • Qué medir. Las cuatro señales doradas: latencia, tráfico, errores y saturación. Latencia por percentiles (semana 2), y separando la de las respuestas con error, que suelen ser rápidas y mejoran el número engañosamente.
  • SLI: el indicador que se mide, como una proporción de eventos buenos sobre eventos válidos (compras que respondieron bien en menos de un segundo, sobre el total de compras). SLO: el objetivo sobre ese indicador en una ventana (99,5 % en 28 días). SLA: el contrato con consecuencias si no se cumple. Un SLO es un escenario de calidad de la semana 2, vigilado en producción.
  • Error budget: lo que el SLO permite fallar. Con 99,5 % y un millón de compras al mes, 5 000 pueden fallar. Mientras quede presupuesto, se despliega y se experimenta; cuando se acaba, la prioridad pasa a ser la confiabilidad. Convierte “¿qué tan confiable debe ser?” en un número que negocian producto y operación. Y 100 % es el objetivo equivocado: es carísimo, y el usuario no nota la diferencia con 99,99 % porque su propia red falla más.
  • Alertar por síntomas y no por causas: alertar porque los compradores ven errores, no porque un CPU está al 90 %. Cada alerta debe pedir una acción humana; las que no, cansan y terminan ignoradas.
  • Health checks: liveness (el proceso vive; si falla, se reinicia) y readiness (puede atender; si falla, se le deja de enviar tráfico). Un health check que comprueba todas las dependencias saca de servicio a todas las instancias cuando cae una dependencia compartida.
  • En Tinkuy: hoy los logs son frases sueltas, sin identificador ni tiempos. P5 pide logs estructurados con el identificador de la petición, las métricas del SLO de compra y la traza de una compra a través del monolito, el broker y el servicio de pagos.
  • Trade-off: la observabilidad cuesta (latencia, almacenamiento, dinero y código). Se muestrean las trazas y se cuida la cardinalidad de las métricas: una etiqueta con el id de usuario crea una serie por usuario.
  • Error común: registrar datos personales o de tarjetas en los logs. Lo que se escribe en un log se copia a muchos lugares y casi nunca se borra.

Laboratorio — Una pasarela de pagos lenta y caída, con Toxiproxy

Referencias: Toxiproxy; Fowler, CircuitBreaker; AWS, Exponential Backoff And Jitter. Material: code/week-14/. En parejas, sobre su copia de Tinkuy.

  1. Preparar: svc start toxiproxy, crear un proxy entre Tinkuy y la pasarela simulada con el script de la carpeta y configurar Tinkuy para que llame a la pasarela a través del proxy. Comprobar que una compra funciona.
  2. Línea de base: make load-sale y make load-browse a la vez. Anotar p95 y errores de cada uno.
  3. Pasarela lenta: agregar un tóxico de latencia de 5 s (toxiproxy-cli toxic add). Repetir las dos cargas. ¿Qué le pasa a la compra? ¿Y a GET /events, que no usa la pasarela? Mirar las conexiones de PostgreSQL (pg_stat_activity, estado idle in transaction) y explicar la cadena completa. Abran la sesión de psql antes de lanzar la carga: cuando se agotan las conexiones, tampoco entra psql.
  4. Timeout: poner un tiempo máximo a la llamada a la pasarela (AbortSignal.timeout) y sacarla de la transacción. Repetir. ¿Qué mejoró para el catálogo? ¿Qué ve ahora quien compra?
  5. Retry: agregar reintentos con el módulo de la carpeta, primero sin espera y luego con backoff exponencial y jitter. Con un tóxico que corta una de cada tres conexiones (la toxicidad se aplica por conexión, y fetch las reutiliza: no esperen que falle exactamente una de cada tres peticiones), medir cuántas compras terminan bien y cuántas peticiones recibe la pasarela en cada variante. ¿Por qué solo es seguro si el cobro lleva una clave de idempotencia?
  6. Circuit breaker: completar lab/circuit-breaker.ts (tres estados, umbral de fallas, tiempo de espera) hasta que pasen sus pruebas, y envolver con él la llamada a la pasarela. Medir cuánto tarda en responder una compra con el circuito cerrado y con el circuito abierto en dos casos: con la pasarela caída (toxiproxy-cli toggle), donde la conexión se rechaza en milisegundos y casi no hay diferencia, y con la pasarela lenta, donde la diferencia es la que justifica el patrón. Volver a levantar la pasarela y observar cuándo se cierra.
  7. Bulkhead y load shedding: limitar a 20 las llamadas concurrentes a la pasarela y responder 503 de inmediato a las que excedan. Repetir el paso 3 y comparar la latencia del catálogo.
  8. Observar: cambiar los console.log de la compra por una línea JSON con identificador de petición, duración y resultado. Con el script de la carpeta, calcular a partir de los logs el SLI “compras que respondieron bien en menos de 1 s” durante cada experimento, y decir cuánto error budget de un SLO de 99 % consumió cada uno. Ojo al comparar: con un generador de carga de modelo cerrado, una variante lenta registra muchas menos peticiones que una rápida en el mismo tiempo.

Entregas

Preguntas de repaso

  1. Expliquen paso a paso cómo una pasarela lenta deja sin responder a un endpoint que no la usa.
  2. Un servicio tiene p99 de 200 ms y quien lo llama usa un timeout de 30 s. ¿Qué problema hay y cómo elegirían el valor?
  3. Tres servicios en cadena reintentan tres veces cada uno. Si el último falla siempre, ¿cuántas peticiones recibe por cada petición del usuario? ¿Qué reglas lo evitan?
  4. Describan los tres estados de un circuit breaker y qué hace pasar de uno a otro.
  5. Con un SLO de 99,9 % sobre 2 millones de peticiones al mes, ¿cuál es el error budget? Un incidente produjo 1 500 errores: ¿qué fracción consumió?
  6. ¿Qué pregunta responden las trazas que no responden las métricas? ¿Y al revés?

Código de la semana

Compilar y probar dentro del contenedor del curso con make y make test.

Ejemplos (25)Errores (2)Pruebas (8)Laboratorio (2)Compilación (3)

Ejemplos

Los programas que usan los apuntes y la clase.

proxy.shDescargar proxy.sh
#!/usr/bin/env bash
# Crea (o vuelve a crear, limpio) un proxy de Toxiproxy entre un servicio y
# su dependencia. Quien llama se conecta al puerto del proxy en vez de al de
# la dependencia; los tóxicos se agregan después con toxiproxy-cli.
#
#   bash proxy.sh <nombre> <puerto del proxy> <puerto de la dependencia>
#   bash proxy.sh gateway 4001 4000     # Tinkuy -> :4001 -> pasarela en :4000
#   bash proxy.sh courier 4101 4100     # la tienda -> :4101 -> courier en :4100
#
# Después:
#   toxiproxy-cli toxic add -t latency -a latency=5000 gateway        la dependencia tarda 5 s más
#   toxiproxy-cli toxic add -t reset_peer --tox 0.33 -a timeout=0 gateway   corta una de cada tres conexiones
#   toxiproxy-cli toxic remove -n latency_downstream gateway          quita el tóxico
#   toxiproxy-cli toggle gateway                                      apaga o enciende el proxy (dependencia caída)
#   toxiproxy-cli inspect gateway                                     qué tóxicos tiene
set -euo pipefail

if [ $# -ne 3 ]; then
    echo "Uso: bash proxy.sh <nombre> <puerto del proxy> <puerto de la dependencia>" >&2
    exit 2
fi
name="$1"; listen="$2"; upstream="$3"

svc start toxiproxy >/dev/null
# Si el proxy ya existía, se borra: así no quedan tóxicos de un experimento anterior.
toxiproxy-cli delete "$name" >/dev/null 2>&1 || true
toxiproxy-cli create --listen "127.0.0.1:$listen" --upstream "127.0.0.1:$upstream" "$name" >/dev/null
echo "Proxy $name: 127.0.0.1:$listen -> 127.0.0.1:$upstream, sin tóxicos."
chaski/courier-client.tsDescargar chaski/courier-client.ts
// El cliente del courier: el punto de integración de la tienda. Aquí se
// arman, una dentro de otra, las defensas de la semana. Cada una se enciende
// o se apaga desde la configuración, para poder medir qué aporta.
//
//   bulkhead ( circuit breaker ( retry ( timeout ( fetch ) ) ) )
//
// El orden importa. El timeout va por intento. El retry va dentro del
// circuit breaker: el circuito cuenta una falla cuando la llamada falló
// también después de reintentar, y con el circuito abierto no se reintenta
// nada. El bulkhead va afuera: lo que no entra no llega ni a preguntar.

import type { BreakerState, CircuitBreaker, CircuitOpenError } from '../lab/circuit-breaker.ts';
import { TRACEPARENT_HEADER } from '../observability/traceparent.ts';
import { REQUEST_ID_HEADER } from '../observability/logger.ts';
import { Bulkhead } from '../resilience/bulkhead.ts';
import { exponentialBackoff, fullJitter, noDelay, retry, type RetryBudget } from '../resilience/retry.ts';
import { DEADLINE_HEADER, DependencyError, fetchWithTimeout, remainingBudget, TimeoutError } from '../resilience/timeout.ts';

export type Backoff = 'none' | 'exponential' | 'jitter';

export type CourierClientOptions = {
  url: string;
  /** Tiempo máximo de cada intento. 0 = sin tiempo máximo. */
  timeoutMs: number;
  /** Intentos en total. 1 = sin reintentos. */
  maxAttempts: number;
  backoff: Backoff;
  backoffBaseMs: number;
  backoffCapMs: number;
  retryBudget?: RetryBudget;
  /** Llamadas concurrentes al courier. 0 = sin límite. */
  maxConcurrent: number;
  breaker?: CircuitBreaker;
};

export type CallContext = { requestId: string; traceparent: string; deadlineAt?: number };

export type Rate = { shippingCents: number; attempts: number };

/** El courier dice que el pedido está mal: reintentar no lo arregla, y no es una falla suya. */
export class InvalidRateRequest extends Error {}

/** Solo se reintenta lo que puede ser transitorio: sin respuesta, timeout o 5xx. */
export function isTransient(error: unknown): boolean {
  return error instanceof TimeoutError || error instanceof DependencyError;
}

/**
 * ¿El circuito estaba abierto? Se mira el nombre y no la clase porque la
 * implementación del circuit breaker se elige al arrancar (lab o solution).
 */
export function isCircuitOpen(error: unknown): error is CircuitOpenError {
  return error instanceof Error && error.name === 'CircuitOpenError';
}

export class CourierClient {
  readonly bulkhead: Bulkhead | undefined;
  readonly breaker: CircuitBreaker | undefined;
  /** Intentos que salieron hacia el courier: lo que la tienda cree que pidió. */
  attempts = 0;
  private readonly options: CourierClientOptions;

  constructor(options: CourierClientOptions) {
    this.options = options;
    this.breaker = options.breaker;
    this.bulkhead =
      options.maxConcurrent > 0 ? new Bulkhead({ name: 'courier', maxConcurrent: options.maxConcurrent }) : undefined;
  }

  get breakerState(): BreakerState | 'off' {
    return this.breaker?.state ?? 'off';
  }

  async rate(district: string, weightGrams: number, context: CallContext): Promise<Rate> {
    const guarded = (): Promise<Rate> =>
      this.breaker ? this.breaker.call(() => this.withRetries(district, weightGrams, context)) : this.withRetries(district, weightGrams, context);
    return this.bulkhead ? this.bulkhead.run(guarded) : guarded();
  }

  private async withRetries(district: string, weightGrams: number, context: CallContext): Promise<Rate> {
    const { backoff, backoffBaseMs: base, backoffCapMs: cap } = this.options;
    const delayMs = backoff === 'none' ? noDelay() : backoff === 'exponential' ? exponentialBackoff(base, cap) : fullJitter(base, cap);
    let attempts = 0;
    const shippingCents = await retry(
      (attempt) => {
        attempts += 1;
        return this.once(district, weightGrams, context, attempt);
      },
      { maxAttempts: this.options.maxAttempts, delayMs, isRetryable: isTransient, budget: this.options.retryBudget },
    );
    return { shippingCents, attempts };
  }

  /** Un intento: una petición HTTP con su tiempo máximo. */
  private async once(district: string, weightGrams: number, context: CallContext, attempt: number): Promise<number> {
    // Nunca se espera más de lo que le queda a quien espera nuestra respuesta.
    const timeoutMs = remainingBudget(this.options.timeoutMs, context.deadlineAt, Date.now());
    if (context.deadlineAt !== undefined && timeoutMs === 0) throw new TimeoutError(0);

    this.attempts += 1;
    const headers: Record<string, string> = {
      [REQUEST_ID_HEADER]: context.requestId,
      [TRACEPARENT_HEADER]: context.traceparent,
      // Qué intento es: así la dependencia puede distinguir carga nueva de reintentos.
      'x-attempt': String(attempt),
    };
    if (timeoutMs > 0) headers[DEADLINE_HEADER] = String(timeoutMs);
    const url = `${this.options.url}/rates?district=${encodeURIComponent(district)}&weightGrams=${weightGrams}`;
    const response = await fetchWithTimeout(url, { headers }, timeoutMs);

    if (response.status >= 500) {
      await response.body?.cancel();
      throw new DependencyError(`El courier respondió ${response.status}`, response.status);
    }
    if (!response.ok) {
      await response.body?.cancel();
      throw new InvalidRateRequest(`El courier no acepta el pedido (${response.status})`);
    }
    const body = (await response.json()) as { shippingCents: number };
    return body.shippingCents;
  }
}
chaski/courier.tsDescargar chaski/courier.ts
// El courier: la dependencia de la tienda. En la vida real sería el servicio
// de otra empresa; aquí es un proceso aparte que calcula la tarifa de un
// envío y que cuenta todo lo que recibe, para poder comparar lo que la tienda
// cree que pidió con lo que de verdad llegó.
//
//   node chaski/courier.ts
//
//   COURIER_PORT         puerto (4100 por omisión)
//   COURIER_LATENCY_MS   demora de cada respuesta (40 por omisión)
//   COURIER_FAIL_EVERY   responde 503 en uno de cada N pedidos (0 = nunca; 1 = siempre)
//
//   GET  /rates?district=&weightGrams=   la tarifa de un envío (leer: repetirla no cambia nada)
//   POST /pickups                        programa un recojo (crear: repetirla crea otro,
//                                        salvo que lleve la cabecera idempotency-key)
//   GET  /stats                          cuántos pedidos recibió y cuántos recojos creó
//   POST /stats/reset                    pone los contadores en cero
//
// Para que los tóxicos de Toxiproxy, que se aplican por conexión, afecten a
// cada pedido por separado, el courier cierra la conexión después de cada
// respuesta (connection: close).

import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
import { createLogger, REQUEST_ID_HEADER, requestIdFrom, type Logger } from '../observability/logger.ts';
import { contextFrom, TRACEPARENT_HEADER } from '../observability/traceparent.ts';

export type CourierOptions = {
  latencyMs: number;
  failEvery: number;
  /** En POST /pickups: hace el trabajo y corta la conexión sin responder, una de cada N veces. */
  dropReplyEvery?: number;
  /** Si devuelve true, el courier responde 503 (los experimentos lo usan para simular una caída corta). */
  unavailable?: () => boolean;
  logger?: Logger;
};

export type CourierStats = { received: number; rates: number; pickupRequests: number; pickupsCreated: number };

export type Courier = {
  server: Server;
  stats: CourierStats;
  /** Cuándo llegó cada pedido de tarifa (performance.now()) y qué intento era, según x-attempt. */
  arrivals: { at: number; attempt: number }[];
};

const BASE_CENTS: Record<string, number> = { lima: 800, callao: 900, arequipa: 1500, cusco: 1700, trujillo: 1400 };

/** La tarifa: una base por destino más S/ 0.50 por cada 100 g. Determinista. */
export function rateCents(district: string, weightGrams: number): number | undefined {
  const base = BASE_CENTS[district.toLowerCase()];
  if (base === undefined || !Number.isInteger(weightGrams) || weightGrams <= 0) return undefined;
  return base + Math.ceil(weightGrams / 100) * 50;
}

function send(response: ServerResponse, status: number, body: unknown): void {
  response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', connection: 'close' });
  response.end(JSON.stringify(body));
}

async function readBody(request: IncomingMessage): Promise<void> {
  for await (const _ of request) {
    // El cuerpo no se usa: basta con terminar de leerlo.
  }
}

export function createCourier(options: CourierOptions): Courier {
  const stats: CourierStats = { received: 0, rates: 0, pickupRequests: 0, pickupsCreated: 0 };
  const arrivals: { at: number; attempt: number }[] = [];
  // Lo que ya se respondió para cada clave de idempotencia.
  const pickupsByKey = new Map<string, number>();
  const logger = options.logger;

  const server = createServer((request, response) => {
    void (async () => {
      const url = new URL(request.url ?? '/', 'http://localhost');
      const route = `${request.method} ${url.pathname}`;

      if (route === 'GET /stats') return send(response, 200, stats);
      if (route === 'POST /stats/reset') {
        stats.received = stats.rates = stats.pickupRequests = stats.pickupsCreated = 0;
        arrivals.length = 0;
        pickupsByKey.clear();
        return send(response, 200, stats);
      }
      if (route === 'GET /health') return send(response, 200, { status: 'ok' });

      const started = performance.now();
      const trace = contextFrom(request.headers[TRACEPARENT_HEADER]);
      const finish = (status: number, body: unknown): void => {
        send(response, status, body);
        logger?.info('request', {
          request_id: requestIdFrom(request.headers[REQUEST_ID_HEADER]),
          trace_id: trace.traceId,
          span_id: trace.spanId,
          parent_span_id: trace.parentSpanId,
          route,
          status,
          duration_ms: Math.round(performance.now() - started),
        });
      };

      if (route === 'GET /rates') {
        stats.received += 1;
        arrivals.push({ at: started, attempt: Number(request.headers['x-attempt'] ?? 1) });
        await sleep(options.latencyMs);
        if (options.unavailable?.() || (options.failEvery > 0 && stats.received % options.failEvery === 0)) {
          return finish(503, { error: 'service unavailable' });
        }
        const district = url.searchParams.get('district') ?? '';
        const cents = rateCents(district, Number(url.searchParams.get('weightGrams')));
        if (cents === undefined) return finish(400, { error: 'invalid rate request' });
        stats.rates += 1;
        return finish(200, { district, shippingCents: cents });
      }

      if (route === 'POST /pickups') {
        await readBody(request);
        stats.received += 1;
        stats.pickupRequests += 1;
        await sleep(options.latencyMs);
        const key = request.headers['idempotency-key'];
        let pickupId = typeof key === 'string' ? pickupsByKey.get(key) : undefined;
        if (pickupId === undefined) {
          stats.pickupsCreated += 1;
          pickupId = stats.pickupsCreated;
          if (typeof key === 'string') pickupsByKey.set(key, pickupId);
        }
        // El trabajo ya está hecho; la respuesta se pierde en el camino.
        const drop = options.dropReplyEvery ?? 0;
        if (drop > 0 && (stats.pickupRequests - 1) % drop === 0) {
          request.socket.destroy();
          return;
        }
        return finish(201, { pickupId });
      }

      return send(response, 404, { error: 'not found' });
    })();
  });

  return { server, stats, arrivals };
}

if (import.meta.main) {
  const port = Number(process.env.COURIER_PORT ?? 4100);
  const options: CourierOptions = {
    latencyMs: Number(process.env.COURIER_LATENCY_MS ?? 40),
    failEvery: Number(process.env.COURIER_FAIL_EVERY ?? 0),
    logger: process.env.COURIER_LOG === 'on' ? createLogger('courier') : undefined,
  };
  const { server } = createCourier(options);
  server.listen(port, '127.0.0.1', () => {
    console.error(`Courier en http://localhost:${port} (demora ${options.latencyMs} ms, falla cada ${options.failEvery})`);
  });
  const shutdown = (): void => {
    server.close(() => process.exit(0));
    server.closeAllConnections();
  };
  process.on('SIGINT', shutdown);
  process.on('SIGTERM', shutdown);
}
chaski/main.tsDescargar chaski/main.ts
// Arranca la tienda con las defensas que digan las variables de entorno.
//
//   node chaski/main.ts
//
//   SHOP_PORT             puerto (3100 por omisión)
//   COURIER_URL           dónde está el courier (http://localhost:4100; con el proxy, :4101)
//   SHOP_POOL             conexiones del pool de PostgreSQL (10)
//
//   SHOP_TIMEOUT_MS       tiempo máximo de cada intento hacia el courier (0 = sin tiempo máximo)
//   SHOP_OUTSIDE_TX=1     llama al courier antes de abrir la transacción
//   SHOP_ATTEMPTS         intentos en total (1 = sin reintentos)
//   SHOP_BACKOFF          none | exponential | jitter (base 100 ms, tope 2 s)
//   SHOP_RETRY_BUDGET     fracción de peticiones que se puede gastar en reintentos (p. ej. 0.1)
//   SHOP_MAX_CONCURRENT   llamadas concurrentes al courier; lo que excede recibe 503 (0 = sin límite)
//   SHOP_BREAKER=1        circuit breaker: 5 fallas seguidas lo abren, 5 s abierto
//   SHOP_BREAKER_IMPL     lab (por omisión) o solution: qué implementación se usa
//   SHOP_FALLBACK=1       con el courier no disponible, responde una tarifa plana estimada
//   SHOP_LOG              archivo donde escribir el log JSON (por omisión, la salida estándar)

import { appendFileSync } from 'node:fs';
import type * as BreakerModule from '../lab/circuit-breaker.ts';
import { createLogger } from '../observability/logger.ts';
import { RetryBudget } from '../resilience/retry.ts';
import { isTransient, type Backoff } from './courier-client.ts';
import { createShop } from './shop.ts';

const env = process.env;
const number = (name: string, fallback: number): number => (env[name] === undefined || env[name] === '' ? fallback : Number(env[name]));

const logFile = env.SHOP_LOG;
const logger = createLogger('shop', logFile ? (line) => appendFileSync(logFile, `${line}\n`) : undefined);

let breaker: BreakerModule.CircuitBreaker | undefined;
if (env.SHOP_BREAKER === '1') {
  const file = env.SHOP_BREAKER_IMPL === 'solution' ? '../solution/circuit-breaker.ts' : '../lab/circuit-breaker.ts';
  const { CircuitBreaker } = (await import(file)) as typeof BreakerModule;
  breaker = new CircuitBreaker({
    failureThreshold: number('SHOP_BREAKER_THRESHOLD', 5),
    resetTimeoutMs: number('SHOP_BREAKER_RESET_MS', 5000),
    // Un pedido que el courier rechaza por mal formado no es una falla del courier.
    isFailure: isTransient,
    // Todo cambio de estado del circuito queda en el log.
    onStateChange: (from, to) => logger.info('breaker_state_change', { dependency: 'courier', from, to }),
  });
}

const budgetRatio = number('SHOP_RETRY_BUDGET', 0);
const port = number('SHOP_PORT', 3100);
const shop = createShop({
  database: env.SHOP_DB ?? 'arq_w14',
  poolSize: number('SHOP_POOL', 10),
  callOutsideTransaction: env.SHOP_OUTSIDE_TX === '1',
  fallbackRate: env.SHOP_FALLBACK === '1',
  logger,
  courier: {
    url: env.COURIER_URL ?? 'http://localhost:4100',
    timeoutMs: number('SHOP_TIMEOUT_MS', 0),
    maxAttempts: number('SHOP_ATTEMPTS', 1),
    backoff: (env.SHOP_BACKOFF ?? 'none') as Backoff,
    backoffBaseMs: 100,
    backoffCapMs: 2000,
    retryBudget: budgetRatio > 0 ? new RetryBudget({ ratio: budgetRatio, initialTokens: 10 }) : undefined,
    maxConcurrent: number('SHOP_MAX_CONCURRENT', 0),
    breaker,
  },
});

shop.server.listen(port, '127.0.0.1', () => {
  console.error(`Tienda en http://localhost:${port}`);
});

const shutdown = (): void => {
  void shop.close().then(() => process.exit(0));
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
chaski/shop.tsDescargar chaski/shop.ts
// La tienda: el servicio que llama. Dos endpoints que importan:
//
//   GET  /products   el catálogo. Solo usa la base de datos.
//   POST /quotes     cotiza el envío de un producto: lee el producto, le pide
//                    la tarifa al courier y guarda la cotización.
//
// y tres para operarla: GET /health (el proceso vive), GET /ready (puede
// atender) y GET /metrics.
//
// La versión sin defensas tiene el mismo defecto que se ve en muchos
// sistemas: llama al courier con una transacción abierta y sin tiempo
// máximo. Cada defensa se enciende con una opción, para medir qué cambia.

import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import pg from 'pg';
import { createLogger, REQUEST_ID_HEADER, requestIdFrom, type Logger } from '../observability/logger.ts';
import { Metrics } from '../observability/metrics.ts';
import { contextFrom, toHeader, TRACEPARENT_HEADER } from '../observability/traceparent.ts';
import { BulkheadFullError } from '../resilience/bulkhead.ts';
import { DEADLINE_HEADER, DependencyError, TimeoutError } from '../resilience/timeout.ts';
import { CourierClient, InvalidRateRequest, isCircuitOpen, type CallContext, type CourierClientOptions } from './courier-client.ts';

export type ShopOptions = {
  database: string;
  /** Conexiones del pool. El catálogo y las cotizaciones lo comparten. */
  poolSize: number;
  courier: CourierClientOptions;
  /** true: la llamada al courier se hace antes de abrir la transacción. */
  callOutsideTransaction: boolean;
  /** true: si el courier no está disponible, se responde con una tarifa plana marcada como estimada. */
  fallbackRate: boolean;
  logger?: Logger;
};

const FLAT_RATE_CENTS = 2000;
// Los límites del histograma de duración, en ms. 1000 está porque es el umbral del SLO.
const DURATION_BOUNDS = [25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];

type Reply = { status: number; body: unknown; outcome: string; extra?: Record<string, string | number | boolean> };

class InvalidInput extends Error {}

function errorBody(code: string, message: string): { error: { code: string; message: string } } {
  return { error: { code, message } };
}

async function readJson(request: IncomingMessage): Promise<unknown> {
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(chunk as Buffer);
  try {
    return JSON.parse(Buffer.concat(chunks).toString('utf8'));
  } catch {
    throw new InvalidInput('El cuerpo no es JSON');
  }
}

export function createShop(options: ShopOptions): { server: Server; courier: CourierClient; metrics: Metrics; close: () => Promise<void> } {
  const pool = new pg.Pool({ database: options.database, max: options.poolSize });
  const courier = new CourierClient(options.courier);
  const metrics = new Metrics();
  const logger = options.logger;

  // Saturación: qué tan lleno está cada recurso con límite.
  metrics.gauge('db_pool_in_use', () => pool.totalCount - pool.idleCount);
  metrics.gauge('db_pool_waiting', () => pool.waitingCount);
  metrics.gauge('courier_in_flight', () => courier.bulkhead?.inFlight ?? 0);

  async function listProducts(): Promise<Reply> {
    const result = await pool.query('SELECT id, name, weight_grams, price_cents FROM products ORDER BY id LIMIT 50');
    return { status: 200, body: { products: result.rows }, outcome: 'ok' };
  }

  /** Pide la tarifa; con fallbackRate, un courier no disponible se convierte en una tarifa estimada. */
  async function shippingFor(district: string, weightGrams: number, context: CallContext): Promise<{ cents: number; estimated: boolean; attempts: number }> {
    try {
      const rate = await courier.rate(district, weightGrams, context);
      return { cents: rate.shippingCents, estimated: false, attempts: rate.attempts };
    } catch (error) {
      const unavailable =
        isCircuitOpen(error) || error instanceof BulkheadFullError || error instanceof TimeoutError || error instanceof DependencyError;
      if (options.fallbackRate && unavailable) return { cents: FLAT_RATE_CENTS, estimated: true, attempts: 0 };
      throw error;
    }
  }

  async function createQuote(body: unknown, context: CallContext): Promise<Reply> {
    const { productId, district } = (body ?? {}) as { productId?: unknown; district?: unknown };
    if (!Number.isInteger(productId) || typeof district !== 'string' || district === '') {
      throw new InvalidInput('Se necesita productId (entero) y district');
    }
    const insert = 'INSERT INTO quotes (product_id, district, shipping_cents, estimated) VALUES ($1, $2, $3, $4) RETURNING id';
    const select = 'SELECT weight_grams FROM products WHERE id = $1';

    if (options.callOutsideTransaction) {
      // Mientras se espera al courier no hay ninguna conexión ocupada.
      const product = (await pool.query<{ weight_grams: number }>(select, [productId])).rows[0];
      if (!product) throw new InvalidInput(`No existe el producto ${String(productId)}`);
      const shipping = await shippingFor(district, product.weight_grams, context);
      const saved = await pool.query<{ id: string }>(insert, [productId, district, shipping.cents, shipping.estimated]);
      return quoteReply(Number(saved.rows[0]!.id), shipping);
    }

    // La versión ingenua: la conexión y su transacción quedan retenidas
    // durante toda la llamada al courier.
    const client = await pool.connect();
    try {
      await client.query('BEGIN');
      const product = (await client.query<{ weight_grams: number }>(select, [productId])).rows[0];
      if (!product) throw new InvalidInput(`No existe el producto ${String(productId)}`);
      const shipping = await shippingFor(district, product.weight_grams, context);
      const saved = await client.query<{ id: string }>(insert, [productId, district, shipping.cents, shipping.estimated]);
      await client.query('COMMIT');
      return quoteReply(Number(saved.rows[0]!.id), shipping);
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    } finally {
      client.release();
    }
  }

  function quoteReply(id: number, shipping: { cents: number; estimated: boolean; attempts: number }): Reply {
    return {
      status: 201,
      body: { quote: { id, shippingCents: shipping.cents, estimated: shipping.estimated } },
      outcome: shipping.estimated ? 'ok_estimated' : 'ok',
      extra: { courier_attempts: shipping.attempts },
    };
  }

  /** Cada error conocido tiene su código de estado: quien llama necesita saber si vale la pena reintentar. */
  function replyForError(error: unknown): Reply {
    if (error instanceof InvalidInput || error instanceof InvalidRateRequest) {
      return { status: 422, body: errorBody('INVALID_INPUT', error.message), outcome: 'invalid' };
    }
    if (error instanceof BulkheadFullError) {
      return { status: 503, body: errorBody('OVERLOADED', 'Demasiadas cotizaciones en curso; intenten en un momento'), outcome: 'shed' };
    }
    if (isCircuitOpen(error)) {
      return {
        status: 503,
        body: errorBody('COURIER_UNAVAILABLE', 'El courier no está disponible; intenten en un momento'),
        outcome: 'circuit_open',
        extra: { retry_after_ms: error.retryAfterMs },
      };
    }
    if (error instanceof TimeoutError) {
      return { status: 504, body: errorBody('COURIER_TIMEOUT', 'El courier no respondió a tiempo'), outcome: 'timeout' };
    }
    if (error instanceof DependencyError) {
      return { status: 502, body: errorBody('COURIER_ERROR', 'El courier no pudo calcular la tarifa'), outcome: 'dependency_error' };
    }
    return { status: 500, body: errorBody('INTERNAL_ERROR', 'Ocurrió un error inesperado'), outcome: 'internal_error', extra: { error: String(error) } };
  }

  async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
    const started = performance.now();
    const url = new URL(request.url ?? '/', 'http://localhost');
    const route = `${request.method} ${url.pathname}`;
    const requestId = requestIdFrom(request.headers[REQUEST_ID_HEADER]);
    const trace = contextFrom(request.headers[TRACEPARENT_HEADER]);
    // Si quien llama dice cuánto le queda, ese es el deadline de todo lo que se haga por él.
    const deadlineMs = Number(request.headers[DEADLINE_HEADER]);
    const context: CallContext = {
      requestId,
      traceparent: toHeader(trace),
      deadlineAt: Number.isFinite(deadlineMs) && deadlineMs > 0 ? Date.now() + deadlineMs : undefined,
    };

    let reply: Reply;
    try {
      if (route === 'GET /health') {
        // Liveness: el proceso responde. No mira ninguna dependencia.
        reply = { status: 200, body: { status: 'ok' }, outcome: 'ok' };
      } else if (route === 'GET /ready') {
        // Readiness: puede atender. Mira lo propio (su base de datos), no al courier:
        // si el courier cae, la tienda sigue sirviendo el catálogo.
        await pool.query('SELECT 1');
        reply = { status: 200, body: { status: 'ready', courierBreaker: courier.breakerState }, outcome: 'ok' };
      } else if (route === 'GET /metrics') {
        response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
        response.end(metrics.render());
        return;
      } else if (route === 'GET /products') {
        reply = await listProducts();
      } else if (route === 'POST /quotes') {
        reply = await createQuote(await readJson(request), context);
      } else {
        reply = { status: 404, body: errorBody('NOT_FOUND', `No existe ${url.pathname}`), outcome: 'not_found' };
      }
    } catch (error) {
      reply = replyForError(error);
    }

    const headers: Record<string, string> = { 'content-type': 'application/json; charset=utf-8', [REQUEST_ID_HEADER]: requestId };
    if (reply.status === 503) headers['retry-after'] = '1';
    response.writeHead(reply.status, headers);
    response.end(JSON.stringify(reply.body));

    const durationMs = Math.round(performance.now() - started);
    // Etiquetas de pocos valores: ruta y estado. El id de la petición va al log, no a la métrica.
    const metricRoute = reply.outcome === 'not_found' ? 'other' : route;
    metrics.inc('http_requests_total', { route: metricRoute, status: reply.status });
    metrics.observe('http_request_duration_ms', DURATION_BOUNDS, durationMs, { route: metricRoute });
    if (route !== 'GET /health' && route !== 'GET /ready') {
      const fields = {
        request_id: requestId,
        trace_id: trace.traceId,
        span_id: trace.spanId,
        route,
        status: reply.status,
        duration_ms: durationMs,
        outcome: reply.outcome,
        ...reply.extra,
      };
      if (reply.status >= 500) logger?.error('request', fields);
      else logger?.info('request', fields);
    }
  }

  const server = createServer((request, response) => {
    void handle(request, response);
  });

  return {
    server,
    courier,
    metrics,
    close: async () => {
      await new Promise<void>((resolve) => {
        server.close(() => resolve());
        server.closeAllConnections();
      });
      await pool.end();
    },
  };
}
experiments/breaker.tsDescargar experiments/breaker.ts
// El circuit breaker visto desde quien llama: cuánto tarda cada llamada al
// courier y en qué estado queda el circuito, mientras el courier pasa por
// tres situaciones.
//
//   node experiments/breaker.ts      (o make breaker; necesita svc start toxiproxy)
//   BREAKER_IMPL=lab|solution        qué implementación se prueba (lab por omisión)
//
//   1. sano
//   2. lento: responde 5 s más tarde (tóxico latency)
//   3. sano otra vez: ¿cuándo se cierra el circuito?
//   4. caído: rechaza la conexión (proxy apagado, como toxiproxy-cli toggle)
//
// Circuito: 5 fallas seguidas lo abren; 3 s abierto. Tiempo máximo: 1 s.

import { once } from 'node:events';
import { setTimeout as sleep } from 'node:timers/promises';
import { CourierClient, isCircuitOpen, isTransient } from '../chaski/courier-client.ts';
import { createCourier } from '../chaski/courier.ts';
import type * as BreakerModule from '../lab/circuit-breaker.ts';
import { TimeoutError } from '../resilience/timeout.ts';
import { addToxic, createProxy, deleteProxy, removeToxic, setEnabled } from './toxiproxy.ts';

const COURIER_PORT = 4210;
const PROXY_PORT = 4211;
const PROXY = 'courier-breaker';

const file = process.env.BREAKER_IMPL === 'solution' ? '../solution/circuit-breaker.ts' : '../lab/circuit-breaker.ts';
const { CircuitBreaker } = (await import(file)) as typeof BreakerModule;

const courier = createCourier({ latencyMs: 40, failEvery: 0 });
courier.server.listen(COURIER_PORT, '127.0.0.1');
await once(courier.server, 'listening');
await createProxy(PROXY, PROXY_PORT, COURIER_PORT);

const start = performance.now();
const seconds = (): string => `${((performance.now() - start) / 1000).toFixed(1).padStart(5)} s`;

const breaker = new CircuitBreaker({
  failureThreshold: 5,
  resetTimeoutMs: 3000,
  isFailure: isTransient,
  onStateChange: (from, to) => console.log(`${seconds()}  -- el circuito pasa de ${from} a ${to}`),
});
const client = new CourierClient({
  url: `http://localhost:${PROXY_PORT}`,
  timeoutMs: 1000,
  maxAttempts: 1,
  backoff: 'none',
  backoffBaseMs: 0,
  backoffCapMs: 0,
  maxConcurrent: 0,
  breaker,
});
const context = { requestId: 'experiment-breaker', traceparent: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01' };

async function call(): Promise<void> {
  const before = breaker.state;
  const started = performance.now();
  let outcome: string;
  try {
    await client.rate('cusco', 800, context);
    outcome = 'tarifa recibida';
  } catch (error) {
    if (isCircuitOpen(error)) outcome = 'rechazada por el circuito';
    else if (error instanceof TimeoutError) outcome = 'timeout';
    else outcome = 'error de conexión';
  }
  const ms = performance.now() - started;
  const duration = ms < 10 ? `${ms.toFixed(1)} ms` : `${Math.round(ms)} ms`;
  console.log(`${seconds()}  ${before.padEnd(9)}  ${outcome.padEnd(26)} ${duration.padStart(9)}`);
}

async function calls(count: number, pauseMs: number): Promise<void> {
  for (let i = 0; i < count; i += 1) {
    await call();
    await sleep(pauseMs);
  }
}

console.log('tiempo   circuito   resultado                    duración');
console.log('1. El courier está sano');
await calls(3, 100);

console.log('2. El courier tarda 5 s más en responder');
await addToxic(PROXY, 'latency', { latency: 5000 });
await calls(8, 100);

console.log('3. El courier vuelve a responder');
await removeToxic(PROXY, 'latency');
await calls(7, 500);

console.log('4. El courier rechaza la conexión');
await setEnabled(PROXY, false);
await calls(8, 100);

console.log(`El courier recibió ${courier.stats.received} pedidos de los ${3 + 8 + 7 + 8} que se intentaron.`);
await deleteProxy(PROXY);
courier.server.close();
courier.server.closeAllConnections();
experiments/cascade.shDescargar experiments/cascade.sh
#!/usr/bin/env bash
# Un courier lento y la tienda con distintas defensas, bajo la misma carga.
# Para cada variante: levanta la tienda, corre load/mixed.js (15 s) y deja el
# log JSON de la tienda en build/logs/<variante>.jsonl.
#
#   bash experiments/cascade.sh                 todas las variantes
#   bash experiments/cascade.sh none bulkhead   solo esas
#
#   healthy       sin tóxico y sin defensas: la línea de base
#   none          courier 5 s más lento, sin defensas
#   long-timeout  tiempo máximo de 10 s: "para que no falle"
#   timeout       tiempo máximo de 1 s
#   bulkhead      como mucho 5 llamadas al courier a la vez; el resto, 503
#   outside-tx    la llamada al courier, fuera de la transacción
#   all           todo junto: 1 s, fuera de la transacción, bulkhead y circuit breaker
#   degrade       como all, y además responde una tarifa plana estimada
#
# LATENCY_MS cambia la demora del tóxico (5000). BREAKER_IMPL elige el circuit
# breaker de la variante all: lab (por omisión) o solution.
set -uo pipefail
cd "$(dirname "$0")/.."

LATENCY_MS="${LATENCY_MS:-5000}"
variants=("$@")
[ ${#variants[@]} -eq 0 ] && variants=(healthy none long-timeout timeout bulkhead outside-tx all degrade)

mkdir -p build/logs
pids=()
cleanup() { for pid in "${pids[@]:-}"; do kill "$pid" 2>/dev/null; done; wait 2>/dev/null; }
trap cleanup EXIT

node chaski/courier.ts 2>/dev/null &
pids+=($!)

for variant in "${variants[@]}"; do
    case "$variant" in
        healthy|none) defenses="" ;;
        long-timeout) defenses="SHOP_TIMEOUT_MS=10000" ;;
        timeout)      defenses="SHOP_TIMEOUT_MS=1000" ;;
        bulkhead)     defenses="SHOP_MAX_CONCURRENT=5" ;;
        outside-tx)   defenses="SHOP_OUTSIDE_TX=1" ;;
        all)          defenses="SHOP_TIMEOUT_MS=1000 SHOP_OUTSIDE_TX=1 SHOP_MAX_CONCURRENT=5 SHOP_BREAKER=1 SHOP_BREAKER_IMPL=${BREAKER_IMPL:-lab}" ;;
        degrade)      defenses="SHOP_TIMEOUT_MS=1000 SHOP_OUTSIDE_TX=1 SHOP_MAX_CONCURRENT=5 SHOP_BREAKER=1 SHOP_BREAKER_IMPL=${BREAKER_IMPL:-lab} SHOP_FALLBACK=1" ;;
        *) echo "Variante desconocida: $variant" >&2; exit 2 ;;
    esac

    bash proxy.sh courier 4101 4100 >/dev/null
    [ "$variant" != healthy ] && toxiproxy-cli toxic add -t latency -a "latency=$LATENCY_MS" courier >/dev/null
    psql -q -d arq_w14 -c "TRUNCATE quotes"
    rm -f "build/logs/$variant.jsonl"

    # shellcheck disable=SC2086
    env $defenses COURIER_URL=http://localhost:4101 SHOP_LOG="build/logs/$variant.jsonl" node chaski/main.ts 2>/dev/null &
    shop=$!
    pids+=($shop)
    for _ in $(seq 1 40); do curl -fs localhost:3100/ready >/dev/null 2>&1 && break; sleep 0.25; done

    echo "== $variant ${defenses:+($defenses)}"
    k6 run --quiet load/mixed.js 2>/dev/null
    kill "$shop" 2>/dev/null; wait "$shop" 2>/dev/null
done
experiments/layer.tsDescargar experiments/layer.ts
// Una capa de una cadena de servicios: recibe GET /work y llama a la capa
// siguiente, con su propia política de reintentos. Sirve para contar qué le
// llega al último servicio cuando todas las capas reintentan.

import { createServer, type Server } from 'node:http';
import { once } from 'node:events';
import { noDelay, retry, type RetryBudget } from '../resilience/retry.ts';

export type LayerOptions = {
  name: string;
  /** La URL completa a la que llama esta capa. */
  nextUrl: string;
  /** Intentos en total hacia la capa siguiente. 1 = no reintenta. */
  maxAttempts: number;
  budget?: RetryBudget;
};

export type Layer = { server: Server; url: string; close: () => void };

export async function startLayer(options: LayerOptions): Promise<Layer> {
  const server = createServer((_request, response) => {
    void (async () => {
      try {
        await retry(
          async () => {
            const reply = await fetch(options.nextUrl);
            await reply.body?.cancel();
            if (!reply.ok) throw new Error(`${options.name}: la capa siguiente respondió ${reply.status}`);
          },
          // Sin espera: aquí se cuentan pedidos, no tiempos.
          { maxAttempts: options.maxAttempts, delayMs: noDelay(), budget: options.budget },
        );
        response.writeHead(200).end('ok');
      } catch {
        // Esta capa falló también después de reintentar: su cliente ve un 503.
        response.writeHead(503).end('unavailable');
      }
    })();
  });
  server.listen(0, '127.0.0.1');
  await once(server, 'listening');
  const address = server.address();
  const port = typeof address === 'object' && address ? address.port : 0;
  return {
    server,
    url: `http://127.0.0.1:${port}/work`,
    close: () => {
      server.close();
      server.closeAllConnections();
    },
  };
}

export type ChainResult = { userRequests: number; userFailures: number; receivedByLast: number };

/**
 * Arma usuario -> capa 1 -> capa 2 -> capa 3 -> un servicio que falla siempre,
 * manda `userRequests` peticiones (una tras otra) y cuenta cuántas le llegan
 * al último. attempts[i] son los intentos de la capa i + 1.
 */
export async function runChain(attempts: [number, number, number], userRequests: number, budget?: () => RetryBudget): Promise<ChainResult> {
  let received = 0;
  const last = createServer((_request, response) => {
    received += 1;
    response.writeHead(503).end('overloaded');
  });
  last.listen(0, '127.0.0.1');
  await once(last, 'listening');
  const lastAddress = last.address();
  const lastUrl = `http://127.0.0.1:${typeof lastAddress === 'object' && lastAddress ? lastAddress.port : 0}/`;

  const layer3 = await startLayer({ name: 'capa 3', nextUrl: lastUrl, maxAttempts: attempts[2], budget: budget?.() });
  const layer2 = await startLayer({ name: 'capa 2', nextUrl: layer3.url, maxAttempts: attempts[1], budget: budget?.() });
  const layer1 = await startLayer({ name: 'capa 1', nextUrl: layer2.url, maxAttempts: attempts[0], budget: budget?.() });

  let userFailures = 0;
  for (let i = 0; i < userRequests; i += 1) {
    const reply = await fetch(layer1.url);
    await reply.body?.cancel();
    if (!reply.ok) userFailures += 1;
  }

  for (const layer of [layer1, layer2, layer3]) layer.close();
  last.close();
  last.closeAllConnections();
  return { userRequests, userFailures, receivedByLast: received };
}
experiments/retries.tsDescargar experiments/retries.ts
// Reintentos, medidos. Dos experimentos sobre el mismo cliente del courier.
//
//   node experiments/retries.ts      (o make retries; necesita svc start toxiproxy)
//
// 1. Fallas independientes: Toxiproxy corta una de cada tres conexiones.
//    Cuántas llamadas terminan bien y cuántos pedidos recibe el courier con
//    1 intento y con 3 intentos (sin espera, con backoff, con jitter).
//
// 2. Una caída corta: el courier responde 503 durante 800 ms y 100 clientes
//    lo llaman a la vez, con hasta 5 intentos. Cuántos pedidos recibe,
//    cuántos reintentos le caen juntos (el pico en una ventana de 50 ms) y
//    cuántas llamadas terminan bien.

import { once } from 'node:events';
import { CourierClient, type Backoff } from '../chaski/courier-client.ts';
import { createCourier } from '../chaski/courier.ts';
import { addToxic, createProxy, deleteProxy } from './toxiproxy.ts';

const COURIER_PORT = 4200;
const PROXY_PORT = 4201;
const PROXY = 'courier-retries';

type Variant = { label: string; maxAttempts: number; backoff: Backoff };

function client(url: string, variant: Variant, baseMs: number): CourierClient {
  return new CourierClient({
    url,
    timeoutMs: 2000,
    maxAttempts: variant.maxAttempts,
    backoff: variant.backoff,
    backoffBaseMs: baseMs,
    backoffCapMs: 2000,
    maxConcurrent: 0,
  });
}

const context = { requestId: 'experiment-retries', traceparent: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01' };

/** Hace `total` llamadas, `concurrency` a la vez, y cuenta cuántas terminaron bien. */
async function runCalls(courierClient: CourierClient, total: number, concurrency: number): Promise<number> {
  let ok = 0;
  let next = 0;
  const worker = async (): Promise<void> => {
    while (next < total) {
      next += 1;
      try {
        await courierClient.rate('lima', 500, context);
        ok += 1;
      } catch {
        // falló también después de los reintentos
      }
    }
  };
  await Promise.all(Array.from({ length: concurrency }, worker));
  return ok;
}

/** El mayor número de llegadas dentro de una ventana de `windowMs`. */
function peak(arrivals: number[], windowMs: number): number {
  const sorted = [...arrivals].sort((a, b) => a - b);
  let best = 0;
  let start = 0;
  for (let end = 0; end < sorted.length; end += 1) {
    while (sorted[end]! - sorted[start]! >= windowMs) start += 1;
    best = Math.max(best, end - start + 1);
  }
  return best;
}

const pad = (value: string | number, width: number): string => String(value).padStart(width);

// --- 1. Una de cada tres conexiones se corta ---------------------------------

async function independentFaults(): Promise<void> {
  const courier = createCourier({ latencyMs: 5, failEvery: 0 });
  courier.server.listen(COURIER_PORT, '127.0.0.1');
  await once(courier.server, 'listening');
  await createProxy(PROXY, PROXY_PORT, COURIER_PORT);
  await addToxic(PROXY, 'reset_peer', { timeout: 0 }, 1 / 3);

  const CALLS = 900;
  const variants: Variant[] = [
    { label: '1 intento', maxAttempts: 1, backoff: 'none' },
    { label: '3 intentos, sin espera', maxAttempts: 3, backoff: 'none' },
    { label: '3 intentos, backoff', maxAttempts: 3, backoff: 'exponential' },
    { label: '3 intentos, backoff + jitter', maxAttempts: 3, backoff: 'jitter' },
  ];

  console.log(`1. Toxiproxy corta una de cada tres conexiones (${CALLS} llamadas, 30 a la vez)`);
  console.log(`${'variante'.padEnd(30)} ${pad('bien', 6)} ${pad('mal', 6)} ${pad('intentos', 9)} ${pad('llegaron', 9)} ${pad('tiempo', 9)}`);
  for (const variant of variants) {
    courier.stats.received = 0;
    const courierClient = client(`http://localhost:${PROXY_PORT}`, variant, 50);
    const started = performance.now();
    const ok = await runCalls(courierClient, CALLS, 30);
    const elapsed = Math.round(performance.now() - started);
    console.log(
      `${variant.label.padEnd(30)} ${pad(ok, 6)} ${pad(CALLS - ok, 6)} ${pad(courierClient.attempts, 9)} ${pad(courier.stats.received, 9)} ${pad(`${elapsed} ms`, 9)}`,
    );
  }

  await deleteProxy(PROXY);
  courier.server.close();
  courier.server.closeAllConnections();
}

// --- 2. Una caída de 800 ms y 100 clientes a la vez --------------------------

async function shortOutage(): Promise<void> {
  const OUTAGE_MS = 800;
  const CLIENTS = 100;
  let outageEnds = 0;
  const courier = createCourier({ latencyMs: 5, failEvery: 0, unavailable: () => performance.now() < outageEnds });
  courier.server.listen(COURIER_PORT, '127.0.0.1');
  await once(courier.server, 'listening');

  const variants: Variant[] = [
    { label: '1 intento', maxAttempts: 1, backoff: 'none' },
    { label: '5 intentos, sin espera', maxAttempts: 5, backoff: 'none' },
    { label: '5 intentos, backoff', maxAttempts: 5, backoff: 'exponential' },
    { label: '5 intentos, backoff + jitter', maxAttempts: 5, backoff: 'jitter' },
  ];

  console.log(`\n2. El courier responde 503 durante ${OUTAGE_MS} ms; ${CLIENTS} clientes llaman a la vez (base del backoff: 200 ms)`);
  console.log(`${'variante'.padEnd(30)} ${pad('bien', 6)} ${pad('mal', 6)} ${pad('llegaron', 9)} ${pad('reintentos', 11)} ${pad('pico de reintentos en 50 ms', 28)}`);
  for (const variant of variants) {
    courier.arrivals.length = 0;
    courier.stats.received = 0;
    const courierClient = client(`http://localhost:${COURIER_PORT}`, variant, 200);
    outageEnds = performance.now() + OUTAGE_MS;
    const ok = await runCalls(courierClient, CLIENTS, CLIENTS);
    // El primer golpe es igual en todas las variantes: los 100 llegan juntos.
    // Lo que el backoff y el jitter cambian es cómo llegan los reintentos.
    const retries = courier.arrivals.filter((arrival) => arrival.attempt > 1).map((arrival) => arrival.at);
    console.log(
      `${variant.label.padEnd(30)} ${pad(ok, 6)} ${pad(CLIENTS - ok, 6)} ${pad(courier.stats.received, 9)} ${pad(retries.length, 11)} ${pad(peak(retries, 50), 28)}`,
    );
  }

  courier.server.close();
  courier.server.closeAllConnections();
}

await independentFaults();
await shortOutage();
experiments/storm.tsDescargar experiments/storm.ts
// La tormenta de reintentos, contada. Tres capas en cadena y, al final, un
// servicio que responde siempre 503.
//
//   node experiments/storm.ts        (o make storm)

import { RetryBudget } from '../resilience/retry.ts';
import { runChain } from './layer.ts';

const USERS = 100;

const cases: { label: string; attempts: [number, number, number]; budget?: () => RetryBudget }[] = [
  { label: 'nadie reintenta', attempts: [1, 1, 1] },
  { label: 'solo la capa 3 reintenta (3 intentos)', attempts: [1, 1, 3] },
  { label: 'las tres capas, 3 intentos cada una', attempts: [3, 3, 3] },
  { label: 'las tres capas, 4 intentos cada una', attempts: [4, 4, 4] },
  { label: 'las tres, 3 intentos y presupuesto del 10 %', attempts: [3, 3, 3], budget: () => new RetryBudget({ ratio: 0.1 }) },
];

console.log(`${USERS} peticiones de usuario; el último servicio falla siempre`);
console.log(`${'quién reintenta'.padEnd(46)} ${'le llegan al último'.padStart(20)} ${'por petición'.padStart(13)}`);
for (const item of cases) {
  const result = await runChain(item.attempts, USERS, item.budget);
  const perRequest = (result.receivedByLast / result.userRequests).toFixed(2);
  console.log(`${item.label.padEnd(46)} ${String(result.receivedByLast).padStart(20)} ${perRequest.padStart(13)}`);
}
experiments/toxiproxy.tsDescargar experiments/toxiproxy.ts
// Lo mínimo de la API HTTP de Toxiproxy (puerto 8474), para que un
// experimento pueda crear su proxy y poner y quitar tóxicos sin salir de
// Node. Es lo mismo que hace toxiproxy-cli.

const API = process.env.TOXIPROXY_URL ?? 'http://localhost:8474';

async function api(method: string, path: string, body?: unknown): Promise<void> {
  const response = await fetch(`${API}${path}`, {
    method,
    headers: { 'content-type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  await response.body?.cancel();
  if (!response.ok && response.status !== 404) throw new Error(`Toxiproxy respondió ${response.status} a ${method} ${path}`);
}

/** Crea el proxy desde cero (si existía, lo borra con sus tóxicos). */
export async function createProxy(name: string, listenPort: number, upstreamPort: number): Promise<void> {
  try {
    await api('DELETE', `/proxies/${name}`);
  } catch (error) {
    throw new Error(`No se pudo hablar con Toxiproxy en ${API}. ¿Corrieron "svc start toxiproxy"? (${String(error)})`);
  }
  await api('POST', '/proxies', { name, listen: `127.0.0.1:${listenPort}`, upstream: `127.0.0.1:${upstreamPort}`, enabled: true });
}

export async function deleteProxy(name: string): Promise<void> {
  await api('DELETE', `/proxies/${name}`);
}

/** Agrega un tóxico. toxicity es la probabilidad de que se aplique a cada conexión. */
export async function addToxic(proxy: string, type: string, attributes: Record<string, number>, toxicity = 1): Promise<void> {
  await api('POST', `/proxies/${proxy}/toxics`, { name: type, type, stream: 'downstream', toxicity, attributes });
}

export async function removeToxic(proxy: string, name: string): Promise<void> {
  await api('DELETE', `/proxies/${proxy}/toxics/${name}`);
}

/** Apaga o enciende el proxy: apagado, rechaza las conexiones (es lo que hace toxiproxy-cli toggle). */
export async function setEnabled(proxy: string, enabled: boolean): Promise<void> {
  await api('POST', `/proxies/${proxy}`, { enabled });
}
load/mixed.jsDescargar load/mixed.js
// Dos tipos de usuario a la vez sobre la tienda, durante 15 segundos:
//
//   40 piden cotizaciones de envío (POST /quotes, que llama al courier)
//   10 miran el catálogo           (GET /products, que no lo llama)
//
//   k6 run load/mixed.js      (o make cascade, que prepara todo lo demás)
//   BASE_URL=http://localhost:3100
//
// La pregunta que responde: cuando el courier se pone lento, ¿qué le pasa a
// quien solo mira el catálogo? Por eso el resumen separa las dos rutas.

import http from 'k6/http';
import { sleep } from 'k6';
import { Counter, Trend } from 'k6/metrics';

const BASE_URL = __ENV.BASE_URL || 'http://localhost:3100';
const DISTRICTS = ['lima', 'callao', 'arequipa', 'cusco', 'trujillo'];

export const options = {
  scenarios: {
    quotes: { executor: 'constant-vus', vus: 40, duration: '15s', exec: 'quote', gracefulStop: '12s' },
    browse: { executor: 'constant-vus', vus: 10, duration: '15s', exec: 'browse', gracefulStop: '12s' },
  },
};

const quoteDuration = new Trend('quote_duration', true);
const quoteOk = new Counter('quote_201');
const quoteShed = new Counter('quote_503');
const quoteFailed = new Counter('quote_other');
const browseDuration = new Trend('browse_duration', true);
const browseOk = new Counter('browse_200');
const browseFailed = new Counter('browse_other');

export function quote() {
  const body = { productId: 1 + Math.floor(Math.random() * 200), district: DISTRICTS[__ITER % DISTRICTS.length] };
  const response = http.post(`${BASE_URL}/quotes`, JSON.stringify(body), {
    headers: { 'Content-Type': 'application/json' },
    timeout: '20s',
  });
  quoteDuration.add(response.timings.duration);
  if (response.status === 201) quoteOk.add(1);
  else if (response.status === 503) quoteShed.add(1);
  else quoteFailed.add(1);
  sleep(0.5);
}

export function browse() {
  const response = http.get(`${BASE_URL}/products`, { timeout: '20s' });
  browseDuration.add(response.timings.duration);
  if (response.status === 200) browseOk.add(1);
  else browseFailed.add(1);
  sleep(0.2);
}

// En vez del resumen completo de k6, dos líneas: una por ruta.
export function handleSummary(data) {
  const count = (name) => (data.metrics[name] ? data.metrics[name].values.count : 0);
  const ms = (name, stat) => (data.metrics[name] ? `${Math.round(data.metrics[name].values[stat])} ms` : '-');
  const lines = [
    `POST /quotes    201: ${count('quote_201')}   503: ${count('quote_503')}   otros: ${count('quote_other')}   ` +
      `p50 ${ms('quote_duration', 'med')}   p95 ${ms('quote_duration', 'p(95)')}   máx ${ms('quote_duration', 'max')}`,
    `GET  /products  200: ${count('browse_200')}   otros: ${count('browse_other')}   ` +
      `p50 ${ms('browse_duration', 'med')}   p95 ${ms('browse_duration', 'p(95)')}   máx ${ms('browse_duration', 'max')}`,
  ];
  return { stdout: `${lines.join('\n')}\n` };
}
observability/logger.tsDescargar observability/logger.ts
// Logs estructurados: una línea JSON por cosa que pasó, con campos que una
// máquina puede filtrar y sumar, y con el identificador de la petición para
// juntar todas las líneas de un mismo caso.

import { randomUUID } from 'node:crypto';

export type LogFields = Record<string, string | number | boolean | undefined>;

export type Logger = {
  info: (msg: string, fields?: LogFields) => void;
  error: (msg: string, fields?: LogFields) => void;
};

/**
 * Crea el logger de un servicio. `write` recibe cada línea ya armada: por
 * omisión va a la salida estándar, que es de donde la recoge quien opera el
 * servicio; las pruebas pasan una función que las guarda en un arreglo.
 */
export function createLogger(
  service: string,
  write: (line: string) => void = (line) => void process.stdout.write(`${line}\n`),
  now: () => Date = () => new Date(),
): Logger {
  const emit = (level: 'info' | 'error', msg: string, fields: LogFields = {}): void => {
    // ts, level, service y msg van primero y siempre con el mismo nombre.
    write(JSON.stringify({ ts: now().toISOString(), level, service, msg, ...fields }));
  };
  return {
    info: (msg, fields) => emit('info', msg, fields),
    error: (msg, fields) => emit('error', msg, fields),
  };
}

export const REQUEST_ID_HEADER = 'x-request-id';

/** El identificador de la petición: el que ya trae, o uno nuevo si es la primera parada. */
export function requestIdFrom(header: string | string[] | undefined): string {
  const value = Array.isArray(header) ? header[0] : header;
  // Solo se acepta algo con forma de identificador: lo que llega de afuera termina en el log.
  return value !== undefined && /^[\w-]{8,64}$/.test(value) ? value : randomUUID();
}

/**
 * Lo que NO va al log: datos personales y de pago. De un correo se deja solo
 * el dominio, y de un número (tarjeta, celular), los últimos cuatro dígitos.
 */
export function maskEmail(email: string): string {
  const at = email.lastIndexOf('@');
  return at < 0 ? '***' : `***${email.slice(at)}`;
}

export function maskDigits(value: string): string {
  return value.length <= 4 ? '****' : `${'*'.repeat(value.length - 4)}${value.slice(-4)}`;
}
observability/metrics.tsDescargar observability/metrics.ts
// Métricas: números agregados. No dicen qué le pasó a una petición, sino
// cuántas hubo, cuántas fallaron y cómo se repartió su duración.
//
// Tres tipos, con los nombres que usan Prometheus y OpenTelemetry:
//   counter    solo sube (peticiones atendidas, errores)
//   gauge      sube y baja (llamadas en curso, conexiones ocupadas)
//   histogram  cuenta observaciones por rangos (duraciones)
//
// Cada combinación distinta de etiquetas es una serie aparte: por eso las
// etiquetas son de pocos valores (ruta, código de estado), nunca un id.

type Labels = Record<string, string | number>;

function seriesKey(name: string, labels: Labels): string {
  const parts = Object.entries(labels).map(([key, value]) => `${key}="${value}"`);
  return parts.length === 0 ? name : `${name}{${parts.join(',')}}`;
}

export class Metrics {
  private readonly counters = new Map<string, number>();
  private readonly gauges = new Map<string, () => number>();
  private readonly histograms = new Map<string, { bounds: number[]; counts: number[]; sum: number; count: number }>();

  inc(name: string, labels: Labels = {}): void {
    const key = seriesKey(name, labels);
    this.counters.set(key, (this.counters.get(key) ?? 0) + 1);
  }

  /** Un gauge se lee en el momento de exponerlo: no hay que acordarse de actualizarlo. */
  gauge(name: string, read: () => number): void {
    this.gauges.set(name, read);
  }

  /** Anota una observación en el histograma: suma uno en el primer rango que la contiene. */
  observe(name: string, bounds: number[], value: number, labels: Labels = {}): void {
    const key = seriesKey(name, labels);
    let histogram = this.histograms.get(key);
    if (!histogram) {
      histogram = { bounds, counts: bounds.map(() => 0), sum: 0, count: 0 };
      this.histograms.set(key, histogram);
    }
    const index = bounds.findIndex((bound) => value <= bound);
    if (index >= 0) histogram.counts[index]! += 1;
    histogram.sum += value;
    histogram.count += 1;
  }

  /** Cuántas series hay: lo que cuesta guardar estas métricas. */
  get seriesCount(): number {
    return this.counters.size + this.gauges.size + this.histograms.size;
  }

  /**
   * De un histograma, la fracción de observaciones que no pasaron de `bound`
   * (que tiene que ser uno de sus límites). Es justo lo que pide un SLI de
   * latencia: "respondieron en 1000 ms o menos".
   */
  fractionAtOrBelow(name: string, bound: number, labels: Labels = {}): number | undefined {
    const histogram = this.histograms.get(seriesKey(name, labels));
    if (!histogram || histogram.count === 0) return undefined;
    const last = histogram.bounds.indexOf(bound);
    if (last < 0) throw new Error(`${bound} no es un límite del histograma ${name}`);
    const within = histogram.counts.slice(0, last + 1).reduce((sum, count) => sum + count, 0);
    return within / histogram.count;
  }

  /** Texto en el formato de exposición de Prometheus (los rangos son acumulados, con le="..."). */
  render(): string {
    const lines: string[] = [];
    for (const [key, value] of this.counters) lines.push(`${key} ${value}`);
    for (const [name, read] of this.gauges) lines.push(`${name} ${read()}`);
    for (const [key, histogram] of this.histograms) {
      const brace = key.indexOf('{');
      const name = brace < 0 ? key : key.slice(0, brace);
      const labels = brace < 0 ? '' : `${key.slice(brace + 1, -1)},`;
      let cumulative = 0;
      histogram.bounds.forEach((bound, index) => {
        cumulative += histogram.counts[index]!;
        lines.push(`${name}_bucket{${labels}le="${bound}"} ${cumulative}`);
      });
      lines.push(`${name}_bucket{${labels}le="+Inf"} ${histogram.count}`);
      lines.push(`${name}_sum{${labels.slice(0, -1)}} ${Math.round(histogram.sum)}`.replace('{}', ''));
      lines.push(`${name}_count{${labels.slice(0, -1)}} ${histogram.count}`.replace('{}', ''));
    }
    return `${lines.join('\n')}\n`;
  }
}
observability/sli-report.tsDescargar observability/sli-report.ts
// Calcula un SLI y el consumo de error budget a partir de un log JSON.
//
//   node observability/sli-report.ts <log.jsonl> [--route "POST /quotes"]
//        [--threshold-ms 1000] [--slo 99] [--window 100000]
//
//   --window   cuántas peticiones válidas se esperan en la ventana del SLO.
//              Un experimento de 20 segundos no es la ventana: es un episodio
//              dentro de ella, y el presupuesto es el de la ventana completa.

import { readFileSync } from 'node:fs';
import { parseArgs } from 'node:util';
import { computeSli, errorBudget, parseRequestLog } from './sli.ts';

const { values, positionals } = parseArgs({
  allowPositionals: true,
  options: {
    route: { type: 'string', default: 'POST /quotes' },
    'threshold-ms': { type: 'string', default: '1000' },
    slo: { type: 'string', default: '99' },
    window: { type: 'string', default: '100000' },
  },
});

const file = positionals[0];
if (!file) {
  console.error('Uso: node observability/sli-report.ts <log.jsonl> [--route R] [--threshold-ms N] [--slo P] [--window N]');
  process.exit(2);
}

const thresholdMs = Number(values['threshold-ms']);
const slo = Number(values.slo);
const windowValid = Number(values.window);
const result = computeSli(parseRequestLog(readFileSync(file, 'utf8')), { route: values.route, thresholdMs });

const percent = (fraction: number): string => `${(fraction * 100).toFixed(2)} %`;

console.log(`SLI: ${values.route} que respondieron bien en menos de ${thresholdMs} ms`);
console.log(`  peticiones a la ruta   ${result.total}`);
console.log(`  no válidas (4xx)       ${result.excluded}`);
console.log(`  válidas                ${result.valid}`);
console.log(`  buenas                 ${result.good}`);
console.log(`  malas                  ${result.bad} (${result.badError} con error 5xx, ${result.badSlow} lentas)`);
if (result.sli === undefined) {
  console.log('  SLI                    sin peticiones válidas: no se puede calcular');
  process.exit(0);
}
console.log(`  SLI                    ${result.good} / ${result.valid} = ${percent(result.sli)}`);

const budget = errorBudget(slo, windowValid, result.bad);
console.log(`SLO de ${slo} % sobre una ventana de ${windowValid} peticiones válidas`);
console.log(`  error budget           ${budget.allowedBad} peticiones malas`);
console.log(`  consumido aquí         ${result.bad} / ${budget.allowedBad} = ${percent(budget.consumed)}`);
console.log(
  budget.remaining >= 0
    ? `  queda                  ${budget.remaining} peticiones malas`
    : `  queda                  nada: el SLO de la ventana ya no se cumple (se pasó por ${-budget.remaining})`,
);
observability/sli.tsDescargar observability/sli.ts
// Del log a un SLI y de un SLI al error budget.
//
//   SLI = peticiones buenas / peticiones válidas
//
// Válida: una petición a la ruta que se mide y que el servicio debía atender.
// Las que respondieron 4xx no cuentan: el pedido estaba mal y eso no dice
// nada de la salud del servicio. Buena: una válida que respondió sin error
// (menos de 400) y en menos del umbral de latencia.

export type RequestEntry = { route: string; status: number; duration_ms: number };

export type SliSpec = {
  /** La ruta que se mide, tal como aparece en el log: "POST /quotes". */
  route: string;
  /** Una petición buena responde en menos de este tiempo. */
  thresholdMs: number;
};

export type SliResult = {
  /** Todas las peticiones a la ruta. */
  total: number;
  /** Las 4xx, que se dejan fuera. */
  excluded: number;
  valid: number;
  good: number;
  bad: number;
  /** De las malas, cuántas respondieron sin error pero tarde. */
  badSlow: number;
  /** De las malas, cuántas respondieron con 5xx. */
  badError: number;
  /** good / valid; undefined si no hubo ninguna petición válida. */
  sli: number | undefined;
};

/** Lee las líneas de un log JSON y se queda con las que describen una petición atendida. */
export function parseRequestLog(text: string): RequestEntry[] {
  const entries: RequestEntry[] = [];
  for (const line of text.split('\n')) {
    if (!line.startsWith('{')) continue;
    let record: unknown;
    try {
      record = JSON.parse(line);
    } catch {
      continue; // una línea cortada no tumba el cálculo
    }
    const { msg, route, status, duration_ms } = record as Record<string, unknown>;
    if (msg !== 'request') continue;
    if (typeof route !== 'string' || typeof status !== 'number' || typeof duration_ms !== 'number') continue;
    entries.push({ route, status, duration_ms });
  }
  return entries;
}

export function computeSli(entries: RequestEntry[], spec: SliSpec): SliResult {
  const ofRoute = entries.filter((entry) => entry.route === spec.route);
  const validEntries = ofRoute.filter((entry) => entry.status < 400 || entry.status >= 500);
  const badError = validEntries.filter((entry) => entry.status >= 500).length;
  const badSlow = validEntries.filter((entry) => entry.status < 400 && entry.duration_ms >= spec.thresholdMs).length;
  const valid = validEntries.length;
  const bad = badError + badSlow;
  return {
    total: ofRoute.length,
    excluded: ofRoute.length - valid,
    valid,
    good: valid - bad,
    bad,
    badSlow,
    badError,
    sli: valid === 0 ? undefined : (valid - bad) / valid,
  };
}

export type Budget = {
  /** Peticiones malas que el SLO permite en la ventana: (1 - SLO) * válidas de la ventana. */
  allowedBad: number;
  /** Fracción del presupuesto que gastaron `bad` peticiones malas (1 = todo; más de 1 = SLO incumplido). */
  consumed: number;
  /** Peticiones malas que todavía se pueden tener en la ventana. */
  remaining: number;
};

/**
 * El error budget de una ventana y lo que consumió un episodio.
 *
 * @param sloPercent     el objetivo, en porcentaje: 99.5
 * @param windowValid    peticiones válidas en toda la ventana del SLO (los 28 días)
 * @param bad            peticiones malas del episodio que se evalúa
 */
export function errorBudget(sloPercent: number, windowValid: number, bad: number): Budget {
  if (!(sloPercent > 0 && sloPercent < 100)) throw new Error('El SLO debe estar entre 0 y 100, sin incluirlos');
  // Se trabaja en centésimas de punto porcentual para no arrastrar errores de punto flotante.
  const allowedBad = (Math.round((100 - sloPercent) * 1000) * windowValid) / 100_000;
  return { allowedBad, consumed: bad / allowedBad, remaining: allowedBad - bad };
}
observability/traceparent.tsDescargar observability/traceparent.ts
// Contexto de traza según W3C Trace Context: la cabecera traceparent.
//
//   traceparent: 00-<trace-id: 32 hex>-<parent-id: 16 hex>-<flags: 2 hex>
//
// El trace-id es el mismo en todos los servicios por los que pasa la
// petición. El parent-id es el span de quien hace la llamada: cada servicio
// crea el suyo y lo manda como parent-id en las llamadas que él hace.

import { randomBytes } from 'node:crypto';

export const TRACEPARENT_HEADER = 'traceparent';

export type TraceContext = {
  traceId: string;
  /** El span de este servicio para esta petición. */
  spanId: string;
  /** El span de quien nos llamó; undefined si la traza empieza aquí. */
  parentSpanId: string | undefined;
  sampled: boolean;
};

const PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;

function newSpanId(): string {
  return randomBytes(8).toString('hex');
}

/**
 * El contexto de esta petición: continúa la traza que llega en la cabecera
 * o, si no hay cabecera (o no es válida), empieza una nueva.
 */
export function contextFrom(header: string | string[] | undefined): TraceContext {
  const value = Array.isArray(header) ? header[0] : header;
  const match = value === undefined ? null : PATTERN.exec(value);
  // Un trace-id o un parent-id con puros ceros no es válido.
  if (!match || /^0+$/.test(match[1]!) || /^0+$/.test(match[2]!)) {
    return { traceId: randomBytes(16).toString('hex'), spanId: newSpanId(), parentSpanId: undefined, sampled: true };
  }
  return {
    traceId: match[1]!,
    spanId: newSpanId(),
    parentSpanId: match[2]!,
    sampled: (Number.parseInt(match[3]!, 16) & 1) === 1,
  };
}

/** La cabecera que este servicio manda en sus llamadas: mismo trace-id, su span como padre. */
export function toHeader(context: TraceContext): string {
  return `00-${context.traceId}-${context.spanId}-${context.sampled ? '01' : '00'}`;
}
resilience/bulkhead.tsDescargar resilience/bulkhead.ts
// Bulkhead: un tope de trabajos concurrentes para un recurso o una
// dependencia. Lo que no cabe se rechaza de inmediato (load shedding) o
// espera en una cola corta y con límite.

/** No hay lugar: ni en ejecución ni en la cola. */
export class BulkheadFullError extends Error {
  constructor(name: string) {
    super(`"${name}" está al tope: la petición se rechaza sin esperar`);
    this.name = 'BulkheadFullError';
  }
}

export type BulkheadOptions = {
  name: string;
  /** Cuántos trabajos pueden estar corriendo a la vez. */
  maxConcurrent: number;
  /** Cuántos pueden esperar turno. 0 (por omisión): el que no cabe, se rechaza. */
  maxQueue?: number;
};

export class Bulkhead {
  private running = 0;
  private readonly waiting: (() => void)[] = [];
  private rejectedCount = 0;
  private readonly name: string;
  private readonly maxConcurrent: number;
  private readonly maxQueue: number;

  constructor(options: BulkheadOptions) {
    this.name = options.name;
    this.maxConcurrent = options.maxConcurrent;
    this.maxQueue = options.maxQueue ?? 0;
  }

  /** Cuántos trabajos están corriendo ahora: es la saturación de este recurso. */
  get inFlight(): number {
    return this.running;
  }

  get queued(): number {
    return this.waiting.length;
  }

  get rejected(): number {
    return this.rejectedCount;
  }

  async run<T>(fn: () => Promise<T>): Promise<T> {
    if (this.running >= this.maxConcurrent) {
      if (this.waiting.length >= this.maxQueue) {
        this.rejectedCount += 1;
        throw new BulkheadFullError(this.name);
      }
      // Espera a que quien termine le pase su lugar (running no baja en el traspaso).
      await new Promise<void>((resolve) => this.waiting.push(resolve));
    } else {
      this.running += 1;
    }
    try {
      return await fn();
    } finally {
      const next = this.waiting.shift();
      if (next) next();
      else this.running -= 1;
    }
  }
}
resilience/retry.tsDescargar resilience/retry.ts
// Reintentos: cuántos, sobre qué errores y cuánto se espera entre uno y otro.

export type RetryPolicy = {
  /** Intentos en total, contando el primero. Con 1 no hay reintentos. */
  maxAttempts: number;
  /** Cuánto esperar antes del reintento k (k = 0 es el primer reintento). */
  delayMs: (retry: number) => number;
  /** Qué errores vale la pena reintentar. Por omisión, todos. */
  isRetryable?: (error: unknown) => boolean;
  /** Presupuesto de reintentos compartido por todas las llamadas de este cliente. */
  budget?: RetryBudget;
  /** Cómo se espera. Las pruebas pasan uno que no espera de verdad. */
  sleep?: (ms: number) => Promise<void>;
};

const realSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));

/**
 * Llama a fn hasta que salga bien, hasta que el error no sea reintentable,
 * hasta agotar los intentos o hasta que el presupuesto diga que no. Devuelve
 * lo que devolvió fn o lanza el último error.
 *
 * Solo es seguro si fn es idempotente: reintentar repite la operación sin
 * saber si el intento anterior llegó a hacerse.
 */
export async function retry<T>(fn: (attempt: number) => Promise<T>, policy: RetryPolicy): Promise<T> {
  const sleep = policy.sleep ?? realSleep;
  policy.budget?.recordRequest();
  for (let attempt = 1; ; attempt += 1) {
    try {
      return await fn(attempt);
    } catch (error) {
      const retryable = policy.isRetryable?.(error) ?? true;
      if (!retryable || attempt >= policy.maxAttempts) throw error;
      if (policy.budget && !policy.budget.tryRetry()) throw error;
      const wait = policy.delayMs(attempt - 1);
      if (wait > 0) await sleep(wait);
    }
  }
}

/** Sin espera: el reintento sale apenas falla el intento anterior. */
export function noDelay(): (retry: number) => number {
  return () => 0;
}

/** Backoff exponencial: min(cap, base * 2^k). Todos los clientes esperan lo mismo. */
export function exponentialBackoff(baseMs: number, capMs: number): (retry: number) => number {
  return (retry) => Math.min(capMs, baseMs * 2 ** retry);
}

/**
 * Backoff exponencial con jitter completo ("full jitter"): un tiempo al azar
 * entre 0 y min(cap, base * 2^k). Clientes que fallaron a la vez reintentan
 * repartidos en ese intervalo, no todos en el mismo instante.
 */
export function fullJitter(baseMs: number, capMs: number, random: () => number = Math.random): (retry: number) => number {
  return (retry) => random() * Math.min(capMs, baseMs * 2 ** retry);
}

/**
 * Presupuesto de reintentos: este cliente puede gastar en reintentos, como
 * mucho, una fracción (ratio) de las peticiones que hace. Cada petición
 * deposita `ratio` fichas y cada reintento gasta una. Cuando la dependencia
 * falla de verdad, las fichas se acaban y los reintentos se detienen: la
 * carga extra queda acotada a (1 + ratio) veces la normal, no a maxAttempts
 * veces.
 */
export class RetryBudget {
  private tokens: number;
  private readonly ratio: number;
  private readonly maxTokens: number;

  constructor(options: { ratio: number; maxTokens?: number; initialTokens?: number }) {
    this.ratio = options.ratio;
    this.maxTokens = options.maxTokens ?? 100;
    this.tokens = options.initialTokens ?? 0;
  }

  recordRequest(): void {
    this.tokens = Math.min(this.maxTokens, this.tokens + this.ratio);
  }

  tryRetry(): boolean {
    if (this.tokens < 1) return false;
    this.tokens -= 1;
    return true;
  }
}
resilience/timeout.tsDescargar resilience/timeout.ts
// Tiempo máximo para una llamada remota, y el deadline que viaja con ella.

/** La dependencia no respondió dentro del tiempo máximo. */
export class TimeoutError extends Error {
  readonly timeoutMs: number;

  constructor(timeoutMs: number) {
    super(`La dependencia no respondió en ${timeoutMs} ms`);
    this.name = 'TimeoutError';
    this.timeoutMs = timeoutMs;
  }
}

/** La dependencia no aceptó la conexión, la cortó o respondió con un error suyo (5xx). */
export class DependencyError extends Error {
  readonly status: number | undefined;

  constructor(message: string, status?: number) {
    super(message);
    this.name = 'DependencyError';
    this.status = status;
  }
}

// La cabecera con la que quien llama dice cuánto tiempo le queda. No es un
// estándar de HTTP: gRPC lleva lo mismo en grpc-timeout.
export const DEADLINE_HEADER = 'x-deadline-ms';

/**
 * El timeout de una llamada interna cuando la petición ya trae un deadline:
 * nunca más de lo que le queda a quien espera la respuesta. Si ya no queda
 * nada, devuelve 0 y no vale la pena hacer la llamada.
 */
export function remainingBudget(ownTimeoutMs: number, deadlineAt: number | undefined, now: number): number {
  if (deadlineAt === undefined) return ownTimeoutMs;
  return Math.max(0, Math.min(ownTimeoutMs, deadlineAt - now));
}

/**
 * fetch con tiempo máximo. AbortSignal.timeout(ms) cancela la petición
 * cuando pasan ms milisegundos: fetch rechaza con un error de nombre
 * "TimeoutError" y el socket se cierra, así que quien llama deja de esperar
 * y deja de ocupar la conexión.
 *
 * Con timeoutMs = 0 no hay tiempo máximo: es lo que hace fetch por omisión.
 */
export async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {
  try {
    const signal = timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined;
    return await fetch(url, { ...init, signal });
  } catch (error) {
    if (error instanceof Error && error.name === 'TimeoutError') throw new TimeoutError(timeoutMs);
    // Conexión rechazada o cortada: fetch dice "fetch failed" y guarda la causa.
    const cause = error instanceof Error && error.cause instanceof Error ? error.cause.message : String(error);
    throw new DependencyError(`No se pudo completar la llamada (${cause})`);
  }
}
tinkuy/connections.sqlDescargar tinkuy/connections.sql
-- Las conexiones de Tinkuy a PostgreSQL, por estado, cada 2 segundos.
-- Hay que abrirla ANTES de lanzar la carga: cuando se llega a max_connections
-- ya no entra ni psql. La usa cascade.sh; a mano:
--
--   psql -d tinkuy -f tinkuy/connections.sql
--
-- "idle in transaction": la conexión tiene una transacción abierta y no está
-- ejecutando nada; espera a que la aplicación le mande la siguiente consulta.
SELECT to_char(now(), 'HH24:MI:SS') AS hora,
       count(*) FILTER (WHERE state = 'idle in transaction') AS idle_in_transaction,
       count(*) FILTER (WHERE state = 'active') AS active,
       count(*) AS total,
       current_setting('max_connections') AS max_connections
  FROM pg_stat_activity
 WHERE backend_type = 'client backend'
\watch i=2 c=20
tinkuy/down.shDescargar tinkuy/down.sh
#!/usr/bin/env bash
# Detiene lo que levantó tinkuy/up.sh y borra el proxy.
cd "$(dirname "$0")/.."
for name in tinkuy gateway; do
    if [ -f "build/pids/$name.pid" ]; then
        kill "$(cat "build/pids/$name.pid")" 2>/dev/null
        rm -f "build/pids/$name.pid"
    fi
done
toxiproxy-cli delete gateway >/dev/null 2>&1 || true
tinkuy/load.shDescargar tinkuy/load.sh
#!/usr/bin/env bash
# Las dos cargas de Tinkuy a la vez, 30 segundos: gente comprando
# (load/sale.js, 200 usuarios) y gente mirando el catálogo (load/browse.js,
# hasta 50). Mientras corren, anota cada 2 segundos en qué estado están las
# conexiones a PostgreSQL. Al final, las líneas que importan de cada resumen.
#
#   bash tinkuy/load.sh      (make tinkuy-load; antes, make tinkuy-up)
#
# Empieza siempre con los datos recién cargados: las compras venden asientos.
set -uo pipefail
cd "$(dirname "$0")/.."
mkdir -p build/logs

make --no-print-directory -C build/tinkuy db >/dev/null
# psql se conecta ANTES de la carga y se queda conectado: después quizá no pueda.
psql -d tinkuy -q -f tinkuy/connections.sql > build/logs/connections.txt 2>&1 &
watch=$!

(cd build/tinkuy && k6 run --quiet load/browse.js) > build/logs/k6-browse.txt 2>&1 &
browse=$!
(cd build/tinkuy && k6 run --quiet load/sale.js) > build/logs/k6-sale.txt 2>&1
wait "$browse"
kill "$watch" 2>/dev/null; wait "$watch" 2>/dev/null

echo "== Compras (load/sale.js)"
grep -E 'orders_|http_req_duration\.|http_req_failed' build/logs/k6-sale.txt
echo "== Catálogo (load/browse.js)"
grep -E '✓ GET|✗ GET|↳|duration_events_list|http_req_failed' build/logs/k6-browse.txt
echo "== Conexiones a PostgreSQL durante la carga (una fila cada 2 s)"
awk '/hora/ && !header { print; header = 1 } /^ [0-9][0-9]:/' build/logs/connections.txt
tinkuy/up.shDescargar tinkuy/up.sh
#!/usr/bin/env bash
# Levanta, en segundo plano, la copia de Tinkuy (build/tinkuy), su pasarela
# de prueba y un proxy de Toxiproxy entre los dos:
#
#   Tinkuy :3000  ->  proxy "gateway" :4001  ->  pasarela :4000
#
# Tinkuy no cambia: solo se le dice, con GATEWAY_URL, que la pasarela está en
# el puerto del proxy. Los mensajes de cada proceso quedan en build/logs/.
#
#   bash tinkuy/up.sh      (make tinkuy-up)
#   bash tinkuy/down.sh    (make tinkuy-down)
set -euo pipefail
cd "$(dirname "$0")/.."

bash tinkuy/down.sh
mkdir -p build/logs build/pids
make --no-print-directory -C build/tinkuy db

(cd build/tinkuy && exec node tools/fake-gateway.ts) > build/logs/gateway.log 2>&1 &
echo $! > build/pids/gateway.pid
bash proxy.sh gateway 4001 4000
(cd build/tinkuy && GATEWAY_URL=http://localhost:4001 exec node src/main.ts) > build/logs/tinkuy.log 2>&1 &
echo $! > build/pids/tinkuy.pid

for _ in $(seq 1 40); do curl -fs localhost:3000/health >/dev/null 2>&1 && break; sleep 0.25; done
echo "Tinkuy en http://localhost:3000, con la pasarela detrás del proxy \"gateway\"."
chaski/db/schema.sqlDescargar chaski/db/schema.sql
-- Chaski: una tienda en línea pequeña. El catálogo y las cotizaciones de
-- envío que la tienda le pidió al courier.
CREATE TABLE products (
  id            integer PRIMARY KEY,
  name          text    NOT NULL,
  weight_grams  integer NOT NULL CHECK (weight_grams > 0),
  price_cents   integer NOT NULL CHECK (price_cents > 0)
);

CREATE TABLE quotes (
  id              bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  product_id      integer NOT NULL REFERENCES products (id),
  district        text    NOT NULL,
  shipping_cents  integer NOT NULL,
  estimated       boolean NOT NULL DEFAULT false,
  created_at      timestamptz NOT NULL DEFAULT now()
);

-- 200 productos deterministas: los mismos en cada corrida.
INSERT INTO products (id, name, weight_grams, price_cents)
SELECT n,
       (ARRAY['Chompa de alpaca', 'Café de Villa Rica', 'Chocolate de Quillabamba', 'Mate burilado', 'Retablo ayacuchano'])[1 + n % 5]
         || ' #' || n,
       200 + (n * 37) % 1800,
       1500 + (n * 911) % 20000
  FROM generate_series(1, 200) AS n;

Errores

Ejemplos con errores a propósito: no compilan, fallan o dan un resultado incorrecto. Los apuntes explican cada uno.

errors/log-personal-data.tsDescargar errors/log-personal-data.ts
// Error: datos personales y de pago en el log.
//
//   node errors/log-personal-data.ts      (o make errors)
//
// La primera línea parece útil para depurar y es un problema: el log se
// copia al agregador, a los respaldos y a la laptop de quien investiga un
// incidente, y casi nunca se borra. La segunda dice lo mismo que hace falta
// para operar (qué pasó, a qué petición, cuánto tardó) sin datos de nadie.

import { createLogger, maskDigits, maskEmail } from '../observability/logger.ts';

const logger = createLogger('shop', undefined, () => new Date('2026-03-02T15:04:05.000Z'));
const order = { email: 'rosa.quispe@correo.pe', cardNumber: '4111111111111111', totalCents: 18400 };

console.log('Mal:');
logger.info('payment', { request_id: 'b1cb8587', email: order.email, card_number: order.cardNumber, total_cents: order.totalCents });

console.log('Bien:');
logger.info('payment', {
  request_id: 'b1cb8587',
  email: maskEmail(order.email),
  card_last4: maskDigits(order.cardNumber).slice(-4),
  total_cents: order.totalCents,
});
errors/retry-not-idempotent.tsDescargar errors/retry-not-idempotent.ts
// Error: reintentar una operación que no es idempotente.
//
//   node errors/retry-not-idempotent.ts      (o make errors)
//
// La tienda le pide al courier que programe el recojo de 10 pedidos
// (POST /pickups, que CREA algo). El courier hace el trabajo, pero la
// respuesta del primer intento de cada pedido se pierde en el camino. La
// tienda ve un error de conexión, no sabe si el recojo se programó, y
// reintenta.
//
// Sin clave de idempotencia, cada reintento crea otro recojo. Con la clave
// (la misma en todos los intentos del mismo pedido), el courier reconoce la
// repetición y devuelve el recojo que ya había creado.

import { once } from 'node:events';
import { createCourier } from '../chaski/courier.ts';
import { noDelay, retry } from '../resilience/retry.ts';

const ORDERS = 10;

async function schedulePickups(withKey: boolean): Promise<{ answered: number; requests: number; created: number }> {
  // dropReplyEvery: 2 -> se pierde la respuesta del pedido 1, 3, 5...: el primer intento de cada orden.
  const courier = createCourier({ latencyMs: 0, failEvery: 0, dropReplyEvery: 2 });
  courier.server.listen(0, '127.0.0.1');
  await once(courier.server, 'listening');
  const address = courier.server.address();
  const url = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}/pickups`;

  let answered = 0;
  for (let order = 1; order <= ORDERS; order += 1) {
    const headers: Record<string, string> = { 'content-type': 'application/json' };
    // La clave identifica la operación ("el recojo de la orden 7"), no el intento.
    if (withKey) headers['idempotency-key'] = `pickup-order-${order}`;
    await retry(
      async () => {
        const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify({ order }) });
        await response.body?.cancel();
      },
      { maxAttempts: 3, delayMs: noDelay() },
    );
    answered += 1;
  }

  courier.server.close();
  courier.server.closeAllConnections();
  return { answered, requests: courier.stats.pickupRequests, created: courier.stats.pickupsCreated };
}

for (const withKey of [false, true]) {
  const result = await schedulePickups(withKey);
  console.log(withKey ? 'Con clave de idempotencia:' : 'Sin clave de idempotencia:');
  console.log(`  pedidos de la tienda con respuesta   ${result.answered}`);
  console.log(`  peticiones que recibió el courier    ${result.requests}`);
  console.log(`  recojos que el courier programó      ${result.created}`);
}

Pruebas

Comprueban lo que afirman los apuntes; se ejecutan con make test.

test/bulkhead.test.tsDescargar test/bulkhead.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { Bulkhead, BulkheadFullError } from '../resilience/bulkhead.ts';

/** Un trabajo que queda en curso hasta que la prueba lo suelta. */
function pending(): { job: () => Promise<string>; finish: () => void; started: { count: number } } {
  const started = { count: 0 };
  let finish: () => void = () => {};
  const done = new Promise<void>((resolve) => (finish = resolve));
  return {
    started,
    finish,
    job: async () => {
      started.count += 1;
      await done;
      return 'listo';
    },
  };
}

test('deja correr hasta maxConcurrent trabajos y rechaza de inmediato el que excede', async () => {
  const bulkhead = new Bulkhead({ name: 'courier', maxConcurrent: 2 });
  const work = pending();

  const first = bulkhead.run(work.job);
  const second = bulkhead.run(work.job);
  await assert.rejects(() => bulkhead.run(work.job), BulkheadFullError);

  assert.equal(work.started.count, 2); // el tercero no llegó a empezar
  assert.equal(bulkhead.inFlight, 2);
  assert.equal(bulkhead.rejected, 1);
  work.finish();
  assert.deepEqual(await Promise.all([first, second]), ['listo', 'listo']);
});

test('cuando un trabajo termina, deja su lugar', async () => {
  const bulkhead = new Bulkhead({ name: 'courier', maxConcurrent: 1 });

  assert.equal(await bulkhead.run(async () => 'uno'), 'uno');
  assert.equal(await bulkhead.run(async () => 'dos'), 'dos');
  assert.equal(bulkhead.inFlight, 0);
});

test('un trabajo que falla también deja su lugar', async () => {
  const bulkhead = new Bulkhead({ name: 'courier', maxConcurrent: 1 });

  await assert.rejects(() => bulkhead.run(async () => Promise.reject(new Error('falló'))), /falló/);

  assert.equal(bulkhead.inFlight, 0);
  assert.equal(await bulkhead.run(async () => 'sigue'), 'sigue');
});

test('con cola: espera turno hasta maxQueue y rechaza al siguiente', async () => {
  const bulkhead = new Bulkhead({ name: 'courier', maxConcurrent: 1, maxQueue: 1 });
  const work = pending();

  const running = bulkhead.run(work.job);
  const queued = bulkhead.run(async () => 'el de la cola');
  await assert.rejects(() => bulkhead.run(async () => 'no entra'), BulkheadFullError);
  assert.equal(bulkhead.queued, 1);

  work.finish();
  assert.equal(await running, 'listo');
  assert.equal(await queued, 'el de la cola');
  assert.equal(bulkhead.inFlight, 0);
});

test('dos bulkheads no se estorban: agotar uno no afecta al otro', async () => {
  const courier = new Bulkhead({ name: 'courier', maxConcurrent: 1 });
  const catalog = new Bulkhead({ name: 'catalog', maxConcurrent: 1 });
  const stuck = pending();

  const slow = courier.run(stuck.job);
  await assert.rejects(() => courier.run(async () => 'otro'), BulkheadFullError);

  assert.equal(await catalog.run(async () => 'catálogo'), 'catálogo');
  stuck.finish();
  await slow;
});
test/helpers.tsDescargar test/helpers.ts
import { once } from 'node:events';
import type { Server } from 'node:http';
import { createCourier, type Courier, type CourierOptions } from '../chaski/courier.ts';
import { createShop, type ShopOptions } from '../chaski/shop.ts';
import type { CourierClientOptions } from '../chaski/courier-client.ts';

export async function listen(server: Server): Promise<string> {
  server.listen(0, '127.0.0.1');
  await once(server, 'listening');
  const address = server.address();
  return `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}`;
}

export function closeServer(server: Server): Promise<void> {
  return new Promise((resolve) => {
    server.close(() => resolve());
    server.closeAllConnections();
  });
}

export type Pair = {
  shopUrl: string;
  courier: Courier;
  shop: ReturnType<typeof createShop>;
  /** Las líneas de log de cada servicio, ya convertidas a objetos. */
  shopLog: Record<string, unknown>[];
  courierLog: Record<string, unknown>[];
  close: () => Promise<void>;
};

/** Levanta un courier y una tienda dentro del proceso de pruebas, en puertos libres. */
export async function startPair(
  courierOptions: Partial<CourierOptions>,
  clientOptions: Partial<CourierClientOptions> = {},
  shopOptions: Partial<ShopOptions> = {},
): Promise<Pair> {
  const shopLog: Record<string, unknown>[] = [];
  const courierLog: Record<string, unknown>[] = [];
  const capture = (into: Record<string, unknown>[]) => ({
    info: (msg: string, fields = {}) => void into.push({ level: 'info', msg, ...fields }),
    error: (msg: string, fields = {}) => void into.push({ level: 'error', msg, ...fields }),
  });

  const courier = createCourier({ latencyMs: 0, failEvery: 0, logger: capture(courierLog), ...courierOptions });
  const courierUrl = await listen(courier.server);
  const shop = createShop({
    database: process.env.SHOP_DB ?? 'arq_w14_test',
    poolSize: 4,
    callOutsideTransaction: false,
    fallbackRate: false,
    logger: capture(shopLog),
    ...shopOptions,
    courier: {
      url: courierUrl,
      timeoutMs: 0,
      maxAttempts: 1,
      backoff: 'none',
      backoffBaseMs: 1,
      backoffCapMs: 5,
      maxConcurrent: 0,
      ...clientOptions,
    },
  });
  const shopUrl = await listen(shop.server);
  return {
    shopUrl,
    courier,
    shop,
    shopLog,
    courierLog,
    close: async () => {
      await shop.close();
      await closeServer(courier.server);
    },
  };
}

export function postQuote(shopUrl: string, headers: Record<string, string> = {}, body: unknown = { productId: 7, district: 'cusco' }): Promise<Response> {
  return fetch(`${shopUrl}/quotes`, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) });
}
test/observability.test.tsDescargar test/observability.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { createLogger, maskDigits, maskEmail, requestIdFrom } from '../observability/logger.ts';
import { Metrics } from '../observability/metrics.ts';
import { contextFrom, toHeader } from '../observability/traceparent.ts';

test('cada línea del log es un objeto JSON con hora, nivel, servicio y mensaje', () => {
  const lines: string[] = [];
  const logger = createLogger('shop', (line) => lines.push(line), () => new Date('2026-03-02T15:04:05.000Z'));

  logger.info('request', { request_id: 'abc12345', route: 'POST /quotes', status: 201, duration_ms: 44 });
  logger.error('request', { request_id: 'abc12346', route: 'POST /quotes', status: 504, duration_ms: 1003 });

  assert.deepEqual(JSON.parse(lines[0]!), {
    ts: '2026-03-02T15:04:05.000Z',
    level: 'info',
    service: 'shop',
    msg: 'request',
    request_id: 'abc12345',
    route: 'POST /quotes',
    status: 201,
    duration_ms: 44,
  });
  assert.equal(JSON.parse(lines[1]!).level, 'error');
  assert.ok(lines.every((line) => !line.includes('\n')));
});

test('el identificador de la petición se conserva si ya viene, y se crea si no', () => {
  assert.equal(requestIdFrom('b1cb8587-dc68-4d64-853d-4eb9177ea38a'), 'b1cb8587-dc68-4d64-853d-4eb9177ea38a');
  assert.match(requestIdFrom(undefined), /^[0-9a-f-]{36}$/);
  // Algo que no parece un identificador no entra al log.
  assert.match(requestIdFrom('"}\n{"level":"error"'), /^[0-9a-f-]{36}$/);
});

test('los datos personales se enmascaran antes de llegar al log', () => {
  assert.equal(maskEmail('rosa.quispe@correo.pe'), '***@correo.pe');
  assert.equal(maskDigits('4111111111111111'), '************1111');
});

test('traceparent: quien recibe continúa la traza con el mismo trace-id y un span nuevo', () => {
  const incoming = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01';
  const context = contextFrom(incoming);

  assert.equal(context.traceId, '0af7651916cd43dd8448eb211c80319c');
  assert.equal(context.parentSpanId, 'b7ad6b7169203331');
  assert.notEqual(context.spanId, 'b7ad6b7169203331');
  // Lo que manda a la siguiente parada: el mismo trace-id y su propio span como padre.
  assert.equal(toHeader(context), `00-0af7651916cd43dd8448eb211c80319c-${context.spanId}-01`);
});

test('traceparent: sin cabecera, o con una inválida, empieza una traza nueva', () => {
  for (const header of [undefined, 'cualquier cosa', '00-00000000000000000000000000000000-b7ad6b7169203331-01']) {
    const context = contextFrom(header);
    assert.match(context.traceId, /^[0-9a-f]{32}$/);
    assert.equal(context.parentSpanId, undefined);
  }
});

test('un histograma responde "qué fracción tardó 1000 ms o menos" sin guardar cada duración', () => {
  const metrics = new Metrics();
  const bounds = [100, 500, 1000, 5000];
  for (const ms of [40, 60, 90, 300, 800, 1200, 4000, 9000]) metrics.observe('duration_ms', bounds, ms, { route: 'POST /quotes' });

  assert.equal(metrics.fractionAtOrBelow('duration_ms', 1000, { route: 'POST /quotes' }), 5 / 8);
  // Pero no puede responder por un límite que no tiene: los rangos se eligen antes.
  assert.throws(() => metrics.fractionAtOrBelow('duration_ms', 750, { route: 'POST /quotes' }));
  assert.match(metrics.render(), /duration_ms_bucket\{route="POST \/quotes",le="1000"\} 5/);
});

test('cada valor distinto de una etiqueta es una serie más: un id como etiqueta las multiplica', () => {
  const byRoute = new Metrics();
  const byUser = new Metrics();
  for (let user = 0; user < 1000; user += 1) {
    byRoute.inc('http_requests_total', { route: 'POST /quotes', status: 201 });
    byUser.inc('http_requests_total', { route: 'POST /quotes', status: 201, user_id: user });
  }
  assert.equal(byRoute.seriesCount, 1);
  assert.equal(byUser.seriesCount, 1000);
});
test/retry.test.tsDescargar test/retry.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { exponentialBackoff, fullJitter, noDelay, retry, RetryBudget } from '../resilience/retry.ts';

// Ninguna prueba espera de verdad: sleep se reemplaza por una función que
// solo anota cuánto se habría esperado.
function recorder(): { waits: number[]; sleep: (ms: number) => Promise<void> } {
  const waits: number[] = [];
  return { waits, sleep: async (ms) => void waits.push(ms) };
}

/** Una operación que falla las primeras `failures` veces. */
function flaky(failures: number): { calls: { count: number }; fn: () => Promise<string> } {
  const calls = { count: 0 };
  return {
    calls,
    fn: async () => {
      calls.count += 1;
      if (calls.count <= failures) throw new Error(`falla ${calls.count}`);
      return 'ok';
    },
  };
}

test('si sale bien a la primera, no hay reintentos ni esperas', async () => {
  const { waits, sleep } = recorder();
  const { calls, fn } = flaky(0);

  assert.equal(await retry(fn, { maxAttempts: 3, delayMs: exponentialBackoff(100, 2000), sleep }), 'ok');
  assert.equal(calls.count, 1);
  assert.deepEqual(waits, []);
});

test('una falta transitoria se recupera: falla dos veces y sale a la tercera', async () => {
  const { waits, sleep } = recorder();
  const { calls, fn } = flaky(2);

  assert.equal(await retry(fn, { maxAttempts: 3, delayMs: exponentialBackoff(100, 2000), sleep }), 'ok');
  assert.equal(calls.count, 3);
  assert.deepEqual(waits, [100, 200]);
});

test('maxAttempts cuenta el primer intento: con 3, la operación se llama 3 veces y se lanza el último error', async () => {
  const { sleep } = recorder();
  const { calls, fn } = flaky(10);

  await assert.rejects(() => retry(fn, { maxAttempts: 3, delayMs: noDelay(), sleep }), /falla 3/);
  assert.equal(calls.count, 3);
});

test('un error que no es reintentable se lanza de inmediato', async () => {
  const { calls, fn } = flaky(10);

  await assert.rejects(() => retry(fn, { maxAttempts: 5, delayMs: noDelay(), isRetryable: () => false }), /falla 1/);
  assert.equal(calls.count, 1);
});

test('backoff exponencial: min(cap, base * 2^k)', () => {
  const delay = exponentialBackoff(100, 1000);
  assert.deepEqual([0, 1, 2, 3, 4, 5].map(delay), [100, 200, 400, 800, 1000, 1000]);
});

test('jitter completo: un valor entre 0 y el backoff exponencial', () => {
  // Con un "azar" fijo se ve la fórmula: random * min(cap, base * 2^k).
  const half = fullJitter(100, 1000, () => 0.5);
  assert.deepEqual([0, 1, 2, 3, 4].map(half), [50, 100, 200, 400, 500]);

  // Con el azar de verdad, nunca se sale del intervalo.
  const real = fullJitter(100, 1000);
  for (let retryNumber = 0; retryNumber < 6; retryNumber += 1) {
    const bound = Math.min(1000, 100 * 2 ** retryNumber);
    for (let i = 0; i < 200; i += 1) {
      const wait = real(retryNumber);
      assert.ok(wait >= 0 && wait < bound, `espera ${wait} fuera de [0, ${bound})`);
    }
  }
});

test('con jitter, 100 clientes que fallan juntos no reintentan en el mismo instante', () => {
  const plain = exponentialBackoff(100, 1000);
  const jittered = fullJitter(100, 1000);

  const withoutJitter = new Set(Array.from({ length: 100 }, () => plain(2)));
  const withJitter = new Set(Array.from({ length: 100 }, () => Math.round(jittered(2))));

  assert.equal(withoutJitter.size, 1); // los 100 esperan exactamente 400 ms
  assert.ok(withJitter.size > 50, `solo ${withJitter.size} esperas distintas`);
});

test('presupuesto de reintentos: con la dependencia caída, la carga extra queda cerca del ratio', async () => {
  const budget = new RetryBudget({ ratio: 0.1 });
  let attempts = 0;
  const alwaysFails = async (): Promise<never> => {
    attempts += 1;
    throw new Error('caída');
  };

  for (let i = 0; i < 1000; i += 1) {
    await assert.rejects(() => retry(alwaysFails, { maxAttempts: 3, delayMs: noDelay(), budget }));
  }

  // Sin presupuesto serían 3000 intentos. Con el 10 %: 1000 más unos 100 reintentos.
  assert.ok(attempts >= 1090 && attempts <= 1100, `fueron ${attempts} intentos`);
});

test('el presupuesto no estorba cuando las fallas son pocas', async () => {
  const budget = new RetryBudget({ ratio: 0.1 });
  let ok = 0;
  for (let i = 0; i < 1000; i += 1) {
    // Una de cada 20 peticiones falla una vez: 5 % de reintentos, dentro del 10 %.
    const { fn } = flaky(i % 20 === 19 ? 1 : 0);
    if ((await retry(fn, { maxAttempts: 3, delayMs: noDelay(), budget })) === 'ok') ok += 1;
  }
  assert.equal(ok, 1000);
});
test/shop.test.tsDescargar test/shop.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { rateCents } from '../chaski/courier.ts';
import { isTransient } from '../chaski/courier-client.ts';
import type * as BreakerModule from '../lab/circuit-breaker.ts';
import { postQuote, startPair } from './helpers.ts';

// La tienda y el courier, levantados dentro del proceso de pruebas, con cada
// defensa por separado. La base de datos es arq_w14_test (la crea make test).

// Las pruebas del circuit breaker dentro de la tienda necesitan uno que
// funcione: W14_BREAKER=lab (el de ustedes; lo pone make lab) o solution.
const breakerFile =
  process.env.W14_BREAKER === 'solution' ? '../solution/circuit-breaker.ts' : process.env.W14_BREAKER === 'lab' ? '../lab/circuit-breaker.ts' : undefined;

test('una cotización: la tienda le pide la tarifa al courier y la guarda', async () => {
  const pair = await startPair({});

  const response = await postQuote(pair.shopUrl);
  const body = (await response.json()) as { quote: { id: number; shippingCents: number; estimated: boolean } };

  assert.equal(response.status, 201);
  assert.equal(body.quote.estimated, false);
  assert.equal(pair.courier.stats.received, 1);
  // Producto 7: 200 + (7 * 37) % 1800 = 459 g a Cusco.
  assert.equal(body.quote.shippingCents, rateCents('cusco', 459));
  await pair.close();
});

test('el courier responde 503: la tienda responde 502 y no reintenta si no se le pidió', async () => {
  const pair = await startPair({ failEvery: 1 });

  const response = await postQuote(pair.shopUrl);

  assert.equal(response.status, 502);
  assert.equal(pair.courier.stats.received, 1);
  await pair.close();
});

test('timeout: con el courier lento, la tienda responde 504 cuando se cumple el tiempo máximo', async () => {
  const pair = await startPair({ latencyMs: 3000 }, { timeoutMs: 100 });

  const started = performance.now();
  const response = await postQuote(pair.shopUrl);
  const elapsed = performance.now() - started;

  assert.equal(response.status, 504);
  assert.ok(elapsed < 1500, `tardó ${Math.round(elapsed)} ms`);
  await pair.close();
});

test('retry: una falla transitoria del courier no llega al usuario', async () => {
  // El courier falla uno de cada dos pedidos: el 2.º, el 4.º...
  const pair = await startPair({ failEvery: 2 }, { maxAttempts: 3 });

  const statuses: number[] = [];
  for (let i = 0; i < 4; i += 1) statuses.push((await postQuote(pair.shopUrl)).status);

  assert.deepEqual(statuses, [201, 201, 201, 201]);
  // 4 cotizaciones, pero el courier recibió más pedidos: los reintentos son carga.
  assert.ok(pair.courier.stats.received > 4, `recibió ${pair.courier.stats.received}`);
  await pair.close();
});

test('retry: un pedido que el courier rechaza por inválido no se reintenta', async () => {
  const pair = await startPair({}, { maxAttempts: 3 });

  const response = await postQuote(pair.shopUrl, {}, { productId: 7, district: 'atlantis' });

  assert.equal(response.status, 422);
  assert.equal(pair.courier.stats.received, 1);
  await pair.close();
});

test('bulkhead y load shedding: lo que excede el límite recibe un 503 inmediato y no llega al courier', async () => {
  const pair = await startPair({ latencyMs: 500 }, { maxConcurrent: 2 }, { poolSize: 8 });

  const started = performance.now();
  const replies = await Promise.all(
    Array.from({ length: 6 }, async () => {
      const response = await postQuote(pair.shopUrl);
      await response.body?.cancel();
      return { status: response.status, retryAfter: response.headers.get('retry-after'), ms: performance.now() - started };
    }),
  );

  const ok = replies.filter((reply) => reply.status === 201);
  const shed = replies.filter((reply) => reply.status === 503);
  assert.equal(ok.length, 2);
  assert.equal(shed.length, 4);
  assert.ok(shed.every((reply) => reply.retryAfter === '1'));
  // Los rechazados no esperaron a los que sí entraron (que tardan al menos 500 ms).
  assert.ok(Math.max(...shed.map((reply) => reply.ms)) < Math.min(...ok.map((reply) => reply.ms)));
  assert.equal(pair.courier.stats.received, 2);
  await pair.close();
});

test('cascada: con el pool agotado por cotizaciones lentas, el catálogo espera; con el bulkhead, no', async () => {
  const timeProducts = async (maxConcurrent: number): Promise<number> => {
    // Pool de 2 conexiones y un courier que tarda 1,5 s. Sin defensas, cada
    // cotización retiene una conexión mientras espera.
    const pair = await startPair({ latencyMs: 1500 }, { maxConcurrent }, { poolSize: 2 });
    const quotes = [postQuote(pair.shopUrl), postQuote(pair.shopUrl)];
    await new Promise((resolve) => setTimeout(resolve, 200)); // las dos ya están esperando al courier
    const started = performance.now();
    const response = await fetch(`${pair.shopUrl}/products`);
    await response.body?.cancel();
    const elapsed = performance.now() - started;
    assert.equal(response.status, 200);
    for (const quote of quotes) await (await quote).body?.cancel();
    await pair.close();
    return elapsed;
  };

  const withoutDefenses = await timeProducts(0);
  const withBulkhead = await timeProducts(1);

  // Sin defensas, el catálogo espera a que una cotización suelte su conexión (más de 1 s).
  assert.ok(withoutDefenses > 900, `sin defensas tardó ${Math.round(withoutDefenses)} ms`);
  // Con una sola llamada concurrente al courier, queda una conexión libre.
  assert.ok(withBulkhead < 700, `con bulkhead tardó ${Math.round(withBulkhead)} ms`);
});

test('fuera de la transacción: mientras se espera al courier no hay conexiones ocupadas', async () => {
  const pair = await startPair({ latencyMs: 1500 }, {}, { poolSize: 2, callOutsideTransaction: true });
  const quotes = [postQuote(pair.shopUrl), postQuote(pair.shopUrl), postQuote(pair.shopUrl)];
  await new Promise((resolve) => setTimeout(resolve, 200));

  const started = performance.now();
  const response = await fetch(`${pair.shopUrl}/products`);
  await response.body?.cancel();
  const elapsed = performance.now() - started;

  assert.ok(elapsed < 700, `tardó ${Math.round(elapsed)} ms`);
  for (const quote of quotes) assert.equal((await quote).status, 201);
  await pair.close();
});

test('degradar: con el courier caído y la tarifa plana activada, la tienda responde con un estimado', async () => {
  const pair = await startPair({ failEvery: 1 }, {}, { fallbackRate: true });

  const response = await postQuote(pair.shopUrl);
  const body = (await response.json()) as { quote: { shippingCents: number; estimated: boolean } };

  assert.equal(response.status, 201);
  assert.deepEqual({ shippingCents: body.quote.shippingCents, estimated: body.quote.estimated }, { shippingCents: 2000, estimated: true });
  await pair.close();
});

test('deadline propagado: si a quien llama le quedan 150 ms, la tienda no espera al courier más que eso', async () => {
  const pair = await startPair({ latencyMs: 3000 }, { timeoutMs: 2500 });

  const started = performance.now();
  const response = await postQuote(pair.shopUrl, { 'x-deadline-ms': '150' });
  const elapsed = performance.now() - started;

  assert.equal(response.status, 504);
  assert.ok(elapsed < 1500, `tardó ${Math.round(elapsed)} ms`);
  await pair.close();
});

test('logs: una línea por petición, con identificador, duración y resultado; el identificador y la traza llegan al courier', async () => {
  const pair = await startPair({});

  const response = await postQuote(pair.shopUrl, {
    'x-request-id': 'req-20260302-0001',
    traceparent: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01',
  });
  await response.body?.cancel();

  const shopLine = pair.shopLog.find((line) => line.msg === 'request');
  const courierLine = pair.courierLog.find((line) => line.msg === 'request');
  assert.ok(shopLine && courierLine);
  assert.equal(shopLine.request_id, 'req-20260302-0001');
  assert.equal(shopLine.route, 'POST /quotes');
  assert.equal(shopLine.status, 201);
  assert.equal(shopLine.outcome, 'ok');
  assert.equal(typeof shopLine.duration_ms, 'number');
  // La misma petición, vista desde el courier: mismo identificador y misma traza,
  // y su padre es el span de la tienda.
  assert.equal(courierLine.request_id, 'req-20260302-0001');
  assert.equal(courierLine.trace_id, '0af7651916cd43dd8448eb211c80319c');
  assert.equal(courierLine.parent_span_id, shopLine.span_id);
  assert.equal(response.headers.get('x-request-id'), 'req-20260302-0001');
  await pair.close();
});

test('health checks: /ready no depende del courier', async () => {
  const pair = await startPair({ failEvery: 1 });

  await (await postQuote(pair.shopUrl)).body?.cancel(); // el courier está caído
  const live = await fetch(`${pair.shopUrl}/health`);
  const ready = await fetch(`${pair.shopUrl}/ready`);

  assert.equal(live.status, 200);
  assert.equal(ready.status, 200);
  await live.body?.cancel();
  await ready.body?.cancel();
  await pair.close();
});

test('métricas: cuentan por ruta y estado, y exponen la saturación', async () => {
  const pair = await startPair({});
  await (await postQuote(pair.shopUrl)).body?.cancel();
  await (await postQuote(pair.shopUrl, {}, { productId: 'x' })).body?.cancel();

  const text = await (await fetch(`${pair.shopUrl}/metrics`)).text();

  assert.match(text, /http_requests_total\{route="POST \/quotes",status="201"\} 1/);
  assert.match(text, /http_requests_total\{route="POST \/quotes",status="422"\} 1/);
  assert.match(text, /http_request_duration_ms_bucket\{route="POST \/quotes",le="1000"\} 2/);
  assert.match(text, /db_pool_in_use \d+/);
  await pair.close();
});

test(
  'circuit breaker: tras 3 fallas seguidas, la tienda responde 503 sin llamar al courier',
  { skip: breakerFile === undefined ? 'se activa con make lab (su circuit breaker) o cuando existe solution/' : false },
  async () => {
    const { CircuitBreaker } = (await import(breakerFile!)) as typeof BreakerModule;
    let now = 0;
    const breaker = new CircuitBreaker({ failureThreshold: 3, resetTimeoutMs: 10_000, now: () => now, isFailure: isTransient });
    const pair = await startPair({ failEvery: 1 }, { breaker });
    // Si el circuito todavía no está hecho, la prueba falla: igual hay que cerrar los servidores.
    try {
      const statuses: number[] = [];
      for (let i = 0; i < 6; i += 1) {
        const response = await postQuote(pair.shopUrl);
        await response.body?.cancel();
        statuses.push(response.status);
      }

      assert.deepEqual(statuses, [502, 502, 502, 503, 503, 503]);
      assert.equal(pair.courier.stats.received, 3);
      // Pasado el tiempo de espera, una llamada de prueba vuelve a tocar al courier.
      now += 10_000;
      await (await postQuote(pair.shopUrl)).body?.cancel();
      assert.equal(pair.courier.stats.received, 4);
    } finally {
      await pair.close();
    }
  },
);
test/sli.test.tsDescargar test/sli.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { computeSli, errorBudget, parseRequestLog, type RequestEntry } from '../observability/sli.ts';

const spec = { route: 'POST /quotes', thresholdMs: 1000 };
const entry = (status: number, duration_ms: number, route = 'POST /quotes'): RequestEntry => ({ route, status, duration_ms });

test('SLI = buenas / válidas: una buena responde sin error y en menos del umbral', () => {
  const result = computeSli([entry(201, 80), entry(201, 999), entry(201, 1000), entry(201, 5200), entry(504, 1001), entry(503, 2)], spec);

  assert.equal(result.valid, 6);
  assert.equal(result.good, 2);
  assert.equal(result.badSlow, 2); // 1000 ms ya no es "menos de 1000 ms"
  assert.equal(result.badError, 2);
  assert.equal(result.sli, 2 / 6);
});

test('un 503 rápido es una petición mala: el load shedding gasta presupuesto', () => {
  const result = computeSli([entry(201, 50), entry(503, 1)], spec);
  assert.equal(result.bad, 1);
  assert.equal(result.sli, 0.5);
});

test('las 4xx no son válidas: no cuentan ni a favor ni en contra', () => {
  const result = computeSli([entry(201, 50), entry(422, 3), entry(404, 2)], spec);

  assert.equal(result.total, 3);
  assert.equal(result.excluded, 2);
  assert.equal(result.valid, 1);
  assert.equal(result.sli, 1);
});

test('solo cuenta la ruta que se mide', () => {
  const result = computeSli([entry(201, 50), entry(500, 9000, 'GET /products')], spec);
  assert.equal(result.valid, 1);
  assert.equal(result.sli, 1);
});

test('sin peticiones válidas no hay SLI (no es 100 % ni 0 %)', () => {
  assert.equal(computeSli([entry(422, 3)], spec).sli, undefined);
});

test('lee el log JSON: se queda con las líneas "request" y salta lo demás', () => {
  const log = [
    '{"ts":"2026-03-02T15:04:05.000Z","level":"info","service":"shop","msg":"request","route":"POST /quotes","status":201,"duration_ms":44}',
    '{"ts":"2026-03-02T15:04:06.000Z","level":"info","service":"shop","msg":"breaker_state_change","from":"closed","to":"open"}',
    'Tienda en http://localhost:3100',
    '{"ts":"2026-03-02T15:04:07.000Z","level":"error","service":"shop","msg":"request","route":"POST /quotes","status":504,"duration_ms":1003}',
    '{"ts":"2026-03-02T15:04:08.000Z","level":"info","msg":"request","route":"POST /quo',
    '',
  ].join('\n');

  assert.deepEqual(parseRequestLog(log), [entry(201, 44), entry(504, 1003)]);
});

// --- Error budget: los números del apunte ---------------------------------------

test('SLO de 99,5 % y un millón de compras: se pueden fallar 5 000', () => {
  assert.equal(errorBudget(99.5, 1_000_000, 0).allowedBad, 5000);
});

test('SLO de 99,9 % y 2 millones de peticiones: 2 000; un incidente de 1 500 errores gasta el 75 %', () => {
  const budget = errorBudget(99.9, 2_000_000, 1500);
  assert.equal(budget.allowedBad, 2000);
  assert.equal(budget.consumed, 0.75);
  assert.equal(budget.remaining, 500);
});

test('SLO de 99 % y 100 000 peticiones: 1 000; 1 186 malas son el 118,6 %: el SLO ya no se cumple', () => {
  const budget = errorBudget(99, 100_000, 1186);
  assert.equal(budget.allowedBad, 1000);
  assert.equal(budget.consumed, 1.186);
  assert.ok(budget.remaining < 0);
});

test('cada nueve que se agrega divide el presupuesto entre diez', () => {
  const allowed = [99, 99.9, 99.99].map((slo) => errorBudget(slo, 1_000_000, 0).allowedBad);
  assert.deepEqual(allowed, [10_000, 1000, 100]);
});

test('100 % no es un SLO: no deja presupuesto', () => {
  assert.throws(() => errorBudget(100, 1_000_000, 0));
});
test/storm.test.tsDescargar test/storm.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { runChain } from '../experiments/layer.ts';
import { RetryBudget } from '../resilience/retry.ts';

// Lo que afirma el apunte sobre la tormenta de reintentos: con el último
// servicio caído, los intentos de cada capa se multiplican.

test('tres capas con 3 intentos cada una: 27 pedidos al último por cada petición del usuario', async () => {
  const result = await runChain([3, 3, 3], 1);
  assert.equal(result.receivedByLast, 27);
  assert.equal(result.userFailures, 1);
});

test('tres capas con 4 intentos cada una: 64', async () => {
  assert.equal((await runChain([4, 4, 4], 1)).receivedByLast, 64);
});

test('si solo reintenta la capa pegada a la dependencia: 3', async () => {
  assert.equal((await runChain([1, 1, 3], 1)).receivedByLast, 3);
});

test('con un presupuesto del 10 % en cada capa, 100 peticiones no llegan a ser 140', async () => {
  const result = await runChain([3, 3, 3], 100, () => new RetryBudget({ ratio: 0.1 }));
  // Cada capa agrega como mucho un 10 %: 100 * 1,1^3 = 133,1.
  assert.ok(result.receivedByLast >= 100 && result.receivedByLast <= 134, `llegaron ${result.receivedByLast}`);
});
test/timeout.test.tsDescargar test/timeout.test.ts
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { test } from 'node:test';
import { DependencyError, fetchWithTimeout, remainingBudget, TimeoutError } from '../resilience/timeout.ts';
import { closeServer, listen } from './helpers.ts';

test('una dependencia lenta: la llamada se corta en el tiempo máximo, no cuando la dependencia quiera', async () => {
  // Responde recién a los 3 segundos.
  const slow = createServer((_request, response) => void setTimeout(() => response.end('tarde'), 3000));
  const url = await listen(slow);

  const started = performance.now();
  await assert.rejects(() => fetchWithTimeout(url, {}, 100), TimeoutError);
  const elapsed = performance.now() - started;

  // Cota generosa: lo que se comprueba es que no esperó los 3 segundos.
  assert.ok(elapsed < 1500, `tardó ${Math.round(elapsed)} ms`);
  await closeServer(slow);
});

test('una dependencia caída falla rápido y con otro error: conexión rechazada', async () => {
  const server = createServer(() => {});
  const url = await listen(server);
  await closeServer(server); // ya nadie escucha en ese puerto

  await assert.rejects(() => fetchWithTimeout(url, {}, 5000), DependencyError);
});

test('dentro del tiempo máximo, la respuesta llega como siempre', async () => {
  const fast = createServer((_request, response) => response.end('a tiempo'));
  const url = await listen(fast);

  const response = await fetchWithTimeout(url, {}, 5000);

  assert.equal(await response.text(), 'a tiempo');
  await closeServer(fast);
});

test('deadline propagado: el timeout de la llamada interna es lo que le queda a quien espera', () => {
  const now = 10_000;
  // Sin deadline, vale el timeout propio.
  assert.equal(remainingBudget(2000, undefined, now), 2000);
  // Al usuario le quedan 300 ms: no tiene sentido esperar 2 s a la dependencia.
  assert.equal(remainingBudget(2000, now + 300, now), 300);
  // Queda más que el timeout propio: manda el timeout propio.
  assert.equal(remainingBudget(2000, now + 9000, now), 2000);
  // El deadline ya pasó: 0, y la llamada ni se hace.
  assert.equal(remainingBudget(2000, now - 50, now), 0);
});

Laboratorio

Archivos de partida del laboratorio de la semana.

lab/circuit-breaker.test.tsDescargar lab/circuit-breaker.test.ts
import assert from 'node:assert/strict';
import { test } from 'node:test';
import type * as BreakerModule from './circuit-breaker.ts';

// Las pruebas del circuit breaker del laboratorio. Están completas: lo que
// falta es el comportamiento de lab/circuit-breaker.ts.
//
//   make lab                     contra lab/circuit-breaker.ts
//   W14_BREAKER=solution ...     contra otra implementación (lo usa make test)
//
// Ninguna prueba espera de verdad: el reloj es un número que la prueba
// adelanta, y por eso el resultado no depende de la máquina.

const implementation = process.env.W14_BREAKER === 'solution' ? '../solution/circuit-breaker.ts' : './circuit-breaker.ts';
const { CircuitBreaker, CircuitOpenError } = (await import(implementation)) as typeof BreakerModule;
type Breaker = BreakerModule.CircuitBreaker;
type BreakerState = BreakerModule.BreakerState;

const THRESHOLD = 3;
const RESET_MS = 10_000;

/** Un reloj que solo avanza cuando la prueba lo dice. */
function fakeClock(): { now: () => number; advance: (ms: number) => void } {
  let t = 1_000_000;
  return { now: () => t, advance: (ms) => void (t += ms) };
}

function setup(extra: Partial<BreakerModule.BreakerOptions> = {}) {
  const clock = fakeClock();
  const transitions: string[] = [];
  const breaker = new CircuitBreaker({
    failureThreshold: THRESHOLD,
    resetTimeoutMs: RESET_MS,
    now: clock.now,
    onStateChange: (from: BreakerState, to: BreakerState) => transitions.push(`${from}->${to}`),
    ...extra,
  });
  return { breaker, clock, transitions };
}

/** La dependencia: cuenta cuántas veces la llamaron de verdad. */
function dependency() {
  const calls = { count: 0 };
  const ok = async (): Promise<string> => {
    calls.count += 1;
    return 'ok';
  };
  const fail = async (): Promise<string> => {
    calls.count += 1;
    throw new Error('la dependencia falló');
  };
  return { calls, ok, fail };
}

async function failTimes(breaker: Breaker, fail: () => Promise<string>, times: number): Promise<void> {
  for (let i = 0; i < times; i += 1) {
    await assert.rejects(() => breaker.call(fail), /la dependencia falló/);
  }
}

// --- closed -----------------------------------------------------------------

test('empieza cerrado y deja pasar las llamadas', async () => {
  const { breaker } = setup();
  const { calls, ok } = dependency();

  assert.equal(breaker.state, 'closed');
  assert.equal(await breaker.call(ok), 'ok');
  assert.equal(calls.count, 1);
});

test('cerrado: el error de la dependencia llega tal cual a quien llama', async () => {
  const { breaker } = setup();
  const { fail } = dependency();

  await assert.rejects(() => breaker.call(fail), /la dependencia falló/);
  assert.equal(breaker.state, 'closed');
});

test('cerrado: menos fallas que el umbral no lo abren', async () => {
  const { breaker, transitions } = setup();
  const { calls, fail } = dependency();

  await failTimes(breaker, fail, THRESHOLD - 1);

  assert.equal(breaker.state, 'closed');
  assert.equal(calls.count, THRESHOLD - 1);
  assert.deepEqual(transitions, []);
});

test('cerrado: un éxito pone la cuenta de fallas en cero (cuentan las fallas seguidas)', async () => {
  const { breaker } = setup();
  const { ok, fail } = dependency();

  await failTimes(breaker, fail, THRESHOLD - 1);
  await breaker.call(ok);
  await failTimes(breaker, fail, THRESHOLD - 1);

  assert.equal(breaker.state, 'closed');
});

test('cerrado -> abierto: al llegar al umbral de fallas seguidas', async () => {
  const { breaker, transitions } = setup();
  const { fail } = dependency();

  await failTimes(breaker, fail, THRESHOLD);

  assert.equal(breaker.state, 'open');
  assert.deepEqual(transitions, ['closed->open']);
});

test('un error que no es falla de la dependencia no cuenta, pero se propaga', async () => {
  class InvalidRequest extends Error {}
  const { breaker } = setup({ isFailure: (error: unknown) => !(error instanceof InvalidRequest) });
  const invalid = async (): Promise<string> => {
    throw new InvalidRequest('pedido mal formado');
  };

  for (let i = 0; i < THRESHOLD * 2; i += 1) {
    await assert.rejects(() => breaker.call(invalid), InvalidRequest);
  }

  assert.equal(breaker.state, 'closed');
});

// --- open -------------------------------------------------------------------

test('abierto: falla de inmediato con CircuitOpenError y no toca la dependencia', async () => {
  const { breaker } = setup();
  const { calls, ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  const before = calls.count;

  await assert.rejects(() => breaker.call(ok), CircuitOpenError);
  await assert.rejects(() => breaker.call(ok), CircuitOpenError);

  assert.equal(calls.count, before);
});

test('abierto: el error dice cuánto falta para la llamada de prueba', async () => {
  const { breaker, clock } = setup();
  const { ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  clock.advance(4_000);

  await assert.rejects(
    () => breaker.call(ok),
    (error: unknown) => error instanceof CircuitOpenError && error.retryAfterMs === RESET_MS - 4_000,
  );
});

test('abierto: sigue abierto hasta un milisegundo antes del tiempo de espera', async () => {
  const { breaker, clock } = setup();
  const { calls, ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  const before = calls.count;

  clock.advance(RESET_MS - 1);

  assert.equal(breaker.state, 'open');
  await assert.rejects(() => breaker.call(ok), CircuitOpenError);
  assert.equal(calls.count, before);
});

test('una llamada lenta que salió con el circuito cerrado y falla con el circuito ya abierto no reinicia la espera', async () => {
  const { breaker, clock } = setup();
  const { fail } = dependency();
  // Una llamada sale con el circuito cerrado y se queda esperando.
  let rejectSlow: (error: Error) => void = () => {};
  const slow = breaker.call(() => new Promise<string>((_, reject) => (rejectSlow = reject)));

  await failTimes(breaker, fail, THRESHOLD); // el circuito se abre en t0
  clock.advance(RESET_MS - 1_000);
  rejectSlow(new Error('la dependencia falló')); // la lenta falla en t0 + 9 s
  await assert.rejects(slow, /la dependencia falló/);
  clock.advance(1_000); // t0 + 10 s

  assert.equal(breaker.state, 'half-open');
});

// --- half-open --------------------------------------------------------------

test('abierto -> semiabierto: cuando pasa el tiempo de espera', async () => {
  const { breaker, clock, transitions } = setup();
  const { fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);

  clock.advance(RESET_MS);

  assert.equal(breaker.state, 'half-open');
  assert.deepEqual(transitions, ['closed->open', 'open->half-open']);
});

test('semiabierto: pasa una sola llamada de prueba; las demás se rechazan mientras esté en curso', async () => {
  const { breaker, clock } = setup();
  const { calls, ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  clock.advance(RESET_MS);
  const before = calls.count;

  // La llamada de prueba queda en curso hasta que la prueba la suelte.
  let release: (value: string) => void = () => {};
  const trial = breaker.call(() => {
    calls.count += 1;
    return new Promise<string>((resolve) => (release = resolve));
  });
  await assert.rejects(() => breaker.call(ok), CircuitOpenError);
  await assert.rejects(() => breaker.call(ok), CircuitOpenError);
  assert.equal(calls.count, before + 1);

  release('ok');
  assert.equal(await trial, 'ok');
});

test('semiabierto -> cerrado: si la llamada de prueba sale bien', async () => {
  const { breaker, clock, transitions } = setup();
  const { calls, ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  clock.advance(RESET_MS);

  assert.equal(await breaker.call(ok), 'ok');

  assert.equal(breaker.state, 'closed');
  assert.deepEqual(transitions, ['closed->open', 'open->half-open', 'half-open->closed']);
  // Y vuelve a dejar pasar todo.
  const before = calls.count;
  await breaker.call(ok);
  await breaker.call(ok);
  assert.equal(calls.count, before + 2);
});

test('al cerrarse, la cuenta de fallas empieza de cero', async () => {
  const { breaker, clock } = setup();
  const { ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  clock.advance(RESET_MS);
  await breaker.call(ok);

  await failTimes(breaker, fail, THRESHOLD - 1);
  assert.equal(breaker.state, 'closed');
  await failTimes(breaker, fail, 1);
  assert.equal(breaker.state, 'open');
});

test('semiabierto -> abierto: si la llamada de prueba falla, y la espera empieza de nuevo', async () => {
  const { breaker, clock, transitions } = setup();
  const { calls, ok, fail } = dependency();
  await failTimes(breaker, fail, THRESHOLD);
  clock.advance(RESET_MS + 2_000);

  await failTimes(breaker, fail, 1); // la llamada de prueba, que falla

  assert.equal(breaker.state, 'open');
  assert.deepEqual(transitions, ['closed->open', 'open->half-open', 'half-open->open']);
  // La espera se cuenta desde esta falla, no desde la primera vez que se abrió.
  const before = calls.count;
  clock.advance(RESET_MS - 1);
  assert.equal(breaker.state, 'open');
  await assert.rejects(() => breaker.call(ok), CircuitOpenError);
  assert.equal(calls.count, before);
  clock.advance(1);
  assert.equal(breaker.state, 'half-open');
});

test('el ciclo completo: cerrado, abierto, semiabierto, abierto, semiabierto, cerrado', async () => {
  const { breaker, clock, transitions } = setup();
  const { ok, fail } = dependency();

  await failTimes(breaker, fail, THRESHOLD);
  clock.advance(RESET_MS);
  await failTimes(breaker, fail, 1);
  clock.advance(RESET_MS);
  await breaker.call(ok);

  assert.deepEqual(transitions, [
    'closed->open',
    'open->half-open',
    'half-open->open',
    'open->half-open',
    'half-open->closed',
  ]);
});
lab/circuit-breaker.tsDescargar lab/circuit-breaker.ts
// Laboratorio, paso 6: un circuit breaker.
//
// Envuelve las llamadas a una dependencia y cuenta sus fallas seguidas.
//
//   closed     las llamadas pasan. Con failureThreshold fallas seguidas, se abre.
//   open       las llamadas fallan de inmediato con CircuitOpenError, sin
//              tocar la dependencia. Pasados resetTimeoutMs, queda half-open.
//   half-open  pasa UNA llamada de prueba; mientras está en curso, las demás
//              se rechazan como en open. Si la prueba sale bien, closed (y la
//              cuenta de fallas vuelve a cero); si falla, open otra vez, y el
//              tiempo de espera empieza de nuevo.
//
// Los tipos, el error y la firma de la clase ya están: son lo que usan las
// pruebas (lab/circuit-breaker.test.ts) y la tienda (chaski/shop.ts). Falta el
// comportamiento: tal como está, el circuito nunca se abre.
//
//   make lab        corre las pruebas contra este archivo
//
// Reglas: el tiempo se lee SIEMPRE con this.now() (las pruebas pasan un reloj
// que ellas mueven; con Date.now() no pasan) y no se usa setTimeout: el paso
// de open a half-open se decide al mirar el reloj cuando llega una llamada o
// cuando alguien pregunta por el estado.

export type BreakerState = 'closed' | 'open' | 'half-open';

/** El circuito está abierto: la llamada no se hizo. */
export class CircuitOpenError extends Error {
  /** Cuánto falta para que el circuito deje pasar una llamada de prueba. */
  readonly retryAfterMs: number;

  constructor(retryAfterMs: number) {
    super('Circuito abierto: la dependencia no se llamó');
    this.name = 'CircuitOpenError';
    this.retryAfterMs = retryAfterMs;
  }
}

export type BreakerOptions = {
  /** Fallas seguidas que abren el circuito. */
  failureThreshold: number;
  /** Cuánto dura abierto antes de dejar pasar una llamada de prueba. */
  resetTimeoutMs: number;
  /** El reloj, en milisegundos. Por omisión, Date.now. */
  now?: () => number;
  /**
   * Qué errores cuentan como falla de la dependencia. Por omisión, todos. Un
   * error que no cuenta (un pedido mal formado, por ejemplo) se propaga
   * igual, pero para el circuito la llamada salió bien.
   */
  isFailure?: (error: unknown) => boolean;
  /** Aviso de cada cambio de estado: para el log y las métricas. */
  onStateChange?: (from: BreakerState, to: BreakerState) => void;
};

export class CircuitBreaker {
  private readonly failureThreshold: number;
  private readonly resetTimeoutMs: number;
  private readonly now: () => number;
  private readonly isFailure: (error: unknown) => boolean;
  private readonly onStateChange: (from: BreakerState, to: BreakerState) => void;

  // TODO: el estado que haga falta (estado actual, fallas seguidas, cuándo
  // se abrió, si hay una llamada de prueba en curso).

  constructor(options: BreakerOptions) {
    this.failureThreshold = options.failureThreshold;
    this.resetTimeoutMs = options.resetTimeoutMs;
    this.now = options.now ?? Date.now;
    this.isFailure = options.isFailure ?? (() => true);
    this.onStateChange = options.onStateChange ?? (() => {});
  }

  /** El estado en este momento, según el reloj. */
  get state(): BreakerState {
    // TODO: si está abierto y ya pasó resetTimeoutMs, el estado es half-open.
    return 'closed';
  }

  /**
   * Hace la llamada si el circuito lo permite y anota cómo salió. Devuelve
   * lo que devuelve fn, o lanza su error tal cual, o lanza CircuitOpenError
   * sin llamar a fn.
   */
  async call<T>(fn: () => Promise<T>): Promise<T> {
    // TODO: decidir según el estado, llamar, contar la falla o el éxito y
    // cambiar de estado (avisando con this.onStateChange).
    return fn();
  }
}

Compilación

Cómo se compilan y ejecutan los ejemplos.

MakefileDescargar Makefile
# Semana 14: resiliencia y observabilidad. Se usa dentro del contenedor del
# curso.
#
#   make                 crea la base de datos arq_w14 (la tienda Chaski), inicia
#                        Toxiproxy y copia Tinkuy en build/tinkuy
#   make test            revisa los tipos (tsc) y corre las pruebas (test/*.test.ts)
#   make lab             las pruebas del circuit breaker contra lab/circuit-breaker.ts
#
# Tinkuy con la pasarela lenta (sobre la copia de build/, sin modificarla):
#   make tinkuy-up       levanta Tinkuy, la pasarela y el proxy "gateway" entre los dos
#   make tinkuy-load     las dos cargas a la vez y las conexiones a PostgreSQL
#   make tinkuy-slow     agrega el tóxico: la pasarela tarda 5 s más
#   make tinkuy-fast     lo quita
#   make tinkuy-down     detiene todo
#
# La tienda Chaski y su courier, con Toxiproxy en medio:
#   make cascade         el courier lento y la tienda con cada defensa, bajo la
#                        misma carga (V="none bulkhead" elige variantes)
#   make sli V=none      el SLI y el error budget, del log que dejó make cascade
#   make retries         reintentos: sin espera, con backoff y con jitter
#   make storm           tres capas que reintentan: cuánto le llega a la última
#   make breaker         el circuito, llamada por llamada (BREAKER_IMPL=lab)
#   make errors          los dos ejemplos de errors/
#   make courier         el courier, en http://localhost:4100
#   make shop            la tienda, en http://localhost:3100 (variables: chaski/main.ts)
#   make proxy           el proxy "courier": :4101 -> :4100
#   make clean           borra build/ y las bases de datos
#
# Nada de esto modifica el Tinkuy del curso (../../tinkuy).

TINKUY ?= ../../tinkuy
DB = arq_w14
V ?=
SLO ?= 99
WINDOW ?= 100000
BREAKER_IMPL ?= lab
# psql no avisa cuando la base de datos que se va a borrar todavía no existe.
PGOPTIONS = --client-min-messages=warning
export PGOPTIONS BREAKER_IMPL

.PHONY: all db toxiproxy test lab tinkuy-up tinkuy-load tinkuy-slow tinkuy-fast tinkuy-down \
        cascade sli retries storm breaker errors courier shop proxy clean

all: db toxiproxy build/tinkuy

db:
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS $(DB) WITH (FORCE)" -c "CREATE DATABASE $(DB)"
	@psql -q -d $(DB) -v ON_ERROR_STOP=1 -f chaski/db/schema.sql
	@echo "Base de datos $(DB) recién creada."

toxiproxy:
	@svc start toxiproxy

build/tinkuy:
	mkdir -p build
	cp -r $(TINKUY) $@

# Las pruebas levantan la tienda y el courier dentro del proceso, con su
# propia base de datos: no necesitan nada corriendo, ni Toxiproxy. Las del
# circuit breaker corren contra solution/ cuando existe; las de lab/ fallan
# hasta que el laboratorio esté hecho, y por eso tienen su propio target.
test:
	tsc -p .
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS $(DB)_test WITH (FORCE)" -c "CREATE DATABASE $(DB)_test"
	@psql -q -d $(DB)_test -v ON_ERROR_STOP=1 -f chaski/db/schema.sql
ifneq ($(wildcard solution/circuit-breaker.ts),)
	W14_BREAKER=solution node --test --test-concurrency=1 "test/*.test.ts" lab/circuit-breaker.test.ts
else
	node --test --test-concurrency=1 "test/*.test.ts"
endif

lab:
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS $(DB)_test WITH (FORCE)" -c "CREATE DATABASE $(DB)_test"
	@psql -q -d $(DB)_test -v ON_ERROR_STOP=1 -f chaski/db/schema.sql
	W14_BREAKER=lab node --test --test-concurrency=1 lab/circuit-breaker.test.ts test/shop.test.ts

tinkuy-up: toxiproxy build/tinkuy
	@bash tinkuy/up.sh

tinkuy-load:
	@bash tinkuy/load.sh

tinkuy-slow:
	toxiproxy-cli toxic add -t latency -a latency=5000 gateway

tinkuy-fast:
	toxiproxy-cli toxic remove -n latency_downstream gateway

tinkuy-down:
	@bash tinkuy/down.sh

cascade: db toxiproxy
	@bash experiments/cascade.sh $(V)

sli:
	@node observability/sli-report.ts build/logs/$(V).jsonl --slo $(SLO) --window $(WINDOW)

retries: toxiproxy
	@node experiments/retries.ts

storm:
	@node experiments/storm.ts

breaker: toxiproxy
	@node experiments/breaker.ts

errors:
	@node errors/retry-not-idempotent.ts
	@node errors/log-personal-data.ts

courier:
	node chaski/courier.ts

shop:
	node chaski/main.ts

proxy: toxiproxy
	@bash proxy.sh courier 4101 4100

clean:
	@bash tinkuy/down.sh 2>/dev/null || true
	@toxiproxy-cli delete courier >/dev/null 2>&1 || true
	@psql -q -d postgres -c "DROP DATABASE IF EXISTS $(DB) WITH (FORCE)" -c "DROP DATABASE IF EXISTS $(DB)_test WITH (FORCE)" \
	  -c "DROP DATABASE IF EXISTS tinkuy WITH (FORCE)"
	rm -rf build
package.jsonDescargar package.json
{
  "private": true,
  "type": "module"
}
tsconfig.jsonDescargar tsconfig.json
{
  "compilerOptions": {
    "target": "es2024",
    "lib": [
      "es2024"
    ],
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "types": [
      "node"
    ],
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true
  },
  "include": [
    "resilience",
    "observability",
    "chaski",
    "experiments",
    "errors",
    "lab",
    "solution",
    "test"
  ]
}