Semana 4 — Estilos monolíticos: capas, modular monolith, pipeline y microkernel
Objetivos
- Explicar qué es un estilo de arquitectura (un vocabulario de elementos y restricciones sobre cómo se conectan) y qué atributos favorece y perjudica cada uno.
- Comparar la arquitectura en capas con el modular monolith: partir por rol técnico o partir por dominio, y qué cambio es barato en cada caso.
- Reconocer y aplicar los estilos pipeline y microkernel, y decir cuándo un punto de extensión vale su costo.
- Agregar una variante a un sistema (un medio de pago) como plug-in, sin modificar el núcleo.
Sesión A — Estilos monolíticos: capas y modular monolith
Lecturas:
- Richards y Ford, Fundamentals of Software Architecture (2.ª ed.), cap. 9 Foundations, cap. 10 Layered Architecture Style y cap. 11 The Modular Monolith Architecture Style.
- Lectura libre: Martin Fowler, PresentationDomainDataLayering y MonolithFirst.
Lecturas complementarias:
- Kirsten Westeinde, Deconstructing the Monolith (Shopify, 2019): cómo un monolito grande se volvió modular sin partirse en servicios.
- Software Architecture in Practice, cap. 8 Modifiability, los patrones del final del capítulo (capas, plug-in).
Temas:
- Estilo de arquitectura: un conjunto de tipos de elementos, de formas de conectarlos y de restricciones. No es una receta: es un punto de partida con propiedades conocidas. Estilo y patrón se usan a veces como sinónimos; en el curso, un estilo describe la forma global del sistema y un patrón resuelve un problema local dentro de él.
- Primera gran división: monolítico (una sola unidad de despliegue) o distribuido (varias, que se comunican por la red). Un monolito no es lo mismo que un big ball of mud: es una decisión de despliegue, no de orden interno.
- Lo que un monolito da: una base de código, llamadas locales (rápidas y que no fallan a medias), transacciones simples sobre una base de datos, un despliegue. Lo que cuesta: todo se despliega junto, una parte lenta afecta a todas, se escala entero, y sin disciplina los límites internos se borran.
- Capas: presentación, dominio, datos. Regla: cada capa usa solo la de abajo. Capas cerradas y abiertas. Fortalezas: simple, conocida, separa lo técnico. Debilidades: se parte por rol técnico, así que un cambio de negocio atraviesa todas las capas, y aparece el antipatrón del sumidero: capas que solo pasan la llamada a la siguiente.
- Partir por rol técnico o por dominio. Por rol:
http/,services/,db/. Por dominio:catalog/,orders/,payments/, cada uno con sus propias capas adentro. La pregunta que decide: ¿qué tipo de cambio llega más seguido? - Modular monolith: un solo despliegue, módulos por dominio con interfaz pública, y los datos de cada módulo son suyos (sus tablas no las lee otro módulo con SQL propio). Cómo se comunican los módulos: llamadas a la interfaz pública, o eventos dentro del proceso. Da buena parte de la modificabilidad que se busca en los microservicios sin el costo de la red.
- Los datos como límite: el esquema por módulo. Qué hacer con un
JOINque cruza dos módulos: pedir el dato por la interfaz, duplicar un dato estable, o aceptar una vista de lectura declarada. - En Tinkuy: hoy es un monolito partido a medias (carpetas por dominio, sin interfaces y con tablas compartidas). P1 lo convierte en un modular monolith con límites comprobados.
- Monolith first (Fowler): los límites de un dominio se descubren con el uso; moverlos entre módulos cuesta poco y entre servicios cuesta mucho.
- Error común: llamar “modular” a un monolito porque tiene carpetas. Sin interfaz pública y sin regla que la proteja, la carpeta es solo un nombre.
Sesión B — Pipeline y microkernel · ✂️ big ball of mud
Lecturas:
- Fundamentals of Software Architecture (2.ª ed.), cap. 12 Pipeline Architecture Style y cap. 13 Microkernel Architecture Style.
- Lectura libre: The Architecture of Open Source Applications, vol. 1, Eclipse: una plataforma hecha de plug-ins.
- ✂️ Brian Foote y Joseph Yoder, Big Ball of Mud, las secciones Introduction y Forces.
Lecturas complementarias:
- The Architecture of Open Source Applications, vol. 1, Graphite: un pipeline de procesamiento de métricas y sus cuellos de botella.
- David Parnas (1972), de nuevo: el índice KWIC es un pipeline.
Temas:
- Pipeline (pipes and filters): filtros que transforman datos y pipes que los llevan del uno al otro. Cada filtro no sabe nada de los demás; solo conoce el formato de entrada y de salida. Tipos de filtro: productor, transformador, verificador (tester) y consumidor. Ejemplos: los comandos de Unix, un compilador, un proceso de carga de datos.
- Qué favorece el pipeline: filtros que se prueban, se reordenan y se reemplazan por separado. Qué cuesta: todos comparten el formato de los datos (el acoplamiento que denunció Parnas), y no sirve para interacciones de ida y vuelta.
- En Tinkuy: la validación de una orden (formato, existencia del evento, límite de asientos, disponibilidad) se puede escribir como un pipeline de validadores; el reporte de ventas, como un pipeline de transformaciones.
- Microkernel (plug-in): un núcleo mínimo y estable, y plug-ins que agregan variantes. El núcleo define el contrato (una interfaz) y un registro donde los plug-ins se inscriben. Ejemplos: un editor con extensiones, un navegador, Eclipse.
- Qué favorece: modificabilidad en un eje concreto (agregar una variante no toca el núcleo ni las demás variantes), y permite que otro equipo escriba plug-ins. Qué cuesta: el contrato es difícil de cambiar una vez que hay plug-ins, y el eje hay que adivinarlo bien: un punto de extensión donde nunca llega una variante es complejidad gratuita.
- Cómo se diseña el contrato de un plug-in: qué puede pedirle el núcleo (validar, calcular la comisión, armar el cobro), qué le está prohibido (tocar la base de datos del núcleo) y cómo se registra. Registro estático (una lista en el código) o descubrimiento (cargar lo que haya en una carpeta).
- En Tinkuy: el
if (method === 'card') … else if (method === 'yape')repartido en varios archivos. Agregar un tercer medio toca el núcleo en cada lugar. Con un microkernel, cada medio de pago es un plug-in que implementaPaymentMethod. - Los estilos se combinan: un modular monolith cuyo módulo de pagos es un microkernel y cuyo módulo de reportes es un pipeline. El estilo se elige por parte del sistema y por atributo.
- ✂️ Big ball of mud: el estilo más común en la práctica. Fuerzas que lo producen: plazos, costo, falta de experiencia en el dominio, cambios que nadie previó. No se llega por una decisión, sino por muchas pequeñas sin nadie que cuide los límites.
- Error común: convertir todo en plug-in “por si acaso”. La extensibilidad se compra para el cambio que un escenario dice que va a llegar.
Laboratorio — Un medio de pago como plug-in
Referencias: Fundamentals of Software Architecture, cap. 13; el README de Tinkuy. Material: code/week-04/. En parejas, sobre su copia de Tinkuy de la semana 3.
- Encontrar todos los lugares de Tinkuy donde el código pregunta por el medio de pago (
grep -rn "'card'\|'yape'" src). Listar archivo, función y qué decide cadaif(validar, calcular la comisión, armar el cobro). - Escribir el escenario de modificabilidad: “agregar un medio de pago nuevo…”, con su medida (cuántos archivos existentes se modifican).
- Estudiar el microkernel pequeño de
code/week-04/(un núcleo, un contrato y dos plug-ins) y correr sus pruebas. Identificar el contrato, el registro y quién llama a quién. - Diseñar el contrato
PaymentMethodpara Tinkuy a partir de la lista del paso 1: una operación por cada decisión que hoy está en unif. Escribirlo como interfaz de TypeScript antes de tocar nada más. - Mover
cardyyapea dos plug-ins que implementan el contrato, y reemplazar cadaifdel núcleo por una llamada al plug-in registrado.make testdebe seguir pasando sin cambiar ninguna prueba. - Agregar un tercer medio,
plin(sin comisión, se identifica con un número de celular, rechazado si termina en 000), como un archivo nuevo más una línea en el registro. Contar los archivos existentes que modificaron y compararlo con la medida del escenario. - Escribir una regla de dependency-cruiser que impida al núcleo importar un plug-in concreto (solo el registro puede hacerlo) y otra que impida a un plug-in importar
pg. - Discusión: ¿qué cambio futuro obligaría a modificar el contrato y, con él, todos los plug-ins? ¿Vale la pena preverlo ahora?
Entregas
Sin entregas esta semana. El plug-in de este laboratorio es la segunda mitad de P1, que se entrega en la semana 5.
Preguntas de repaso
- Un sistema en capas necesita un campo nuevo en un formulario, que debe guardarse y mostrarse. ¿Cuántas capas toca? ¿Y en un modular monolith partido por dominio?
- ¿Qué diferencia a un modular monolith de un monolito con carpetas? Den dos condiciones que se puedan comprobar.
- Dos módulos de un modular monolith necesitan datos del otro para un reporte. Den dos formas de resolverlo sin que uno lea las tablas del otro, y el costo de cada una.
- ¿Por qué en un pipeline el formato de los datos es el acoplamiento más fuerte? ¿Qué diría Parnas?
- En un microkernel, ¿qué es más caro de cambiar: un plug-in o el contrato? ¿Qué implica eso para el momento de diseñarlo?
- Den un ejemplo de un punto de extensión que no vale su costo.
Código de la semana
Compilar y probar dentro del contenedor del curso con make y make test.
Ejemplos (71)Errores (4)Pruebas (14)Compilación (3)
Ejemplos
Los programas que usan los apuntes y la clase.
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
// dependency-cruiser ve los imports, no el SQL. Esta comprobación cubre lo que
// le falta: busca en cada módulo las tablas que nombra su SQL y reporta las
// que están en el esquema de otro módulo.
//
// node data-ownership.ts <carpeta src> termina con código 1 si encuentra alguna
export type OwnershipViolation = { file: string; module: string; table: string };
const TABLE_REFERENCE = /\b(?:FROM|JOIN|INTO|UPDATE)\s+([a-z_]+)\.([a-z_]+)/gi;
export function findForeignTables(source: string, module: string, schemas: string[]): string[] {
const foreign: string[] = [];
for (const match of source.matchAll(TABLE_REFERENCE)) {
const schema = match[1]!.toLowerCase();
if (schemas.includes(schema) && schema !== module) foreign.push(`${schema}.${match[2]!.toLowerCase()}`);
}
return foreign;
}
/** Revisa src/<módulo>/*.ts de una aplicación organizada por dominio. */
export function checkDataOwnership(srcDir: string, modules: string[], schemas: string[]): OwnershipViolation[] {
const violations: OwnershipViolation[] = [];
for (const module of modules) {
const dir = join(srcDir, module);
for (const name of readdirSync(dir).filter((entry) => entry.endsWith('.ts'))) {
const file = join(dir, name);
for (const table of findForeignTables(readFileSync(file, 'utf8'), module, schemas)) {
violations.push({ file: `src/${module}/${name}`, module, table });
}
}
}
return violations;
}
if (import.meta.main) {
const srcDir = process.argv[2] ?? new URL('./by-domain/src', import.meta.url).pathname;
const violations = checkDataOwnership(srcDir, ['catalog', 'orders', 'reports'], ['catalog', 'orders']);
for (const { file, module, table } of violations) {
console.log(`${file}: el módulo ${module} nombra la tabla ${table}, que no es suya`);
}
console.log(violations.length === 0 ? 'Cada módulo nombra solo sus tablas' : `${violations.length} tabla(s) ajena(s)`);
process.exitCode = violations.length === 0 ? 0 : 1;
}import { dispatchNote } from './dispatch-note.ts';
import { shippingQuote } from './shipping-cost.ts';
import { METHOD_LABELS, type Destination, type MethodId, type Parcel } from './types.ts';
import { validateDestination } from './validate-destination.ts';
export type DeliveryRequest = { methodId: string; destination: Destination; parcel: Parcel };
export type DeliveryPlan = {
methodId: string;
label: string;
shippingCents: number;
totalCents: number;
businessDays: number;
dispatchNote: string;
};
export class DeliveryError extends Error {
readonly problems: readonly string[];
constructor(problems: readonly string[]) {
super(problems.join('; '));
this.problems = problems;
}
}
const isMethodId = (id: string): id is MethodId => id in METHOD_LABELS;
export function planDelivery(request: DeliveryRequest): DeliveryPlan {
const { methodId } = request;
if (!isMethodId(methodId)) {
throw new DeliveryError([
`Forma de entrega desconocida: ${methodId} (hay: ${Object.keys(METHOD_LABELS).join(', ')})`,
]);
}
const problems = validateDestination(methodId, request.destination);
if (problems.length > 0) throw new DeliveryError(problems);
const quote = shippingQuote(methodId, request.parcel, request.destination);
return {
methodId,
label: METHOD_LABELS[methodId],
shippingCents: quote.costCents,
totalCents: request.parcel.subtotalCents + quote.costCents,
businessDays: quote.businessDays,
dispatchNote: dispatchNote(methodId, request.destination),
};
}import { STORES, type Destination, type MethodId } from './types.ts';
export function dispatchNote(method: MethodId, destination: Destination): string {
if (method === 'pickup') {
return `RECOJO EN TIENDA · ${STORES[destination.store ?? '']}`;
} else if (method === 'courier') {
return `DOMICILIO · ${(destination.address ?? '').trim()}, ${(destination.district ?? '').trim()}`;
}
throw new Error('Forma de entrega desconocida');
}import { zoneOf, type Destination, type MethodId, type Parcel } from './types.ts';
const BASE_CENTS = { 1: 800, 2: 1200 } as const;
const BUSINESS_DAYS = { 1: 2, 2: 3 } as const;
const EXTRA_KG_CENTS = 200;
const FREE_SHIPPING_FROM_CENTS = 15000;
export function shippingQuote(
method: MethodId,
parcel: Parcel,
destination: Destination,
): { costCents: number; businessDays: number } {
if (method === 'pickup') {
return { costCents: 0, businessDays: 1 };
} else if (method === 'courier') {
const zone = zoneOf(destination.district)!;
if (parcel.subtotalCents >= FREE_SHIPPING_FROM_CENTS) return { costCents: 0, businessDays: BUSINESS_DAYS[zone] };
const extraKg = Math.max(0, Math.ceil(parcel.weightGrams / 1000) - 1);
return { costCents: BASE_CENTS[zone] + extraKg * EXTRA_KG_CENTS, businessDays: BUSINESS_DAYS[zone] };
}
throw new Error('Forma de entrega desconocida');
}// La versión de partida: las formas de entrega son un valor en una unión, y
// cada archivo pregunta por él con un if.
export type MethodId = 'pickup' | 'courier';
export const METHOD_LABELS: Readonly<Record<MethodId, string>> = {
pickup: 'Recojo en tienda',
courier: 'Envío a domicilio',
};
export type Parcel = { weightGrams: number; subtotalCents: number };
export type Destination = Readonly<Record<string, string>>;
export const STORES: Readonly<Record<string, string>> = {
centro: 'Jr. Camaná 615, Lima',
miraflores: 'Av. Larco 345, Miraflores',
};
export const ZONE_OF_DISTRICT: Readonly<Record<string, 1 | 2>> = {
lima: 1,
breña: 1,
miraflores: 1,
'san isidro': 1,
comas: 2,
'san juan de lurigancho': 2,
'villa el salvador': 2,
};
export const zoneOf = (district: string | undefined): 1 | 2 | undefined =>
ZONE_OF_DISTRICT[(district ?? '').trim().toLowerCase()];import { STORES, zoneOf, type Destination, type MethodId } from './types.ts';
export function validateDestination(method: MethodId, destination: Destination): string[] {
if (method === 'pickup') {
const store = destination.store ?? '';
return store in STORES ? [] : [`store debe ser una de: ${Object.keys(STORES).join(', ')}`];
} else if (method === 'courier') {
const problems: string[] = [];
if (zoneOf(destination.district) === undefined) {
problems.push(`No hacemos envíos a domicilio al distrito "${destination.district ?? ''}"`);
}
if ((destination.address ?? '').trim().length < 5) problems.push('address debe ser la dirección de entrega');
return problems;
}
throw new Error('Forma de entrega desconocida');
}diff --git a/before/dispatch-note.ts b/before/dispatch-note.ts
index 4590dfa..46dc45f 100644
--- a/before/dispatch-note.ts
+++ b/before/dispatch-note.ts
@@ -5,6 +5,8 @@ export function dispatchNote(method: MethodId, destination: Destination): string
return `RECOJO EN TIENDA · ${STORES[destination.store ?? '']}`;
} else if (method === 'courier') {
return `DOMICILIO · ${(destination.address ?? '').trim()}, ${(destination.district ?? '').trim()}`;
+ } else if (method === 'locker') {
+ return `CASILLERO · ${destination.locker}`;
}
throw new Error('Forma de entrega desconocida');
}
diff --git a/before/shipping-cost.ts b/before/shipping-cost.ts
index 481076d..07fb8cf 100644
--- a/before/shipping-cost.ts
+++ b/before/shipping-cost.ts
@@ -17,6 +17,8 @@ export function shippingQuote(
if (parcel.subtotalCents >= FREE_SHIPPING_FROM_CENTS) return { costCents: 0, businessDays: BUSINESS_DAYS[zone] };
const extraKg = Math.max(0, Math.ceil(parcel.weightGrams / 1000) - 1);
return { costCents: BASE_CENTS[zone] + extraKg * EXTRA_KG_CENTS, businessDays: BUSINESS_DAYS[zone] };
+ } else if (method === 'locker') {
+ return { costCents: 500, businessDays: 2 };
}
throw new Error('Forma de entrega desconocida');
}
diff --git a/before/types.ts b/before/types.ts
index a21781a..de9463e 100644
--- a/before/types.ts
+++ b/before/types.ts
@@ -1,11 +1,12 @@
// La versión de partida: las formas de entrega son un valor en una unión, y
// cada archivo pregunta por él con un if.
-export type MethodId = 'pickup' | 'courier';
+export type MethodId = 'pickup' | 'courier' | 'locker';
export const METHOD_LABELS: Readonly<Record<MethodId, string>> = {
pickup: 'Recojo en tienda',
courier: 'Envío a domicilio',
+ locker: 'Casillero',
};
export type Parcel = { weightGrams: number; subtotalCents: number };
@@ -26,5 +27,7 @@ export const ZONE_OF_DISTRICT: Readonly<Record<string, 1 | 2>> = {
'villa el salvador': 2,
};
+export const LOCKER_CODE = /^LK-\d{4}$/;
+
export const zoneOf = (district: string | undefined): 1 | 2 | undefined =>
ZONE_OF_DISTRICT[(district ?? '').trim().toLowerCase()];
diff --git a/before/validate-destination.ts b/before/validate-destination.ts
index 7c75cb6..7958daf 100644
--- a/before/validate-destination.ts
+++ b/before/validate-destination.ts
@@ -1,4 +1,4 @@
-import { STORES, zoneOf, type Destination, type MethodId } from './types.ts';
+import { LOCKER_CODE, STORES, zoneOf, type Destination, type MethodId } from './types.ts';
export function validateDestination(method: MethodId, destination: Destination): string[] {
if (method === 'pickup') {
@@ -11,6 +11,8 @@ export function validateDestination(method: MethodId, destination: Destination):
}
if ((destination.address ?? '').trim().length < 5) problems.push('address debe ser la dirección de entrega');
return problems;
+ } else if (method === 'locker') {
+ return LOCKER_CODE.test(destination.locker ?? '') ? [] : ['locker debe ser un código de casillero, como LK-0420'];
}
throw new Error('Forma de entrega desconocida');
}diff --git a/src/registry.ts b/src/registry.ts
index a80daab..84f7ba1 100644
--- a/src/registry.ts
+++ b/src/registry.ts
@@ -1,7 +1,8 @@
import { createRegistry } from './core/method-registry.ts';
import courier from './plugins/courier.ts';
+import locker from './plugins/locker.ts';
import pickup from './plugins/pickup.ts';
// El registro estático: la lista de formas de entrega que trae la aplicación.
// Es el único archivo que conoce a los plug-ins por su nombre.
-export const registry = createRegistry([pickup, courier]);
+export const registry = createRegistry([pickup, courier, locker]);import type { ShippingMethod } from '../core/shipping-method.ts';
// La tercera forma de entrega: un casillero de autoservicio. Tarifa única,
// dos días. Este archivo está fuera de src/plugins a propósito: `make
// tercer-plugin` lo agrega a una copia para contar qué más hay que tocar.
const LOCKER_CODE = /^LK-\d{4}$/;
const locker: ShippingMethod = {
id: 'locker',
label: 'Casillero',
validate(destination) {
return LOCKER_CODE.test(destination.locker ?? '') ? [] : ['locker debe ser un código de casillero, como LK-0420'];
},
quote() {
return { costCents: 500, businessDays: 2 };
},
dispatchNote(destination) {
return `CASILLERO · ${destination.locker}`;
},
};
export default locker;import { readdirSync } from 'node:fs';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { createRegistry, type MethodRegistry } from './core/method-registry.ts';
import type { ShippingMethod } from './core/shipping-method.ts';
// La alternativa al registro estático: cargar todo lo que haya en una carpeta.
// Agregar una forma de entrega ya no toca ningún archivo existente; a cambio,
// el compilador deja de ver a los plug-ins y el contrato se revisa al arrancar.
function isShippingMethod(value: unknown): value is ShippingMethod {
if (typeof value !== 'object' || value === null) return false;
const method = value as Record<string, unknown>;
return (
typeof method.id === 'string' &&
typeof method.label === 'string' &&
typeof method.validate === 'function' &&
typeof method.quote === 'function' &&
typeof method.dispatchNote === 'function'
);
}
/** Registra el `export default` de cada archivo .ts de la carpeta, en orden alfabético. */
export async function discoverRegistry(pluginsDir: string): Promise<MethodRegistry> {
const files = readdirSync(pluginsDir)
.filter((name) => name.endsWith('.ts') && !name.endsWith('.test.ts'))
.sort();
const methods: ShippingMethod[] = [];
for (const file of files) {
const loaded = (await import(pathToFileURL(join(pluginsDir, file)).href)) as { default?: unknown };
if (!isShippingMethod(loaded.default)) {
throw new Error(`${file} no exporta por omisión una forma de entrega que cumpla el contrato`);
}
methods.push(loaded.default);
}
return createRegistry(methods);
}import { DeliveryError, deliveryOptions, planDelivery, type DeliveryRequest } from './core/checkout.ts';
import type { MethodRegistry } from './core/method-registry.ts';
import { discoverRegistry } from './discover.ts';
import { registry as staticRegistry } from './registry.ts';
// Cotiza el mismo paquete con cada forma de entrega registrada.
//
// node src/main.ts usa el registro estático (src/registry.ts)
// node src/main.ts --discover carga lo que haya en src/plugins/
const soles = (cents: number): string => `S/ ${(cents / 100).toFixed(2)}`;
// Un destino de ejemplo con los campos de todas las formas de entrega: cada
// una lee los suyos y no mira los demás.
const destination = { store: 'miraflores', district: 'Comas', address: 'Av. Túpac Amaru 1234', locker: 'LK-0420' };
const parcel = { weightGrams: 2300, subtotalCents: 9700 };
const registry: MethodRegistry = process.argv.includes('--discover')
? await discoverRegistry(new URL('./plugins/', import.meta.url).pathname)
: staticRegistry;
console.log(`Paquete de ${parcel.weightGrams} g, compra de ${soles(parcel.subtotalCents)}`);
for (const option of deliveryOptions(registry)) {
const request: DeliveryRequest = { methodId: option.id, destination, parcel };
try {
const plan = planDelivery(registry, request);
console.log(
` ${plan.methodId.padEnd(8)} ${plan.label.padEnd(20)} envío ${soles(plan.shippingCents).padStart(8)}` +
` total ${soles(plan.totalCents).padStart(9)} ${plan.businessDays} día(s) [${plan.dispatchNote}]`,
);
} catch (error) {
if (!(error instanceof DeliveryError)) throw error;
console.log(` ${option.id.padEnd(8)} no disponible: ${error.message}`);
}
}import { createRegistry } from './core/method-registry.ts';
import courier from './plugins/courier.ts';
import pickup from './plugins/pickup.ts';
// El registro estático: la lista de formas de entrega que trae la aplicación.
// Es el único archivo que conoce a los plug-ins por su nombre.
export const registry = createRegistry([pickup, courier]);isbn;titulo;categoria;precio;stock
# Lista de precios del distribuidor, segunda quincena
978-612-0001;Yawar fiesta;novela;42,00;6
978-612-0002;Redoble por Rancas;NOVELA;48.50;4
978-612-0003;La casa de cartón;novela;35,00;0
978-612-0004;España, aparta de mí este cáliz;poesia;28,00;9
978-612-0005;Cinco metros de poemas;poesia;31,90;3
978-612-0006;El laberinto de la choledad;ensayo;;5
978-612-0007;Perú: problema y posibilidad;ensayo;39,00;2
978-612-0002;Redoble por Rancas;novela;48,50;4
978-612-0008;Canto ceremonial contra un oso hormiguero;poesia;27,00;-1
978-612-0009;Lima la horrible;ensayo;36,00;7
978-612-0010;Un mundo para Julius;cuento;55,00;2
978-612-0011;País de Jauja;novela;59,00;1;oferta// Los formatos que viajan por los pipes. Es lo único que dos filtros vecinos
// comparten, y por eso es lo que más cuesta cambiar.
/** Una fila del archivo, todavía como texto. `line` es su número de línea en el archivo. */
export type RawRow = {
line: number;
fields: Readonly<Record<string, string>>;
};
export const CATEGORIES = ['novela', 'poesia', 'ensayo'] as const;
export type Category = (typeof CATEGORIES)[number];
/** Un libro listo para cargar al catálogo. */
export type Book = {
isbn: string;
title: string;
category: Category;
priceCents: number;
stock: number;
};
export type Rejection = { line: number; reason: string };import { summarize } from './consumers/summarize.ts';
import { dropDuplicates } from './filters/drop-duplicates.ts';
import { onlyValid } from './filters/only-valid.ts';
import { parseRows } from './filters/parse-rows.ts';
import { toBook } from './filters/to-book.ts';
import type { Rejection } from './formats.ts';
import { from } from './pipe.ts';
import { readLines } from './sources.ts';
// La carga de la lista de precios de un distribuidor:
//
// readLines → parseRows → onlyValid → toBook → dropDuplicates → summarize
//
// node src/main.ts [archivo.csv]
const file = process.argv[2] ?? new URL('../data/supplier-books.csv', import.meta.url).pathname;
const rejected: Rejection[] = [];
const duplicated: string[] = [];
const summary = await from(readLines(file))
.through(parseRows(';'))
.through(onlyValid((rejection) => rejected.push(rejection)))
.through(toBook)
.through(dropDuplicates((book) => duplicated.push(book.isbn)))
.into(summarize);
const soles = (cents: number): string => `S/ ${(cents / 100).toFixed(2)}`;
console.log('categoría títulos ejemplares valor del stock');
for (const row of summary) {
console.log(
`${row.category.padEnd(10)} ${String(row.titles).padStart(7)} ${String(row.copies).padStart(10)} ${soles(row.valueCents).padStart(15)}`,
);
}
console.log(`\nFilas rechazadas: ${rejected.length}`);
for (const { line, reason } of rejected) console.log(` línea ${line}: ${reason}`);
console.log(`ISBN repetidos: ${duplicated.join(', ') || 'ninguno'}`);// Pipes and filters con iteradores asíncronos. Un filtro recibe una secuencia
// y devuelve otra; el pipe es la secuencia misma, que entrega un elemento
// cada vez que el filtro siguiente lo pide.
export type Filter<In, Out> = (input: AsyncIterable<In>) => AsyncIterable<Out>;
export type Consumer<In, Result> = (input: AsyncIterable<In>) => Promise<Result>;
export type Pipeline<T> = {
/** Conecta un filtro. El compilador exige que su entrada sea lo que sale del anterior. */
through<U>(filter: Filter<T, U>): Pipeline<U>;
/** Conecta el consumidor y pone todo en marcha: hasta aquí no se leyó nada. */
into<Result>(consumer: Consumer<T, Result>): Promise<Result>;
};
export function from<T>(source: AsyncIterable<T>): Pipeline<T> {
return {
through: (filter) => from(filter(source)),
into: (consumer) => consumer(source),
};
}import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
// Productores: el comienzo de un pipeline. No reciben nada; solo entregan.
/** Las líneas de un archivo de texto, una por una, sin cargarlo entero en memoria. */
export async function* readLines(path: string): AsyncIterable<string> {
const stream = createReadStream(path, { encoding: 'utf8' });
try {
yield* createInterface({ input: stream, crlfDelay: Infinity });
} finally {
// Si el consumidor deja de pedir antes del final, el archivo igual se cierra.
stream.destroy();
}
}
/** Una secuencia a partir de un arreglo: el productor de las pruebas. */
export async function* fromArray<T>(items: readonly T[]): AsyncIterable<T> {
yield* items;
}diff --git a/src/orders/place-order.ts b/src/orders/place-order.ts
index 623e29f..10a0212 100644
--- a/src/orders/place-order.ts
+++ b/src/orders/place-order.ts
@@ -5,6 +5,7 @@ import { findOrder, insertOrder, sumSalesByProduct } from './repository.ts';
import type { NewOrder, Order, OrderLine, ProductSales } from './types.ts';
export const MAX_ITEMS_PER_ORDER = 5;
+export const MAX_GIFT_NOTE_LENGTH = 140;
function checkItems(order: NewOrder): void {
if (order.items.length < 1 || order.items.length > MAX_ITEMS_PER_ORDER) {
@@ -12,6 +13,9 @@ function checkItems(order: NewOrder): void {
}
const ids = order.items.map((item) => item.productId);
if (new Set(ids).size !== ids.length) throw invalidInput('Una orden no repite un producto');
+ if (order.giftNote !== undefined && order.giftNote.length > MAX_GIFT_NOTE_LENGTH) {
+ throw invalidInput(`La dedicatoria tiene como máximo ${MAX_GIFT_NOTE_LENGTH} caracteres`);
+ }
}
/** Descuenta el stock y guarda la orden, todo o nada. */
@@ -34,7 +38,7 @@ export async function placeOrder(order: NewOrder): Promise<Order> {
unitPriceCents: product.priceCents,
});
}
- return insertOrder(tx, order.buyerEmail, lines);
+ return insertOrder(tx, order.buyerEmail, lines, order.giftNote);
});
}
diff --git a/src/orders/repository.ts b/src/orders/repository.ts
index 04e41b9..722d8f7 100644
--- a/src/orders/repository.ts
+++ b/src/orders/repository.ts
@@ -3,16 +3,21 @@ import type { Order, OrderLine, ProductSales } from './types.ts';
// El único archivo que conoce las tablas del esquema orders.
-type OrderRow = { id: number; buyer_email: string; total_cents: number; created_at: Date };
+type OrderRow = { id: number; buyer_email: string; total_cents: number; created_at: Date; gift_note: string | null };
type LineRow = { product_id: number; title: string; quantity: number; unit_price_cents: number };
type SalesRow = { product_id: number; units: number; revenue_cents: number };
-export async function insertOrder(tx: Tx, buyerEmail: string, lines: OrderLine[]): Promise<Order> {
+export async function insertOrder(
+ tx: Tx,
+ buyerEmail: string,
+ lines: OrderLine[],
+ giftNote?: string,
+): Promise<Order> {
const totalCents = lines.reduce((sum, line) => sum + line.quantity * line.unitPriceCents, 0);
const inserted = await tx.query<OrderRow>(
- `INSERT INTO orders.orders (buyer_email, total_cents) VALUES ($1, $2)
- RETURNING id, buyer_email, total_cents, created_at`,
- [buyerEmail, totalCents],
+ `INSERT INTO orders.orders (buyer_email, total_cents, gift_note) VALUES ($1, $2, $3)
+ RETURNING id, buyer_email, total_cents, created_at, gift_note`,
+ [buyerEmail, totalCents, giftNote ?? null],
);
const order = inserted.rows[0]!;
for (const line of lines) {
@@ -27,13 +32,14 @@ export async function insertOrder(tx: Tx, buyerEmail: string, lines: OrderLine[]
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
+ giftNote: order.gift_note ?? undefined,
lines,
};
}
export async function findOrder(id: number): Promise<Order | undefined> {
const orders = await query<OrderRow>(
- 'SELECT id, buyer_email, total_cents, created_at FROM orders.orders WHERE id = $1',
+ 'SELECT id, buyer_email, total_cents, created_at, gift_note FROM orders.orders WHERE id = $1',
[id],
);
const order = orders[0];
@@ -50,6 +56,7 @@ export async function findOrder(id: number): Promise<Order | undefined> {
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
+ giftNote: order.gift_note ?? undefined,
lines: lines.map((line) => ({
productId: line.product_id,
title: line.title,
diff --git a/src/orders/routes.ts b/src/orders/routes.ts
index 5fbc642..bb91769 100644
--- a/src/orders/routes.ts
+++ b/src/orders/routes.ts
@@ -26,7 +26,10 @@ function parseNewOrder(body: unknown): NewOrder {
throw invalidInput('buyerEmail no es un correo válido');
}
if (!Array.isArray(body.items)) throw invalidInput('items debe ser una lista');
- return { buyerEmail: body.buyerEmail.toLowerCase(), items: body.items.map(parseItem) };
+ if (body.giftNote !== undefined && typeof body.giftNote !== 'string') {
+ throw invalidInput('giftNote debe ser un texto');
+ }
+ return { buyerEmail: body.buyerEmail.toLowerCase(), items: body.items.map(parseItem), giftNote: body.giftNote };
}
export const ordersRoutes: Route[] = [
diff --git a/src/orders/types.ts b/src/orders/types.ts
index ea0c281..9cd9464 100644
--- a/src/orders/types.ts
+++ b/src/orders/types.ts
@@ -3,6 +3,7 @@ export type OrderItem = { productId: number; quantity: number };
export type NewOrder = {
buyerEmail: string;
items: OrderItem[];
+ giftNote?: string;
};
export type OrderLine = {
@@ -17,6 +18,7 @@ export type Order = {
buyerEmail: string;
totalCents: number;
createdAt: string;
+ giftNote?: string;
lines: OrderLine[];
};
diff --git a/src/db/order-repository.ts b/src/db/order-repository.ts
index e9d7f51..3f53b48 100644
--- a/src/db/order-repository.ts
+++ b/src/db/order-repository.ts
@@ -1,15 +1,20 @@
import type { Order, OrderLine } from '../types.ts';
import { query, type Tx } from './pool.ts';
-type OrderRow = { id: number; buyer_email: string; total_cents: number; created_at: Date };
+type OrderRow = { id: number; buyer_email: string; total_cents: number; created_at: Date; gift_note: string | null };
type LineRow = { product_id: number; title: string; quantity: number; unit_price_cents: number };
-export async function insertOrder(tx: Tx, buyerEmail: string, lines: OrderLine[]): Promise<Order> {
+export async function insertOrder(
+ tx: Tx,
+ buyerEmail: string,
+ lines: OrderLine[],
+ giftNote?: string,
+): Promise<Order> {
const totalCents = lines.reduce((sum, line) => sum + line.quantity * line.unitPriceCents, 0);
const inserted = await tx.query<OrderRow>(
- `INSERT INTO orders (buyer_email, total_cents) VALUES ($1, $2)
- RETURNING id, buyer_email, total_cents, created_at`,
- [buyerEmail, totalCents],
+ `INSERT INTO orders (buyer_email, total_cents, gift_note) VALUES ($1, $2, $3)
+ RETURNING id, buyer_email, total_cents, created_at, gift_note`,
+ [buyerEmail, totalCents, giftNote ?? null],
);
const order = inserted.rows[0]!;
for (const line of lines) {
@@ -23,14 +28,16 @@ export async function insertOrder(tx: Tx, buyerEmail: string, lines: OrderLine[]
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
+ giftNote: order.gift_note ?? undefined,
lines,
};
}
export async function findOrder(id: number): Promise<Order | undefined> {
- const orders = await query<OrderRow>('SELECT id, buyer_email, total_cents, created_at FROM orders WHERE id = $1', [
- id,
- ]);
+ const orders = await query<OrderRow>(
+ 'SELECT id, buyer_email, total_cents, created_at, gift_note FROM orders WHERE id = $1',
+ [id],
+ );
const order = orders[0];
if (!order) return undefined;
// El título no se guarda en la línea: se trae del producto con un JOIN.
@@ -47,6 +54,7 @@ export async function findOrder(id: number): Promise<Order | undefined> {
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
+ giftNote: order.gift_note ?? undefined,
lines: lines.map((line) => ({
productId: line.product_id,
title: line.title,
diff --git a/src/http/order-handlers.ts b/src/http/order-handlers.ts
index 402727f..246916d 100644
--- a/src/http/order-handlers.ts
+++ b/src/http/order-handlers.ts
@@ -29,7 +29,10 @@ function parseNewOrder(body: unknown): NewOrder {
throw invalidInput('buyerEmail no es un correo válido');
}
if (!Array.isArray(body.items)) throw invalidInput('items debe ser una lista');
- return { buyerEmail: body.buyerEmail.toLowerCase(), items: body.items.map(parseItem) };
+ if (body.giftNote !== undefined && typeof body.giftNote !== 'string') {
+ throw invalidInput('giftNote debe ser un texto');
+ }
+ return { buyerEmail: body.buyerEmail.toLowerCase(), items: body.items.map(parseItem), giftNote: body.giftNote };
}
export const placeOrderHandler: Handler = async ({ body }) => {
diff --git a/src/services/order-service.ts b/src/services/order-service.ts
index a8e0143..b0fefc7 100644
--- a/src/services/order-service.ts
+++ b/src/services/order-service.ts
@@ -5,6 +5,7 @@ import { invalidInput, notFound, outOfStock } from '../errors.ts';
import type { NewOrder, Order, OrderLine } from '../types.ts';
export const MAX_ITEMS_PER_ORDER = 5;
+export const MAX_GIFT_NOTE_LENGTH = 140;
function checkItems(order: NewOrder): void {
if (order.items.length < 1 || order.items.length > MAX_ITEMS_PER_ORDER) {
@@ -12,6 +13,9 @@ function checkItems(order: NewOrder): void {
}
const ids = order.items.map((item) => item.productId);
if (new Set(ids).size !== ids.length) throw invalidInput('Una orden no repite un producto');
+ if (order.giftNote !== undefined && order.giftNote.length > MAX_GIFT_NOTE_LENGTH) {
+ throw invalidInput(`La dedicatoria tiene como máximo ${MAX_GIFT_NOTE_LENGTH} caracteres`);
+ }
}
/** Descuenta el stock y guarda la orden, todo o nada. */
@@ -35,7 +39,7 @@ export async function placeOrder(order: NewOrder): Promise<Order> {
unitPriceCents: product.priceCents,
});
}
- return insertOrder(tx, order.buyerEmail, lines);
+ return insertOrder(tx, order.buyerEmail, lines, order.giftNote);
});
}
diff --git a/src/types.ts b/src/types.ts
index 75005dd..560375e 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -16,6 +16,7 @@ export type OrderItem = { productId: number; quantity: number };
export type NewOrder = {
buyerEmail: string;
items: OrderItem[];
+ giftNote?: string;
};
export type OrderLine = {
@@ -30,6 +31,7 @@ export type Order = {
buyerEmail: string;
totalCents: number;
createdAt: string;
+ giftNote?: string;
lines: OrderLine[];
};
import assert from 'node:assert/strict';
import type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
// Comprueba el cambio de ejemplo (una dedicatoria en la orden) sobre una copia
// de Qhatu que ya lo tiene aplicado. Lo usa `make cambio`:
//
// node gift-note.check.ts <ruta del módulo con createServer> <ruta del módulo con closePool>
const [serverModule, poolModule] = process.argv.slice(2);
if (!serverModule || !poolModule) throw new Error('Faltan las rutas de los dos módulos');
const { createServer } = (await import(serverModule)) as { createServer: () => Server };
const { closePool } = (await import(poolModule)) as { closePool: () => Promise<void> };
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const post = (payload: unknown): Promise<Response> =>
fetch(`${url}/orders`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
});
try {
const items = [{ productId: 5, quantity: 1 }];
const created = await post({ buyerEmail: 'rosa.quispe@correo.pe', items, giftNote: 'Para Julia, con cariño' });
assert.equal(created.status, 201);
const { order } = (await created.json()) as { order: { id: number; giftNote?: string } };
assert.equal(order.giftNote, 'Para Julia, con cariño');
const fetched = await fetch(`${url}/orders/${order.id}`);
const body = (await fetched.json()) as { order: { giftNote?: string } };
assert.equal(body.order.giftNote, 'Para Julia, con cariño');
const tooLong = await post({ buyerEmail: 'rosa.quispe@correo.pe', items, giftNote: 'x'.repeat(141) });
assert.equal(tooLong.status, 422);
const without = await post({ buyerEmail: 'rosa.quispe@correo.pe', items });
assert.equal(without.status, 201);
console.log('dedicatoria: se guarda, se muestra, se valida y sigue siendo opcional');
} finally {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
await closePool();
}-- La columna nueva del cambio de ejemplo. La tabla se pasa con
-- psql -v orders=..., como en seed.sql.
ALTER TABLE :orders ADD COLUMN gift_note text;-- Qhatu organizada por capas: todas las tablas en un solo esquema. Cualquier
-- archivo de src/db puede leer cualquier tabla.
CREATE TABLE products (
id integer PRIMARY KEY,
title text NOT NULL,
category text NOT NULL CHECK (category IN ('novela', 'poesia', 'ensayo')),
price_cents integer NOT NULL CHECK (price_cents > 0),
stock integer NOT NULL CHECK (stock >= 0)
);
CREATE TABLE orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
buyer_email text NOT NULL,
total_cents integer NOT NULL CHECK (total_cents > 0),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE order_lines (
order_id integer NOT NULL REFERENCES orders (id),
product_id integer NOT NULL REFERENCES products (id),
quantity integer NOT NULL CHECK (quantity > 0),
unit_price_cents integer NOT NULL CHECK (unit_price_cents > 0),
PRIMARY KEY (order_id, product_id)
);-- Qhatu organizada por dominio: un esquema de PostgreSQL por módulo. Las
-- tablas de un esquema solo las lee y las escribe el repository.ts de su
-- módulo; el módulo de reportes no tiene tablas.
CREATE SCHEMA catalog;
CREATE SCHEMA orders;
CREATE TABLE catalog.products (
id integer PRIMARY KEY,
title text NOT NULL,
category text NOT NULL CHECK (category IN ('novela', 'poesia', 'ensayo')),
price_cents integer NOT NULL CHECK (price_cents > 0),
stock integer NOT NULL CHECK (stock >= 0)
);
CREATE TABLE orders.orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
buyer_email text NOT NULL,
total_cents integer NOT NULL CHECK (total_cents > 0),
created_at timestamptz NOT NULL DEFAULT now()
);
-- product_id guarda el id de un producto del catálogo, pero no hay llave
-- foránea hacia catalog.products: una restricción que cruza dos esquemas
-- ataría las tablas de un módulo a las del otro. El título y el precio se
-- copian al momento de la venta: son los de ese día, aunque el catálogo cambie.
CREATE TABLE orders.order_lines (
order_id integer NOT NULL REFERENCES orders.orders (id),
product_id integer NOT NULL,
title text NOT NULL,
quantity integer NOT NULL CHECK (quantity > 0),
unit_price_cents integer NOT NULL CHECK (unit_price_cents > 0),
PRIMARY KEY (order_id, product_id)
);-- Los mismos ocho libros para las dos versiones. La tabla se pasa con
-- psql -v products=..., porque en una versión se llama products y en la otra
-- catalog.products.
INSERT INTO :products (id, title, category, price_cents, stock) VALUES
(1, 'Los ríos profundos', 'novela', 4500, 12),
(2, 'La ciudad y los perros', 'novela', 5200, 8),
(3, 'El mundo es ancho y ajeno', 'novela', 4900, 5),
(4, 'Trilce', 'poesia', 3200, 10),
(5, 'Los heraldos negros', 'poesia', 2900, 7),
(6, 'Poemas humanos', 'poesia', 3400, 3),
(7, 'Siete ensayos', 'ensayo', 3900, 6),
(8, 'Tradiciones peruanas', 'ensayo', 4100, 1);// Eventos dentro del proceso: la otra forma en que dos módulos de un monolito
// se comunican. Quien publica no importa a quien escucha; los dos conocen
// solo este archivo y la forma del evento.
export type OrderPlaced = {
type: 'OrderPlaced';
orderId: number;
lines: { productId: number; quantity: number; unitPriceCents: number }[];
};
export type ShopEvent = OrderPlaced;
export type Subscriber = (event: ShopEvent) => void | Promise<void>;
export type EventBus = {
subscribe(type: ShopEvent['type'], subscriber: Subscriber): void;
/** Entrega el evento a cada suscriptor, uno tras otro, y devuelve los errores que hubo. */
publish(event: ShopEvent): Promise<unknown[]>;
};
export function createEventBus(): EventBus {
const subscribers = new Map<string, Subscriber[]>();
return {
subscribe(type, subscriber) {
subscribers.set(type, [...(subscribers.get(type) ?? []), subscriber]);
},
async publish(event) {
const errors: unknown[] = [];
for (const subscriber of subscribers.get(event.type) ?? []) {
try {
await subscriber(event);
} catch (error) {
// Un suscriptor que falla no le impide escuchar a los demás ni tumba a quien publicó.
errors.push(error);
}
}
return errors;
},
};
}import type { MethodRegistry } from './method-registry.ts';
import type { Destination, Parcel } from './shipping-method.ts';
// El núcleo: arma el plan de entrega de un pedido. Aquí no hay ningún `if`
// que pregunte por una forma de entrega concreta.
export type DeliveryRequest = {
methodId: string;
destination: Destination;
parcel: Parcel;
};
export type DeliveryPlan = {
methodId: string;
label: string;
shippingCents: number;
totalCents: number;
businessDays: number;
dispatchNote: string;
};
export class DeliveryError extends Error {
readonly problems: readonly string[];
constructor(problems: readonly string[]) {
super(problems.join('; '));
this.problems = problems;
}
}
/** Las formas de entrega que se le ofrecen al comprador. */
export function deliveryOptions(registry: MethodRegistry): { id: string; label: string }[] {
return registry.all().map((method) => ({ id: method.id, label: method.label }));
}
export function planDelivery(registry: MethodRegistry, request: DeliveryRequest): DeliveryPlan {
const method = registry.get(request.methodId);
if (!method) {
const known = registry.all().map((each) => each.id);
throw new DeliveryError([`Forma de entrega desconocida: ${request.methodId} (hay: ${known.join(', ')})`]);
}
const problems = method.validate(request.destination);
if (problems.length > 0) throw new DeliveryError(problems);
const quote = method.quote(request.parcel, request.destination);
// El núcleo no confía a ciegas en un plug-in: lo que devuelve tiene que ser un costo y un plazo.
if (!Number.isInteger(quote.costCents) || quote.costCents < 0 || quote.businessDays < 1) {
throw new Error(`La forma de entrega ${method.id} devolvió una cotización no válida`);
}
return {
methodId: method.id,
label: method.label,
shippingCents: quote.costCents,
totalCents: request.parcel.subtotalCents + quote.costCents,
businessDays: quote.businessDays,
dispatchNote: method.dispatchNote(request.destination),
};
}import type { ShippingMethod } from './shipping-method.ts';
// El registro: dónde se inscriben las formas de entrega y dónde las busca el
// núcleo. No conoce ninguna en particular.
export type MethodRegistry = {
get(id: string): ShippingMethod | undefined;
all(): readonly ShippingMethod[];
};
const VALID_ID = /^[a-z][a-z0-9-]*$/;
export function createRegistry(methods: readonly ShippingMethod[]): MethodRegistry {
const byId = new Map<string, ShippingMethod>();
for (const method of methods) {
if (!VALID_ID.test(method.id)) throw new Error(`Id de forma de entrega no válido: "${method.id}"`);
if (byId.has(method.id)) throw new Error(`Forma de entrega registrada dos veces: "${method.id}"`);
byId.set(method.id, method);
}
return {
get: (id) => byId.get(id),
all: () => [...byId.values()],
};
}// El contrato: lo único que el núcleo sabe de una forma de entrega, y lo
// único del núcleo que una forma de entrega puede importar.
/** El paquete que se va a enviar. */
export type Parcel = {
weightGrams: number;
subtotalCents: number;
};
/**
* Los datos de destino que escribió el comprador, como campos de texto. Cada
* forma de entrega pide los suyos (una tienda, una dirección, un casillero);
* el núcleo los transporta sin mirarlos.
*/
export type Destination = Readonly<Record<string, string>>;
export type Quote = {
costCents: number;
businessDays: number;
};
export interface ShippingMethod {
/** Identificador estable, en minúsculas: es lo que llega en el pedido. */
readonly id: string;
/** El nombre que ve el comprador. */
readonly label: string;
/** Los problemas del destino, en español; una lista vacía quiere decir que es válido. */
validate(destination: Destination): string[];
/** Costo y plazo. El núcleo solo la llama con un destino que pasó validate. */
quote(parcel: Parcel, destination: Destination): Quote;
/** La línea que se imprime en la etiqueta del paquete. Igual: solo con un destino válido. */
dispatchNote(destination: Destination): string;
}import type { ShippingMethod } from '../core/shipping-method.ts';
// Envío a domicilio: la tarifa depende de la zona del distrito y del peso.
// Desde S/ 150 de compra, el envío es gratis.
const ZONE_OF_DISTRICT: Readonly<Record<string, 1 | 2>> = {
lima: 1,
breña: 1,
miraflores: 1,
'san isidro': 1,
comas: 2,
'san juan de lurigancho': 2,
'villa el salvador': 2,
};
const BASE_CENTS = { 1: 800, 2: 1200 } as const;
const BUSINESS_DAYS = { 1: 2, 2: 3 } as const;
const EXTRA_KG_CENTS = 200;
const FREE_SHIPPING_FROM_CENTS = 15000;
const zoneOf = (district: string | undefined): 1 | 2 | undefined =>
ZONE_OF_DISTRICT[(district ?? '').trim().toLowerCase()];
const courier: ShippingMethod = {
id: 'courier',
label: 'Envío a domicilio',
validate(destination) {
const problems: string[] = [];
if (zoneOf(destination.district) === undefined) {
problems.push(`No hacemos envíos a domicilio al distrito "${destination.district ?? ''}"`);
}
if ((destination.address ?? '').trim().length < 5) problems.push('address debe ser la dirección de entrega');
return problems;
},
quote(parcel, destination) {
const zone = zoneOf(destination.district)!;
if (parcel.subtotalCents >= FREE_SHIPPING_FROM_CENTS) return { costCents: 0, businessDays: BUSINESS_DAYS[zone] };
// El primer kilo va en la tarifa base; cada kilo adicional, o fracción, se cobra aparte.
const extraKg = Math.max(0, Math.ceil(parcel.weightGrams / 1000) - 1);
return { costCents: BASE_CENTS[zone] + extraKg * EXTRA_KG_CENTS, businessDays: BUSINESS_DAYS[zone] };
},
dispatchNote(destination) {
return `DOMICILIO · ${(destination.address ?? '').trim()}, ${(destination.district ?? '').trim()}`;
},
};
export default courier;import type { ShippingMethod } from '../core/shipping-method.ts';
// Recojo en tienda: gratis, al día siguiente, en una de las dos tiendas.
const STORES: Readonly<Record<string, string>> = {
centro: 'Jr. Camaná 615, Lima',
miraflores: 'Av. Larco 345, Miraflores',
};
const pickup: ShippingMethod = {
id: 'pickup',
label: 'Recojo en tienda',
validate(destination) {
const store = destination.store ?? '';
return store in STORES ? [] : [`store debe ser una de: ${Object.keys(STORES).join(', ')}`];
},
quote() {
return { costCents: 0, businessDays: 1 };
},
dispatchNote(destination) {
return `RECOJO EN TIENDA · ${STORES[destination.store ?? '']}`;
},
};
export default pickup;/** Consumidor: junta todo en un arreglo. */
export async function collect<T>(input: AsyncIterable<T>): Promise<T[]> {
const items: T[] = [];
for await (const item of input) items.push(item);
return items;
}import { CATEGORIES, type Book, type Category } from '../formats.ts';
export type CategorySummary = {
category: Category;
titles: number;
copies: number;
valueCents: number;
};
/** Consumidor: cuántos títulos, cuántos ejemplares y cuánto vale el stock de cada categoría. */
export async function summarize(books: AsyncIterable<Book>): Promise<CategorySummary[]> {
const totals = new Map<Category, CategorySummary>(
CATEGORIES.map((category) => [category, { category, titles: 0, copies: 0, valueCents: 0 }]),
);
for await (const book of books) {
const total = totals.get(book.category)!;
total.titles += 1;
total.copies += book.stock;
total.valueCents += book.stock * book.priceCents;
}
return [...totals.values()];
}import type { Filter } from '../pipe.ts';
import type { Book } from '../formats.ts';
/**
* Verificador con memoria: deja pasar la primera aparición de cada ISBN. A
* diferencia de los otros, recuerda lo que ya vio, así que su resultado
* depende de lo que tenga antes en el pipeline.
*/
export function dropDuplicates(onDuplicate: (book: Book) => void = () => {}): Filter<Book, Book> {
return async function* (books) {
const seen = new Set<string>();
for await (const book of books) {
if (seen.has(book.isbn)) {
onDuplicate(book);
continue;
}
seen.add(book.isbn);
yield book;
}
};
}import type { Filter } from '../pipe.ts';
import { CATEGORIES, type Category, type RawRow, type Rejection } from '../formats.ts';
export const PRICE = /^(\d+)(?:[.,](\d{2}))?$/;
const EXPECTED_FIELDS = ['isbn', 'titulo', 'categoria', 'precio', 'stock'];
/** Por qué no se puede cargar una fila, o undefined si se puede. */
export function problemOf(row: RawRow): string | undefined {
const { fields } = row;
const extra = Object.keys(fields).filter((name) => !EXPECTED_FIELDS.includes(name));
if (extra.length > 0) return `tiene ${extra.length} campo(s) de más`;
for (const name of EXPECTED_FIELDS) {
if ((fields[name] ?? '') === '') return `falta ${name}`;
}
if (!CATEGORIES.includes(fields.categoria!.toLowerCase() as Category)) {
return `categoría desconocida: ${fields.categoria}`;
}
if (!PRICE.test(fields.precio!)) return `precio no válido: ${fields.precio}`;
if (!/^\d+$/.test(fields.stock!)) return `stock no válido: ${fields.stock}`;
return undefined;
}
/**
* Verificador: deja pasar las filas que se pueden cargar y descarta las
* demás. Lo descartado no desaparece en silencio: se le avisa a `onReject`.
*/
export function onlyValid(onReject: (rejection: Rejection) => void = () => {}): Filter<RawRow, RawRow> {
return async function* (rows) {
for await (const row of rows) {
const reason = problemOf(row);
if (reason === undefined) yield row;
else onReject({ line: row.line, reason });
}
};
}import type { Filter } from '../pipe.ts';
import type { Book, Category } from '../formats.ts';
// Verificadores sin memoria: cada libro pasa o no pasa por lo que es.
export const onlyInStock: Filter<Book, Book> = async function* (books) {
for await (const book of books) if (book.stock > 0) yield book;
};
export function onlyCategory(category: Category): Filter<Book, Book> {
return async function* (books) {
for await (const book of books) if (book.category === category) yield book;
};
}
/** Deja pasar los primeros `limit` elementos y deja de pedir. Sirve para cualquier tipo. */
export function take<T>(limit: number): Filter<T, T> {
return async function* (items) {
if (limit <= 0) return;
let taken = 0;
for await (const item of items) {
yield item;
taken += 1;
if (taken >= limit) return;
}
};
}import type { Filter } from '../pipe.ts';
import type { RawRow } from '../formats.ts';
/**
* Transformador: de líneas de texto a filas con nombre de campo. La primera
* línea con contenido es el encabezado; las líneas vacías y las que empiezan
* con # no producen nada. No decide si una fila es válida: solo la separa.
*/
export function parseRows(separator = ';'): Filter<string, RawRow> {
return async function* (lines) {
let header: string[] | undefined;
let line = 0;
for await (const text of lines) {
line += 1;
if (text.trim() === '' || text.startsWith('#')) continue;
const cells = text.split(separator).map((cell) => cell.trim());
if (!header) {
header = cells;
continue;
}
const fields: Record<string, string> = {};
// Las celdas que sobran se guardan con su posición, para que el verificador las vea.
cells.forEach((cell, i) => (fields[header![i] ?? `#${i + 1}`] = cell));
yield { line, fields };
}
};
}import type { Filter } from '../pipe.ts';
import type { Book, Category, RawRow } from '../formats.ts';
import { PRICE } from './only-valid.ts';
/** "42,00" o "48.50" a céntimos, con aritmética de enteros. */
export function parsePriceCents(text: string): number {
const match = PRICE.exec(text);
if (!match) throw new Error(`Precio no válido: ${text}`);
return Number(match[1]) * 100 + Number(match[2] ?? '0');
}
/** Transformador: de una fila válida a un libro, con la categoría en minúsculas y el precio en céntimos. */
export const toBook: Filter<RawRow, Book> = async function* (rows) {
for await (const { fields } of rows) {
yield {
isbn: fields.isbn!,
title: fields.titulo!,
category: fields.categoria!.toLowerCase() as Category,
priceCents: parsePriceCents(fields.precio!),
stock: Number(fields.stock),
};
}
};import type { Server } from 'node:http';
import { catalogRoutes } from './catalog/index.ts';
import { ordersRoutes } from './orders/index.ts';
import { createApp } from './platform/http.ts';
import { reportsRoutes } from './reports/index.ts';
// Aquí se arma la aplicación: cada módulo aporta sus rutas.
export function createServer(): Server {
return createApp([...catalogRoutes, ...ordersRoutes, ...reportsRoutes]);
}import { createServer } from './app.ts';
import { closePool } from './platform/db.ts';
const port = Number(process.env.PORT ?? 3200);
const server = createServer();
server.listen(port, () => console.log(`Qhatu (por dominio) en http://localhost:${port}`));
process.on('SIGINT', () => {
server.close(() => void closePool());
});// Los errores que la API sabe explicar: cada uno lleva su código HTTP.
export class AppError extends Error {
readonly status: number;
readonly code: string;
constructor(status: number, code: string, message: string) {
super(message);
this.status = status;
this.code = code;
}
}
export const invalidInput = (message: string): AppError => new AppError(422, 'INVALID_INPUT', message);
export const notFound = (what: string): AppError => new AppError(404, 'NOT_FOUND', `No existe ${what}`);
export const outOfStock = (title: string): AppError =>
new AppError(409, 'OUT_OF_STOCK', `No hay suficientes ejemplares de ${title}`);import { closePool } from './db/pool.ts';
import { createServer } from './http/server.ts';
const port = Number(process.env.PORT ?? 3100);
const server = createServer();
server.listen(port, () => console.log(`Qhatu (por capas) en http://localhost:${port}`));
process.on('SIGINT', () => {
server.close(() => void closePool());
});// El modelo que comparten las tres capas.
export const CATEGORIES = ['novela', 'poesia', 'ensayo'] as const;
export type Category = (typeof CATEGORIES)[number];
export type Product = {
id: number;
title: string;
category: Category;
priceCents: number;
stock: number;
};
export type OrderItem = { productId: number; quantity: number };
export type NewOrder = {
buyerEmail: string;
items: OrderItem[];
};
export type OrderLine = {
productId: number;
title: string;
quantity: number;
unitPriceCents: number;
};
export type Order = {
id: number;
buyerEmail: string;
totalCents: number;
createdAt: string;
lines: OrderLine[];
};
export type CategorySales = {
category: Category;
units: number;
revenueCents: number;
};// Catálogo: los libros, sus precios y su stock.
// Esto es todo lo que otro módulo puede usar de catalog.
export { getProducts, takeStock } from './products.ts';
export { catalogRoutes } from './routes.ts';
export { CATEGORIES } from './types.ts';
export type { Category, Product } from './types.ts';import { notFound, outOfStock } from '../platform/errors.ts';
import type { Tx } from '../platform/transaction.ts';
import { decrementStock, findProducts, findProductsByIds } from './repository.ts';
import type { Category, Product } from './types.ts';
export async function listProducts(category?: Category): Promise<Product[]> {
return findProducts(category);
}
/** Los productos con esos ids. Los ids que no existen simplemente no vienen. */
export async function getProducts(ids: number[]): Promise<Product[]> {
return ids.length === 0 ? [] : findProductsByIds(ids);
}
/**
* Aparta `quantity` ejemplares dentro de la transacción de quien llama y
* devuelve el producto con el precio de ese momento. Lanza 404 si el producto
* no existe y 409 si no alcanza el stock.
*/
export async function takeStock(tx: Tx, productId: number, quantity: number): Promise<Product> {
const taken = await decrementStock(tx, productId, quantity);
if (taken) return taken;
const [product] = await findProductsByIds([productId]);
if (!product) throw notFound(`el producto ${productId}`);
throw outOfStock(product.title);
}import { query, type Tx } from '../platform/db.ts';
import type { Category, Product } from './types.ts';
// El único archivo que conoce las tablas del esquema catalog.
type ProductRow = { id: number; title: string; category: Category; price_cents: number; stock: number };
const toProduct = (row: ProductRow): Product => ({
id: row.id,
title: row.title,
category: row.category,
priceCents: row.price_cents,
stock: row.stock,
});
export async function findProducts(category?: Category): Promise<Product[]> {
const rows = await query<ProductRow>(
`SELECT id, title, category, price_cents, stock
FROM catalog.products
WHERE $1::text IS NULL OR category = $1
ORDER BY id`,
[category ?? null],
);
return rows.map(toProduct);
}
export async function findProductsByIds(ids: number[]): Promise<Product[]> {
const rows = await query<ProductRow>(
`SELECT id, title, category, price_cents, stock
FROM catalog.products
WHERE id = ANY($1::int[])
ORDER BY id`,
[ids],
);
return rows.map(toProduct);
}
/** Descuenta el stock si alcanza y devuelve el producto; si no alcanza o no existe, undefined. */
export async function decrementStock(tx: Tx, id: number, quantity: number): Promise<Product | undefined> {
const result = await tx.query<ProductRow>(
`UPDATE catalog.products SET stock = stock - $2
WHERE id = $1 AND stock >= $2
RETURNING id, title, category, price_cents, stock`,
[id, quantity],
);
const row = result.rows[0];
return row ? toProduct(row) : undefined;
}import { invalidInput } from '../platform/errors.ts';
import type { Route } from '../platform/http.ts';
import { listProducts } from './products.ts';
import { CATEGORIES, type Category } from './types.ts';
export const catalogRoutes: Route[] = [
{
method: 'GET',
path: '/products',
handler: async ({ query }) => {
const category = query.get('category') ?? undefined;
if (category !== undefined && !CATEGORIES.includes(category as Category)) {
throw invalidInput(`category debe ser una de: ${CATEGORIES.join(', ')}`);
}
return { status: 200, body: { products: await listProducts(category as Category | undefined) } };
},
},
];export const CATEGORIES = ['novela', 'poesia', 'ensayo'] as const;
export type Category = (typeof CATEGORIES)[number];
export type Product = {
id: number;
title: string;
category: Category;
priceCents: number;
stock: number;
};// Órdenes: la compra y lo que se vendió.
// Esto es todo lo que otro módulo puede usar de orders.
export { salesByProduct } from './place-order.ts';
export { ordersRoutes } from './routes.ts';
export type { NewOrder, Order, OrderItem, OrderLine, ProductSales } from './types.ts';import { takeStock } from '../catalog/index.ts';
import { invalidInput, notFound } from '../platform/errors.ts';
import { inTransaction } from '../platform/transaction.ts';
import { findOrder, insertOrder, sumSalesByProduct } from './repository.ts';
import type { NewOrder, Order, OrderLine, ProductSales } from './types.ts';
export const MAX_ITEMS_PER_ORDER = 5;
function checkItems(order: NewOrder): void {
if (order.items.length < 1 || order.items.length > MAX_ITEMS_PER_ORDER) {
throw invalidInput(`Una orden lleva entre 1 y ${MAX_ITEMS_PER_ORDER} productos distintos`);
}
const ids = order.items.map((item) => item.productId);
if (new Set(ids).size !== ids.length) throw invalidInput('Una orden no repite un producto');
}
/** Descuenta el stock y guarda la orden, todo o nada. */
export async function placeOrder(order: NewOrder): Promise<Order> {
checkItems(order);
// Siempre en el mismo orden de producto: dos órdenes simultáneas con los
// mismos libros no pueden quedar esperándose una a la otra.
const items = [...order.items].sort((a, b) => a.productId - b.productId);
return inTransaction(async (tx) => {
const lines: OrderLine[] = [];
for (const item of items) {
// El stock es de catalog: se le pide por su interfaz, dentro de esta
// misma transacción. El título y el precio se copian a la línea.
const product = await takeStock(tx, item.productId, item.quantity);
lines.push({
productId: product.id,
title: product.title,
quantity: item.quantity,
unitPriceCents: product.priceCents,
});
}
return insertOrder(tx, order.buyerEmail, lines);
});
}
export async function getOrder(id: number): Promise<Order> {
const order = await findOrder(id);
if (!order) throw notFound(`la orden ${id}`);
return order;
}
export async function salesByProduct(): Promise<ProductSales[]> {
return sumSalesByProduct();
}import { query, type Tx } from '../platform/db.ts';
import type { Order, OrderLine, ProductSales } from './types.ts';
// El único archivo que conoce las tablas del esquema orders.
type OrderRow = { id: number; buyer_email: string; total_cents: number; created_at: Date };
type LineRow = { product_id: number; title: string; quantity: number; unit_price_cents: number };
type SalesRow = { product_id: number; units: number; revenue_cents: number };
export async function insertOrder(tx: Tx, buyerEmail: string, lines: OrderLine[]): Promise<Order> {
const totalCents = lines.reduce((sum, line) => sum + line.quantity * line.unitPriceCents, 0);
const inserted = await tx.query<OrderRow>(
`INSERT INTO orders.orders (buyer_email, total_cents) VALUES ($1, $2)
RETURNING id, buyer_email, total_cents, created_at`,
[buyerEmail, totalCents],
);
const order = inserted.rows[0]!;
for (const line of lines) {
await tx.query(
`INSERT INTO orders.order_lines (order_id, product_id, title, quantity, unit_price_cents)
VALUES ($1, $2, $3, $4, $5)`,
[order.id, line.productId, line.title, line.quantity, line.unitPriceCents],
);
}
return {
id: order.id,
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
lines,
};
}
export async function findOrder(id: number): Promise<Order | undefined> {
const orders = await query<OrderRow>(
'SELECT id, buyer_email, total_cents, created_at FROM orders.orders WHERE id = $1',
[id],
);
const order = orders[0];
if (!order) return undefined;
const lines = await query<LineRow>(
`SELECT product_id, title, quantity, unit_price_cents
FROM orders.order_lines
WHERE order_id = $1
ORDER BY product_id`,
[id],
);
return {
id: order.id,
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
lines: lines.map((line) => ({
productId: line.product_id,
title: line.title,
quantity: line.quantity,
unitPriceCents: line.unit_price_cents,
})),
};
}
export async function sumSalesByProduct(): Promise<ProductSales[]> {
const rows = await query<SalesRow>(
`SELECT product_id,
sum(quantity)::int AS units,
sum(quantity * unit_price_cents)::int AS revenue_cents
FROM orders.order_lines
GROUP BY product_id
ORDER BY product_id`,
);
return rows.map((row) => ({ productId: row.product_id, units: row.units, revenueCents: row.revenue_cents }));
}import { invalidInput } from '../platform/errors.ts';
import type { Route } from '../platform/http.ts';
import { getOrder, placeOrder } from './place-order.ts';
import type { NewOrder, OrderItem } from './types.ts';
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isPositiveInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value) && value > 0;
}
function parseItem(value: unknown): OrderItem {
if (!isRecord(value) || !isPositiveInteger(value.productId) || !isPositiveInteger(value.quantity)) {
throw invalidInput('Cada ítem lleva productId y quantity, enteros positivos');
}
return { productId: value.productId, quantity: value.quantity };
}
function parseNewOrder(body: unknown): NewOrder {
if (!isRecord(body)) throw invalidInput('El cuerpo debe ser un objeto JSON');
if (typeof body.buyerEmail !== 'string' || !EMAIL.test(body.buyerEmail)) {
throw invalidInput('buyerEmail no es un correo válido');
}
if (!Array.isArray(body.items)) throw invalidInput('items debe ser una lista');
return { buyerEmail: body.buyerEmail.toLowerCase(), items: body.items.map(parseItem) };
}
export const ordersRoutes: Route[] = [
{
method: 'POST',
path: '/orders',
handler: async ({ body }) => {
const order = await placeOrder(parseNewOrder(body));
return { status: 201, body: { order } };
},
},
{
method: 'GET',
path: '/orders/:id',
handler: async ({ params }) => {
const id = Number(params.id);
if (!isPositiveInteger(id)) throw invalidInput('El id de la orden debe ser un entero positivo');
return { status: 200, body: { order: await getOrder(id) } };
},
},
];export type OrderItem = { productId: number; quantity: number };
export type NewOrder = {
buyerEmail: string;
items: OrderItem[];
};
export type OrderLine = {
productId: number;
title: string;
quantity: number;
unitPriceCents: number;
};
export type Order = {
id: number;
buyerEmail: string;
totalCents: number;
createdAt: string;
lines: OrderLine[];
};
/** Lo vendido de un producto, sumando todas las órdenes. */
export type ProductSales = {
productId: number;
units: number;
revenueCents: number;
};import pg from 'pg';
// El host y el usuario salen de PGHOST y PGUSER, que el contenedor ya define.
// Este archivo es para los repository.ts: es la puerta a las tablas.
export const pool = new pg.Pool({ database: process.env.SHOP_DB ?? 'arq_w04', max: 5 });
export type Tx = pg.PoolClient;
export async function query<Row extends pg.QueryResultRow>(text: string, params: unknown[] = []): Promise<Row[]> {
const result = await pool.query<Row>(text, params);
return result.rows;
}
export async function closePool(): Promise<void> {
await pool.end();
}// Los errores que la API sabe explicar: cada uno lleva su código HTTP.
export class AppError extends Error {
readonly status: number;
readonly code: string;
constructor(status: number, code: string, message: string) {
super(message);
this.status = status;
this.code = code;
}
}
export const invalidInput = (message: string): AppError => new AppError(422, 'INVALID_INPUT', message);
export const notFound = (what: string): AppError => new AppError(404, 'NOT_FOUND', `No existe ${what}`);
export const outOfStock = (title: string): AppError =>
new AppError(409, 'OUT_OF_STOCK', `No hay suficientes ejemplares de ${title}`);import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { AppError } from './errors.ts';
// Un router mínimo sobre node:http: rutas con segmentos :param, cuerpo JSON
// y un solo lugar donde un error se convierte en respuesta.
export type HttpRequest = {
params: Record<string, string>;
query: URLSearchParams;
body: unknown;
};
export type HttpResponse = { status: number; body: unknown };
export type Handler = (request: HttpRequest) => Promise<HttpResponse>;
export type Route = { method: 'GET' | 'POST'; path: string; handler: Handler };
function matchPath(pattern: string, path: string): Record<string, string> | undefined {
const expected = pattern.split('/');
const actual = path.split('/');
if (expected.length !== actual.length) return undefined;
const params: Record<string, string> = {};
for (const [i, segment] of expected.entries()) {
const value = actual[i] ?? '';
if (segment.startsWith(':')) params[segment.slice(1)] = value;
else if (segment !== value) return undefined;
}
return params;
}
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 AppError(422, 'INVALID_INPUT', 'El cuerpo debe ser JSON');
}
}
function send(response: ServerResponse, status: number, body: unknown): void {
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
response.end(JSON.stringify(body));
}
async function handle(routes: Route[], request: IncomingMessage, response: ServerResponse): Promise<void> {
const url = new URL(request.url ?? '/', 'http://localhost');
try {
for (const route of routes) {
const params = route.method === request.method ? matchPath(route.path, url.pathname) : undefined;
if (!params) continue;
const body = route.method === 'POST' ? await readJson(request) : undefined;
const result = await route.handler({ params, query: url.searchParams, body });
send(response, result.status, result.body);
return;
}
throw new AppError(404, 'NOT_FOUND', `No existe ${url.pathname}`);
} catch (error) {
if (error instanceof AppError) {
send(response, error.status, { error: { code: error.code, message: error.message } });
} else {
console.error(error);
send(response, 500, { error: { code: 'INTERNAL_ERROR', message: 'Ocurrió un error inesperado' } });
}
}
}
/** El servidor HTTP con esas rutas, todavía sin escuchar en ningún puerto. */
export function createApp(routes: Route[]): Server {
return createServer((request, response) => {
void handle(routes, request, response);
});
}import { pool, type Tx } from './db.ts';
// Abrir una transacción no es consultar una tabla: lo puede hacer la lógica
// de un módulo, que después le pasa `tx` a los repositorios que participan.
export type { Tx };
/** Corre `fn` dentro de una transacción: COMMIT si termina, ROLLBACK si lanza. */
export async function inTransaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T> {
const tx = await pool.connect();
try {
await tx.query('BEGIN');
const result = await fn(tx);
await tx.query('COMMIT');
return result;
} catch (error) {
await tx.query('ROLLBACK');
throw error;
} finally {
tx.release();
}
}// Reportes: ventas por categoría. No tiene tablas propias.
export { reportsRoutes } from './routes.ts';
export type { CategorySales } from './sales-report.ts';import type { Route } from '../platform/http.ts';
import { salesByCategory } from './sales-report.ts';
export const reportsRoutes: Route[] = [
{
method: 'GET',
path: '/reports/sales',
handler: async () => ({ status: 200, body: { sales: await salesByCategory() } }),
},
];import { CATEGORIES, getProducts, type Category } from '../catalog/index.ts';
import { salesByProduct } from '../orders/index.ts';
// El reporte necesita datos de dos módulos: cuánto se vendió de cada producto
// (orders) y de qué categoría es cada producto (catalog). No tiene tablas ni
// SQL: le pide a cada módulo lo suyo por su interfaz y lo combina en memoria.
export type CategorySales = {
category: Category;
units: number;
revenueCents: number;
};
/** Ventas por categoría; las categorías sin ventas aparecen con cero. */
export async function salesByCategory(): Promise<CategorySales[]> {
const sales = await salesByProduct();
const products = await getProducts(sales.map((sale) => sale.productId));
const categoryOf = new Map(products.map((product) => [product.id, product.category]));
const totals = new Map<Category, CategorySales>(
CATEGORIES.map((category) => [category, { category, units: 0, revenueCents: 0 }]),
);
for (const sale of sales) {
const category = categoryOf.get(sale.productId);
// Un producto retirado del catálogo ya no tiene categoría: no se cuenta.
const total = category && totals.get(category);
if (!total) continue;
total.units += sale.units;
total.revenueCents += sale.revenueCents;
}
return [...totals.values()];
}import type { Order, OrderLine } from '../types.ts';
import { query, type Tx } from './pool.ts';
type OrderRow = { id: number; buyer_email: string; total_cents: number; created_at: Date };
type LineRow = { product_id: number; title: string; quantity: number; unit_price_cents: number };
export async function insertOrder(tx: Tx, buyerEmail: string, lines: OrderLine[]): Promise<Order> {
const totalCents = lines.reduce((sum, line) => sum + line.quantity * line.unitPriceCents, 0);
const inserted = await tx.query<OrderRow>(
`INSERT INTO orders (buyer_email, total_cents) VALUES ($1, $2)
RETURNING id, buyer_email, total_cents, created_at`,
[buyerEmail, totalCents],
);
const order = inserted.rows[0]!;
for (const line of lines) {
await tx.query(
'INSERT INTO order_lines (order_id, product_id, quantity, unit_price_cents) VALUES ($1, $2, $3, $4)',
[order.id, line.productId, line.quantity, line.unitPriceCents],
);
}
return {
id: order.id,
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
lines,
};
}
export async function findOrder(id: number): Promise<Order | undefined> {
const orders = await query<OrderRow>('SELECT id, buyer_email, total_cents, created_at FROM orders WHERE id = $1', [
id,
]);
const order = orders[0];
if (!order) return undefined;
// El título no se guarda en la línea: se trae del producto con un JOIN.
const lines = await query<LineRow>(
`SELECT l.product_id, p.title, l.quantity, l.unit_price_cents
FROM order_lines l
JOIN products p ON p.id = l.product_id
WHERE l.order_id = $1
ORDER BY l.product_id`,
[id],
);
return {
id: order.id,
buyerEmail: order.buyer_email,
totalCents: order.total_cents,
createdAt: order.created_at.toISOString(),
lines: lines.map((line) => ({
productId: line.product_id,
title: line.title,
quantity: line.quantity,
unitPriceCents: line.unit_price_cents,
})),
};
}import pg from 'pg';
// El host y el usuario salen de PGHOST y PGUSER, que el contenedor ya define.
const pool = new pg.Pool({ database: process.env.SHOP_DB ?? 'arq_w04_layers', max: 5 });
export type Tx = pg.PoolClient;
export async function query<Row extends pg.QueryResultRow>(text: string, params: unknown[] = []): Promise<Row[]> {
const result = await pool.query<Row>(text, params);
return result.rows;
}
/** Corre `fn` dentro de una transacción: COMMIT si termina, ROLLBACK si lanza. */
export async function inTransaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T> {
const tx = await pool.connect();
try {
await tx.query('BEGIN');
const result = await fn(tx);
await tx.query('COMMIT');
return result;
} catch (error) {
await tx.query('ROLLBACK');
throw error;
} finally {
tx.release();
}
}
export async function closePool(): Promise<void> {
await pool.end();
}import type { Category, Product } from '../types.ts';
import { query, type Tx } from './pool.ts';
type ProductRow = { id: number; title: string; category: Category; price_cents: number; stock: number };
const toProduct = (row: ProductRow): Product => ({
id: row.id,
title: row.title,
category: row.category,
priceCents: row.price_cents,
stock: row.stock,
});
export async function findProducts(category?: Category): Promise<Product[]> {
const rows = await query<ProductRow>(
`SELECT id, title, category, price_cents, stock
FROM products
WHERE $1::text IS NULL OR category = $1
ORDER BY id`,
[category ?? null],
);
return rows.map(toProduct);
}
export async function findProduct(tx: Tx, id: number): Promise<Product | undefined> {
const result = await tx.query<ProductRow>(
'SELECT id, title, category, price_cents, stock FROM products WHERE id = $1',
[id],
);
const row = result.rows[0];
return row ? toProduct(row) : undefined;
}
/**
* Descuenta `quantity` del stock si alcanza. La condición va en el mismo
* UPDATE: entre dos órdenes simultáneas por el último ejemplar, solo una
* encuentra la fila con stock suficiente.
*/
export async function takeStock(tx: Tx, id: number, quantity: number): Promise<boolean> {
const result = await tx.query('UPDATE products SET stock = stock - $2 WHERE id = $1 AND stock >= $2', [
id,
quantity,
]);
return result.rowCount === 1;
}import type { CategorySales } from '../types.ts';
import { query } from './pool.ts';
type SalesRow = { category: CategorySales['category']; units: number; revenue_cents: number };
export async function sumSalesByCategory(): Promise<CategorySales[]> {
const rows = await query<SalesRow>(
`SELECT p.category,
sum(l.quantity)::int AS units,
sum(l.quantity * l.unit_price_cents)::int AS revenue_cents
FROM order_lines l
JOIN products p ON p.id = l.product_id
GROUP BY p.category`,
);
return rows.map((row) => ({ category: row.category, units: row.units, revenueCents: row.revenue_cents }));
}import { invalidInput } from '../errors.ts';
import { getOrder, placeOrder } from '../services/order-service.ts';
import type { NewOrder, OrderItem } from '../types.ts';
import type { Handler } from './router.ts';
// La capa de presentación traduce: de JSON a un NewOrder con la forma
// correcta, y de un Order a la respuesta. Las reglas del negocio no van aquí.
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isPositiveInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value) && value > 0;
}
function parseItem(value: unknown): OrderItem {
if (!isRecord(value) || !isPositiveInteger(value.productId) || !isPositiveInteger(value.quantity)) {
throw invalidInput('Cada ítem lleva productId y quantity, enteros positivos');
}
return { productId: value.productId, quantity: value.quantity };
}
function parseNewOrder(body: unknown): NewOrder {
if (!isRecord(body)) throw invalidInput('El cuerpo debe ser un objeto JSON');
if (typeof body.buyerEmail !== 'string' || !EMAIL.test(body.buyerEmail)) {
throw invalidInput('buyerEmail no es un correo válido');
}
if (!Array.isArray(body.items)) throw invalidInput('items debe ser una lista');
return { buyerEmail: body.buyerEmail.toLowerCase(), items: body.items.map(parseItem) };
}
export const placeOrderHandler: Handler = async ({ body }) => {
const order = await placeOrder(parseNewOrder(body));
return { status: 201, body: { order } };
};
export const getOrderHandler: Handler = async ({ params }) => {
const id = Number(params.id);
if (!isPositiveInteger(id)) throw invalidInput('El id de la orden debe ser un entero positivo');
return { status: 200, body: { order: await getOrder(id) } };
};import { invalidInput } from '../errors.ts';
import { listProducts } from '../services/product-service.ts';
import { CATEGORIES, type Category } from '../types.ts';
import type { Handler } from './router.ts';
export const listProductsHandler: Handler = async ({ query }) => {
const category = query.get('category') ?? undefined;
if (category !== undefined && !CATEGORIES.includes(category as Category)) {
throw invalidInput(`category debe ser una de: ${CATEGORIES.join(', ')}`);
}
const products = await listProducts(category as Category | undefined);
return { status: 200, body: { products } };
};import { salesByCategory } from '../services/report-service.ts';
import type { Handler } from './router.ts';
export const salesReportHandler: Handler = async () => {
return { status: 200, body: { sales: await salesByCategory() } };
};import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { AppError } from '../errors.ts';
// Un router mínimo sobre node:http: rutas con segmentos :param, cuerpo JSON
// y un solo lugar donde un error se convierte en respuesta.
export type HttpRequest = {
params: Record<string, string>;
query: URLSearchParams;
body: unknown;
};
export type HttpResponse = { status: number; body: unknown };
export type Handler = (request: HttpRequest) => Promise<HttpResponse>;
export type Route = { method: 'GET' | 'POST'; path: string; handler: Handler };
function matchPath(pattern: string, path: string): Record<string, string> | undefined {
const expected = pattern.split('/');
const actual = path.split('/');
if (expected.length !== actual.length) return undefined;
const params: Record<string, string> = {};
for (const [i, segment] of expected.entries()) {
const value = actual[i] ?? '';
if (segment.startsWith(':')) params[segment.slice(1)] = value;
else if (segment !== value) return undefined;
}
return params;
}
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 AppError(422, 'INVALID_INPUT', 'El cuerpo debe ser JSON');
}
}
function send(response: ServerResponse, status: number, body: unknown): void {
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
response.end(JSON.stringify(body));
}
async function handle(routes: Route[], request: IncomingMessage, response: ServerResponse): Promise<void> {
const url = new URL(request.url ?? '/', 'http://localhost');
try {
for (const route of routes) {
const params = route.method === request.method ? matchPath(route.path, url.pathname) : undefined;
if (!params) continue;
const body = route.method === 'POST' ? await readJson(request) : undefined;
const result = await route.handler({ params, query: url.searchParams, body });
send(response, result.status, result.body);
return;
}
throw new AppError(404, 'NOT_FOUND', `No existe ${url.pathname}`);
} catch (error) {
if (error instanceof AppError) {
send(response, error.status, { error: { code: error.code, message: error.message } });
} else {
console.error(error);
send(response, 500, { error: { code: 'INTERNAL_ERROR', message: 'Ocurrió un error inesperado' } });
}
}
}
/** El servidor HTTP con esas rutas, todavía sin escuchar en ningún puerto. */
export function createApp(routes: Route[]): Server {
return createServer((request, response) => {
void handle(routes, request, response);
});
}import type { Server } from 'node:http';
import { getOrderHandler, placeOrderHandler } from './order-handlers.ts';
import { listProductsHandler } from './product-handlers.ts';
import { salesReportHandler } from './report-handlers.ts';
import { createApp } from './router.ts';
export function createServer(): Server {
return createApp([
{ method: 'GET', path: '/products', handler: listProductsHandler },
{ method: 'POST', path: '/orders', handler: placeOrderHandler },
{ method: 'GET', path: '/orders/:id', handler: getOrderHandler },
{ method: 'GET', path: '/reports/sales', handler: salesReportHandler },
]);
}import { findOrder, insertOrder } from '../db/order-repository.ts';
import { inTransaction } from '../db/pool.ts';
import { findProduct, takeStock } from '../db/product-repository.ts';
import { invalidInput, notFound, outOfStock } from '../errors.ts';
import type { NewOrder, Order, OrderLine } from '../types.ts';
export const MAX_ITEMS_PER_ORDER = 5;
function checkItems(order: NewOrder): void {
if (order.items.length < 1 || order.items.length > MAX_ITEMS_PER_ORDER) {
throw invalidInput(`Una orden lleva entre 1 y ${MAX_ITEMS_PER_ORDER} productos distintos`);
}
const ids = order.items.map((item) => item.productId);
if (new Set(ids).size !== ids.length) throw invalidInput('Una orden no repite un producto');
}
/** Descuenta el stock y guarda la orden, todo o nada. */
export async function placeOrder(order: NewOrder): Promise<Order> {
checkItems(order);
// Siempre en el mismo orden de producto: dos órdenes simultáneas con los
// mismos libros no pueden quedar esperándose una a la otra.
const items = [...order.items].sort((a, b) => a.productId - b.productId);
return inTransaction(async (tx) => {
const lines: OrderLine[] = [];
for (const item of items) {
const product = await findProduct(tx, item.productId);
if (!product) throw notFound(`el producto ${item.productId}`);
const taken = await takeStock(tx, item.productId, item.quantity);
if (!taken) throw outOfStock(product.title);
lines.push({
productId: product.id,
title: product.title,
quantity: item.quantity,
unitPriceCents: product.priceCents,
});
}
return insertOrder(tx, order.buyerEmail, lines);
});
}
export async function getOrder(id: number): Promise<Order> {
const order = await findOrder(id);
if (!order) throw notFound(`la orden ${id}`);
return order;
}import { findProducts } from '../db/product-repository.ts';
import type { Category, Product } from '../types.ts';
// Esta función no decide nada: recibe la llamada de la capa de arriba y se la
// pasa a la de abajo. Los apuntes la usan como ejemplo del sumidero.
export async function listProducts(category?: Category): Promise<Product[]> {
return findProducts(category);
}import { sumSalesByCategory } from '../db/report-repository.ts';
import { CATEGORIES, type CategorySales } from '../types.ts';
/** Ventas por categoría; las categorías sin ventas aparecen con cero. */
export async function salesByCategory(): Promise<CategorySales[]> {
const rows = await sumSalesByCategory();
return CATEGORIES.map(
(category) => rows.find((row) => row.category === category) ?? { category, units: 0, revenueCents: 0 },
);
}Errores
Ejemplos con errores a propósito: no compilan, fallan o dan un resultado incorrecto. Los apuntes explican cada uno.
// ERROR A PROPÓSITO: una función del núcleo que conoce a un plug-in por su
// nombre. `make cruces` copia este archivo dentro de src/core/ del microkernel
// y muestra la regla que lo detecta.
//
// "Solo para courier, avisar al comprador si el envío tarda más de dos días."
// Es un if por forma de entrega, igual que los de la versión de partida: el
// siguiente plug-in con plazo largo obligará a volver a tocar el núcleo.
import courier from '../plugins/courier.ts';
import type { DeliveryPlan } from './checkout.ts';
export function slowDeliveryWarning(plan: DeliveryPlan): string | undefined {
if (plan.methodId === courier.id && plan.businessDays > 2) {
return 'Tu pedido puede tardar hasta tres días hábiles';
}
return undefined;
}// ERROR A PROPÓSITO: un handler de la versión por capas que se salta la capa
// de dominio y llama al repositorio. "Total, el servicio solo pasaba la
// llamada." `make cruces` copia este archivo dentro de src/http/ y muestra la
// regla que lo detecta.
import { findProducts } from '../db/product-repository.ts';
import type { Handler } from './router.ts';
export const listProductsFastHandler: Handler = async () => {
return { status: 200, body: { products: await findProducts() } };
};// ERROR A PROPÓSITO: una forma de entrega que consulta la base de datos para
// saber su tarifa. `make cruces` copia este archivo dentro de src/plugins/ del
// microkernel y muestra la regla que lo detecta.
//
// El contrato dice que quote() es una función síncrona que calcula. Este
// plug-in necesita una tarifa que cambia todos los días y la va a buscar por
// su cuenta: abre conexiones que el núcleo no conoce, puede fallar por razones
// que el núcleo no espera y ya no se puede probar sin PostgreSQL.
import pg from 'pg';
import type { ShippingMethod } from '../core/shipping-method.ts';
const pool = new pg.Pool({ database: 'arq_w04' });
let todaysRateCents = 900;
void pool
.query<{ rate_cents: number }>('SELECT rate_cents FROM express_rates WHERE day = current_date')
.then((result) => (todaysRateCents = result.rows[0]?.rate_cents ?? todaysRateCents));
const express: ShippingMethod = {
id: 'express',
label: 'Envío el mismo día',
validate: (destination) => ((destination.address ?? '').trim().length < 5 ? ['address debe ser la dirección'] : []),
quote: () => ({ costCents: todaysRateCents, businessDays: 1 }),
dispatchNote: (destination) => `EXPRESS · ${destination.address}`,
};
export default express;// ERROR A PROPÓSITO: el reporte de la versión por dominio escrito "como
// siempre", con un JOIN entre las tablas de orders y las de catalog.
//
// Funciona y da el mismo resultado que src/reports/sales-report.ts. El
// problema es de límites: reports pasa a depender de los nombres de las
// tablas y de las columnas de dos módulos que no son suyos. `make cruces`
// copia este archivo dentro de src/reports/ y muestra qué regla lo detecta.
import { query } from '../platform/db.ts';
type SalesRow = { category: string; units: number; revenue_cents: number };
export async function salesByCategoryWithJoin(): Promise<SalesRow[]> {
return query<SalesRow>(
`SELECT p.category,
sum(l.quantity)::int AS units,
sum(l.quantity * l.unit_price_cents)::int AS revenue_cents
FROM orders.order_lines l
JOIN catalog.products p ON p.id = l.product_id
GROUP BY p.category`,
);
}Pruebas
Comprueban lo que afirman los apuntes; se ejecutan con make test.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { planDelivery as planBefore } from '../before/checkout.ts';
import { planDelivery as planAfter } from '../src/core/checkout.ts';
import type { Destination } from '../src/core/shipping-method.ts';
import { registry } from '../src/registry.ts';
// La versión con ifs y la versión con plug-ins responden lo mismo. El cambio
// de estilo no cambió lo que el sistema hace: cambió lo que cuesta agregarle
// una forma de entrega.
const parcels = [
{ weightGrams: 800, subtotalCents: 4500 },
{ weightGrams: 2300, subtotalCents: 9700 },
{ weightGrams: 4000, subtotalCents: 15000 },
];
const destinations: Destination[] = [
{ store: 'centro' },
{ store: 'surco' },
{ district: 'Comas', address: 'Av. Túpac Amaru 1234' },
{ district: 'Arequipa', address: 'Calle Mercaderes 100' },
{ district: 'Miraflores', address: '' },
{},
];
const outcome = (plan: () => unknown): unknown => {
try {
return plan();
} catch (error) {
return { error: (error as Error).message };
}
};
test('las dos versiones dan el mismo plan o el mismo error en 54 pedidos', () => {
let compared = 0;
for (const methodId of ['pickup', 'courier', 'drone']) {
for (const parcel of parcels) {
for (const destination of destinations) {
const request = { methodId, destination, parcel };
assert.deepEqual(
outcome(() => planAfter(registry, request)),
outcome(() => planBefore(request)),
);
compared += 1;
}
}
}
assert.equal(compared, 54);
});import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
// Cuántos archivos existentes hay que modificar para agregar la tercera forma
// de entrega, contado sobre los .diff que aplica `make tercer-plugin`.
function touchedFiles(diffName: string): string[] {
const diff = readFileSync(new URL(`../extra/${diffName}`, import.meta.url), 'utf8');
return [...diff.matchAll(/^\+\+\+ b\/(.+)$/gm)].map((match) => match[1]!).sort();
}
test('con ifs: agregar locker modifica los cuatro archivos que preguntan por la forma de entrega', () => {
assert.deepEqual(touchedFiles('locker.before.diff'), [
'before/dispatch-note.ts',
'before/shipping-cost.ts',
'before/types.ts',
'before/validate-destination.ts',
]);
});
test('con plug-ins: agregar locker modifica solo el registro', () => {
assert.deepEqual(touchedFiles('locker.registry.diff'), ['src/registry.ts']);
});import assert from 'node:assert/strict';
import { test } from 'node:test';
import { DeliveryError, deliveryOptions, planDelivery } from '../src/core/checkout.ts';
import { createRegistry } from '../src/core/method-registry.ts';
import type { ShippingMethod } from '../src/core/shipping-method.ts';
// El núcleo se prueba sin ningún plug-in de verdad: basta un objeto que
// cumpla el contrato y que anote cómo lo llamaron.
function recordingMethod(problems: string[] = []): { method: ShippingMethod; calls: string[] } {
const calls: string[] = [];
const method: ShippingMethod = {
id: 'fake',
label: 'De prueba',
validate() {
calls.push('validate');
return problems;
},
quote() {
calls.push('quote');
return { costCents: 250, businessDays: 4 };
},
dispatchNote() {
calls.push('dispatchNote');
return 'NOTA';
},
};
return { method, calls };
}
const parcel = { weightGrams: 500, subtotalCents: 4500 };
test('el núcleo valida, cotiza y arma el plan con lo que responde el plug-in', () => {
const { method, calls } = recordingMethod();
const plan = planDelivery(createRegistry([method]), { methodId: 'fake', destination: {}, parcel });
assert.deepEqual(plan, {
methodId: 'fake',
label: 'De prueba',
shippingCents: 250,
totalCents: 4750,
businessDays: 4,
dispatchNote: 'NOTA',
});
assert.deepEqual(calls, ['validate', 'quote', 'dispatchNote']);
});
test('si el destino no es válido, el núcleo no le pide al plug-in nada más', () => {
const { method, calls } = recordingMethod(['falta la dirección']);
assert.throws(
() => planDelivery(createRegistry([method]), { methodId: 'fake', destination: {}, parcel }),
(error: unknown) => error instanceof DeliveryError && error.problems[0] === 'falta la dirección',
);
assert.deepEqual(calls, ['validate']);
});
test('una forma de entrega que no está registrada es un error del pedido', () => {
const { method } = recordingMethod();
assert.throws(
() => planDelivery(createRegistry([method]), { methodId: 'drone', destination: {}, parcel }),
/Forma de entrega desconocida: drone \(hay: fake\)/,
);
});
test('el núcleo rechaza una cotización que no tiene sentido', () => {
const { method } = recordingMethod();
const broken: ShippingMethod = { ...method, quote: () => ({ costCents: -1, businessDays: 1 }) };
assert.throws(
() => planDelivery(createRegistry([broken]), { methodId: 'fake', destination: {}, parcel }),
/cotización no válida/,
);
});
test('las opciones que ve el comprador son las del registro, en su orden', () => {
const { method } = recordingMethod();
const other: ShippingMethod = { ...method, id: 'other', label: 'Otra' };
assert.deepEqual(deliveryOptions(createRegistry([method, other])), [
{ id: 'fake', label: 'De prueba' },
{ id: 'other', label: 'Otra' },
]);
});
test('el registro no acepta dos plug-ins con el mismo id ni un id mal escrito', () => {
const { method } = recordingMethod();
assert.throws(() => createRegistry([method, { ...method }]), /registrada dos veces: "fake"/);
assert.throws(() => createRegistry([{ ...method, id: 'Fake Method' }]), /no válido/);
});import assert from 'node:assert/strict';
import { test } from 'node:test';
import { registry } from '../src/registry.ts';
// Pruebas del contrato: lo que el núcleo supone de cualquier forma de
// entrega, comprobado sobre todas las registradas. Un plug-in nuevo queda
// cubierto por estas pruebas sin escribir ninguna.
const parcels = [
{ weightGrams: 1, subtotalCents: 100 },
{ weightGrams: 2300, subtotalCents: 9700 },
{ weightGrams: 30000, subtotalCents: 500000 },
];
// Un destino válido por cada forma de entrega. Quien agrega un plug-in agrega aquí su destino.
const validDestinations: Record<string, Record<string, string>> = {
pickup: { store: 'centro' },
courier: { district: 'Lima', address: 'Jr. de la Unión 300' },
locker: { locker: 'LK-0420' },
};
for (const method of registry.all()) {
test(`${method.id}: tiene un destino válido de ejemplo`, () => {
assert.ok(validDestinations[method.id], `Falta el destino de ejemplo de ${method.id}`);
assert.deepEqual(method.validate(validDestinations[method.id]!), []);
});
test(`${method.id}: un destino vacío se rechaza con un mensaje, sin lanzar`, () => {
const problems = method.validate({});
assert.ok(problems.length > 0);
assert.ok(problems.every((problem) => typeof problem === 'string' && problem.length > 0));
});
test(`${method.id}: cotiza un costo entero no negativo y al menos un día`, () => {
for (const parcel of parcels) {
const quote = method.quote(parcel, validDestinations[method.id]!);
assert.ok(Number.isInteger(quote.costCents) && quote.costCents >= 0);
assert.ok(Number.isInteger(quote.businessDays) && quote.businessDays >= 1);
}
});
test(`${method.id}: no modifica lo que recibe y responde lo mismo dos veces`, () => {
const destination = Object.freeze({ ...validDestinations[method.id]! });
const parcel = Object.freeze({ ...parcels[1]! });
assert.deepEqual(method.quote(parcel, destination), method.quote(parcel, destination));
assert.equal(method.dispatchNote(destination), method.dispatchNote(destination));
assert.ok(method.dispatchNote(destination).length > 0);
});
}import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
import { discoverRegistry } from '../src/discover.ts';
import { registry } from '../src/registry.ts';
const PLUGINS = new URL('../src/plugins/', import.meta.url).pathname;
test('el descubrimiento encuentra las mismas formas de entrega que el registro estático', async () => {
const discovered = await discoverRegistry(PLUGINS);
const ids = (all: readonly { id: string }[]): string[] => all.map((method) => method.id).sort();
assert.deepEqual(ids(discovered.all()), ids(registry.all()));
});
test('un archivo que no cumple el contrato se detecta al arrancar, no al compilar', async () => {
const dir = mkdtempSync(join(tmpdir(), 'plugins-'));
try {
// Le falta dispatchNote. tsc nunca ve este archivo: nadie lo importa por su nombre.
writeFileSync(
join(dir, 'half-done.ts'),
"export default { id: 'half-done', label: 'A medias', validate: () => [], quote: () => ({ costCents: 0, businessDays: 1 }) };\n",
);
await assert.rejects(discoverRegistry(dir), /half-done\.ts no exporta por omisión una forma de entrega/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});import assert from 'node:assert/strict';
import { test } from 'node:test';
import courier from '../src/plugins/courier.ts';
import pickup from '../src/plugins/pickup.ts';
// Cada plug-in se prueba solo: no hace falta el núcleo ni el registro.
const light = { weightGrams: 800, subtotalCents: 4500 };
test('pickup: gratis, al día siguiente, solo en una tienda que existe', () => {
assert.deepEqual(pickup.validate({ store: 'miraflores' }), []);
assert.deepEqual(pickup.validate({ store: 'surco' }), ['store debe ser una de: centro, miraflores']);
assert.deepEqual(pickup.validate({}), ['store debe ser una de: centro, miraflores']);
assert.deepEqual(pickup.quote(light, { store: 'centro' }), { costCents: 0, businessDays: 1 });
assert.equal(pickup.dispatchNote({ store: 'centro' }), 'RECOJO EN TIENDA · Jr. Camaná 615, Lima');
});
test('courier: la tarifa base depende de la zona del distrito', () => {
const address = 'Av. Arequipa 1500';
assert.deepEqual(courier.quote(light, { district: 'Miraflores', address }), { costCents: 800, businessDays: 2 });
assert.deepEqual(courier.quote(light, { district: 'comas', address }), { costCents: 1200, businessDays: 3 });
});
test('courier: cada kilo adicional o fracción cuesta S/ 2.00', () => {
const destination = { district: 'lima', address: 'Jr. de la Unión 300' };
const cost = (weightGrams: number): number =>
courier.quote({ weightGrams, subtotalCents: 4500 }, destination).costCents;
assert.equal(cost(1000), 800);
assert.equal(cost(1001), 1000);
assert.equal(cost(2300), 1200);
});
test('courier: desde S/ 150 de compra el envío es gratis, y el plazo no cambia', () => {
const destination = { district: 'comas', address: 'Av. Túpac Amaru 1234' };
assert.equal(courier.quote({ weightGrams: 4000, subtotalCents: 14999 }, destination).costCents, 1800);
assert.deepEqual(courier.quote({ weightGrams: 4000, subtotalCents: 15000 }, destination), {
costCents: 0,
businessDays: 3,
});
});
test('courier: reporta todos los problemas del destino, no solo el primero', () => {
assert.deepEqual(courier.validate({ district: 'Arequipa', address: '' }), [
'No hacemos envíos a domicilio al distrito "Arequipa"',
'address debe ser la dirección de entrega',
]);
assert.deepEqual(courier.validate({ district: ' San Isidro ', address: 'Calle Las Flores 120' }), []);
});import assert from 'node:assert/strict';
import { test } from 'node:test';
import { collect } from '../src/consumers/collect.ts';
import { summarize } from '../src/consumers/summarize.ts';
import { dropDuplicates } from '../src/filters/drop-duplicates.ts';
import { onlyCategory, onlyInStock, take } from '../src/filters/only.ts';
import { onlyValid, problemOf } from '../src/filters/only-valid.ts';
import { parseRows } from '../src/filters/parse-rows.ts';
import { parsePriceCents, toBook } from '../src/filters/to-book.ts';
import type { Book, RawRow, Rejection } from '../src/formats.ts';
import { fromArray } from '../src/sources.ts';
// Cada filtro se prueba solo: se le da una secuencia hecha a mano y se mira
// lo que sale. Ninguna de estas pruebas lee un archivo ni arma el pipeline.
const row = (line: number, isbn: string, titulo: string, categoria: string, precio: string, stock: string): RawRow => ({
line,
fields: { isbn, titulo, categoria, precio, stock },
});
const book = (isbn: string, category: Book['category'], priceCents: number, stock: number): Book => ({
isbn,
title: `Libro ${isbn}`,
category,
priceCents,
stock,
});
test('parseRows: usa el encabezado y se salta líneas vacías y comentarios', async () => {
const lines = ['a;b', '# comentario', '1; x ', '', '2;y;z'];
assert.deepEqual(await collect(parseRows(';')(fromArray(lines))), [
{ line: 3, fields: { a: '1', b: 'x' } },
{ line: 5, fields: { a: '2', b: 'y', '#3': 'z' } },
]);
});
test('parseRows: el separador es un parámetro del filtro', async () => {
assert.deepEqual(await collect(parseRows(',')(fromArray(['a,b', '1,2']))), [{ line: 2, fields: { a: '1', b: '2' } }]);
});
test('onlyValid: deja pasar lo que se puede cargar y avisa de lo demás', async () => {
const rejected: Rejection[] = [];
const rows = [
row(2, 'A', 'Uno', 'novela', '42,00', '6'),
row(3, 'B', 'Dos', 'ensayo', '', '5'),
row(4, 'C', 'Tres', 'cuento', '10,00', '1'),
row(5, 'D', 'Cuatro', 'POESIA', '48.50', '0'),
row(6, 'E', 'Cinco', 'poesia', '27,00', '-1'),
row(7, 'F', 'Seis', 'poesia', '27,5', '1'),
];
const passed = await collect(onlyValid((rejection) => rejected.push(rejection))(fromArray(rows)));
assert.deepEqual(
passed.map((each) => each.line),
[2, 5],
);
assert.deepEqual(rejected, [
{ line: 3, reason: 'falta precio' },
{ line: 4, reason: 'categoría desconocida: cuento' },
{ line: 6, reason: 'stock no válido: -1' },
{ line: 7, reason: 'precio no válido: 27,5' },
]);
});
test('onlyValid: una fila con campos de más se rechaza', () => {
const extra: RawRow = { line: 9, fields: { ...row(9, 'A', 'Uno', 'novela', '1,00', '1').fields, '#6': 'oferta' } };
assert.equal(problemOf(extra), 'tiene 1 campo(s) de más');
});
test('toBook: categoría en minúsculas y precio en céntimos, con coma o con punto', async () => {
const rows = [row(2, 'A', 'Uno', 'NOVELA', '48.50', '4'), row(3, 'B', 'Dos', 'poesia', '31,90', '3')];
assert.deepEqual(await collect(toBook(fromArray(rows))), [
{ isbn: 'A', title: 'Uno', category: 'novela', priceCents: 4850, stock: 4 },
{ isbn: 'B', title: 'Dos', category: 'poesia', priceCents: 3190, stock: 3 },
]);
assert.equal(parsePriceCents('42'), 4200);
assert.equal(parsePriceCents('0,05'), 5);
});
test('dropDuplicates: se queda con la primera aparición de cada ISBN', async () => {
const duplicates: string[] = [];
const books = [book('A', 'novela', 100, 1), book('B', 'novela', 100, 1), book('A', 'poesia', 900, 9)];
const unique = await collect(dropDuplicates((each) => duplicates.push(each.isbn))(fromArray(books)));
assert.deepEqual(
unique.map((each) => [each.isbn, each.category]),
[
['A', 'novela'],
['B', 'novela'],
],
);
assert.deepEqual(duplicates, ['A']);
});
test('onlyInStock y onlyCategory: cada libro pasa o no por lo que es', async () => {
const books = [book('A', 'novela', 100, 0), book('B', 'poesia', 100, 2), book('C', 'novela', 100, 3)];
assert.deepEqual((await collect(onlyInStock(fromArray(books)))).map((each) => each.isbn), ['B', 'C']);
assert.deepEqual((await collect(onlyCategory('novela')(fromArray(books)))).map((each) => each.isbn), ['A', 'C']);
});
test('take: sirve para cualquier tipo de elemento', async () => {
assert.deepEqual(await collect(take<number>(2)(fromArray([7, 8, 9]))), [7, 8]);
assert.deepEqual(await collect(take<string>(0)(fromArray(['a']))), []);
});
test('summarize: títulos, ejemplares y valor por categoría, con ceros donde no hay', async () => {
const books = [book('A', 'novela', 4200, 6), book('B', 'novela', 4850, 4), book('C', 'ensayo', 3900, 2)];
assert.deepEqual(await summarize(fromArray(books)), [
{ category: 'novela', titles: 2, copies: 10, valueCents: 44600 },
{ category: 'poesia', titles: 0, copies: 0, valueCents: 0 },
{ category: 'ensayo', titles: 1, copies: 2, valueCents: 7800 },
]);
});import assert from 'node:assert/strict';
import { test } from 'node:test';
import { collect } from '../src/consumers/collect.ts';
import { summarize } from '../src/consumers/summarize.ts';
import { dropDuplicates } from '../src/filters/drop-duplicates.ts';
import { onlyCategory, onlyInStock, take } from '../src/filters/only.ts';
import { onlyValid } from '../src/filters/only-valid.ts';
import { parseRows } from '../src/filters/parse-rows.ts';
import { toBook } from '../src/filters/to-book.ts';
import type { Book, Rejection } from '../src/formats.ts';
import { from } from '../src/pipe.ts';
import { fromArray, readLines } from '../src/sources.ts';
const CSV = new URL('../data/supplier-books.csv', import.meta.url).pathname;
const books = (): ReturnType<typeof from<Book>> =>
from(readLines(CSV)).through(parseRows(';')).through(onlyValid()).through(toBook);
test('el pipeline completo sobre la lista del distribuidor', async () => {
const rejected: Rejection[] = [];
const duplicated: string[] = [];
const summary = await from(readLines(CSV))
.through(parseRows(';'))
.through(onlyValid((rejection) => rejected.push(rejection)))
.through(toBook)
.through(dropDuplicates((book) => duplicated.push(book.isbn)))
.into(summarize);
assert.deepEqual(summary, [
{ category: 'novela', titles: 3, copies: 10, valueCents: 44600 },
{ category: 'poesia', titles: 2, copies: 12, valueCents: 34770 },
{ category: 'ensayo', titles: 2, copies: 9, valueCents: 33000 },
]);
assert.deepEqual(
rejected.map((rejection) => rejection.line),
[9, 12, 14, 15],
);
assert.deepEqual(duplicated, ['978-612-0002']);
});
test('reemplazar el consumidor no toca ningún filtro', async () => {
const titles = (await books().through(dropDuplicates()).into(collect)).map((book) => book.title);
assert.equal(titles.length, 7);
assert.equal(titles[0], 'Yawar fiesta');
});
test('dos verificadores sin memoria se pueden cambiar de orden', async () => {
const one = await books().through(onlyInStock).through(onlyCategory('novela')).into(collect);
const other = await books().through(onlyCategory('novela')).through(onlyInStock).into(collect);
assert.deepEqual(one, other);
assert.equal(one.length, 3);
});
test('un filtro con memoria no siempre se puede cambiar de orden', async () => {
// El mismo ISBN aparece dos veces, con categorías distintas.
const source: Book[] = [
{ isbn: 'A', title: 'Primera', category: 'novela', priceCents: 100, stock: 1 },
{ isbn: 'A', title: 'Segunda', category: 'poesia', priceCents: 100, stock: 1 },
];
const dedupeFirst = await from(fromArray(source)).through(dropDuplicates()).through(onlyCategory('poesia')).into(collect);
const dedupeLast = await from(fromArray(source)).through(onlyCategory('poesia')).through(dropDuplicates()).into(collect);
assert.deepEqual(dedupeFirst, []);
assert.deepEqual(
dedupeLast.map((book) => book.title),
['Segunda'],
);
});
test('los datos se piden de uno en uno: con take(2), el productor entrega dos y se cierra', async () => {
let produced = 0;
let closed = false;
async function* countingSource(): AsyncIterable<number> {
try {
for (let n = 1; n <= 1000; n += 1) {
produced += 1;
yield n;
}
} finally {
closed = true;
}
}
const firstTwo = await from(countingSource()).through(take(2)).into(collect);
assert.deepEqual(firstTwo, [1, 2]);
assert.equal(produced, 2);
assert.equal(closed, true);
});
test('nada se lee hasta que se conecta el consumidor', async () => {
let started = false;
async function* source(): AsyncIterable<string> {
started = true;
yield 'isbn;titulo;categoria;precio;stock';
}
const pipeline = from(source()).through(parseRows(';')).through(onlyValid()).through(toBook);
assert.equal(started, false);
assert.deepEqual(await pipeline.into(collect), []);
assert.equal(started, true);
});import assert from 'node:assert/strict';
import { test } from 'node:test';
import { createEventBus, type OrderPlaced } from './event-bus.ts';
const event: OrderPlaced = {
type: 'OrderPlaced',
orderId: 7,
lines: [{ productId: 1, quantity: 2, unitPriceCents: 4500 }],
};
test('quien publica no sabe cuántos escuchan: se agrega un suscriptor sin tocarlo', async () => {
const bus = createEventBus();
// "orders": publica y no conoce a nadie.
const placeOrder = (): Promise<unknown[]> => bus.publish(event);
let unitsSold = 0;
bus.subscribe('OrderPlaced', (placed) => {
unitsSold += placed.lines.reduce((sum, line) => sum + line.quantity, 0);
});
await placeOrder();
assert.equal(unitsSold, 2);
// Un segundo módulo se suscribe; placeOrder es la misma función de antes.
const mailed: number[] = [];
bus.subscribe('OrderPlaced', (placed) => void mailed.push(placed.orderId));
await placeOrder();
assert.equal(unitsSold, 4);
assert.deepEqual(mailed, [7]);
});
test('un suscriptor que falla no afecta a los demás, y quien publica se entera', async () => {
const bus = createEventBus();
const heard: string[] = [];
bus.subscribe('OrderPlaced', () => {
throw new Error('el servidor de correo no responde');
});
bus.subscribe('OrderPlaced', () => void heard.push('reports'));
const errors = await bus.publish(event);
assert.deepEqual(heard, ['reports']);
assert.equal(errors.length, 1);
assert.match(String(errors[0]), /servidor de correo/);
});
test('el evento vive en la memoria del proceso: lo que nadie escuchaba a tiempo se pierde', async () => {
const bus = createEventBus();
await bus.publish(event);
// Este suscriptor llega tarde, como un módulo que arranca después o un proceso que se reinició.
const heard: number[] = [];
bus.subscribe('OrderPlaced', (placed) => void heard.push(placed.orderId));
assert.deepEqual(heard, []);
});import assert from 'node:assert/strict';
import type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { after, before, describe, test } from 'node:test';
// Las mismas pruebas para las dos versiones de Qhatu. Solo usan la API HTTP:
// no saben cómo está organizado el código por dentro, y por eso sirven para
// afirmar que las dos versiones hacen lo mismo.
type Json = Record<string, any>;
export function shopBehaviour(name: string, createServer: () => Server, closePool: () => Promise<void>): void {
describe(name, () => defineTests(createServer, closePool));
}
function defineTests(createServer: () => Server, closePool: () => Promise<void>): void {
let server: Server;
let url = '';
const get = async (path: string): Promise<{ status: number; body: Json }> => {
const response = await fetch(url + path);
return { status: response.status, body: (await response.json()) as Json };
};
const post = async (path: string, payload: unknown): Promise<{ status: number; body: Json }> => {
const response = await fetch(url + path, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
});
return { status: response.status, body: (await response.json()) as Json };
};
const stockOf = async (id: number): Promise<number> => {
const { body } = await get('/products');
return body.products.find((product: Json) => product.id === id).stock;
};
before(async () => {
server = createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
await closePool();
});
test('lista los ocho libros y filtra por categoría', async () => {
const all = await get('/products');
assert.equal(all.status, 200);
assert.equal(all.body.products.length, 8);
const novels = await get('/products?category=novela');
assert.deepEqual(
novels.body.products.map((product: Json) => product.title),
['Los ríos profundos', 'La ciudad y los perros', 'El mundo es ancho y ajeno'],
);
const wrong = await get('/products?category=cocina');
assert.equal(wrong.status, 422);
assert.equal(wrong.body.error.code, 'INVALID_INPUT');
});
test('una compra descuenta el stock y devuelve la orden con sus líneas', async () => {
const created = await post('/orders', {
buyerEmail: 'Rosa.Quispe@correo.pe',
items: [
{ productId: 4, quantity: 1 },
{ productId: 1, quantity: 2 },
],
});
assert.equal(created.status, 201);
const { order } = created.body;
assert.equal(order.buyerEmail, 'rosa.quispe@correo.pe');
assert.equal(order.totalCents, 2 * 4500 + 3200);
assert.deepEqual(order.lines, [
{ productId: 1, title: 'Los ríos profundos', quantity: 2, unitPriceCents: 4500 },
{ productId: 4, title: 'Trilce', quantity: 1, unitPriceCents: 3200 },
]);
assert.equal(await stockOf(1), 10);
assert.equal(await stockOf(4), 9);
const fetched = await get(`/orders/${order.id}`);
assert.equal(fetched.status, 200);
assert.deepEqual(fetched.body.order, order);
});
test('rechaza lo que no es una orden válida', async () => {
const noEmail = await post('/orders', { buyerEmail: 'rosa', items: [{ productId: 1, quantity: 1 }] });
assert.equal(noEmail.status, 422);
const repeated = await post('/orders', {
buyerEmail: 'rosa.quispe@correo.pe',
items: [
{ productId: 1, quantity: 1 },
{ productId: 1, quantity: 1 },
],
});
assert.equal(repeated.status, 422);
const unknown = await post('/orders', {
buyerEmail: 'rosa.quispe@correo.pe',
items: [{ productId: 99, quantity: 1 }],
});
assert.equal(unknown.status, 404);
assert.equal((await get('/orders/9999')).status, 404);
});
test('si un producto no alcanza, la orden entera no se guarda', async () => {
// Del libro 8 queda un ejemplar; del libro 2 hay de sobra.
const rejected = await post('/orders', {
buyerEmail: 'luis.mamani@correo.pe',
items: [
{ productId: 2, quantity: 1 },
{ productId: 8, quantity: 2 },
],
});
assert.equal(rejected.status, 409);
assert.equal(rejected.body.error.code, 'OUT_OF_STOCK');
// El libro 2 ya se había descontado dentro de la transacción: el ROLLBACK lo devuelve.
assert.equal(await stockOf(2), 8);
assert.equal(await stockOf(8), 1);
});
test('cinco compras simultáneas por el último ejemplar: solo una lo consigue', async () => {
const attempts = await Promise.all(
[1, 2, 3, 4, 5].map((n) =>
post('/orders', { buyerEmail: `comprador${n}@correo.pe`, items: [{ productId: 8, quantity: 1 }] }),
),
);
const statuses = attempts.map((attempt) => attempt.status).sort();
assert.deepEqual(statuses, [201, 409, 409, 409, 409]);
assert.equal(await stockOf(8), 0);
});
test('el reporte suma por categoría lo que se vendió en las pruebas anteriores', async () => {
const report = await get('/reports/sales');
assert.equal(report.status, 200);
assert.deepEqual(report.body.sales, [
{ category: 'novela', units: 2, revenueCents: 9000 },
{ category: 'poesia', units: 1, revenueCents: 3200 },
{ category: 'ensayo', units: 1, revenueCents: 4100 },
]);
});
}import { createServer } from '../by-domain/src/app.ts';
import { closePool } from '../by-domain/src/platform/db.ts';
import { shopBehaviour } from './behaviour.ts';
shopBehaviour('Qhatu por dominio', createServer, closePool);import { closePool } from '../by-layer/src/db/pool.ts';
import { createServer } from '../by-layer/src/http/server.ts';
import { shopBehaviour } from './behaviour.ts';
shopBehaviour('Qhatu por capas', createServer, closePool);import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { test } from 'node:test';
// Los apuntes cuentan cuántos archivos y cuántas carpetas toca el mismo cambio
// de negocio (una dedicatoria en la orden) en cada versión. Aquí se cuenta
// sobre los .diff de verdad, los mismos que aplica `make cambio`.
function touchedFiles(diffName: string): string[] {
const diff = readFileSync(new URL(`../changes/${diffName}`, import.meta.url), 'utf8');
return [...diff.matchAll(/^\+\+\+ b\/(.+)$/gm)].map((match) => match[1]!);
}
const folders = (files: string[]): string[] => [...new Set(files.map((file) => dirname(file)))].sort();
test('por capas: el cambio toca cuatro archivos repartidos en cuatro carpetas', () => {
const files = touchedFiles('gift-note.by-layer.diff');
assert.deepEqual(files.sort(), [
'src/db/order-repository.ts',
'src/http/order-handlers.ts',
'src/services/order-service.ts',
'src/types.ts',
]);
assert.deepEqual(folders(files), ['src', 'src/db', 'src/http', 'src/services']);
});
test('por dominio: el mismo cambio toca cuatro archivos de una sola carpeta', () => {
const files = touchedFiles('gift-note.by-domain.diff');
assert.equal(files.length, 4);
assert.deepEqual(folders(files), ['src/orders']);
});
test('por dominio: el cambio no toca la interfaz pública del módulo', () => {
assert.ok(!touchedFiles('gift-note.by-domain.diff').includes('src/orders/index.ts'));
});import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import { checkDataOwnership, findForeignTables } from '../data-ownership.ts';
const SRC = new URL('../by-domain/src', import.meta.url).pathname;
const MODULES = ['catalog', 'orders', 'reports'];
const SCHEMAS = ['catalog', 'orders'];
test('en la versión por dominio, ningún módulo nombra tablas de otro', () => {
assert.deepEqual(checkDataOwnership(SRC, MODULES, SCHEMAS), []);
});
test('la comprobación sí encuentra un JOIN que cruza dos esquemas', () => {
const source = readFileSync(new URL('../../errors/report-with-join.ts', import.meta.url), 'utf8');
assert.deepEqual(findForeignTables(source, 'reports', SCHEMAS), ['orders.order_lines', 'catalog.products']);
});
test('un módulo puede nombrar sus propias tablas', () => {
const sql = 'SELECT title FROM catalog.products WHERE id = $1';
assert.deepEqual(findForeignTables(sql, 'catalog', SCHEMAS), []);
assert.deepEqual(findForeignTables(sql, 'orders', SCHEMAS), ['catalog.products']);
});Compilación
Cómo se compilan y ejecutan los ejemplos.
# Semana 4: estilos monolíticos. Se usa dentro del contenedor del curso.
#
# make crea las bases de datos de Qhatu (arq_w04 y arq_w04_layers)
# make test revisa los tipos (tsc), las reglas de dependencia (make deps)
# y corre las pruebas (*.test.ts), que comprueban lo que
# dicen los apuntes
# make deps dependency-cruiser sobre Qhatu por capas, Qhatu por dominio
# y el microkernel, más la comprobación de quién nombra
# qué tablas
# make cambio el mismo cambio de negocio (una dedicatoria en la orden)
# aplicado a las dos versiones de Qhatu: qué archivos toca
# make sql el cambio contrario, uno técnico: qué archivos tienen SQL
# make cruces los ejemplos de errors/, cada uno con la regla que lo detecta
# make cotizar el microkernel: el mismo paquete con cada forma de entrega
# make tercer-plugin agrega la tercera forma de entrega a la versión con ifs y
# a la versión con plug-ins, y cuenta los archivos tocados
# make pipeline la carga de la lista de precios, y lo mismo con comandos de Unix
# make medios paso 1 del laboratorio: dónde pregunta Tinkuy por el medio de pago
# make clean borra build/ y las bases de datos de la semana
#
# Nada de esto modifica el Tinkuy del curso (../../tinkuy).
TINKUY ?= ../../tinkuy
GIT = git
# psql no avisa cuando la base de datos que se va a borrar todavía no existe.
PGOPTIONS = --client-min-messages=warning
export PGOPTIONS
DEPCRUISE = depcruise src --config .dependency-cruiser.cjs
RECREATE = psql -q -d postgres -c "DROP DATABASE IF EXISTS $(1) WITH (FORCE)" -c "CREATE DATABASE $(1)"
LAYERS_DB = psql -q -d $(1) -v ON_ERROR_STOP=1 -f shop/db/schema-layers.sql -v products=products -f shop/db/seed.sql
MODULES_DB = psql -q -d $(1) -v ON_ERROR_STOP=1 -f shop/db/schema-modules.sql -v products=catalog.products -f shop/db/seed.sql
.PHONY: all db test deps cambio sql cruces cotizar tercer-plugin pipeline medios clean
all: db
db:
@$(call RECREATE,arq_w04_layers)
@$(call LAYERS_DB,arq_w04_layers)
@$(call RECREATE,arq_w04)
@$(call MODULES_DB,arq_w04)
# Las pruebas de Qhatu comparten base de datos: los archivos corren uno después de otro.
test: db
tsc -p .
@$(MAKE) --no-print-directory deps
node --test --test-concurrency=1 "shop/test/*.test.ts" "shop/events/*.test.ts" "microkernel/test/*.test.ts" "pipeline/test/*.test.ts"
deps:
cd shop/by-layer && $(DEPCRUISE)
cd shop/by-domain && $(DEPCRUISE)
node shop/data-ownership.ts shop/by-domain/src
cd microkernel && $(DEPCRUISE)
# Cada versión se copia a build/, se le aplica su .diff y se comprueba que el
# cambio funciona contra una base de datos propia.
cambio:
@rm -rf build/cambio && mkdir -p build/cambio
@cp -r shop/by-layer build/cambio/by-layer && cp -r shop/by-domain build/cambio/by-domain
@echo "== Por capas"
@cd build/cambio/by-layer && $(GIT) apply --stat ../../../shop/changes/gift-note.by-layer.diff && $(GIT) apply ../../../shop/changes/gift-note.by-layer.diff
@echo "== Por dominio"
@cd build/cambio/by-domain && $(GIT) apply --stat ../../../shop/changes/gift-note.by-domain.diff && $(GIT) apply ../../../shop/changes/gift-note.by-domain.diff
@$(call RECREATE,arq_w04_cambio_layers)
@$(call LAYERS_DB,arq_w04_cambio_layers)
@psql -q -d arq_w04_cambio_layers -v ON_ERROR_STOP=1 -v orders=orders -f shop/changes/gift-note.sql
@$(call RECREATE,arq_w04_cambio)
@$(call MODULES_DB,arq_w04_cambio)
@psql -q -d arq_w04_cambio -v ON_ERROR_STOP=1 -v orders=orders.orders -f shop/changes/gift-note.sql
@echo "== Las dos copias, con el cambio aplicado"
@SHOP_DB=arq_w04_cambio_layers node shop/changes/gift-note.check.ts \
$(CURDIR)/build/cambio/by-layer/src/http/server.ts $(CURDIR)/build/cambio/by-layer/src/db/pool.ts
@SHOP_DB=arq_w04_cambio node shop/changes/gift-note.check.ts \
$(CURDIR)/build/cambio/by-domain/src/app.ts $(CURDIR)/build/cambio/by-domain/src/platform/db.ts
@psql -q -d postgres -c "DROP DATABASE arq_w04_cambio_layers WITH (FORCE)" -c "DROP DATABASE arq_w04_cambio WITH (FORCE)"
# El cambio contrario: uno técnico. Si cambiara algo que afecta a todo el SQL
# (el motor de base de datos, por ejemplo), ¿qué archivos habría que revisar?
sql:
@echo "== Por capas: archivos con SQL"
@cd shop/by-layer && grep -rlE "SELECT|INSERT|UPDATE" src | sort
@echo "== Por dominio: archivos con SQL"
@cd shop/by-domain && grep -rlE "SELECT|INSERT|UPDATE" src | sort
# depcruise termina con error cuando encuentra algo: aquí eso es lo que se quiere ver.
cruces:
@rm -rf build/cruces && mkdir -p build/cruces
@cp -r shop/by-layer build/cruces/by-layer && cp -r shop/by-domain build/cruces/by-domain && cp -r microkernel build/cruces/microkernel
@cp errors/handler-skips-service.ts build/cruces/by-layer/src/http/
@cp errors/report-with-join.ts build/cruces/by-domain/src/reports/
@cp errors/plugin-reads-db.ts build/cruces/microkernel/src/plugins/
@cp errors/core-knows-plugin.ts build/cruces/microkernel/src/core/
@echo "== errors/handler-skips-service.ts en Qhatu por capas"
@cd build/cruces/by-layer && $(DEPCRUISE) ; echo "depcruise terminó con código $$?"
@echo "== errors/report-with-join.ts en Qhatu por dominio"
@cd build/cruces/by-domain && $(DEPCRUISE) ; echo "depcruise terminó con código $$?"
@node shop/data-ownership.ts build/cruces/by-domain/src ; echo "data-ownership terminó con código $$?"
@echo "== errors/plugin-reads-db.ts y errors/core-knows-plugin.ts en el microkernel"
@cd build/cruces/microkernel && $(DEPCRUISE) ; echo "depcruise terminó con código $$?"
cotizar:
@node microkernel/src/main.ts
tercer-plugin:
@rm -rf build/tercer-plugin && mkdir -p build/tercer-plugin
@cp -r microkernel/before microkernel/src microkernel/test microkernel/.dependency-cruiser.cjs build/tercer-plugin/
@echo "== Con ifs (before/): archivos existentes que cambian"
@cd build/tercer-plugin && $(GIT) apply --stat ../../microkernel/extra/locker.before.diff && $(GIT) apply ../../microkernel/extra/locker.before.diff
@echo "== Con plug-ins (src/): un archivo nuevo, y los existentes que cambian"
@cp microkernel/extra/locker.ts build/tercer-plugin/src/plugins/locker.ts
@cd build/tercer-plugin && $(GIT) apply --stat ../../microkernel/extra/locker.registry.diff && $(GIT) apply ../../microkernel/extra/locker.registry.diff
@echo "== La copia con el tercer plug-in"
@node build/tercer-plugin/src/main.ts
@cd build/tercer-plugin && $(DEPCRUISE)
@cd build/tercer-plugin && node --test "test/contract.test.ts" 2>&1 | grep -E "^(✔|✖) locker|^ℹ (tests|pass|fail)"
pipeline:
@node pipeline/src/main.ts
@echo
@echo "== Títulos por categoría, con comandos de Unix"
tail -n +2 pipeline/data/supplier-books.csv | grep -v -e '^#' -e '^$$' | cut -d';' -f3 | tr 'A-Z' 'a-z' | sort | uniq -c
medios:
cd $(TINKUY) && grep -rn "'card'\|'yape'" src
clean:
rm -rf build
@psql -q -d postgres -c "DROP DATABASE IF EXISTS arq_w04 WITH (FORCE)" -c "DROP DATABASE IF EXISTS arq_w04_layers WITH (FORCE)" \
-c "DROP DATABASE IF EXISTS arq_w04_cambio WITH (FORCE)" -c "DROP DATABASE IF EXISTS arq_w04_cambio_layers WITH (FORCE)"{
"private": true,
"type": "module"
}{
"compilerOptions": {
"target": "es2024",
"lib": ["es2024"],
"module": "nodenext",
"moduleResolution": "nodenext",
"types": ["node"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["shop", "microkernel", "pipeline"],
"exclude": ["build", "microkernel/extra"]
}