Case study Β· PR #18 Β· multi-health-careio

Rust Microservices,
Hexagonal Architecture & Expert Code Review

Every concept here β€” Cargo workspaces, modules, ports, adapters, DTOs, Firestore β€” is taught through the real code of svc-family: an 18-endpoint family-management microservice merged in PR #18 (33 files, ~6,000 lines). Learn the architecture, then stress-test yourself with hard review drills built from real findings in that same PR.

β¬’ View PR #18 on GitHub β†—
0% read
01

Why Rust for Microservices?

svc-family compiles to a single ~15MB static binary with no runtime, no GC pauses, and compile-time guarantees about concurrency. For health data (HIPAA/GDPR territory) the pitch is stronger still: the compiler enforces who owns what data, so entire bug classes β€” use-after-free, data races, iterator invalidation β€” cannot reach production.

Memory safety, no GC

Ownership + borrow checker prove at compile time that every allocation has exactly one owner and no dangling references.

Fearless concurrency

Send/Sync marker traits make "safe to share across threads" a type-level fact. Data races are compiler errors.

Cheap abstraction

Traits are zero-cost: dyn Trait is one vtable pointer, generics are monomorphised. Hexagonal indirection costs ~nothing.

Spring Boot β†’ Rust concept map

If you're coming from Java/Spring, this mapping makes the transition concrete:

Spring BootRust (this guide)Key Difference
@SpringBootApplicationsrc/main.rsMuch thinner β€” just config + server start
@Service, @RepositoryPlain structs + traitsNo annotations; DI is manual
JVM + GCCompiled binary, no GCMemory managed at compile time
Maven multi-moduleCargo workspaceSame idea, different syntax
Spring Data JPATraits (ports)You define the interface, implement per backend
Lombok @Data#[derive(...)]Compile-time code generation via macros

The Big Idea: Rust has no runtime. No JVM, no Spring context, no reflection. Everything is explicit, and the compiler checks it all before you ship. This means many bugs that would be runtime exceptions in Java become compile-time errors in Rust.

The three ownership concepts you must internalise first

ConceptRuleWhere you'll see it in svc-family
OwnershipEvery value has exactly one owner; assignment moves ownership by defaultFamilyService::new(...) takes repos by value and stores them
BorrowingMany immutable borrows (&T) XOR one mutable borrow (&mut T) at a timeRepo methods take &self and read &Family
LifetimesBorrows can't outlive their owner (usually inferred)Handlers borrow request data only for the handler's scope

Mental model: imagine family2 = family in Java did not copy the reference but actually transferred it and family became null automatically. That is Rust's default. The side-by-side:

Java Β· references are copied
Family family = new Family("Smith");
Family family2 = family;
// family is still valid!
System.out.println(family.getName()); // OK
Rust Β· ownership moves
let family = Family::new("Smith");
let family2 = family;
// println!("{:?}", family);  // COMPILE ERROR!
// family is no longer valid

Interactive: watch ownership move

Click each step to see what happens. Steps 3 and 5 would be compile errors.

Step 1: Create a FamilyClick to execute
let family = Family::new("Smith");
Step 2: Move to family2Click to execute
let family2 = family;
Step 3: Try to use familyClick to execute
println!("{:?}", family);
Step 4: Borrow insteadClick to execute
let family_ref = &family2; // immutable borrow
Step 5: Try mutable borrowClick to execute
let family_mut = &mut family2;

Shared ownership across async tasks: Arc<T>

An HTTP server handles thousands of concurrent requests on a thread pool. Every request handler needs access to the same service. Rust's answer is Arc β€” Atomic Reference Counting β€” a heap pointer whose count is incremented/decremented atomically. Clone an Arc and both clones point at the same object:

// handlers.rs β€” every request gets a cheap Arc clone of the service #[derive(Clone)] pub struct AppState { pub service: Arc<FamilyService>, // shared handle, not a copy }

Why AppState derives Clone: Axum clones state per request internally. Cloning an Arc is a single atomic increment β€” nanoseconds. Cloning the underlying FamilyService would be impossible anyway (it holds non-clonable trait objects), which is exactly why we wrap it.

Spring developers: where's your @Service injection?

Spring injects singleton beans into controllers via @Autowired. Rust has no DI framework β€” you build the shared state yourself and hand it to the router once. A clone of the Arc is your "injected dependency":

Java Β· Spring β€” @Service singleton
@Service
public class FamilyService { ... }

@RestController
public class FamilyController {
    @Autowired
    private FamilyService service;   // injected by the container
}
Rust Β· Axum β€” manual Arc state
#[derive(Clone)]
pub struct AppState {
    pub service: Arc<FamilyService>, // what handlers receive
}
// router.with_state(AppState{ service }) β€” injected ONCE,
// each request gets a cheap Arc clone (atomic increment)

Send and Sync: the two markers tokio demands

MarkerMeansJava equivalentWhy it matters here
SendThe value can be moved to another threadLike Serializable, but for thread boundariesTokio may poll your future on any worker thread
Sync&T is safe to share between threadsThread-safe read-only accessMany requests hold references to the same Arc<FamilyService> simultaneously

This is why every port trait declares : Send + Sync as a supertrait β€” see Section 06. Drop those bounds and Arc<dyn FamilyRepository> refuses to compile inside axum's threaded runtime. The compiler, not a code review, catches the design mistake.

02

Cargo & Workspaces

Cargo is Rust's build tool and package manager. A workspace is a group of crates that share one Cargo.lock, one target/ directory, and one dependency graph β€” so all services in the repo build with the same versions of axum, serde, uuid, etc.

services/Cargo.toml β€” workspace root (PR adds svc-family as a member)
[workspace] resolver = "2" // v2 resolver: dev-deps don't leak into normal builds members = [ "svc-shared", "svc-family", // ← added by PR #18 ] [workspace.dependencies] // single source of truth for versions across services
services/svc-family/Cargo.toml β€” the service crate
[package] name = "svc-family" version = "0.1.0" edition = "2021" [dependencies] svc-shared = { path = "../svc-shared" } // shared kernel: domain types live here axum = { version = "0.8", features = ["ws", "macros"] } utoipa-swagger-ui = { version = "9", features = ["axum"] } thiserror = "1.0" serde = { version = "1.0", features = ["derive"] } uuid = { version = "1.12", features = ["v4", "serde"] } chrono = { version = "0.4", features = ["serde"] } bcrypt = "0.15" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "json"] } firestore-db-and-auth = "0.8" async-trait = "0.1" tokio = { version = "1.0", features = ["full"] } [dev-dependencies] mockall = "0.12" // test-only β€” never shipped in the binary

One crate, two artifacts: library + binary

src/lib.rs β†’ library target

Compiles to libsvc_family.rlib. Other crates (the gateway binary) depend on svc_family and reuse its router, service, and in-memory doubles without spawning a process.

src/main.rs β†’ binary target

Compiles to the deployable executable svc-family for standalone Cloud Run deploys. It's thin on purpose β€” just config + server startup (Section 12).

The binary imports from the library via the crate name with underscores: use svc_family::{build_router_with_firestore, openapi_router}; β€” hyphens in package names become underscores in code.

Concepts that trip people up

ConceptWhat it doesIn this PR
EditionDialect of the language; opt-in per crate, never breaking existing codeedition = "2021"
FeaturesCargo's conditional compilation; crates gate optional code behind feature flagsaxum's ws (websockets) and macros; serde's derive; uuid's v4
Cargo.lockExact resolved versions for reproducible builds; committed for binaries+2,355 lines in this PR alone
dev-dependenciesAvailable only to tests/examples/benches β€” excluded from release buildsmockall
Path dependencyLocal sibling crate reference instead of a registry versionsvc-shared = { path = "../svc-shared" }

