refactor(backend): standardize errors and simplify configuration and test setup
This commit is contained in:
1 parent
1535c19b8c
commit
138666a7bb
92 files changed
+3994
-210
No files matched your search
+30
-1
@@ -36,6 +36,8 @@ Use each area's Makefile for its focused loop, for example make -C backend help,
|
||||
|
||||
make check is not a business end-to-end suite. make verify runs a deployment smoke with Docker and a backend integration target. See [TESTING.md](TESTING.md) for validation scope and [DEPLOY.md](DEPLOY.md) for the local stack.
|
||||
|
||||
Security tools have a separate install and work loop: `make -C security install`, then `make -C security check`. Use `make -C security test` after changing local rules or scanner integration and `make -C security images` to build and scan service images. These checks are separate from the ordinary root `make check`; see [SECURITY.md](SECURITY.md) for prerequisites, policies, and reports.
|
||||
|
||||
## Layout
|
||||
|
||||
| Directory | Purpose |
|
||||
@@ -49,6 +51,7 @@ make check is not a business end-to-end suite. make verify runs a deployment smo
|
||||
| ml/ | Python service, lockfile, and Pydantic model generator |
|
||||
| deploy/ | Compose, Nginx, and smoke script |
|
||||
| observability/ | Prometheus, Loki, Alloy, provisioning, and dashboard JSON |
|
||||
| security/ | Scanner configuration, installation, Make targets, and local reports |
|
||||
| .agents/ | Canonical project instructions and working standards |
|
||||
| docs/ru/, docs/en/ | User documentation in Russian and English |
|
||||
|
||||
@@ -72,7 +75,11 @@ Go follows domain, usecase, port, adapter, and bootstrap boundaries. The HTTP ad
|
||||
|
||||
Shared backend settings live in backend/config/. The service uses go-logkit 0.6.0 through its slog bridge and go-httpkit 0.7.0 for request IDs, request logging, and panic recovery. It retains custom Prometheus middleware because it bounds method labels and uses chi route patterns; go-httpkit/metrics accepts the raw method name as a label.
|
||||
|
||||
PostgreSQL uses pgxpool.NewWithConfig, and a generated SELECT 1 readiness query checks connectivity. Pool construction must not wait for the database during startup. go-pgkit 1.4.0 is not used because its constructor probes and retries before returning a pool, coupling service startup to database availability. Health handlers remain explicit: go-httpkit's helper returns ok/degraded with check details, while the shared contract uses ok/ready/not_ready. Do not add pgkit, httpkit/metrics, JWT, cache, or WebSocket without a concrete need and a check of the pinned version's behavior.
|
||||
PostgreSQL uses pgxpool.NewWithConfig, and a generated SELECT 1 readiness query checks connectivity. Pool construction must not wait for the database during startup. go-pgkit 1.4.0 is not used because its constructor probes and retries before returning a pool, coupling service startup to database availability. Health handlers remain explicit: go-httpkit's helper returns ok/degraded with check details, while the shared contract uses ok/ready/not_ready. Do not add pgkit, httpkit/metrics, JWT or WebSocket without a concrete need and a check of the pinned version's behavior.
|
||||
|
||||
Redis connects through the outbound cache port and `backend/internal/adapter/secondary/redis/`. The adapter uses `go-cachekit` 0.7.0 for key/value operations over go-redis; library details stay behind this boundary. Bootstrap constructs the client without waiting for connectivity and closes it on shutdown; shared /readyz checks PostgreSQL, Redis, and SeaweedFS. Use Get/Set/Del with a positive TTL and distinguish a missing key from a Redis error. This is a technical adapter; product cache consumers have not been added. Connection settings are described in [DEPLOY.md](DEPLOY.md).
|
||||
|
||||
S3 storage connects through the outbound `ObjectStorage` port and `backend/internal/adapter/secondary/seaweedfs/`. SeaweedFS is a separate server; AWS SDK for Go v2 is the Go client inside the adapter. Put/Get stream content; Put requires a known byte length, and callers must close the body returned by Get. The Get timeout covers reading the response body. The adapter bounds operation time and distinguishes a missing object from a service error. The container initializes its bucket; Go checks it with HeadBucket instead of creating infrastructure while handling requests. Do not add direct Nginx delivery of private files or product upload/download endpoints without access rules.
|
||||
|
||||
The frontend is a React/Vite SPA. Keep FSD boundaries as product screens are added. Generated transport types are not automatically entity models. MSW supports UI development; its fixtures do not prove that the API is implemented.
|
||||
|
||||
@@ -80,6 +87,28 @@ ML runs as a separate FastAPI process. It currently provides operational health/
|
||||
|
||||
Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English.
|
||||
|
||||
## Go readability
|
||||
|
||||
- Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call.
|
||||
- Name non-obvious limits, timeouts, retry settings, protocol bounds, and shared fixture values with constants in the owning package. Derive counts with `len` when they depend on data. Equal numbers with different meanings need separate names. Obvious zero values, indexes, and clear test inputs can stay inline.
|
||||
- Environment settings belong in config with named defaults and validation. Parse each value once; distinguish an unset variable from an explicitly invalid value.
|
||||
- Give each function one clear purpose. Prefer early returns, shallow nesting, and named complex conditions. Do not add generic helpers, interfaces, or layers without consumers.
|
||||
- Pass `context.Context` first. Keep resource ownership and dependencies explicit; register cleanup immediately after acquisition, including partial startup. Helpers must not hide goroutines or global mutable state.
|
||||
- Check errors and explain non-obvious discarded results. Do not use error-string comparisons for control flow or expose internal errors in HTTP responses.
|
||||
- Write English comments explaining constraints and decisions. Use gofmt/goimports. Refactors preserve behavior; tests cover meaningful boundaries and edge cases rather than constant names or helper internals.
|
||||
|
||||
## Error format
|
||||
|
||||
Handwritten Go errors use `Component.Method - operation: %w` when wrapping a cause and `Component.Method - reason` without a cause. For a free function, use `package.Function`. For example:
|
||||
|
||||
```go
|
||||
if err != nil {
|
||||
return fmt.Errorf("EmailUseCase.Send - read ctf_name: %w", err)
|
||||
}
|
||||
```
|
||||
|
||||
Create a static error without a cause using `errors.New("EmailUseCase.Send - ctf_name is empty")`. The prefix identifies the actual method; descriptions are in English without trailing punctuation. Preserve `errors.Is/As` and sentinel identities, adding context at the error's origin. Avoid redundant wrappers for pass-through returns. Sanitize external SDK errors before wrapping to exclude secrets, URLs, and private object keys. Do not edit generated code. Log errors at the handling boundary rather than at every layer.
|
||||
|
||||
## Change rules
|
||||
|
||||
- Inspect current code and ownership before editing a shared file.
|
||||
|
||||
Reference in new issue
Block a user