refactor(api): enforce protocol-neutral service boundaries

- refactor: move HTTP status and DTO concerns out of model and service
  layers into API and handler code.
- feat: add admin service boundary and route auth through services
  instead of direct repository access.
- test: add architecture and error tests covering package boundaries,
  redaction, and service behavior.
- docs: record the protocol-neutral boundary decision and update
  architecture and roadmap notes.
This commit is contained in:
2026-07-05 23:30:17 +08:00
parent 28e17a5b08
commit 63ede5c237
34 changed files with 1028 additions and 438 deletions
+11 -4
View File
@@ -14,7 +14,12 @@ Repository (GORM data access) Storage (file I/O)
Rules:
- Handler has no business logic — parse request, call service, write response.
- Handler and middleware never access repositories directly; they depend on services.
- Service has no HTTP awareness — operates on domain models and interfaces.
- `internal/model` and `internal/service` do not import `net/http`, Gin, or `internal/api`.
- JSON response DTOs live in HTTP packages. Domain and service result structs are not the public REST schema.
- Domain models may use `json:"-"` for defensive redaction of sensitive fields; this is not a REST response contract.
- Domain errors carry a protocol-neutral kind, a safe message, and an optional cause. HTTP status mapping happens only at the API boundary.
- Repository abstracts the database; Storage abstracts where bytes live, including staged upload promotion.
- `internal/server` is the composition root — wires all dependencies together.
@@ -31,12 +36,12 @@ Rules:
| **HTTP** | `internal/server` | Gin router init, route registration (public/protected split), graceful shutdown | ✅ |
| | `internal/handler` | HTTP handlers (auth, file, admin, webdav...) | 🛠 WIP |
| | `internal/middleware` | Gin middleware (logger, jwt, cors, auth) | 🛠 WIP |
| **Business** | `internal/service` | Business logic: `AuthService` (register, login, refresh, logout, passkey CRUD) | ✅ |
| | `internal/model` | Domain types (User, File, Credential, Session), error codes | ✅ |
| **Business** | `internal/service` | Business logic: `AuthService`, `FileService`, `AdminService`; protocol-neutral results and errors | ✅ |
| | `internal/model` | Domain types (User, File, Credential, Session), protocol-neutral error kinds | ✅ |
| **Data** | `internal/repository` | Repository interfaces + GORM implementations (User, Session, File, Credential) | ✅ |
| | `internal/storage` | Storage backend interface + local disk impl, with staging and promotion | 🛠 WIP |
| **Util** | `internal/auth` | JWT sign/verify (HS256), token type discrimination (access/refresh), password hashing (bcrypt), app passkey tokens | ✅ |
| | `internal/api` | Unified JSON error response helpers | ✅ |
| | `internal/api` | Unified JSON error response helpers and REST error-kind mapping | ✅ |
## API Routes (v0)
@@ -72,7 +77,9 @@ Applied globally by `gin.Default()`: logger → recovery
Planned globally: cors
Applied to protected groups: auth (JWT validation, inject user into gin.Context)
Applied to protected groups: auth (extract bearer token, delegate access-token authentication to `AuthService`, inject principal into gin.Context)
Applied to admin groups: admin (check authenticated principal from context)
## Server Responsibilities
+19
View File
@@ -87,3 +87,22 @@
- Interrupted, malformed, and oversized uploads leave only staging objects, which are safe to clean by path prefix and age.
- Local storage promotes with `os.Rename` and falls back to copy/delete on cross-device `EXDEV`; future S3 storage can implement promotion with copy/delete while keeping business visibility controlled by the DB row.
- A DB failure after promotion can still leave a long-term orphan object, but it is not visible through the file API and can be cleaned independently.
## 2026-07-05: Protocol-Neutral Service Boundary
**Context**: The service and model layers carried HTTP status codes and JSON response tags, and some middleware and handlers accessed repositories directly. That made the business layer harder to reuse for future WebDAV and Nextcloud-compatible APIs.
**Decisions**:
| Decision | Guidance |
|----------|----------|
| Protocol-neutral errors | `model.AppError` uses an error `Kind`, safe message, and optional cause. REST status codes are mapped in `internal/api` only. |
| API log references | REST error responses may include `error.log_id` for server-recorded errors: all 5xx responses and 4xx responses with internal causes. |
| Service boundaries | Handlers and middleware depend on services, not repositories. `AuthService` authenticates access tokens into a principal; `AdminService` owns admin user operations. |
| DTO ownership | Service and model structs are internal/domain data. HTTP handlers assemble response DTOs with JSON tags. |
| Architecture enforcement | Package-level tests reject HTTP imports in model/service and repository imports in handlers/middleware. Targeted model tests verify defensive JSON redaction for sensitive fields. |
**Consequences**:
- REST remains a handler/API concern, and future protocols can reuse services without HTTP leakage.
- Error responses keep the same top-level shape, with optional `log_id` instead of embedding log references in the message.
- Admin and auth middleware behavior is testable through service contracts rather than database access.
+6 -5
View File
@@ -8,7 +8,7 @@
| JWT authentication | ✅ | access + refresh tokens, refresh token in DB, app passkey support |
| Web API foundation | ✅ | WebApp composition, Gin router, graceful shutdown, `GET /api/v1/version` |
| File upload/download/manage APIs | 🛠 WIP | REST API via Gin |
| Admin endpoints | 🛠 WIP | user CRUD for superusers |
| Admin endpoints | 🛠 WIP | user service boundary in place for superusers |
| WebDAV | 🛠 WIP | future v0 or v1 |
## Implementation Tasks
@@ -18,16 +18,17 @@ Package-level implementation order (each task includes unit tests):
1. `internal/config` — Viper loader, config struct ✅
2. `internal/app` — runtime dependency container ✅
3. `internal/model` — domain types, error codes ✅
4. `internal/api`error response helpers
4. `internal/api`protocol-neutral error kind to REST response mapping
5. `internal/auth` — JWT utils ✅
6. `internal/storage` — backend interface + local fs with staged upload promotion
7. `internal/repository` — interfaces + GORM/SQLite impl ✅
8. `internal/service` — auth, file, admin services ✅ (auth done)
9. `internal/middleware` — logger, cors, auth ✅ (auth done)
10. `internal/handler` — auth, account, file, admin handlers 🛠 (auth + account done)
8. `internal/service` — auth, file, admin services ✅
9. `internal/middleware` — logger, cors, auth ✅ (auth done; principal boundary enforced)
10. `internal/handler` — auth, account, file, admin handlers 🛠 (HTTP DTO mapping in place)
11. `internal/server` — Gin router, route registration, graceful shutdown ✅
12. `cmd/serve.go`, `cmd/config.go`, `cmd/status.go` ✅ (serve done)
13. Integration tests
14. Architecture boundary tests ✅
## Future