Files
hapi/MVP-SPEC.md
T

9.6 KiB

HAPI MVP Spec

Problem Statement

I'm building a personal API project called HAPI (Home API). It needs to be a flexible, extensible foundation for various domains (fitness, finance, maintenance, etc.) that I and my family will use. The system should:

  • Start simple but scale as features grow
  • Be easy to develop locally and deploy to cloud
  • Include observability (logging, alerts, health checks)
  • Support automation (cron jobs, webhooks)
  • Store files (uploads to Linode Object Storage + NextCloud backup)
  • Be testable and maintainable as a solo developer

Currently, the repository is empty (just .git), so we're building from scratch.


Solution

Build an MVP with:

  1. Layered FastAPI Application: Modular structure (models/, routers/, schemas/, services/, db/) with JWT auth and rate limiting.

  2. Database: PostgreSQL with Alembic migrations, separate databases for staging and production.

  3. Infrastructure: Terraform-managed Linode resources (VMs, PostgreSQL, Object Storage, LCR) and Kubernetes StatefulSet for PostgreSQL.

  4. Observability: JSON structured logging with NTFY alerts, UptimeKuma polling of /health.

  5. CI/CD: Gitea Actions with act_runner for build, test, and deploy workflows.

  6. Local Dev: Docker Compose with FastAPI (hot reload), PostgreSQL, and Adminer.

The seam for testing is at the FastAPI application level—tests cross the HTTP interface to verify behavior end-to-end.


User Stories

  1. As a developer, I want a FastAPI application with a layered structure, so that I can keep concerns separated and scale the codebase cleanly.

  2. As a developer, I want JWT authentication for API access, so that only authorized users and bots can use the API.

  3. As a developer, I want rate limiting on API endpoints, so that I can protect the system from abuse or accidental overuse by bots.

  4. As a developer, I want PostgreSQL with migrations, so that schema changes are tracked and reversible.

  5. As a developer, I want separate staging and production databases, so that I can test changes safely before releasing to production.

  6. As a developer, I want a /health endpoint, so that UptimeKuma can monitor API availability.

  7. As a developer, I want dependency checks in /health (DB, object storage), so that I can see which components are down vs. just the API.

  8. As a developer, I want JSON structured logging, so that logs are queryable and analyzable.

  9. As a developer, I want NTFY alerts for errors and warnings, so that I get notified in real-time when something breaks.

  10. As a developer, I want file upload support (Linode Object Storage + NextCloud backup), so that I can store documents, images, or other assets.

  11. As a developer, I want Docker Compose for local development, so that I can run the full stack locally with hot reload.

  12. As a developer, I want Adminer for local database access, so that I can inspect and query the database without extra tooling.

  13. As a developer, I want Terraform for infrastructure provisioning, so that my cloud resources are versioned and reproducible.

  14. As a developer, I want Kubernetes StatefulSet for PostgreSQL, so that I can learn about Kubernetes storage and stateful workloads.

  15. As a developer, I want Gitea CI/CD with automated deployment, so that new code is deployed automatically to staging.

  16. As a developer, I want staging to deploy automatically on main branch, so that I can test changes quickly.

  17. As a developer, I want production to deploy on tags, so that I can control releases manually.

  18. As a developer, I want SOPS + age for secrets management, so that sensitive values are encrypted in Git.

  19. As a developer, I want to store SOPS age keys in Vaultwarden, so that I have one place for all secrets.

  20. As a developer, I want Gitea Actions to build Docker images with buildx, so that I have full control over the build process.

  21. As a developer, I want Pytest tests with a separate test database, so that I can test API endpoints without affecting dev data.

  22. As a developer, I want a simple branching strategy (main + feature branches), so that I can keep development straightforward.

  23. As a developer, I want cron/webhook hooks for automation, so that I can trigger tasks or external actions.

  24. As a developer, I want a lean MVP scope, so that I can focus on core functionality first.

  25. As a developer, I want breadth-first learning, so that I gain exposure to many tools before diving deep.

  26. As a user (myself), I want to access the API from my phone or laptop, so that I can use it on the go.

  27. As a user (my wife), I want a simple interface for her dashboard, so that she can view and manage shared data.

  28. As a bot developer, I want API keys for bot access, so that each bot has isolated permissions.

  29. As a developer, I want to expand the API with new modules (fitness, finance, maintenance), so that I can extend functionality over time.

  30. As a developer, I want to add WebSockets later, so that real-time features don't block the MVP.

  31. As a developer, I want to add GraphQL later, so that I can evaluate if it's needed for frontend complexity.

  32. As a developer, I want to scale infrastructure as needed, so that I can handle more users or data without rework.