βœ… Check yourself β€” Cargo

1. What does having both src/lib.rs and src/main.rs in one crate produce?

2. Why is mockall under [dev-dependencies] rather than [dependencies]?

03

Modules & lib.rs β€” the Crate's Public API

Rust has no folders-as-namespaces magic: every directory needs a module declaration. mod.rs is the module's front door, and pub use re-exports flatten the tree into an ergonomic API. Here is the complete module layout of svc-family:

services/svc-family/src/ β”œβ”€β”€ lib.rs # declares modules + public API surface β”œβ”€β”€ main.rs # binary entry point (thin) β”œβ”€β”€ domain/ # pure business logic β”‚ β”œβ”€β”€ mod.rs β”‚ β”œβ”€β”€ model.rs # re-exports shared domain types β”‚ β”œβ”€β”€ service.rs # FamilyService (608 lines of rules) β”‚ └── error.rs # FamilyError enum β”œβ”€β”€ ports/ # interfaces the domain defines β”‚ β”œβ”€β”€ mod.rs β”‚ β”œβ”€β”€ family_repo.rs β”‚ β”œβ”€β”€ member_repo.rs β”‚ β”œβ”€β”€ invitation_repo.rs β”‚ └── consent_repo.rs └── adapters/ β”œβ”€β”€ mod.rs β”œβ”€β”€ primary/ # drive the domain (inbound) β”‚ └── http/ β”‚ β”œβ”€β”€ mod.rs β”‚ β”œβ”€β”€ dto.rs β”‚ β”œβ”€β”€ handlers.rs β”‚ └── router.rs └── secondary/ # driven by the domain (outbound) β”œβ”€β”€ firestore/ # production persistence β”‚ β”œβ”€β”€ firestore_client.rs β”‚ β”œβ”€β”€ family_repo.rs Β· member_repo.rs Β· invitation_repo.rs Β· consent_repo.rs β”‚ └── mod.rs └── in_memory/ # test doubles, same ports

lib.rs is a contract, not a formality

// lib.rs pub mod domain; pub mod ports; pub mod adapters; // Curated re-exports β€” consumers import from the crate root, // not the deep module paths: pub use domain::service::FamilyService; pub use ports::{ConsentRepository, FamilyRepository, InvitationRepository, MemberRepository}; pub use adapters::primary::http::{router, AppState}; pub use adapters::secondary::in_memory::{ InMemoryConsentRepository, InMemoryFamilyRepository, InMemoryInvitationRepository, InMemoryMemberRepository, };
  • pub mod makes a whole submodule public β€” anyone can reach crate::adapters::secondary::firestore::family_repo::FirestoreFamilyRepository.
  • pub use creates an alias at the current path β€” use svc_family::FamilyRepository; works because of the re-export above.
  • Anything not marked pub is private to the module β€” Rust's default is encapsulation, unlike Java/C#.
  • //! at file top is an inner doc comment documenting the module itself (see //! svc-family - Family management... in lib.rs).

The three path keywords you'll read in every file

KeywordResolves relative toExample from the PR
crate::This crate's rootuse crate::domain::model::Family; in handlers.rs
super::Parent modulerepos referencing super::firestore_client::FirestoreClient-style siblings
self::Current modulerare; usually omitted

Design signal worth copying: domain/model.rs contains exactly five lines β€” re-exports from svc_shared. The shared kernel crate owns canonical domain types (Family, ConsentGrant, PatientId…); each service aliases them locally. One definition, every service consistent β€” no drift between services on what a PatientId is.

βœ… Check yourself β€” Modules

3. ports/mod.rs contains pub use family_repo::FamilyRepository;. What does this enable?

04

Hexagonal Architecture (Ports & Adapters)

Alistair Cockburn's hexagonal architecture puts business logic at the centre, with everything else plugged in through explicit interfaces. The dependency rule: all source dependencies point inward. The domain knows nothing about HTTP or Firestore; the outside world knows the domain.

Primary / driving adapters (left side)
handlers.rs dto.rs router.rs + Swagger UI
↓ calls (via AppState: Arc<FamilyService>) ↓
Ports β€” traits owned by the core
FamilyRepository MemberRepository InvitationRepository ConsentRepository
↓ implemented by ↓
Secondary / driven adapters (right side)
Firestore repos (prod) In-memory repos (tests) future gRPC/Kafka repos
⬑ centre ⬑
Domain β€” pure business logic, zero I/O
service.rs Β· FamilyService model.rs (from svc-shared) error.rs Β· FamilyError
Dependency arrows: primary adapters depend on domain + ports. Domain depends only on ports (its own abstractions). Secondary adapters implement ports. Nothing outside depends inward-out β€” ever.

Why teams actually adopt this (not just aesthetics)

  • Swap Firestore for Postgres by writing four new structs β€” zero lines change in domain or handlers.
  • Test business rules in microseconds against in-memory doubles, no emulator, no network, no flakiness.
  • Parallel workstreams: one engineer ships endpoints against in-memory repos while another builds the Firestore adapter.
  • Compile-time architecture enforcement: if domain/service.rs tries to use crate::adapters::..., that's visible in review β€” and linters like cargo-deny or module-visibility tricks can make it fail CI outright.

Deep dive: where each layer is ALLOWED to import from

+

