Rust Domain Boundaries
Use this skill to keep invalid states out of Rust service internals. Parse raw
input once at the boundary, store validated values in narrow domain types, and
make unchecked construction difficult.
Core Workflow
- Find raw input boundaries: HTTP payloads, path/query parameters, config
files, environment variables, database rows, queues, and CLI flags.
- Separate transport DTOs from domain types. Let
serde deserialize incoming
shapes, then convert DTO fields into validated domain values.
- Replace primitive strings with small types for ruled values: email addresses,
usernames, passwords, subscriber names, slugs, tenant IDs, idempotency keys,
and money-like or duration-like values.
- Give domain types private fields and smart constructors. Avoid unchecked
pub fields or impl From<String> for fallible conversions.
- Return typed validation errors that map to useful HTTP responses without
leaking internal details.
- Keep database and external API mapping explicit. Convert to raw strings at
the final persistence or serialization edge.
- Test invariants directly. Cover valid examples, malformed inputs, boundary
lengths, normalization rules, and round trips.
Type Design Rules
- Prefer
TryFrom<String>, TryFrom<&str>, or FromStr for fallible parsing.
- Keep stored values owned unless profiling proves borrowing is necessary.
- Implement
AsRef<str> or a named accessor for read-only exposure.
- Implement
Display only when the formatted value is safe to show in logs,
errors, and UI.
- Avoid deriving
Debug for secret-bearing values unless the debug output is
redacted.
- Make normalization visible in tests: trim, lowercase, Unicode handling, and
canonicalization.
Request Boundary Pattern
Deserialize into a request shape, then construct a command:
#[derive(serde::Deserialize)]
pub struct SubscribeRequest {
email: String,
name: String,
}
pub struct SubscribeCommand {
pub email: EmailAddress,
pub name: SubscriberName,
}
impl TryFrom<SubscribeRequest> for SubscribeCommand {
type Error = SubscribeValidationError;
fn try_from(value: SubscribeRequest) -> Result<Self, Self::Error> {
Ok(Self {
email: EmailAddress::parse(value.email)?,
name: SubscriberName::parse(value.name)?,
})
}
}
Handlers should reject invalid input before business logic or database code. If
validation needs database state, keep pure parsing separate from uniqueness or
authorization checks.
Tests
Read references/property-testing.md when invariants have many edge cases or
when an AI agent is likely to miss invalid inputs with example-only tests.
Minimum tests for a new domain type:
- Accept a realistic valid value.
- Reject empty input and whitespace-only input.
- Reject too-long input when storage or product rules impose limits.
- Reject format violations.
- Preserve or normalize exactly as documented by tests.
- Round-trip through
serde or SQL mapping when that type crosses those
boundaries.
Reference Files
references/newtype-patterns.md: constructor, trait, serde, and persistence
patterns for Rust newtypes.
references/property-testing.md: property-testing strategy for parsers and
domain constructors.
1---2name: rust-domain-boundaries3description: Use when modeling, validating, refactoring, or reviewing Rust service domain boundaries, especially when replacing primitive String fields with newtypes, parse-don't-validate constructors, private invariants, TryFrom/FromStr parsers, request DTO boundaries, or property tests.4license: MIT5compatibility: Codex, Claude Code, and other Agent Skills-compatible clients.6metadata:7 version: "0.1.0"8 displayName: Rust Domain Boundaries9 category: Rust10 tags: rust,domain-modeling,newtypes,validation,property-testing11---1213# Rust Domain Boundaries1415Use this skill to keep invalid states out of Rust service internals. Parse raw16input once at the boundary, store validated values in narrow domain types, and17make unchecked construction difficult.1819## Core Workflow20211. Find raw input boundaries: HTTP payloads, path/query parameters, config22 files, environment variables, database rows, queues, and CLI flags.232. Separate transport DTOs from domain types. Let `serde` deserialize incoming24 shapes, then convert DTO fields into validated domain values.253. Replace primitive strings with small types for ruled values: email addresses,26 usernames, passwords, subscriber names, slugs, tenant IDs, idempotency keys,27 and money-like or duration-like values.284. Give domain types private fields and smart constructors. Avoid unchecked29 `pub` fields or `impl From<String>` for fallible conversions.305. Return typed validation errors that map to useful HTTP responses without31 leaking internal details.326. Keep database and external API mapping explicit. Convert to raw strings at33 the final persistence or serialization edge.347. Test invariants directly. Cover valid examples, malformed inputs, boundary35 lengths, normalization rules, and round trips.3637## Type Design Rules3839- Prefer `TryFrom<String>`, `TryFrom<&str>`, or `FromStr` for fallible parsing.40- Keep stored values owned unless profiling proves borrowing is necessary.41- Implement `AsRef<str>` or a named accessor for read-only exposure.42- Implement `Display` only when the formatted value is safe to show in logs,43 errors, and UI.44- Avoid deriving `Debug` for secret-bearing values unless the debug output is45 redacted.46- Make normalization visible in tests: trim, lowercase, Unicode handling, and47 canonicalization.4849## Request Boundary Pattern5051Deserialize into a request shape, then construct a command:5253```rust54#[derive(serde::Deserialize)]55pub struct SubscribeRequest {56 email: String,57 name: String,58}5960pub struct SubscribeCommand {61 pub email: EmailAddress,62 pub name: SubscriberName,63}6465impl TryFrom<SubscribeRequest> for SubscribeCommand {66 type Error = SubscribeValidationError;6768 fn try_from(value: SubscribeRequest) -> Result<Self, Self::Error> {69 Ok(Self {70 email: EmailAddress::parse(value.email)?,71 name: SubscriberName::parse(value.name)?,72 })73 }74}75```7677Handlers should reject invalid input before business logic or database code. If78validation needs database state, keep pure parsing separate from uniqueness or79authorization checks.8081## Tests8283Read `references/property-testing.md` when invariants have many edge cases or84when an AI agent is likely to miss invalid inputs with example-only tests.8586Minimum tests for a new domain type:8788- Accept a realistic valid value.89- Reject empty input and whitespace-only input.90- Reject too-long input when storage or product rules impose limits.91- Reject format violations.92- Preserve or normalize exactly as documented by tests.93- Round-trip through `serde` or SQL mapping when that type crosses those94 boundaries.9596## Reference Files9798- `references/newtype-patterns.md`: constructor, trait, serde, and persistence99 patterns for Rust newtypes.100- `references/property-testing.md`: property-testing strategy for parsers and101 domain constructors.