Implementation Decisions

Module Structure

  • Layered Architecture: Modules are organized by layer (models/, routers/, schemas/, services/, db/) rather than domain, to keep the codebase simple for a solo developer.

  • FastAPI as the Core Framework: Chosen for its async support, automatic OpenAPI docs, and ease of testing.

Database

  • PostgreSQL with Alembic: Alembic handles migrations with additive-by-default changes; destructive changes are behind flags.

  • Separate Databases for Environments: Staging and production have separate databases on possibly shared instances to keep data isolated.

  • StatefulSet for Production: Kubernetes StatefulSet for PostgreSQL provides learnable infrastructure with persistent storage.

Authentication

  • JWT Tokens: Simple token-based auth with a secret key (stored in Vaultwarden). Designed to support multiple signers or OAuth later.

  • Token-Based Rate Limiting: Per-token limits in FastAPI middleware; extensible to Redis or Traefik later.

Observability

  • JSON Structured Logging: Logs include timestamp, level, message, and context (e.g., request ID, user ID).

  • NTFY Alerts: API pushes errors/warnings to NTFY with severity and topic (e.g., "Database connection failures").

  • Health Endpoint: /health checks DB and object storage; /health/ready and /health/live added later if needed.

File Storage

  • Linode Object Storage Primary: S3-compatible for uploads; integrated via Python SDK.

  • NextCloud Backup: Secondary storage for uploads, mirrored from Linode for redundancy.

CI/CD

  • Gitea + act_runner: Uses GitHub Actions-compatible workflows for build, test, push, and deploy.

  • Auto-Deploy Staging: On main branch push; manual/tag-triggered for production.

  • Docker buildx: Full control over image builds with caching and multi-platform support.

Testing

  • Pytest with Separate Test DB: Tests run against hapi_test database to avoid affecting dev data.

  • Test Through HTTP Interface: Tests call API endpoints (not internal functions) to verify real-world behavior.

Secrets Management

  • SOPS + age: Encrypted files in Git; age keys stored in Vaultwarden.

Future-Ready

  • WebSockets Later: Ready for future frontend; not included in MVP.

  • GraphQL Optional: REST-only for now; GraphQL can be added as a separate module.


Testing Decisions

What Makes a Good Test

  • Tests verify external behavior (HTTP responses, side effects) not implementation details (e.g., which service method was called).

  • Tests cover edge cases (auth failures, DB down, storage errors) and happy paths.

  • Tests are fast (in-memory DB or test fixtures where possible) and isolated (test DB per test run).

Modules to Test

  • API Endpoints: Pytest fixtures for TestClient; test all routers.

  • Auth Module: Token generation, validation, and revocation.

  • Health Endpoint: DB and storage dependency checks.

  • Logging: JSON output format and context fields.

  • Object Storage: Upload/download/cleanup workflows.

Prior Art

  • FastAPI's own testing guide (test client, fixtures).

  • Alembic's migration testing patterns.

  • NTFY API for alert payload testing.


Out of Scope

  • WebSockets: Real-time features for frontend; added later.

  • GraphQL Layer: Optional alternative to REST; added if frontend complexity grows.

  • OAuth2 Providers: Auth is JWT-only for MVP; OAuth can be added later.

  • Advanced PostgreSQL Features: TimescaleDB, PostGIS, etc.; added as needed.

  • Multi-Region Deployment: Single-region for MVP; scaling out later.

  • Advanced Monitoring: Prometheus/Grafana for metrics; NTFY/structured logs suffice for MVP.

  • CI/CD Advanced Features: Automated changelog generation, release notes; simple deploy for MVP.


Further Notes

  • Learning Focus: The design prioritizes breadth-first learning (Terraform, Kubernetes, SOPS, etc.) while keeping the MVP lean.

  • Cost Flexibility: Since cloud costs aren't a concern, we favor robust setups (separate DBs, object storage redundancy) over minimal cost.

  • Extensibility: Modules are designed to be added incrementally (fitness, finance, maintenance) without refactoring.

  • Tooling Choices: Tools are selected for learning value (e.g., StatefulSet for PostgreSQL over managed DBs) and ease of use (SOPS over HashiCorp Vault for secrets).