The architecture
Why not MVC
Section titled “Why not MVC”MVC is a good way to start and a hard way to grow. Business rules end up wherever it was convenient to write them: a callback on the model, a check in the controller, a query scope. Testing a rule then means a database and an HTTP request, and changing the database means touching the rules.
Puerto generates the alternative from the first command. Domain-Driven Design gives the vocabulary (entities, value objects, repositories, domain events) and Clean Architecture, also known as hexagonal or ports and adapters, gives the rule that keeps it clean.
The dependency rule
Section titled “The dependency rule”- rest
Routes, DTOs, response enums, error mapping, route tests
rest_<c> depends on aplicacion_<c>, dominio_<c>
- infraestructura
Adapters: in-memory or Postgres repositories, units of work, mail senders
infra_<c> depends on dominio_<c>
- aplicacion
Use cases, one file each: params, trait, double, implementation, tests
aplicacion_<c> depends on dominio_<c>
- dominio
Models, typed ids, value objects, errors, repository ports, events
dominio_<c> depends on nucleo and puerto-nucleo only
presentacion/, the wiring and the binaries, sees them all.Each entity is a context with four crates, and dependencies point inward only:
rest_<c> → aplicacion_<c> → dominio_<c> → nucleo, puerto-nucleoinfra_<c> → dominio_<c>presentacion/ (cableado, api, worker) → all of themdominio_<c>(domain) holds the model, value objects, errors and the repository port. It depends onnucleo(the shared value objects) andpuerto-nucleo, and on no database driver and no HTTP framework. Its tests need nothing butcargo test.aplicacion_<c>(application) holds the use cases, one file each: params, trait, implementation, mock and tests. It knows its domain and nothing else.infra_<c>(infrastructure) holds the adapters that implement the domain’s ports: an in-memory or Postgres repository, a unit of work. It knows the domain, never the use cases or the routes.rest_<c>is HTTP: routes, DTOs, response enums, error mapping. It is just another adapter, the one that turns requests into use case calls. It knows the application and the domain, neverinfra_<c>.presentacion/is the composition root.cableadobuilds each context’s repositories and use cases;api, andworkerin projects with events, are the binaries. Only they depend on theinfra_*crates.
This is not a guideline you keep by discipline: each layer of each context is its own crate, and
a crate cannot import what it does not depend on. A domain model that tries to use sqlx does
not compile, and neither does a route that reaches for the Postgres repository. A reference
between entities (cliente_id:ref:Cliente) makes dominio_pedido depend on dominio_cliente,
and Cargo refuses a cycle, so the map between contexts is checked by the compiler too
(ADR-0023).
A request, end to end
Section titled “A request, end to end”POST /api/productos with {"nombre":"Lampara","precio":4900,"sku":"LMP-01"}, in a --db
project:
rest_producto.ApiProducto::crearreceivesJson<PeticionCrearProducto>, a DTO. It buildsParamsCrearProductoand callsself.crear_producto.ejecutar(params).crear_productois anArc<dyn CrearProducto>: the route depends on a port, not an implementation (ADR-0012).aplicacion_producto.CrearProductoImplbuilds the entity withProducto::new(props), where the domain’s rules run, and callsself.repositorio.guardar(&entidad)on anArc<dyn RepositorioProducto>.infra_producto.RepositorioProductoPostgres::guardarwrites the row. A unique violation comes back from Postgres asErrorRepositorio::Duplicado, converted once inpuerto-sqlx(ADR-0015).- Back up.
ErrorProducto::Duplicadoreaches the route, anda_respuesta_errorinerrores.rsmaps it to409with{"codigo":"producto.duplicado"}. It has no catch-all arm: a new error variant does not compile until someone decides its status (ADR-0007).
The domain never sees JSON, and the route never sees SQL.
Wiring without a container
Section titled “Wiring without a container”Who decides that ApiProducto::crear_producto is a CrearProductoImpl backed by a
RepositorioProductoPostgres? One crate: presentacion/cableado, the composition root.
Puerto generates it from puerto.toml, as plain Rust you can read:
pub fn construir(pool: &sqlx::PgPool) -> CasosDeUso { let repositorio: Arc<dyn RepositorioProducto> = Arc::new(RepositorioProductoPostgres::new(pool.clone())); CasosDeUso { crear_producto: Arc::new(CrearProductoImpl { repositorio: Arc::clone(&repositorio), }), obtener_producto: Arc::new(ObtenerProductoImpl { repositorio: Arc::clone(&repositorio), }), // listar_productos, actualizar_producto, borrar_producto: the same }}cableado knows nothing about HTTP. presentacion/api/src/generado/bootstrap.rs calls
cableado::producto::construir(&pool) and hands each use case to ApiProducto, then mounts the
routes. There is no runtime container, no reflection, and no macro that registers routes behind
your back. “Go to definition” works everywhere, for you and for an agent. The price is that you
never edit these files by hand: change puerto.toml and run puerto generar bootstrap.
Your own wiring, extra middleware or routes outside the OpenAPI service goes in
presentacion/api/src/app.rs, a file Puerto writes once and never touches again.
The frontend follows the same rule
Section titled “The frontend follows the same rule”web/ has the same layers: domain (types and the repository port) ← application ←
infrastructure (the HTTP adapter) ← presentation (screens). The rule is checked by
dependency-cruiser in make web/lint, and the OpenAPI spec is the contract between the two
halves. See The web frontend.
What the compiler enforces for you
Section titled “What the compiler enforces for you”| If someone… | …then | Because |
|---|---|---|
imports sqlx in a domain model |
it does not compile | dominio_<c> does not depend on it |
| uses the Postgres repository in a route | it does not compile | rest_<c> does not depend on infra_<c> (ADR-0023) |
passes an IdCliente where an IdProducto goes |
it does not compile | ids are generated newtypes (ADR-0014) |
| writes through the repository in an events project | it does not compile | the repository has no guardar; writes go through the unit of work (ADR-0018) |
| adds an error variant without a status | it does not compile | a_respuesta_error is exhaustive (ADR-0007) |
| removes an event a consumer listens to | the worker does not compile | consumers match on generated constants |
changes a DTO without make web/sync |
make test fails |
the exported spec is compared in a test |