Add a Module (feature end to end)
Build inside-out, proving each ring before the next. Use references/module-template.md as an adaptable example, not a project preset. Consult fastapi-foundation/references/layout.md only if the existing repository follows that layout.
The recipe
0. Inventory the actual project before proposing a design. Inspect the repository tree, project instructions, dependency manifests/lockfiles and installed/runtime versions, app entrypoints and settings, existing modules and tests, auth/identity types and their source, and the real persistence clients/adapters/schema/migrations. Identify the existing ID generator/representation, event mechanism, test commands, and any architecture contracts. Report the observed facts and gaps briefly. Do not assume Profile A, MongoDB, Redis, ObjectId, or even a database; do not install or introduce infrastructure just to fit this template. If the storage or identity cannot be established, ask only the clarifying question that blocks a safe design.
1. Scope - one paragraph: purpose, actor, endpoints, explicit exclusions, and guided/delivery mode. Decide whether work is synchronous; defer workers/fan-out unless required.
2. Domain (domain/, or the project's equivalent)
- Keep business rules in entities/value objects. Validate and normalize at creation; bound sizes.
- Add domain errors using the repository's existing taxonomy and unique codes.
- Represent external needs as intent-named ports with documented consistency/atomicity semantics.
3. Application (application/, or equivalent)
- Follow the project's use-case conventions. Inject clocks, ID generation, persistence ports, and event ports where appropriate.
- Typical write flow: load/decide -> persist -> publish only after successful persistence -> return. Make idempotency and event-delivery semantics explicit; see Hard rules.
- Keep read models/ports separate where the project does. Catch only known, typed failures when degrading; do not swallow arbitrary exceptions.
4. Unit tests with fakes - follow existing test locations and conventions. Cover success, domain errors, authorization, bounds, duplicate/idempotent requests, event behavior, and ID conversions as applicable. These tests should not need a real database or FastAPI. Run them before implementing adapters when the repository supports this sequence.
5. Persistence adapter - use only the storage technology actually used by the project. Match its driver and version, guard/error translation, schema/migration/index conventions, and atomicity guarantees. Add concurrency-safe constraints/conditional writes and an integration test against the real store when available. Do not copy the Mongo sample below into a different storage stack.
6. HTTP adapter - follow existing DTO, dependency, auth, rate-limit, and error-mapping patterns. Keep routes thin; obtain identity from the established authenticated principal, never a client-supplied actor ID.
7. Wire and document - register the adapter/route in the actual composition root; update architecture contracts, API/module docs, error catalogs, or migrations only where the repository requires them. State verified and unverified behavior honestly.
8. Verify - discover commands from the repository (for example, its Makefile, pyproject, CI, and project instructions); run the relevant checks and integration tests only when their dependencies are available. Report exact commands and outcomes. Do not claim tests passed if they were not run.
Hard rules
- A module does not import another module's internals. Use an owned port/bridge or the project's established event boundary.
- Align new IDs with the actual foundation's
IdGenerator, public representation, persistence codec, and existing IDs. Treat UUID and ObjectId as configurable alternatives, not interchangeable strings. Test parse/encode round trips and malformed inputs for the selected representation. - Never call a write idempotent just because it persists before publishing. A retry that creates a fresh ID is not idempotent unless the request carries a stable idempotency key and persistence atomically enforces that key (with request-fingerprint conflict handling) and returns the original result. Otherwise say plainly that it is not safe to retry.
- For create requests, scope the key to the authenticated actor and operation; validate its size/format, retain it for a documented window or for the resource lifetime, and atomically bind it to a request fingerprint and result. Define behavior for key reuse with different input. Test concurrent duplicates and replay.
- If persistence succeeds but event publication fails, do not rerun the create as a new operation or generate a second resource. Make client response/retry behavior explicit and use a stable event ID with consumer deduplication where relevant. Events sent directly after persistence are best-effort and can be lost or delivered more than once. If losing an event is unacceptable, persist an outbox record atomically with the business write and dispatch/retry it separately; make consumers idempotent.
- Lists enforce a server-side maximum and validate requested limits. Cursors are opaque API tokens, signed/verified (or protected by an equivalent authenticated mechanism), versioned/documented, bound to the relevant filters/order, and rejected on tampering or invalid shape. Signing does not encrypt cursor contents; do not put secrets in them.
- Check authorization against the authenticated actor in the application/domain boundary. Do not trust client-sent identity fields.
Guided mode specifics
Give each ring as a step (goal -> files -> code -> why -> alternatives -> verify). When the user submits their version, first state what matches, then gaps by severity (correctness > security > layering > naming > style), including production cost. A below-reference version is normal; explain the delta plainly and let the user complete it where useful.
Done checklist
- Repository structure, dependency/runtime versions, identity, and actual persistence inspected; no unobserved profile/technology assumed
- Domain rules and ports follow project conventions; errors are unique
- ID representation aligns with foundation and has conversion tests
- Retry semantics are honest; idempotency key is atomically enforced or operation is explicitly non-retryable
- Event best-effort/failure behavior is explicit; outbox used if event loss is unacceptable
- Unit tests and applicable real-store integration tests run and results are reported accurately
- List limit is bounded; cursor is opaque, signed/validated, and documented
- Auth, wiring, architecture contracts, and docs follow the actual repository