Read the use block at the top of any file and you know instantly whether the dependency rule holds:

  • domain/service.rs may import: std, uuid, chrono, tracing, its own ports and models. It must NOT import axum, firestore_db_and_auth, or anything from adapters/.
  • ports/*.rs may import: async_trait, domain models, domain error. Nothing else.
  • adapters/** may import: everything β€” framework SDKs, DTOs, ports, domain. Adapters sit at the rim; they see it all.

PR #18 mostly holds this rule β€” but Section 13, Drill 7 shows where the "pure domain" claim bends (bcrypt inside service.rs).

05

Domain Layer β€” Pure Business Logic

FamilyService is the heart of the service: 608 lines of business rules β€” who may join a family, when an invitation expires, what "effective permissions" means. It holds four repository ports, injected once at construction, and every method returns the domain's own Result<T>.

domain/service.rs β€” constructor injection of four ports
pub struct FamilyService { family_repo: Arc<dyn FamilyRepository>, member_repo: Arc<dyn MemberRepository>, invitation_repo: Arc<dyn InvitationRepository>, consent_repo: Arc<dyn ConsentRepository>, } impl FamilyService { pub fn new( family_repo: Arc<dyn FamilyRepository>, member_repo: Arc<dyn MemberRepository>, invitation_repo: Arc<dyn InvitationRepository>, consent_repo: Arc<dyn ConsentRepository>, ) -> Self { /* field init shorthand */ } }
domain/service.rs β€” a typical use-case method: guard, mutate, persist
pub async fn update_family(&self, family_id: Uuid, user_id: Uuid, name: String) -> Result<Family> { let mut family = self.get_family(family_id, user_id).await?; // loads + authorises // Business rule: only owner can rename if family.owner_user_id != user_id { return Err(FamilyError::Forbidden("Only family owner can update family name".into())); } family.name = name; family.updated_at = Utc::now(); self.family_repo.update(&family).await?; info!("Updated family {} by user {}", family_id, user_id); Ok(family) }

The shape every service method follows

StepMechanismExample
1 Β· Loadrepo.get_...().await?get_by_id(family_id) β†’ Option<Family>
2 Β· Convert None to error.ok_or(...)?ok_or(FamilyError::FamilyNotFound(family_id))?
3 Β· Authoriseexplicit rule callverify_family_access(&family, user_id).await?
4 Β· Enforce rulesearly-return errorsForbidden, InvitationExpired, DuplicateMember…
5 Β· Persist + returnrepo write, then Okcreate(&member).await?; Ok(member)

Note the absence of HTTP concepts. No StatusCode, no JSON, no request structs. The domain speaks in FamilyError::Forbidden; only the adapter layer (Section 09) translates that to a 403. That translation table is the entire contract between layers β€” which is why the same service can later serve gRPC or Lambda without touching one line here.

06

Ports β€” Repository Traits with async_trait

A port is just a Rust trait the core owns. It states what persistence capability the domain needs β€” never how. PR #18 defines four, one per aggregate. In Spring Data terms, the port replaces the @Repository interface:

Java Β· Spring β€” @Repository interface
public interface FamilyRepository {
    Family save(Family family);
    Optional<Family> findById(UUID id);
    List<Family> findByUserId(UUID userId);
}
Rust β€” port trait (same job)
#[async_trait]
pub trait FamilyRepository: Send + Sync {
    async fn create(&self, family: &Family) -> Result<()>;
    async fn get_by_id(&self, id: Uuid) -> Result<Option<Family>>;
    async fn list_for_user(&self, user_id: Uuid,
        after: Option<String>, limit: usize) -> Result<Vec<Family>>;
}

What the annotations hide: Spring @Repository silently wires an implementation (JPA proxy, Redis, whatever); Rust makes you implement the interface per backend yourself β€” Firestore, in-memory, Postgres. That's the whole hexagonal payoff: you see every backend, and the domain never knows which one is plugged in.

ports/family_repo.rs β€” complete file
#[async_trait] pub trait FamilyRepository: Send + Sync { async fn create(&self, family: &Family) -> Result<()>; async fn get_by_id(&self, family_id: Uuid) -> Result<Option<Family>>; async fn update(&self, family: &Family) -> Result<()>; async fn list_for_user(&self, user_id: Uuid, after: Option<String>, limit: usize) -> Result<Vec<Family>>; async fn list_member_families(&self, user_id: Uuid) -> Result<Vec<Family>>; }

Anatomy lesson β€” four details doing heavy lifting

DetailWhy it's there
#[async_trait]Rust traits historically couldn't have async fns usable as trait objects. This macro rewrites each async fn to return Pin<Box<dyn Future + Send + 'async>>, making the trait object-safe (dyn-compatible). Without it, Arc<dyn FamilyRepository> won't compile. (Native async-in-traits stabilised in 1.75 but still isn't dyn-compatible.)
: Send + SyncSupertrait bounds. Tokio shares repos across worker threads inside Arc; without these bounds the future produced by handlers isn't Send and axum rejects the handler at compile time.
&self, never &mut selfShared ownership via Arc means mutable access is impossible. Adapters achieve interior mutability themselves (Firestore is remote state; in-memory uses locks). Ports encode the concurrency contract: all methods are callable concurrently.
Result<T> aliastype Result<T> = std::result::Result<T, FamilyError> from domain/error.rs β€” repo failures speak the domain's vocabulary (Conflict, Internal), not Firestore's.

Port design smell to watch for: methods that leak storage dialect into the port name or signature (query_by_firestore_cursor, upsert_document). Compare get_by_token_hash(&str) β€” good: expresses intent ("find by hashed token") that both Firestore and in-memory can honour differently.

Deep dive: object safety (dyn compatibility) β€” the #1 beginner trap

+

To create dyn Trait, the compiler must build a vtable: one function pointer per method, called through the trait object. Rules that break it:

  • Generic methods (fn save<T: Entity>(&self, e: T)) β€” vtable can't list infinite monomorphisations β†’ not dyn-compatible.
  • Self: Sized requirements on methods used through dyn.
  • Native async fn in traits β€” desugars to an associated type/impl-Trait generic, same problem. Hence #[async_trait]'s Boxed-future rewrite costs one heap allocation per call β€” negligible next to a network hop to Firestore.
  • Associated consts / static dispatch helpers similarly block dyn.

Compiler error you'll see if violated: "the trait FamilyRepository cannot be made into an object." When you hit it, either drop the generics from the trait or reach for #[async_trait]/boxed returns.

βœ… Check yourself β€” Ports

4. Why does FamilyRepository need #[async_trait] for Arc<dyn FamilyRepository> to work?

5. Port methods take &self even though they insert/update data. How do implementations mutate safely?

07

DTOs β€” the API Contract Layer

Data Transfer Objects live in the primary adapter (adapters/primary/http/dto.rs) and exist for one reason: the wire format must evolve independently of the domain model. Domain types change when business rules change; DTOs change when API clients need a different shape. Conflating them couples every frontend release to your internal refactors.

dto.rs β€” requests, partial updates, generic envelopes
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct CreateMemberRequest { pub name: String, pub relation: Relation, pub date_of_birth: Option<DateTime<Utc>>, pub nhs_number: Option<String>, pub pmi_provider: Option<String>, pub user_id: Option<Uuid>, // optional account link } // PATCH semantics: every field optional β€” "absent" means "don't change" #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct UpdateMemberRequest { pub name: Option<String>, pub relation: Option<Relation>, pub date_of_birth: Option<DateTime<Utc>>, // ... all Option<T> } // Generic pagination envelope β€” reused by every list endpoint #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ListResponse<T> { pub items: Vec<T>, pub next_cursor: Option<String>, } // Secret exposure control: raw token present ONLY on creation response #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct InvitationResponse { pub invitation: FamilyInvitation, pub token: Option<String>, // Some(token) only on POST create }

Each derive is load-bearing

DeriveGives you
Serialize / Deserializeserde generates JSON ⇄ struct code. Axum's Json<T> extractor requires Deserialize; responses require Serialize.
ToSchemautoipa generates the OpenAPI schema component β€” powers Swagger UI and generated client SDKs.
Debug, CloneLoggable in handlers; cloneable for retries/multi-insert paths (invitation + consents).

DTO ↔ domain conversion happens explicitly

The handler destructures the DTO, passes plain values into the service, and wraps the returned domain model back in the envelope. No From<Dto> for DomainModel magic β€” conversions stay visible at the boundary where mistakes are easiest to spot. Note also the standard error envelope every endpoint shares:

pub struct ErrorResponse { pub error: ErrorDetail } pub struct ErrorDetail { pub code: String, pub message: String, #[serde(skip_serializing_if = "Option::is_none")] pub details: Option<serde_json::Value> }

Machine-readable code strings (FAMILY_NOT_FOUND, INVITATION_EXPIRED) let frontends switch on behaviour without parsing prose messages. skip_serializing_if keeps payloads clean instead of emitting "details": null.

08

Axum HTTP Layer β€” Handlers, Extractors, Router, OpenAPI

Axum handlers are plain async functions whose parameters declare their dependencies as extractors. Axum inspects each argument's type and pulls the right piece out of the request: path segments, query string, headers, or the JSON body. A Spring @PostMapping controller and its axum twin:

Java Β· Spring MVC
@PostMapping("/families")
public ResponseEntity<Family> create(
    @RequestHeader("X-User-ID") UUID userId,
    @RequestBody CreateFamilyRequest req
) {
    Family f = service.createFamily(userId, req.getName());
    return ResponseEntity.status(201).body(f);
}
Rust Β· Axum
#[utoipa::path(post, path = "/api/v1/families",
    request_body = CreateFamilyRequest, responses(
    (status = 201, body = Family), tag = "Families"))]
pub async fn create_family(
    State(state): State<AppState>,   // ← @Autowired state
    headers: HeaderMap,             // ← @RequestHeader
    Json(req): Json<CreateFamilyRequest>, // ← @RequestBody (last!)
) -> Result<(StatusCode, Json<Family>), AppError> {
    let user_id = extract_user_id(&headers)?;
    let family = state.service.create_family(user_id, req.name).await?;
    Ok((StatusCode::CREATED, Json(family)))
}

What extractors buy you: Spring binds params by annotation; axum binds by type. The compiler enforces that Json<T> comes last, that the return type implements IntoResponse, and that errors implement it too β€” errors you'd only catch at runtime in Spring are compile errors here. Scroll on for the ordered dissection.

handlers.rs β€” annotated handler, dissected
#[utoipa::path( // ← OpenAPI metadata for Swagger UI post, path = "/api/v1/families", request_body = CreateFamilyRequest, responses( (status = 201, description = "Family created", body = Family), (status = 401, description = "Unauthorized", body = ErrorResponse), (status = 422, description = "Validation error", body = ErrorResponse), ), tag = "Families" )] #[axum::debug_handler] // ← human-readable compile errors pub async fn create_family( State(state): State<AppState>, // 1. app state (cloned Arc) headers: HeaderMap, // 2. auth header (TODO: JWT) Json(req): Json<CreateFamilyRequest>, // 3. body β€” MUST be last ) -> Result<(StatusCode, Json<Family>), AppError> { let user_id = extract_user_id(&headers)?; let family = state.service.create_family(user_id, req.name).await?; Ok((StatusCode::CREATED, Json(family))) }

Extractor rules that matter

  • Order matters: Path, Query, State, HeaderMap consume parts of the request and can appear in any order β€” but the body extractor (Json<T>) must be the last argument because it consumes the whole request stream.
  • Exactly one body extractor per handler.
  • Return types implement IntoResponse: tuples like (StatusCode, Json<T>) compose β€” status plus typed body.
  • Errors must implement IntoResponse too β€” that's AppError/FamilyError, Section 09.
  • Path(family_id): Path<Uuid> parses the segment and rejects non-UUIDs with 400 automatically.
router.rs β€” routes + OpenAPI registry
pub fn family_router() -> Router<AppState> { Router::new() .route("/families", post(create_family).get(list_families)) .route("/families/:family_id", get(get_family).patch(update_family)) .route("/families/:family_id/members/:member_id", get(get_member).patch(update_member).delete(archive_member)) .route("/invitations/:token/accept", post(accept_invitation)) // …18 endpoints total across Families / Members / Invitations / Consents } pub fn openapi_router() -> Router { Router::new().merge( SwaggerUi::new("/swagger-ui/{_:.*}") .url("/api-docs/openapi.json", ApiDoc::openapi()) ) }

How utoipa wires up (three moving parts)

  1. #[utoipa::path] on each handler emits metadata + a hidden item named __path_create_family.
  2. #[derive(OpenApi)] #[openapi(paths(...), components(schemas(...)), tags(...), servers(...))] collects them into one spec β€” note the explicit import of those __path_* items in router.rs.
  3. SwaggerUi mounts interactive docs at /swagger-ui serving the generated openapi.json. Free documentation that cannot rot β€” it compiles from the same signatures as the routes.

Generic-state trick: Router<AppState> is "missing its state". Calling .with_state(state) converts it to plain Router once, in lib.rs composition roots. This means the router function itself never touches Firestore or config β€” another dependency-rule win.

βœ… Check yourself β€” Axum

6. A colleague writes a handler with signature (Json(body), State(state)). What happens?

09

Error Handling β€” thiserror β†’ HTTP Mapping

The domain defines one enum of every failure mode. thiserror derives the boilerplate (Display, std::error::Error); a single From impl defines how each variant becomes an HTTP response. Errors flow upward through ? and get translated exactly once, at the edge.

Java Β· inherited exceptions
public enum FamilyError extends RuntimeException {
    FAMILY_NOT_FOUND, FORBIDDEN,
    INVITATION_EXPIRED, INTERNAL
}
// throwing (anywhere...)
throw new FamilyException(FamilyError.FORBIDDEN, "Only owner");
// catching (one layer, if you remember)
@ExceptionHandler(FamilyException.class)
public ResponseEntity<ErrorResponse> handle(FamilyException e) { ... }
Rust Β· explicit Result
#[derive(Debug, Error)]
pub enum FamilyError {
    #[error("Family not found: {0}")] FamilyNotFound(Uuid),
    #[error("Forbidden: {0}")] Forbidden(String),
    #[error("Invitation expired")] InvitationExpired,
}
pub type Result<T> = std::result::Result<T, FamilyError>;
// EVERY fallible call returns Result β€” the compiler
// forces you to handle or propagate with `?`

Exceptions hide in the stack; Results sit in the signature. A Spring method can throw anything passengers-wise and you discover it in testing; a Rust function's return type is the complete failure contract β€” nobody can forget to handle a case the compiler listed. What Spring calls @ExceptionHandler wiring, Rust does in one From impl per error type (below).

domain/error.rs β€” variants carry context data
#[derive(Debug, Error)] pub enum FamilyError { #[error("Family not found: {0}")] FamilyNotFound(Uuid), #[error("Invitation expired")] InvitationExpired, #[error("Invitation already {status}")] InvitationInvalid { status: String }, #[error("Forbidden: {0}")] Forbidden(String), #[error("Internal error: {0}")] Internal(String), // …13 variants total incl. Unauthorized, Conflict, Validation, // InvitationExpired, SelfConsent, DuplicateMember… } pub type Result<T> = std::result::Result<T, FamilyError>;
domain/error.rs β€” the single translation point to HTTP
impl From<FamilyError> for axum::response::Response { fn from(err: FamilyError) -> Self { let (status, code, message) = match &err { FamilyError::FamilyNotFound(_) => (StatusCode::NOT_FOUND, "FAMILY_NOT_FOUND", err.to_string()), FamilyError::Unauthorized(_) => (StatusCode::UNAUTHORIZED, "UNAUTHORIZED", err.to_string()), FamilyError::Forbidden(_) => (StatusCode::FORBIDDEN, "FORBIDDEN", err.to_string()), FamilyError::Validation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "VALIDATION_ERROR", err.to_string()), FamilyError::InvitationExpired => (StatusCode::GONE, "INVITATION_EXPIRED", err.to_string()), FamilyError::DuplicateMember => (StatusCode::CONFLICT, "DUPLICATE_MEMBER", err.to_string()), FamilyError::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "Internal server error".to_string()), // …one line per variant }; let body = json!({ "error": { "code": code, "message": message } }); (status, Json(body)).into_response() } }

The propagation chain, end to end

Handler returns Result<_, AppError>
service call fails β†’ Err(FamilyError::Conflict(..))
↓ ? operator converts via From<FamilyError> for AppError ↓
AppError(FamilyError)
implements IntoResponse by delegating to the From impl above
↓ axum calls into_response() on Err ↓
Client receives
409 {"error":{"code":"CONFLICT","message":"Conflict: ..."}}
StatusVariants mappedRationale
404 Not FoundFamilyNotFound Β· MemberNotFound Β· InvitationNotFound Β· ConsentNotFoundResource lookup miss
401 / 403Unauthorized Β· ForbiddenIdentity vs permission distinction preserved
409 ConflictConflict Β· InvitationInvalid Β· DuplicateMemberState-machine violations
422 UnprocessableValidation Β· SelfConsentSyntactically valid JSON, semantically rejected
410 GoneInvitationExpiredWas valid once, no longer actionable
500InternalGeneric message only β€” see below

Security detail worth praising in review: Internal(_) maps to the fixed string "Internal server error", deliberately discarding the real message. Internal details (SQL fragments, file paths, Firestore doc names) must never leak to clients. Log the full error server-side; return the generic body.

10

Firestore Adapter β€” Persistence Model & Mapping

The secondary adapters implement the ports against real infrastructure. The Firestore adapter uses firestore-db-and-auth 0.8 with a ServiceSession (service-account auth, no user tokens). Three ideas matter: a thin client wrapper, a separate persistence struct per aggregate, and explicit two-way mapping.

firestore_client.rs β€” shared session wrapper
pub struct FirestoreClient { session: ServiceSession, // holds auth + project routing } impl FirestoreClient { pub async fn new(project_id: &str) -> Result<Self> { // ServiceSession::new(service_account) β€” ADC/service-account creds } } // Collection path helpers keep naming consistent across repos: pub fn family_collection_path() -> String { "families".into() }
family_repo.rs β€” persistence struct + two-way From conversions
#[derive(Debug, Clone, Serialize, Deserialize)] struct FamilyDoc { id: String, // Firestore stores strings, not Uuids name: String, owner_user_id: String, created_at: DateTime<Utc>, updated_at: DateTime<Utc>, } impl From<&Family> for FamilyDoc { fn from(family: &Family) -> Self { Self { id: family.id.to_string(), // domain β†’ storage name: family.name.clone(), owner_user_id: family.owner_user_id.to_string(), created_at: family.created_at, updated_at: family.updated_at, } } } impl From<FamilyDoc> for Family { fn from(doc: FamilyDoc) -> Self { Self { id: Uuid::parse_str(&doc.id).unwrap_or(Uuid::nil()), // ⚠ Drill #1 name: doc.name, owner_user_id: Uuid::parse_str(&doc.owner_user_id).unwrap_or(Uuid::nil()), created_at: doc.created_at, updated_at: doc.updated_at, } } }
family_repo.rs β€” reading raw Firestore dto documents field-by-field
fn doc_to_family(doc: &dto::Document) -> Result<Family> { let fields = doc.fields.as_ref() .ok_or_else(|| FamilyError::Internal("Missing document fields".into()))?; let name = fields.get("name") .and_then(|v| v.string_value.as_ref()) .ok_or_else(|| FamilyError::Internal("Missing name field".into()))? .clone(); // …same pattern for every field }

Why a separate FamilyDoc at all? serde could serialize Family directly…

  • Schema evolution: rename a domain field without a live migration of stored documents β€” the mapping layer absorbs old/new shapes.
  • Type coercion: Firestore has no UUID type; documents store strings. Storage format β‰  memory format.
  • No accidental writes: domain models can gain computed/transient fields that must not persist; the doc struct is the allow-list.
  • Multi-backend symmetry: Postgres row structs or Kafka payloads follow the same pattern β€” the port stays stable while each adapter picks its own representation.

Field-mapping fragility: this low-level fields.get("name") style means adding one domain field requires touching create/read/update paths by hand β€” miss one and you get silent data loss on read-back. Newer crates (firestore) derive this mapping from structs with serde. Worth flagging as future maintenance cost, not a blocker.

11

Test Doubles β€” In-Memory Adapters & Composition Roots

Because the ports are traits, tests get real implementations β€” just backed by HashMaps instead of GCP. These doubles ship in the library crate (not dev-deps) so integration harnesses and the gateway binary can reuse them.

Why this beats @MockBean/Mockito: Spring tests swap in a mocked bean per test; the mock's behaviour is declared in test code, so it can silently diverge from the real implementation. Rust's portfolio of doubles (InMemoryFamilyRepository etc.) are real implementations of the same trait β€” they behave like the production repo, just faster and in-process. You mock only when asserting an interaction, not as your default test strategy.

in_memory/consent_repo.rs β€” indexed double with interior mutability
pub struct InMemoryConsentRepository { consents: Arc<RwLock<HashMap<Uuid, ConsentGrant>>>, // std sync lock inside async fn ⚠ Drill #3 family_index: Arc<RwLock<HashMap<Uuid, Vec<Uuid>>>>, // family_id β†’ consent_ids grantee_index: Arc<RwLock<HashMap<Uuid, Vec<Uuid>>>>, } #[async_trait::async_trait] impl ConsentRepository for InMemoryConsentRepository { async fn create(&self, grant: &ConsentGrant) -> Result<()> { let mut consents = self.consents.write().unwrap(); // poisoning panic risk // insert + update indexes… Ok(()) } // list_by_family sorts by granted_at β€” deterministic test output βœ“ }

Two composition roots β€” production vs testing

lib.rs provides both wiring functions. This is the hexagonal payoff in its purest form: identical routers, identical service, different adapters.

// lib.rs β€” PRODUCTION wiring pub async fn build_router_with_firestore(project_id: &str) -> Result<Router> { let client = Arc::new(FirestoreClient::new(project_id).await?); let family_repo: Arc<dyn FamilyRepository> = Arc::new(FirestoreFamilyRepository::new(client.clone())); // …three more repos share the same Arc<FirestoreClient> let service = Arc::new(FamilyService::new(family_repo, member_repo, invitation_repo, consent_repo)); Ok(router::family_router().with_state(AppState { service })) } // lib.rs β€” TEST wiring: zero network, microseconds to construct pub fn build_router_in_memory() -> Router { let family_repo: Arc<dyn FamilyRepository> = Arc::new(InMemoryFamilyRepository::new()); // … router::family_router().with_state(AppState { service }) }

The testing pyramid this enables

LevelMechanismSpeedCatches
Unitmockall mocks of ports; assert service rules in isolationΞΌsBusiness-rule logic
Integration (HTTP)build_router_in_memory() + tower's oneshot/axum-test β€” real request/response cycles, no socketsmsExtractor wiring, status codes, JSON contracts
E2EFirestore emulator or staging project behind build_router_with_firestoresReal query semantics, index requirements

The fidelity trap: a double that doesn't honour port semantics makes every test built on it a fiction. PR #18's in-memory get_effective_permissions returns an empty map "for now" β€” Drill #4 dissects why that's the most dangerous kind of bug in this architecture: everything compiles, all green, prod diverges.

12

Wiring & main.rs β€” Config, Tokio, Tracing

The binary is deliberately boring β€” read env config, build the router, serve. All interesting logic lives in the library.

main.rs β€” complete
#[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { // Structured logs: RUST_LOG filter + JSON output for Cloud Logging tracing_subscriber::registry() .with(tracing_subscriber::EnvFilter::new( std::env::var("RUST_LOG").unwrap_or_else(|_| "info,svc_family=debug".into()))) .with(tracing_subscriber::fmt::layer().json()) .init(); // Env fallback chain: GCP_PROJECT_ID β†’ FIRESTORE_PROJECT_ID β†’ default let project_id = std::env::var("GCP_PROJECT_ID") .or_else(|_| std::env::var("FIRESTORE_PROJECT_ID")) .unwrap_or_else(|_| "agentic-health-dev".into()); let port = std::env::var("PORT").unwrap_or_else(|_| "8080".into()).parse::<u16>()?; let app = Router::new() .merge(build_router_with_firestore(&project_id).await?) .merge(openapi_router()); // Swagger UI mounted alongside API let addr = SocketAddr::from(([0, 0, 0, 0], port)); // all interfaces β€” Cloud Run requirement let listener = tokio::net::TcpListener::bind(addr).await?; axum::serve(listener, app).await?; Ok(()) }

Cloud Run readiness checklist β€” what this main gets right & what it's missing

RequirementStatusNote
Listen on $PORT, all interfacesdoneSocketAddr::from(([0,0,0,0], port))
Structured JSON loggingdonefmt layer json() β€” parses natively into Cloud Logging
Config via env with safe defaultsdoneFallback chain pattern
Graceful shutdown on SIGTERMmissingNeeds axum::serve(...).with_graceful_shutdown(signal_handler); Cloud Run gives ~10s before hard-kill β€” in-flight requests should drain
Liveness/readiness endpointsmissingAdd /healthz returning 200 without touching Firestore; readiness can check a cheap session ping
Startup failure = fast crashdonebuild_router_with_firestore(...)? propagates β€” bad creds kill the container immediately instead of serving 500s forever

Return type decode: Box<dyn Error + Send + Sync> is idiomatic main() ergonomics β€” "any error type, as long as it's thread-safe". Every error in the chain auto-converts via From. In libraries prefer concrete typed errors; boxed dyn errors are for binaries and FFI boundaries.

βœ… Check yourself β€” Production wiring

7. Why bind to 0.0.0.0 instead of localhost?

8. What's the operational risk of the missing graceful-shutdown handler?

13

Code Review Playbook

You now know the architecture. This section trains the harder skill: finding the bugs that don't fail CI. First a rubric to structure any hexagonal-Rust review; then seven drills built from real issues in PR #18 β€” each one subtle enough that it shipped merged.

The reviewer's rubric for hexagonal Rust services

LensAsk yourself
Dependency ruleDo domain/ports import adapters or frameworks? Read only the use blocks of every file under domain/ first.
Error integrityAny unwrap/expect/unwrap_or(default) on fallible external input? Any error swallowed into a default value? Any Internal message leaked to clients?
Async hygienestd::sync locks inside async fns? Blocking calls (bcrypt! heavy CPU!) on the runtime? .unwrap() on lock poisoning = panic cascade?
Security surfaceWhere does identity come from? Are secrets returned more than once? Is there rate limiting on expensive unauthenticated endpoints? TOCTOU races on state transitions?
Contract honestyDoes pagination actually paginate? Does the OpenAPI spec match real behaviour? Do status codes match semantics?
Test-double fidelityDoes each in-memory adapter implement port semantics fully, or return placeholder results that make tests green while prod diverges?
Data integrityMulti-document writes atomic? Corrupt records fail loudly or silently coerce? Sort keys stable for pagination?
Operational readinessGraceful shutdown? Health endpoints? Startup fails fast? Log levels sane? PII in logs?

How to use the drills: read the snippet, form your own hypothesis before answering, then check. The analysis sections go deeper than the multiple-choice answer β€” root cause β†’ blast radius β†’ concrete fix β†’ how to phrase it in review.

Drill 1 Β· Severity: HIGH

Silent coercion at the persistence boundary

data integrity

Context: Firestore adapter converts stored documents back into domain models during every read.

impl From<FamilyDoc> for Family { fn from(doc: FamilyDoc) -> Self { Self { id: Uuid::parse_str(&doc.id).unwrap_or(Uuid::nil()), owner_user_id: Uuid::parse_str(&doc.owner_user_id).unwrap_or(Uuid::nil()), name: doc.name, created_at: doc.created_at, updated_at: doc.updated_at, } } }

A document was hand-edited in the Firestore console and its id is now "fam_123". What happens on read?

Root cause

unwrap_or(default) converts "this data is invalid" into "here is a valid-looking wrong value". The failure mode moves from loud-and-immediate to silent-and-deferred β€” the worst trade you can make at a trust boundary between storage and business logic.

Blast radius
  • All corrupt docs share identity 00000000-…-0000: authorization checks against owner_user_id == nil, updates writing to nil-keyed paths, cross-family leakage if nil matches another nil record's checks.
  • No observability signal exists, so MTTR β‰ˆ ∞. You find out from a user report weeks later.
  • It also hides programmer errors β€” e.g. accidentally storing an int-typed id field reads as corrupt rather than failing the deploy loudly.
Fix pattern
id: Uuid::parse_str(&doc.id) .map_err(|e| FamilyError::Internal(format!( "corrupt family doc {}: bad uuid: {e}", doc_path)))?, // or skip+metric at repo level

Fail the single read with context, or skip-and-count corrupt docs behind a metric/alert β€” never invent identities. Reserve defaults for values that are genuinely optional, not for validating identifiers.

Review phrasing: β€œThis conversion silently coerces malformed IDs into the nil UUID instead of failing β€” corrupt documents become indistinguishable from valid ones sharing one identity. Can we propagate a typed error (or skip-with-metric) so bad data surfaces immediately?”
Drill 2 Β· Severity: CRITICAL

Identity from a spoofable header

security

Context: All 18 endpoints call this helper before touching data. There is no JWT middleware yet.

fn extract_user_id(headers: &HeaderMap) -> Result<Uuid, AppError> { // In production, this would be from JWT/session // TODO: Replace with proper auth middleware if let Some(user_id_str) = headers.get("X-User-ID").and_then(|v| v.to_str().ok()) { return Uuid::parse_str(user_id_str) .map_err(|_| FamilyError::Unauthorized("Invalid X-User-ID header".into())) .map_err(AppError); } Err(AppError(FamilyError::Unauthorized("Missing X-User-ID".into()))) }

The service deploys to Cloud Run behind an API gateway that is supposed to inject X-User-ID after JWT verification. What's still wrong?

Root cause

The security boundary lives outside the artifact being reviewed. Header-based identity is legitimate only when the network path makes spoofing impossible (service mesh stripping inbound headers, mTLS between known callers). Nothing here enforces stripping, so any caller that can reach the port β€” including other workloads in the same project β€” declares itself as anyone.

Blast radius
  • This is health data: family membership, NHS numbers, consent grants over data categories. Impersonation = reading strangers' medical relationships and granting yourself consent scope.
  • Audit trail poisoned: logs attribute actions to victim's user_id.
  • "We'll add JWT later" TODOs have no issue link, no milestone β€” they don't exist until scheduled.
Fix pattern
  • Validate a signed token in-service (jsonwebtoken middleware extracting sub) β€” even behind a gateway, verify independently.
  • If header-mode must exist for local dev: gate it behind a compile feature flag or explicit env like AUTH_MODE=header-dev that refuses to boot in prod config.
  • Add the follow-up as a tracked issue linked from the TODO before merging.
Review phrasing: β€œIdentity currently derives from an unauthenticated, client-controlled header. Even with the planned gateway, the service itself trusts whatever arrives. Please gate header mode behind a non-prod config flag and track the JWT middleware as a blocking issue β€” right now a single misconfigured ingress exposes all family/consent data.”
Drill 3 Β· Severity: MEDIUM-HIGH

Blocking locks + poisoning panics inside async fns

async correctness

Context: The in-memory repositories run under tokio's multi-threaded runtime, shared by every test/integration request via Arc.

async fn create(&self, grant: &ConsentGrant) -> Result<()> { let mut consents = self.consents.write().unwrap(); // std RwLock #1 // …insert… let mut family_index = self.family_index.write().unwrap(); // std RwLock #2 // …update index… let mut grantee_index = self.grantee_index.write().unwrap(); // …update index… Ok(()) }

Which combination of problems does this code carry?

Root cause Γ—3
  • Poisoning: std::sync::RwLock marks itself poisoned if a thread panics while holding it; subsequent .write().unwrap() panics forever. One flaky panic cascades into permanent 500s / test-suite chaos until process restart.
  • Non-atomic multi-lock: consents map updated before indexes; a reader between acquisitions sees a consent with no index entry. Three locks also invite ordering bugs (deadlock) as code grows.
  • Blocking the executor: sync locks stall a tokio worker thread. Tolerable at microsecond scale, but it's a habit that gets copy-pasted around long critical sections β€” and reviewers can't tell which without reading each body.
Fix pattern
// Option A: single Mutex over one struct β€” atomicity by construction struct State { consents: HashMap<Uuid, ConsentGrant>, family_index: HashMap<Uuid, Vec<Uuid>>, … } consents_state: parking_lot::Mutex<State>, // parking_lot = no poisoning // Option B: keep std but handle poisoning explicitly let mut g = self.state.read().unwrap_or_else(|p| p.into_inner());

For pure in-memory doubles, short critical sections with std/parking_lot locks are idiomatic β€” the fix is collapsing to one lock (atomicity) and eliminating unwraps (poisoning), not reaching for tokio::sync (async locks) which these hot paths don't need.

Review phrasing: β€œThree separately-locked maps make create() observable mid-mutation, and .unwrap() turns any panic into a permanently poisoned lock for the rest of the process. Could we consolidate into a single parking_lot::Mutex<State>? Same speed, kills both issues.”
Drill 4 Β· Severity: HIGH (architectural)

The lying test double

test fidelity

Context: GET /families/:id/consents/effective is the endpoint other services will trust for authorization decisions.

async fn get_effective_permissions(&self, family_id: Uuid, user_id: Uuid) -> Result<HashMap<PatientId, Vec<DataCategory>>> { // For now, we'll return a simplified implementation… // Since we don't have access to member repo here, // we'll return empty. The service layer will need to // call this and then enhance with member data. Ok(HashMap::new()) // ← always empty, always Ok }

Integration tests hit build_router_in_memory(), grant a consent, then request effective permissions and get {}. What is the deepest problem?

Root cause

Misplaced responsibility: computing effective permissions needs two aggregates (consents + members), but the method sits on ConsentRepository, which by design can't see members. The double "solves" the impossibility by returning nothing; the comment admits the design flaw and defers it invisibly.

Blast radius
  • Any consumer coding against in-memory behaviour ships authorization logic that grants nobody anything β€” or worse, devs invert logic ("empty means deny") that breaks catastrophically against real Firestore responses.
  • The divergence is invisible in diffs: trait signature satisfied, types match, CI green.
Fix pattern β€” push orchestration up where the repos already meet
// domain/service.rs β€” already holds BOTH ports: pub async fn effective_permissions(&self, family_id: Uuid, grantee: Uuid) -> Result<Permissions> { let members = self.member_repo.list_by_family(family_id, false).await?; let consents = self.consent_repo.list_active_for_grantee(family_id, grantee).await?; compute_effective(members, consents) // PURE function β†’ unit-testable } // Port shrinks to what any backend can honour: list_active_for_grantee. // Both doubles and prod become trivially faithful.

Rule of thumb: a double that returns canned data for logic-bearing methods is a design complaint in disguise β€” the method belongs higher, where dependencies are available, or the port is too wide.

Review phrasing: β€œInMemoryConsentRepository.get_effective_permissions returns an empty map by admission of a missing dependency. That makes our integration suite validate a behaviour prod doesn't have β€” dangerous for a consent/authorization path. Proposal: move computation into FamilyService (which owns both repos) as a pure function, and narrow the port. Doubles then stay honest.”
Drill 5 Β· Severity: HIGH

Pagination theatre β€” cursor accepted, never used

contract bug

Context: The list endpoint advertises cursor pagination via ListResponse<T>.next_cursor.

#[derive(Debug, serde::Deserialize)] pub struct FamilyListParams { pub after: Option<String>, pub limit: Option<usize> } pub async fn list_families( State(state): State<AppState>, headers: HeaderMap, Query(params): Query<FamilyListParams>, ) -> Result<Json<ListResponse<Family>>, AppError> { let user_id = extract_user_id(&headers)?; let families = state.service.list_families_for_user(user_id).await?; // no cursor passed! let limit = params.limit.unwrap_or(20).min(100); let items: Vec<Family> = families.into_iter().take(limit).collect(); let next_cursor = items.last().map(|f| f.id.to_string()); Ok(Json(ListResponse { items, next_cursor })) }

A well-behaved client pages: fetch β†’ get 20 items + cursor C β†’ fetch again with ?after=C. What do they see?

Root cause

Layer-by-layer param dropping: handler parses after but calls a service method whose signature has no room for it; the service method likewise calls list_for_user(user_id, after, limit)-shaped port... except here even the port's own after/limit params go unused by implementations. Each layer individually looks plausible β€” the bug is only visible tracing one parameter across four layers. Classic distributed monolith review failure.

Blast radius
  • Infinite duplicate loops in spec-following clients; data loss appearance (users with >limit families can never see beyond page one).
  • Cursor derived from last item's id, not a sort key β€” even if wired through, unordered Firestore queries give no stable "after this" position.
Fix pattern
// Thread the cursor through EVERY layer, and define ordering: // port: list_for_user(user_id, after: Option<Cursor>, limit) // firestore: .order(created_at).order(id) // tiebreak = stable pagination // .start_after(after.created_at, after.id).limit(limit) // encode cursor opaque: base64("{created_at}|{id}") β€” never raw ids alone // handler: pass through; validate decode errors as 400 VALIDATION_ERROR

And add the missing test: "requesting with the returned next_cursor yields zero overlap and eventually termination."

Review phrasing: β€œnext_cursor implies keyset pagination, but `after` never influences the query β€” page two repeats page one. Either wire cursorβ†’Firestore start_after with a deterministic (created_at, id) ordering, or drop next_cursor from the response until implemented; shipping a contract we don't honour invites infinite loops in clients.”
Drill 6 Β· Severity: CRITICAL

Unauthenticated O(n) bcrypt scan + TOCTOU race

security Β· concurrency

Context: Accept-invitation is intentionally public (that's the invitation flow). bcrypt DEFAULT_COST = 12 β‰ˆ 250ms per verify. Status transitions happen on plain read-modify-write.

pub async fn accept_invitation(&self, token: &str) -> Result<FamilyMember> { for inv in self.invitation_repo.list_all_pending().await? { // load ALL pending… if verify(token, &inv.token).map_err(Internal)? { // ~250ms EACH ⚠ if inv.status != InvitationStatus::Pending { // check… return Err(InvitationInvalid { .. }); } let member = build_member(&inv); self.member_repo.create(&member).await?; // act β€” gap ↑ inv.status = InvitationStatus::Accepted; self.invitation_repo.update(&inv).await?; // …separate write return Ok(member); } } Err(InvitationNotFound) }

An attacker POSTs garbage tokens in a tight loop to /invitations/{token}/accept while two legit tabs accept the same valid invitation simultaneously. What goes wrong?

Root cause Γ—2
  • Crypto in the wrong place: bcrypt is built for verifying a known password hash pair, not for looking up which row matches. Lookup requires a deterministic, indexable digest β€” bcrypt salts are random per hash, so you cannot query by hash directly, forcing the full scan.
  • Check-then-act without transaction: status read, member inserted, status written β€” three operations, no transaction, no conditional update. Firestore executes them independently; interleaved requests interleave states.
Blast radius
  • DoS: ~100 pending invitations Γ— 250ms β‰ˆ 25s CPU per crafted request; 40 req/s saturates a 1-vCPU instance. No auth needed β€” invitations are public by design.
  • Duplicate membership / consent rows from the race; second accept may also resurrect an already-revoked invitation depending on timing.
Fix pattern
// 1. Deterministic lookup hash (token is high-entropy β‡’ fast hash OK): lookup_hash = HMAC_SHA256(server_secret, token); // store THIS, index it inv = repo.get_by_token_hash(lookup_hash).await? // O(1), no scan // 2. Atomic transition β€” Firestore transaction or conditional update: repo.run_transaction(|tx| { inv = tx.get(invitation_ref); ensure!(inv.status == Pending, InvitationInvalid{..}); // re-check INSIDE tx tx.update(invitation_ref, status: Accepted); }) // 3. Rate-limit the route (tower_governor) β€” it's unauthenticated by nature.

Note how Drill 7 completes this fix: hashing/generating tokens should be a port anyway — moving crypto out of the domain is what makes swapping bcrypt→HMAC possible without touching business rules.

Review phrasing: β€œAccept-invitation scans every pending invitation doing a ~250ms bcrypt verify per row on an unauthenticated endpoint β€” a cheap DoS vector β€” and the Pending check + update isn't transactional, so concurrent accepts double-create members. Store an HMAC lookup hash for O(1) retrieval, wrap the transition in a Firestore transaction (or conditional update), and rate-limit the route.”
Drill 7 Β· Severity: DESIGN

The "pure domain" that imports bcrypt

architecture

Context: The PR description claims: β€œdomain/ β€” Pure business logic (FamilyService), zero external crate imports”. Top of domain/service.rs:

use chrono::{DateTime, Duration, Utc, Datelike}; use rand::{Rng, RngExt}; // token generation in domain use bcrypt::{hash, verify, DEFAULT_COST}; // password-grade KDF in domain use tracing::info;

What's the most defensible review position on this?

Root cause

The claim vs reality gap matters less than the coupling itself. Domain purity isn't aesthetic: it exists so that (a) business rules can be tested without paying infrastructure costs, and (b) policies that change for non-business reasons (upgrade bcrypt→argon2, rotate token entropy) touch exactly one layer. Crypto embedded in service.rs couples invitation lifecycle rules to a specific KDF and its cost parameter forever.

Blast radius
  • Every invitation unit test pays ~250ms Γ— cases; suites slow down multiplicatively as flows grow.
  • Algorithm migration requires editing business logic β€” the highest-review-cost file in the crate.
  • Domain tests can't stub verification, so edge-case matrices (expired+accepted+revokedΓ—valid token) need the real slow path.
Fix pattern
// ports/token_service.rs β€” capability port, owned by core like the repos #[async_trait] // not needed here β€” sync is fine pub trait TokenService: Send + Sync { fn generate(&self) -> String; // CSPRNG at the edge fn lookup_hash(&self, raw: &str) -> String; // enables Drill 6 fix fn verify(&self, raw: &str, stored: &str) -> bool; } // adapters/secondary/crypto/bcrypt_token_service.rs implements it; // tests inject a fake returning instant results. Domain keeps the RULES // (β€œpending expires after 7 days”), loses the MECHANISM (bcrypt=12).

Calibration for reviews: treat uuid/chrono/tracing/serde as ecosystem-stdlib β€” acceptable in domain. Treat I/O, crypto, randomness sources, clock implementations (inject Clock if determinism matters), HTTP clients as ports. Say why in review; "it's impure" convinces no one.

Review phrasing: β€œDescription says zero external imports in domain, but service.rs pulls bcrypt/rand. Beyond the doc mismatch: token generation/hashing is policy we WILL change (cost tuning, argon2 migration, HMAC lookups). Extract a small TokenService port β€” domain keeps lifecycle rules, adapters keep crypto, tests get a free instant fake. uuid/chrono/tracing I'm fine leaving as-is.”

Bonus quick-fire findings (from the same PR)

SpotFinding
main.rsSilent fallback to project "agentic-health-dev" if env vars unset β€” in prod this boots successfully pointed at the WRONG database. Prefer expect("GCP_PROJECT_ID required") outside dev profiles.
Cargo.tomlMissing trailing newline; tokio features=["full"] pulls unused subsystems β€” slim to ["macros","rt-multi-thread"].
router.rsRoute params use :param (axum ≀0.7 style); axum 0.8 moved to {param} β€” works now via compat, flagged deprecated. Watch for it in the upgrade.
handlers.rsDouble .map_err(...).map_err(AppError) chains β€” a newtype would collapse them; minor readability.
dto.rs / InvitationResponseGood instinct: raw token present only on create response. Worth a comment stating the invariant so future edits preserve it.
πŸ“–

Glossary

TermMeaning
Hexagonal architectureCockburn's pattern: core logic surrounded by ports/interfaces; adapters plug in. Dependencies point inward only.
PortA trait the core owns defining a capability boundary (e.g. FamilyRepository). Primary ports are implemented by the core & called by drivers; secondary ports are called by the core & implemented by driven adapters.
AdapterConcrete implementation connecting a technology to a port: axum handlers (primary/driving), Firestore & in-memory repos (secondary/driven).
DTOData Transfer Object β€” wire-shaped struct in the adapter layer, decoupled from domain models; carries serde + OpenAPI derives.
Composition rootSingle place where concrete implementations are chosen and injected (build_router_with_firestore vs build_router_in_memory).
Trait object / dynType-erased dispatch through a vtable: dyn FamilyRepository. Requires object safety.
Object safety (dyn compatibility)Rules a trait must satisfy to be usable as dyn β€” no generic methods, no native async fn without boxing.
#[async_trait]Proc macro rewriting trait async fns to return boxed futures, enabling dyn-compatible async traits.
Arc<T>Atomically reference-counted shared pointer; the mechanism for sharing service/repos across tokio tasks.
Send / SyncMarker traits: movable across threads / referable from many threads. Required bounds for multi-threaded runtimes.
Interior mutabilityMutation through shared references using locks/atomics (RwLock, Mutex, Cell) β€” how &self repo methods persist data.
thiserrorDerive macro generating Display/Error impls for typed error enums.
IntoResponseAxum trait converting any type into an HTTP response; the hook where FamilyError becomes status+JSON.
utoipaOpenAPI codegen from annotations/derives; pairs with SwaggerUi mount for live docs.
ServiceSessionfirestore-db-and-auth session authenticated via GCP service account (server-to-server).
Test double fidelityDegree to which an in-memory implementation honours port semantics; low fidelity = tests validate fiction.
TOCTOUTime-of-check to time-of-use race: state validated, then changed by others before acting β€” fixed with transactions/conditional updates.
Keyset (cursor) paginationPage tokens derived from ordered last-seen key (created_at,id), not offsets; requires deterministic sort + start_after support.
WorkspaceCargo multi-crate layout sharing one lockfile/target dir; versions unified via [workspace.dependencies].
Graceful shutdownOn SIGTERM: stop accepting, drain in-flight requests, then exit β€” axum::serve(..).with_graceful_shutdown(..).