From 671ab2928bb04cf76d0afb46e067675d2fa87682 Mon Sep 17 00:00:00 2001 From: Bobby Date: Mon, 16 Nov 2026 16:48:32 -0500 Subject: [PATCH] docs: add MVP spec and glossary for HAPI --- GLOSSARY.md | 85 ++++++++++++++++++++ MVP-SPEC.md | 226 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 311 insertions(+) create mode 100644 GLOSSARY.md create mode 100644 MVP-SPEC.md diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..cfca83a --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,85 @@ +# HAPI Glossary + +## Core Concepts + +### API +The central service exposing HTTP endpoints for clients (humans, bots, frontend). Built with FastAPI, providing REST endpoints, JSON logs, and health checks. + +### Environment +An instance of the API serving requests. **Staging** mirrors production for testing; **Production** serves real users. Each has its own PostgreSQL database. + +### Migration +A versioned change to the database schema, managed by Alembic. Migrations are additive by default, with destructive changes behind flags. + +### Secret +A sensitive value (password, API key, token) stored encrypted. Managed via SOPS with age encryption, committed to Git alongside code. + +### Object Storage +A service for storing files (uploads, assets). We use Linode Object Storage as primary, with NextCloud as a backup destination. + +### Health Check +An endpoint (`/health`) that reports the API's operational status and dependency health (DB, object storage, etc.). + +### Alert +A notification sent to NTFY when an error or warning occurs. Includes severity, context, and details for quick triage. + +## Modules + +### Auth Module +Handles user authentication via JWT tokens. Supports token-based rate limiting; extensible for OAuth2 and API keys. + +### Router Module +API endpoints grouped by domain (users, items, etc.). Each router is a self-contained module with its own schemas and service calls. + +### Schema Module +Pydantic models defining request/response shapes. Separated from routers to enable reuse and testing. + +### Service Module +Business logic separated from HTTP concerns. Services are testable in isolation and called by routers. + +### DB Module +Database connection and utility functions. Includes session management, connection pooling, and migration orchestration. + +## Infrastructure + +### Kubernetes Cluster +Self-hosted Kubernetes for production and staging deployments. Uses StatefulSet for PostgreSQL. + +### Terraform +Infrastructure as code for Linode resources (VMs, PostgreSQL, Object Storage, LCR). + +### Gitea CI/CD +Automated workflows for building, testing, and deploying the API. Uses act_runner for GitHub Actions-compatible workflows. + +### Docker Compose +Local development environment with FastAPI, PostgreSQL, and Adminer. + +## Observability + +### Structured Logging +JSON-formatted logs for structured querying and analysis. Each log entry includes timestamp, level, message, and context. + +### UptimeKuma +Monitoring service that polls `/health` endpoint to track API availability. + +### NTFY +Push notification service for alerts. API sends error/warning notifications with configurable topics. + +## Deployment + +### Rollout +Deployment of a new API version to an environment. Uses Kubernetes rolling updates for zero-downtime. + +### Tagging +Version tags (e.g., `v1.0.0`) trigger production deployments. Staging deploys from `main` branch. + +## Future Considerations + +### WebSockets +Real-time communication layer for frontend. Not included in MVP; ready for later addition. + +### GraphQL +Alternative query layer for complex frontend queries. Not included in MVP; REST is sufficient initially. + +### NextCloud Backup +Secondary storage for uploads, mirroring Linode Object Storage to NextCloud for redundancy. diff --git a/MVP-SPEC.md b/MVP-SPEC.md new file mode 100644 index 0000000..75eb608 --- /dev/null +++ b/MVP-SPEC.md @@ -0,0 +1,226 @@ +# 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).