Skip to content

The architecture

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.

  1. rest

    Routes, DTOs, response enums, error mapping, route tests

    rest_<c> depends on aplicacion_<c>, dominio_<c>

  2. infraestructura

    Adapters: in-memory or Postgres repositories, units of work, mail senders

    infra_<c> depends on dominio_<c>

  3. aplicacion

    Use cases, one file each: params, trait, double, implementation, tests

    aplicacion_<c> depends on dominio_<c>

  4. dominio

    Models, typed ids, value objects, errors, repository ports, events

    dominio_<c> depends on nucleo and puerto-nucleo only

One context, from the outside in. Dependencies point inward only, and each layer of each context is its own crate, so Cargo checks the rule. 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-nucleo
infra_<c> → dominio_<c>
presentacion/ (cableado, api, worker) → all of them
  • dominio_<c> (domain) holds the model, value objects, errors and the repository port. It depends on nucleo (the shared value objects) and puerto-nucleo, and on no database driver and no HTTP framework. Its tests need nothing but cargo 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, never infra_<c>.
  • presentacion/ is the composition root. cableado builds each context’s repositories and use cases; api, and worker in projects with events, are the binaries. Only they depend on the infra_* 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).

POST /api/productos with {"nombre":"Lampara","precio":4900,"sku":"LMP-01"}, in a --db project:

  1. rest_producto. ApiProducto::crear receives Json<PeticionCrearProducto>, a DTO. It builds ParamsCrearProducto and calls self.crear_producto.ejecutar(params). crear_producto is an Arc<dyn CrearProducto>: the route depends on a port, not an implementation (ADR-0012).
  2. aplicacion_producto. CrearProductoImpl builds the entity with Producto::new(props), where the domain’s rules run, and calls self.repositorio.guardar(&entidad) on an Arc<dyn RepositorioProducto>.
  3. infra_producto. RepositorioProductoPostgres::guardar writes the row. A unique violation comes back from Postgres as ErrorRepositorio::Duplicado, converted once in puerto-sqlx (ADR-0015).
  4. Back up. ErrorProducto::Duplicado reaches the route, and a_respuesta_error in errores.rs maps it to 409 with {"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.

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:

presentacion/cableado/src/lib.rs (excerpt, --db)
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.

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.

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